如何在变量中保存编辑文本并创建API查询

时间:2017-09-15 16:43:18

标签: java android api listview

我有一个屏幕应用程序。用户在编辑视图中放置一些数据,并根据该uri构建器创建URI。但是我不知道如何在点击按钮搜索后自动更新uri。

现在它正在从编辑文本中保存字符串,但我不知道如何在uri构建器中保存它,然后创建一个新查询来更新列表。

我已经记录了程序工作的每一步。在那里

09-15 06:17:07.025 28944-28944/eu.laramartin.newsfeed V/MyLogs: === MAIN ACTIVITY /// onCreate START ===
        09-15 06:17:07.029 28944-28944/eu.laramartin.newsfeed V/MyLogs: === MAIN ACTIVITY /// OnCreate /// New object Adapter ===
        09-15 06:17:07.030 28944-28944/eu.laramartin.newsfeed V/MyLogs: === MAIN ACTIVITY /// OnCreate /// List Atached with adapter ===
        09-15 06:17:07.038 28944-28944/eu.laramartin.newsfeed V/MyLogs: === MAIN ACTIVITY /// OnCreateLoader start ===
        09-15 06:17:07.045 28944-28944/eu.laramartin.newsfeed V/MyLogs: === MAIN ACTIVITY /// OnCreate /// getSupportLoaderManager done ===
        09-15 06:17:07.055 28944-28944/eu.laramartin.newsfeed V/MyLogs: === NEWS LOADER /// onStartLoading DONE ===
        09-15 06:17:07.055 28944-29030/eu.laramartin.newsfeed V/MyLogs: === NEWS LOADER /// loadInBackground START===
        09-15 06:17:07.063 28944-29030/eu.laramartin.newsfeed V/MyLogs: === QUERY UTILS /// createUrl DONE ===
        09-15 06:17:07.063 28944-29030/eu.laramartin.newsfeed V/MyLogs: === QUERY UTILS /// createStringUrl ===
        09-15 06:17:07.064 28944-29030/eu.laramartin.newsfeed V/MyLogs: === QUERY UTILS /// createStringUrl /// MAKING URI===https://content.guardianapis.com/search?show-tags=null&q=null&api-key=test
        09-15 06:17:07.064 28944-29030/eu.laramartin.newsfeed V/MyLogs: === QUERY UTILS /// makeHttpRequest START ===
        09-15 06:17:07.922 28944-29030/eu.laramartin.newsfeed V/MyLogs: === QUERY UTILS /// readFromStream START ===
        09-15 06:17:07.931 28944-29030/eu.laramartin.newsfeed V/MyLogs: === QUERY UTILS /// readFromStream FINISHED ==={"response":{"status":"ok","userTier":"developer","total":1014,"startIndex":1,"pageSize":10,"currentPage":1,"pages":102,"orderBy":"relevance","results":[{"id":"football/2017/jul/29/naby-keita-100-per-cent-stay-at-rb-leipzig-says-coach-liverpool","type":"article","sectionId":"football","sectionName":"Football","webPublicationDate":"2017-07-29T16:30:19Z","webTitle":"Naby Keïta will ‘100%’ stay at RB Leipzig, coach  tells Liverpool","webUrl":"https://www.theguardian.com/football/2017/jul/29/naby-keita-100-per-cent-stay-at-rb-leipzig-says-coach-liverpool","apiUrl":"https://content.guardianapis.com/football/2017/jul/29/naby-keita-100-per-cent-stay-at-rb-leipzig-says-coach-liverpool","tags":[],"isHosted":false},{"id":"global-development/2017/aug/21/no-gay-promotion-can-be-allowed-uganda-cancels-pride-events-lgbt","type":"article","sectionId":"global-development","sectionName":"Global development","webPublicationDate":"2017-08-21T12:09:20Z","webTitle":"'No gay promotion can be allowed': Uganda cancels pride events","webUrl":"https://www.theguardian.com/global-development/2017/aug/21/no-gay-promotion-can-be-allowed-uganda-cancels-pride-events-lgbt","apiUrl":"https://content.guardianapis.com/global-development/2017/aug/21/no-gay-promotion-can-be-allowed-uganda-cancels-pride-events-lgbt","tags":[],"isHosted":false},{"id":"media/greenslade/2015/dec/18/nctj-declares-training-centres-shorthand-exams-null-and-void","type":"article","sectionId":"media","sectionName":"Media","webPublicationDate":"2015-12-18T11:18:21Z","webTitle":"NCTJ declares training centre's shorthand exams 'null and void'","webUrl":"https://www.theguardian.com/media/greenslade/2015/dec/18/nctj-declares-training-centres-shorthand-exams-null-and-void","apiUrl":"https://content.guardianapis.com/media/greenslade/2015/dec/18/nctj-declares-training-centres-shorthand-exams-null-and-void","tags":[],"isHosted":false},{"id":"travel/shortcuts/2016/jul/31/the-swiss-hotel-thats-just-a-bed-on-a-mountain","type":"article","sectionId":"travel","sectionName":"Travel","webPublicationDate":"2016-07-31T16:33:07Z","webTitle":"The Swiss hotel that’s just a bed on a mountain","webUrl":"https://www.theguardian.com/travel/shortcuts/2016/jul/31/the-swiss-hotel-thats-just-a-bed-on-a-mountain","apiUrl":"https://content.guardianapis.com/travel/shortcuts/2016/jul/31/the-swiss-hotel-thats-just-a-bed-on-a-mountain","tags":[],"isHosted":false},{"id":"us-news/2017/mar/24/nepotism-data-ivanka-trump","type":"article","sectionId":"us-news","sectionName":"US news","webPublicationDate":"2017-03-24T11:00:31Z","webTitle":"Measuring nepotism: is it more prevalent in the US than in other countries?","webUrl":"https://www.theguardian.com/us-news/2017/mar/24/nepotism-data-ivanka-trump","apiUrl":"https://content.guardianapis.com/us-news/2017/mar/24/nepotism-data-ivanka-trump","tags":[],"isHosted":false},{"id":"small-business-network/2017/mar/18/letter-to-my-younger-self-student-beans-causr-james-eder","type":"article","sectionId":"small-business-network","sectionName":"Guardian Small Business Network","webPublicationDate":"2017-03-18T09:00:34Z","webTitle":"Letter to my younger self: what would you do if you couldn't fail?","webUrl":"https://www.theguardian.com/small-business-network/2017/mar/18/letter-to-my-younger-self-student-beans-causr-james-eder","apiUrl":"https://content.guardianapis.com/small-business-network/2017/mar/18/letter-to-my-younger-self-student-beans-causr-james-eder","tags":[],"isHosted":false},{"id":"public-leaders-network/2017/jan/13/the-2017-public-leaders-editorial-advisory-board","type":"article","sectionId":"public-leaders-network","sectionName":"Public Leaders Network","webPublicationDate":"2017-01-13T10:23:00Z","webTitle":"The 2017 Public Leaders editorial advisory board","webUrl":"https://www.theguardian.com/public-leaders-network/2017/jan/13/the-2017-public-leaders-editorial-advisory-board","apiUrl":"https://content.guardianapis.com/public-leaders-network/2017/jan/13/the-2017-public-leaders-edi
        09-15 06:17:07.931 28944-29030/eu.laramartin.newsfeed V/MyLogs: === QUERY UTILS /// makeHttpRequest START ===
        09-15 06:17:07.931 28944-29030/eu.laramartin.newsfeed V/MyLogs: === QUERY UTILS /// parseJson START===
        09-15 06:17:07.947 28944-29030/eu.laramartin.newsfeed V/MyLogs: === QUERY UTILS /// formatDate DONE ===
        09-15 06:17:07.959 28944-29030/eu.laramartin.newsfeed V/MyLogs: === QUERY UTILS /// formatDate DONE ===
        09-15 06:17:07.967 28944-29030/eu.laramartin.newsfeed V/MyLogs: === QUERY UTILS /// formatDate DONE ===
        09-15 06:17:07.975 28944-29030/eu.laramartin.newsfeed V/MyLogs: === QUERY UTILS /// formatDate DONE ===
        09-15 06:17:07.982 28944-29030/eu.laramartin.newsfeed V/MyLogs: === QUERY UTILS /// formatDate DONE ===
        09-15 06:17:07.992 28944-29030/eu.laramartin.newsfeed V/MyLogs: === QUERY UTILS /// formatDate DONE ===
        09-15 06:17:08.000 28944-29030/eu.laramartin.newsfeed V/MyLogs: === QUERY UTILS /// formatDate DONE ===
        09-15 06:17:08.004 28944-29030/eu.laramartin.newsfeed V/MyLogs: === QUERY UTILS /// formatDate DONE ===
        09-15 06:17:08.009 28944-29030/eu.laramartin.newsfeed V/MyLogs: === QUERY UTILS /// formatDate DONE ===
        09-15 06:17:08.014 28944-29030/eu.laramartin.newsfeed V/MyLogs: === QUERY UTILS /// formatDate DONE ===
        09-15 06:17:08.021 28944-29030/eu.laramartin.newsfeed V/MyLogs: === QUERY UTILS /// parseJson FINISHED===
        09-15 06:17:08.022 28944-29030/eu.laramartin.newsfeed V/MyLogs: === NEWS LOADER /// loadInBackground FINISHED===
        09-15 06:17:08.180 28944-28944/eu.laramartin.newsfeed V/MyLogs: === MAIN ACTIVITY /// onLoadFinished START ===
        09-15 06:17:08.181 28944-28944/eu.laramartin.newsfeed V/MyLogs: === MAIN ACTIVITY /// onLoadFinished FINISHED ===
        09-15 06:17:08.209 28944-28944/eu.laramartin.newsfeed V/MyLogs: === NEWS ADAPTER START===
        09-15 06:17:08.232 28944-28944/eu.laramartin.newsfeed V/MyLogs: === NEWS ADAPTER FINISHED===
        09-15 06:17:08.264 28944-28944/eu.laramartin.newsfeed V/MyLogs: === NEWS ADAPTER START===
        09-15 06:17:08.309 28944-28944/eu.laramartin.newsfeed V/MyLogs: === NEWS ADAPTER FINISHED===
        09-15 06:17:08.315 28944-28944/eu.laramartin.newsfeed V/MyLogs: === NEWS ADAPTER START===
        09-15 06:17:08.330 28944-28944/eu.laramartin.newsfeed V/MyLogs: === NEWS ADAPTER FINISHED===
        09-15 06:17:08.343 28944-28944/eu.laramartin.newsfeed V/MyLogs: === NEWS ADAPTER START===
        09-15 06:17:08.457 28944-28944/eu.laramartin.newsfeed V/MyLogs: === NEWS ADAPTER FINISHED===

Mainactivity

public class MainActivity
        extends AppCompatActivity
        implements LoaderManager.LoaderCallbacks<List<News>>, SwipeRefreshLayout.OnRefreshListener {

    //Пишем Лог
    final public static String TAG = "MyLogs";

    // Переменная объекта адаптера
    private NewsAdapter adapter;

    //Константа загрузки
    private static int LOADER_ID = 0;

    //ХЗ
    SwipeRefreshLayout swipe;

    EditText editSearch;
    Button buttonSearch;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editSearch = (EditText) findViewById(R.id.edit_search);
        buttonSearch = (Button) findViewById(R.id.button_search);

        final News news = new News(null, null, null, null,null,null);

        buttonSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String m = editSearch.getText().toString();
                news.searchText = m;
                Log.v(TAG, "--- Сохраненные данные --- " + news.searchText);
            }
        });

        //Какой то лейаут Swipe
        swipe = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
        swipe.setOnRefreshListener(this);
        swipe.setColorSchemeColors(getResources().getColor(R.color.colorAccent));

        // Инициализируем листвью
        ListView listView = (ListView) findViewById(R.id.list_view);

        // Инициализируем адаптер, передаем в него контекст
        adapter = new NewsAdapter(this);

        // На лист вешаем текущий адаптер
        listView.setAdapter(adapter);

        // Листенер на айтем
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                // ХЗ откуда объект ews
                News news = adapter.getItem(i);

                Log.v(TAG, "--- Оьъект news содержит ---" + news.toString());

                // ХЗ
                String url = news.url;
                Log.v(TAG, "--- Оьъект url содержит ---" + url.toString());


                //Создаем интент
                Intent intent = new Intent(Intent.ACTION_VIEW);

                // В интент передаем данные из урла
                intent.setData(Uri.parse(url));

                Log.v(TAG, "--- Оьъект Intent содержит ---" + intent.toString());

                startActivity(intent);
            }
        });

        //ХЗ
        getSupportLoaderManager().initLoader(LOADER_ID, null, this);
    }

    //Создаем загрузчик
    @Override
    public Loader<List<News>> onCreateLoader(int id, Bundle args) {
        return new NewsLoader(this);
    }

    //Метод после того как загрузка завершена
    // ХЗ
    @Override
    public void onLoadFinished(Loader<List<News>> loader, List<News> data) {
        swipe.setRefreshing(false);
        if (data != null) {
            adapter.setNotifyOnChange(false);
            adapter.clear();
            adapter.setNotifyOnChange(true);
            adapter.addAll(data);
        }
    }

    @Override
    public void onLoaderReset(Loader<List<News>> loader) {

    }

    @Override
    public void onRefresh() {
        getSupportLoaderManager().restartLoader(LOADER_ID, null, this);
    }

}

网络连接器

public class QueryUtils {

    static String createStringUrl() {

        //Создаем
        Uri.Builder builder = new Uri.Builder();

        News newsQuery = new News(null, null, null, null, null, null);

        //Формирование УРЛ запроса
        builder.scheme("https")
                .encodedAuthority("content.guardianapis.com")
                .appendPath("search")
//                .appendQueryParameter("order-by", "newest")
//                .appendQueryParameter("show-references", "author")
                .appendQueryParameter("show-tags", null)
                .appendQueryParameter("q", newsQuery.getSearchText())
                .appendQueryParameter("api-key", "test");

        // Полученный урл делаем в строку
        String url = builder.build().toString();

        Log.v(TAG, "---URI IS 111--- " + url.toString());
        return url;
    }

    static URL createUrl() {
        String stringUrl = createStringUrl();
        try {
            return new URL(stringUrl);
        } catch (MalformedURLException e) {
            Log.e("Queryutils", "Error creating URL: ", e);
            return null;
        }
    }

    private static String formatDate(String rawDate) {
            String jsonDatePattern = "yyyy-MM-dd'T'HH:mm:ss'Z'";
            SimpleDateFormat jsonFormatter = new SimpleDateFormat(jsonDatePattern, Locale.US);
            try {
                Date parsedJsonDate = jsonFormatter.parse(rawDate);
                String finalDatePattern = "MMM d, yyy";
                SimpleDateFormat finalDateFormatter = new SimpleDateFormat(finalDatePattern, Locale.US);
                return finalDateFormatter.format(parsedJsonDate);
            } catch (ParseException e) {
                Log.e("QueryUtils", "Error parsing JSON date: ", e);
                return "";
            }
    }

    static String makeHttpRequest(URL url) throws IOException {
        String jsonResponse = "";

        if (url == null){
            return jsonResponse;
        }
        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;

        try {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setReadTimeout(10000 /* milliseconds */);
            urlConnection.setConnectTimeout(15000 /* milliseconds */);
            urlConnection.connect();
            if (urlConnection.getResponseCode() == 200){
                inputStream = urlConnection.getInputStream();
                jsonResponse = readFromStream(inputStream);
            } else {
                Log.e("mainActivity", "Error response code: " + urlConnection.getResponseCode());
            }
        } catch (IOException e) {
            Log.e("Queryutils", "Error making HTTP request: ", e);
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
        return jsonResponse;
    }

    private static String readFromStream(InputStream inputStream) throws IOException {
        StringBuilder output = new StringBuilder();
        if (inputStream != null) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line = reader.readLine();
            while (line != null) {
                output.append(line);
                line = reader.readLine();
            }
        }
        return output.toString();
    }

    static List<News> parseJson(String response) {
        ArrayList<News> listOfNews = new ArrayList<>();
        try {
            JSONObject jsonResponse = new JSONObject(response);
            JSONObject jsonResults = jsonResponse.getJSONObject("response");
            JSONArray resultsArray = jsonResults.getJSONArray("results");

            for (int i = 0; i < resultsArray.length(); i++) {
                JSONObject oneResult = resultsArray.getJSONObject(i);
                String webTitle = oneResult.getString("webTitle");
                String url = oneResult.getString("webUrl");
                String date = oneResult.getString("webPublicationDate");
                date = formatDate(date);
                String section = oneResult.getString("sectionName");
                JSONArray tagsArray = oneResult.getJSONArray("tags");
                String author = "";

                if (tagsArray.length() == 0) {
                    author = null;
                } else {
                    for (int j = 0; j < tagsArray.length(); j++) {
                        JSONObject firstObject = tagsArray.getJSONObject(j);
                        author += firstObject.getString("webTitle") + ". ";
                    }
                }
                listOfNews.add(new News(webTitle, author, url, date, section, null));
            }
        } catch (JSONException e) {
            Log.e("Queryutils", "Error parsing JSON response", e);
        }
        return listOfNews;
    }
}

装载机

public class NewsLoader extends AsyncTaskLoader<List<News>> {

    public NewsLoader(Context context) {
        super(context);
    }

    @Override
    protected void onStartLoading() {
        super.onStartLoading();
        forceLoad();
    }

    @Override
    public List<News> loadInBackground() {

        //Создаем пустой список новостей
        List<News> listOfNews = null;

        try {
            //Создаем УРЛ
            URL url = QueryUtils.createUrl();

            // Создаем запрос json
            String jsonResponse = QueryUtils.makeHttpRequest(url);

            // В лист парсим из json запроса
            listOfNews = QueryUtils.parseJson(jsonResponse);
        } catch (IOException e) {
            Log.e("Queryutils", "Error Loader LoadInBackground: ", e);
        }
        return listOfNews;
    }
}

0 个答案:

没有答案