I am working on a News app using newsapi. I have a homepage that downloads the top 15 articles and another page that has does the same but from the hackernews api. Each time I run the app from Android Studio, it shows a white screen for a few minutes before populating the list view.
I tried limiting the download rate, kept a check on the SQLite indexes and other things from StackOverflow but I can't seem to solve my issue.
- When I go to the hackernews page and click on list, the app will just refresh itself and come back to the homepage
- When running app from the emulator, it will either go to hackernews without loading homepage or just crash
- java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 when clicking last item in listview
- App will only load 2 articles and give me a java.io.FileNotFoundException: https://www.summarizebot.com/api/summariz... error. This is because the URL from the API doesn't work (tested in the browser)
Homepage
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
...
//START THE BACKGROUND TASK
task = new BackgroundTask();
String s = task.execute("https://newsapi.org/v2/top-headlines?country=us&apiKey").get();
...
//POPULATE LIST WITH DATABASE CONTENT
updateContent();
public void updateContent(){
...
if(cursor.moveToFirst()){
homeStories.clear();
homeLinks.clear();
}
if(cursor.getCount() > 0) {
do {
homeStories.add(cursor.getString(nameIndex));
homeLinks.add(cursor.getString(addressIndex));
} while (cursor.moveToNext());
adapter.notifyDataSetChanged();
}
//BACKGROUND TASK
public class BackgroundTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground (String...urls){
//GET JSON AND SUMMARIES IN SINGLE FOR LOOP FOR EACH ARTICLE
...
for (int i = 0; i < 16; i++) {
JSONObject content = jsonArray.getJSONObject(i);
...
//ADD TO DATABASE
database.execSQL("INSERT INTO trending (name, address) VALUES ('" + title + "','" + address + "')");
//GET THE SUMMARY OF EACH ARTICLE
url = new URL("https://www.summarizebot.com/api/summarize?...
JSONArray j2Array = new JSONArray(s1);
for (int j = 0; j < j2Array.length(); j++) {
JSONObject object2 = j2Array.getJSONObject(j);
s2 += object2.getString("sentence");
}
//END OF MAIN FOR LOOP
}
Hackernews Page
//SAME AS ABOVE
After attempting to troubleshoot, I came up with a few questions:
- How can I speed up background tasks for news articles?
- How can I open an app and start background downloads without it crashing because of indexOutOfBounds?
- How can I give download priority to the current activity instead of downloading everything at once?
- How do I skip over broken links and continue getting the rest of the articles? App stops downloading at that point [FIXED: Surrounded InputStream with Try/Catch]