2017-08-15 9 views
0

私は簡単なニュースリーダーアプリを作っています。ニュースは、ニュースのリストのように、1つのRecyclerViewに表示する必要があります。問題は、複数のURLがあるため、データを抽出し、どのように解析するかしかわかりませんが、より多くのデータを処理する方法はわかりません。ここに私のコードです:Android、解析用に複数のURLを扱う

public class NewsActivity extends AppCompatActivity { 

    public static final String LOG_TAG = NewsActivity.class.getSimpleName(); 
    public static final String newsUrl1 = "http://tests.intellex.rs/api/v1/news/list?page=1"; 
    public static final String newsUrl2 = "http://tests.intellex.rs/api/v1/news/list?page=2"; 
    public static final String newsUrl3 = "http://tests.intellex.rs/api/v1/news/list?page=3"; 
    public static final String newsUrl4 = "http://tests.intellex.rs/api/v1/news/list?page=4"; 

    private NewsAdapter adapter; 
    private RecyclerView recyclerView; 
    private ArrayList<NewsModel> newsArray; 

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

     newsArray = new ArrayList<>(); 
     adapter = new NewsAdapter(this, newsArray); 
     RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); 
     recyclerView = (RecyclerView) findViewById(R.id.newsRecyclerView); 
     recyclerView.setLayoutManager(mLayoutManager); 
     recyclerView.addItemDecoration(new SimpleDividerItemDecoration(getApplicationContext())); 

     recyclerView.setAdapter(adapter); 
     recyclerView.setHasFixedSize(true); 

     NewsAsyncTask task = new NewsAsyncTask(); 
     task.execute(); 
    } 
    private class NewsAsyncTask extends AsyncTask<URL, Void, ArrayList<NewsModel>> { 
     @Override 
     protected ArrayList<NewsModel> doInBackground(URL... urls) { 

      URL url = createUrl(newsUrl1); 
      String jsonResponse = ""; 
      try { 
       jsonResponse = makeHttpRequest(url); 

      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      return extractFeatureFromJson(jsonResponse); 
     } 

     @Override 
     protected void onPostExecute(ArrayList<NewsModel> news) { 
      if (news == null) { 
       return; 
      } 
      adapter.addAll(news); 
     } 
     private URL createUrl(String stringUrl) { 
      URL url = null; 
      try { 
       url = new URL(stringUrl); 
      } catch (MalformedURLException exception) { 
       Log.e(LOG_TAG, "Error with creating URL", exception); 
       return null; 
      } 
      return url; 
     } 

     private String makeHttpRequest(URL url) throws IOException { 
      String jsonResponse = ""; 
      HttpURLConnection urlConnection = null; 
      InputStream inputStream = null; 
      try { 
       urlConnection = (HttpURLConnection) url.openConnection(); 
       urlConnection.setRequestMethod("GET"); 
       urlConnection.setReadTimeout(10000); 
       urlConnection.setConnectTimeout(15000); 
       urlConnection.connect(); 

       if (urlConnection.getResponseCode() == 200) { 
        inputStream = urlConnection.getInputStream(); 
        jsonResponse = readFromStream(inputStream); 
       } else { 
        Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode()); 
       } 
      } catch (IOException e) { 
       Log.e(LOG_TAG, "Problem retrieving the JSON results.", e); 
      } finally { 
       if (urlConnection != null) { 
        urlConnection.disconnect(); 
       } 
       if (inputStream != null) { 
        // function must handle java.io.IOException here 
        inputStream.close(); 
       } 
      } 
      return jsonResponse; 
     } 

     private 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(); 
     } 

     private ArrayList<NewsModel> extractFeatureFromJson(String newsJson) { 
      if (TextUtils.isEmpty(newsJson)) { 
       return null; 
      } 
      ArrayList<NewsModel> news_information = new ArrayList<>(); 
      try { 
       JSONObject baseJsonResponse = new JSONObject(newsJson); 
       JSONArray newsArray = baseJsonResponse.getJSONArray("list"); 
       for (int i = 0; i < newsArray.length(); i++) { 
        JSONObject news = newsArray.getJSONObject(i); 
        try { 
         news = newsArray.getJSONObject(i); 
         String newsImage = news.getString("image"); 
         String newsTitle = news.getString("title"); 
         String newsPublished = news.getString("published"); 
         String newsAuthor = news.getString("author"); 
         String newsID = news.getString("id"); 

         NewsModel newsModel = new NewsModel(newsImage, newsTitle, newsPublished, newsAuthor, newsID); 
         news_information.add(newsModel); 
        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
      return news_information; 
     } 
    } 
} 

助けていただければ幸いです。前もって感謝します。

+0

私が唯一の違いことがわかりますが、アレイを使用する場合は コード内のURLはページ番号です。あなたが必要とするのは、後続のページからのニュースを表示することです。この質問を見て、AsyncTaskで実装されていることを確認してください:https://stackoverflow.com/q/42854142/2688283。ただし、Retrofitを代わりに使用することをお勧めします。http://square.github.io/retrofit/ここに設定方法に関する情報があります:https://guides.codepath.com/android/Consuming-APIs -with-Retrofit – iRuth

答えて

0

なぜ "リンク"を配列として使用しないのですか?あなたはすべてのキーを取得し、次々に移動し、各 EDITを照会、とにかく

JSONObject jsonObject = new JSONObject(); 
JSONArray keys = jsonObject.getJSONArray("links"); 
int length = keys.length(); 
for (int i = 0; i < length; i++) { 
    new ReadJSON().execute(keys.getString(i)); 
} 

JSONObject jsonObject = new JSONObject(/*Your links json*/); 
JSONObject links = jsonObject.get("links"); 
Iterator<String> keys = links.keys(); 
while (keys.hasNext()) { 
    new ReadJSON().execute(links.getString(keys.next())); 
} 
+0

私はこれをUdacityのチュートリアルで見ましたが、私はプログラミングの面で比較的新しいです。私はそれを書く必要があるあなたの解決策? –

関連する問題