Просматривая базу данных с помощью курсоров, чего-то не хватает?

#android #android-asynctask #android-sqlite #android-cursor

#Android #android-asynctask #android-sqlite #android-курсор

Вопрос:

Я пытаюсь создать приложение для чтения новостей, в котором содержимое новостей извлекается из API с использованием JSON и сохраняется в ListView, чтобы пользователи могли видеть разные названия статей. Я создал 2 AsyncTask :

Первый используется для извлечения списка идентификаторов статей из Top Stories из JSONArray.Я извлекаю каждый отдельный идентификатор статьи, используя цикл for, который выполняется 10 раз, чтобы получить 10 идентификаторов статей.

Вторая AsyncTask вызывается внутри первой. Мне нужно передать другой URL-адрес во второй асинхронной задаче, используя конкретный идентификатор статьи, чтобы получить articleId, заголовок и ссылку, которые я хочу вставить в столбец «articleId», «title» и «url» моей таблицы.

У меня проблема с отображением содержимого таблицы. Я стремлюсь к тому, чтобы только после того, как все 10 строк были заполнены благодаря AsynTask, я показывал содержимое моей таблицы один раз.

Вот как выглядит мой код сейчас:

 public class MainActivity extends AppCompatActivity {

DownloadIdList idTask;
DownloadArticle articleTask;
SQLiteDatabase newsReaderDB;

ListView listView;
ArrayList<String> articlesList = new ArrayList<String>();
ArrayAdapter<String> arrayAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    idTask = new DownloadIdList();
    listView = (ListView) findViewById(R.id.listView);
    arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, articlesList);
    listView.setAdapter(arrayAdapter);

    try {

        newsReaderDB = this.openOrCreateDatabase("News", MODE_PRIVATE, null);

        newsReaderDB.execSQL("CREATE TABLE IF NOT EXISTS topStories (id INTEGER PRIMARY KEY, articleId INT(10), title VARCHAR, url VARCHAR)");

        //newsReaderDB.execSQL("DROP TABLE topStories");

        //Toast.makeText(getApplicationContext(),"Database deleted", Toast.LENGTH_LONG).show();

    }   catch (Exception e) {

        Toast.makeText(getApplicationContext(), "Can't create or open Database On Create", Toast.LENGTH_LONG).show();

    }


    try {

        idTask.execute("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty");

    }   catch (Exception e) {
            e.printStackTrace();
        Toast.makeText(getApplicationContext(),"Can't download URL", Toast.LENGTH_LONG).show();

    }
}

public class DownloadIdList extends AsyncTask<String, Void, String>    {

    @Override
    protected String doInBackground(String... urls) {

        String result = "";

        URL url;

        HttpURLConnection urlConnection = null;

        try {

            url = new URL(urls[0]);

            urlConnection = (HttpURLConnection) url.openConnection();

            InputStream inputStream = urlConnection.getInputStream();

            InputStreamReader reader = new InputStreamReader(inputStream);

            int data = reader.read();

            while (data != -1)  {

                char current = (char) data;

                result  = current;

                data = reader.read();

            }

            return resu<

        }catch (Exception e)    {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(),"Can't get Top Stories Id's" ,Toast.LENGTH_LONG).show();

        }

        return null;
    }


    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        try {

            JSONArray idArray = new JSONArray(result);

            for (int i=0; i < 10; i  )    {

                int value = idArray.getInt(i);
                Log.i("Top Stories Id", String.valueOf(value));
                String id = String.valueOf(value);

                articleTask = new DownloadArticle();

                    try {
                        articleTask.execute("https://hacker-news.firebaseio.com/v0/item/"   id   ".json?print=pretty");


                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(getApplicationContext(),"can't get article info from id",Toast.LENGTH_LONG).show();

                    }
            }

        }catch (JSONException e)    {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(),"Can't get JSON Object",Toast.LENGTH_LONG).show();
        }


    }
}

public class DownloadArticle extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {

        String content = "";

        URL url;

        HttpURLConnection urlConnection = null;

        try {

            url = new URL(urls[0]);

            urlConnection = (HttpURLConnection) url.openConnection();

            InputStream inputStream = urlConnection.getInputStream();

            InputStreamReader reader = new InputStreamReader(inputStream);

            int data = reader.read();

            while (data != -1) {

                char current = (char) data;

                content  = current;

                data = reader.read();

            }

            return content;

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "Can't get Articles after retrieving the id", Toast.LENGTH_LONG).show();

        }

        return null;
    }

    @Override
    protected void onPostExecute(String content) {
        super.onPostExecute(content);

        try {

            JSONObject jsonObject = new JSONObject(content);

            int idInfo = jsonObject.getInt("id");
            String title = String.valueOf(jsonObject.getString("title"));
            title = title.replaceAll("'","''");
            String urlien = String.valueOf(jsonObject.getString("url"));


            //newsReaderDB = openOrCreateDatabase("News", MODE_PRIVATE, null);
            newsReaderDB.execSQL("INSERT INTO topStories (articleId, title, url) VALUES("   idInfo   ", '"   title   "','"   urlien   "');");
            showData();


        }catch (JSONException   e)  {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "Can't get Article", Toast.LENGTH_LONG).show();

        }
    }
}

/*public void showDatabase()  {

    try {

        newsReaderDB = this.openOrCreateDatabase("News", MODE_PRIVATE, null);

        Cursor c = newsReaderDB.rawQuery("SELECT * FROM topStories", null);

        c.moveToFirst();

        int idIndex = c.getColumnIndex("id");

        int a_idIndex = c.getColumnIndex("articleId");

        int titleIndex = c.getColumnIndex("title");

        int urlIndex = c.getColumnIndex("url");

        c.moveToFirst();

        while (c != null ) {

            Log.i("Id", String.valueOf(c.getInt(idIndex)));
            Log.i("Article id", String.valueOf(c.getInt(a_idIndex)));
            Log.i("Title", c.getString(titleIndex));
            Log.i("Url Link", c.getString(urlIndex));

            c.moveToNext();
        }

    }   catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(getApplicationContext(), "Unable to List Database", Toast.LENGTH_LONG).show();
    }
}*/

public void showData()  {
try {
    Cursor cursor = newsReaderDB.rawQuery("SELECT * FROM topStories", null);
    if (cursor.moveToFirst()) {
        do {
            String id = String.valueOf(cursor.getInt(cursor.getColumnIndex("id")));
            String a_id = String.valueOf(cursor.getInt(cursor.getColumnIndex("articleId")));
            String title = cursor.getString(cursor.getColumnIndex("title"));
            String url = cursor.getString(cursor.getColumnIndex("url"));

            Log.i("id", id);
            Log.i("article id", a_id);
            Log.i("title", title);
            Log.i("url", url);
        } while (cursor.moveToNext());
    } cursor.close();
}catch (Exception e)    {

    e.printStackTrace();
}

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}
 

Вывод :

     10-15 12:23:42.755 32635-32635/com.iboundiaye.newsreader I/Top Stories Id: 12713089
    10-15 12:23:42.756 32635-32635/com.iboundiaye.newsreader I/Top Stories Id: 12713249
    10-15 12:23:42.756 32635-32635/com.iboundiaye.newsreader I/Top Stories Id: 12711343
    10-15 12:23:42.756 32635-32635/com.iboundiaye.newsreader I/Top Stories Id: 12711511
    10-15 12:23:42.757 32635-32635/com.iboundiaye.newsreader I/Top Stories Id: 12713056
    10-15 12:23:42.757 32635-32635/com.iboundiaye.newsreader I/Top Stories Id: 12709220
    10-15 12:23:42.757 32635-32635/com.iboundiaye.newsreader I/Top Stories Id: 12707606
    10-15 12:23:42.757 32635-32635/com.iboundiaye.newsreader I/Top Stories Id: 12712577
    10-15 12:23:42.757 32635-32635/com.iboundiaye.newsreader I/Top Stories Id: 12709820
    10-15 12:23:42.757 32635-32635/com.iboundiaye.newsreader I/Top Stories Id: 12712454
    10-15 12:23:43.013 32635-32635/com.iboundiaye.newsreader I/id: 1
    10-15 12:23:43.013 32635-32635/com.iboundiaye.newsreader I/article id: 12713089
    10-15 12:23:43.013 32635-32635/com.iboundiaye.newsreader I/title: KiCad: A commitment to freedom
    10-15 12:23:43.013 32635-32635/com.iboundiaye.newsreader I/url: https://giving.web.cern.ch/content/kicad-development-1
    10-15 12:23:43.259 32635-32635/com.iboundiaye.newsreader I/id: 1
    10-15 12:23:43.259 32635-32635/com.iboundiaye.newsreader I/article id: 12713089
    10-15 12:23:43.259 32635-32635/com.iboundiaye.newsreader I/title: KiCad: A commitment to freedom
    10-15 12:23:43.259 32635-32635/com.iboundiaye.newsreader I/url: https://giving.web.cern.ch/content/kicad-development-1
    10-15 12:23:43.259 32635-32635/com.iboundiaye.newsreader I/id: 2
    10-15 12:23:43.259 32635-32635/com.iboundiaye.newsreader I/article id: 12713249
    10-15 12:23:43.259 32635-32635/com.iboundiaye.newsreader I/title: What has happened down here is the winds have changed
    10-15 12:23:43.259 32635-32635/com.iboundiaye.newsreader I/url: http://andrewgelman.com/2016/09/21/what-has-happened-down-here-is-the-winds-have-changed/
    10-15 12:23:43.467 32635-32635/com.iboundiaye.newsreader I/id: 1
    10-15 12:23:43.467 32635-32635/com.iboundiaye.newsreader I/article id: 12713089
    10-15 12:23:43.467 32635-32635/com.iboundiaye.newsreader I/title: KiCad: A commitment to freedom
    10-15 12:23:43.467 32635-32635/com.iboundiaye.newsreader I/url: https://giving.web.cern.ch/content/kicad-development-1
    10-15 12:23:43.467 32635-32635/com.iboundiaye.newsreader I/id: 2
    10-15 12:23:43.467 32635-32635/com.iboundiaye.newsreader I/article id: 12713249
    10-15 12:23:43.467 32635-32635/com.iboundiaye.newsreader I/title: What has happened down here is the winds have changed
    10-15 12:23:43.467 32635-32635/com.iboundiaye.newsreader I/url: http://andrewgelman.com/2016/09/21/what-has-happened-down-here-is-the-winds-have-changed/
    10-15 12:23:43.467 32635-32635/com.iboundiaye.newsreader I/id: 3
    10-15 12:23:43.467 32635-32635/com.iboundiaye.newsreader I/article id: 12711343
    10-15 12:23:43.467 32635-32635/com.iboundiaye.newsreader I/title: A single byte write opened a root execution exploit
    10-15 12:23:43.467 32635-32635/com.iboundiaye.newsreader I/url: https://daniel.haxx.se/blog/2016/10/14/a-single-byte-write-opened-a-root-execution-exploit/
    10-15 12:23:43.722 32635-32635/com.iboundiaye.newsreader I/id: 1
    10-15 12:23:43.722 32635-32635/com.iboundiaye.newsreader I/article id: 12713089
    10-15 12:23:43.722 32635-32635/com.iboundiaye.newsreader I/title: KiCad: A commitment to freedom
    10-15 12:23:43.722 32635-32635/com.iboundiaye.newsreader I/url: https://giving.web.cern.ch/content/kicad-development-1
    10-15 12:23:43.722 32635-32635/com.iboundiaye.newsreader I/id: 2
    10-15 12:23:43.722 32635-32635/com.iboundiaye.newsreader I/article id: 12713249
    10-15 12:23:43.722 32635-32635/com.iboundiaye.newsreader I/title: What has happened down here is the winds have changed
    10-15 12:23:43.722 32635-32635/com.iboundiaye.newsreader I/url: http://andrewgelman.com/2016/09/21/what-has-happened-down-here-is-the-winds-have-changed/
    10-15 12:23:43.722 32635-32635/com.iboundiaye.newsreader I/id: 3
    10-15 12:23:43.722 32635-32635/com.iboundiaye.newsreader I/article id: 12711343
    10-15 12:23:43.722 32635-32635/com.iboundiaye.newsreader I/title: A single byte write opened a root execution exploit
    10-15 12:23:43.723 32635-32635/com.iboundiaye.newsreader I/url: https://daniel.haxx.se/blog/2016/10/14/a-single-byte-write-opened-a-root-execution-exploit/
    10-15 12:23:43.723 32635-32635/com.iboundiaye.newsreader I/id: 4
    10-15 12:23:43.723 32635-32635/com.iboundiaye.newsreader I/article id: 12711511
    10-15 12:23:43.723 32635-32635/com.iboundiaye.newsreader I/title: Books Programmers Don't Really Read (2008)
    10-15 12:23:43.723 32635-32635/com.iboundiaye.newsreader I/url: http://www.billthelizard.com/2008/12/books-programmers-dont-really-read.html
    10-15 12:23:43.909 32635-32635/com.iboundiaye.newsreader W/System.err: org.json.JSONException: No value for url
    10-15 12:23:43.910 32635-32635/com.iboundiaye.newsreader W/System.err:     at org.json.JSONObject.get(JSONObject.java:389)
    10-15 12:23:43.910 32635-32635/com.iboundiaye.newsreader W/System.err:     at org.json.JSONObject.getString(JSONObject.java:550)
    10-15 12:23:43.910 32635-32635/com.iboundiaye.newsreader W/System.err:     at com.iboundiaye.newsreader.MainActivity$DownloadArticle.onPostExecute(MainActivity.java:216)
    10-15 12:23:43.910 32635-32635/com.iboundiaye.newsreader W/System.err:     at com.iboundiaye.newsreader.MainActivity$DownloadArticle.onPostExecute(MainActivity.java:161)
    10-15 12:23:43.910 32635-32635/com.iboundiaye.newsreader W/System.err:     at android.os.AsyncTask.finish(AsyncTask.java:632)
    10-15 12:23:43.910 32635-32635/com.iboundiaye.newsreader W/System.err:     at android.os.AsyncTask.access$600(AsyncTask.java:177)
    10-15 12:23:43.910 32635-32635/com.iboundiaye.newsreader W/System.err:     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
    10-15 12:23:43.910 32635-32635/com.iboundiaye.newsreader W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
    10-15 12:23:43.910 32635-32635/com.iboundiaye.newsreader W/System.err:     at android.os.Looper.loop(Looper.java:135)
    10-15 12:23:43.910 32635-32635/com.iboundiaye.newsreader W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5221)
    10-15 12:23:43.910 32635-32635/com.iboundiaye.newsreader W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
    10-15 12:23:43.910 32635-32635/com.iboundiaye.newsreader W/System.err:     at java.lang.reflect.Method.invoke(Method.java:372)
    10-15 12:23:43.914 32635-32635/com.iboundiaye.newsreader W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
    10-15 12:23:43.914 32635-32635/com.iboundiaye.newsreader W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
 

и затем он продолжает выдавать набор увеличенных данных до статьи 9.
На данный момент он должен отображаться до статьи 10, но по какой-то причине он находит его нулевым, поэтому пропускает один набор и показывает до статьи 9.

Мой желаемый результат:

 10-15 12:23:42.755 32635-32635/com.iboundiaye.newsreader I/Top Stories Id: 12713089
10-15 12:23:42.756 32635-32635/com.iboundiaye.newsreader I/Top Stories Id: 12713249
10-15 12:23:42.756 32635-32635/com.iboundiaye.newsreader I/Top Stories Id: 12711343
10-15 12:23:42.756 32635-32635/com.iboundiaye.newsreader I/Top Stories Id: 12711511
10-15 12:23:42.757 32635-32635/com.iboundiaye.newsreader I/Top Stories Id: 12713056
10-15 12:23:42.757 32635-32635/com.iboundiaye.newsreader I/Top Stories Id: 12709220
10-15 12:23:42.757 32635-32635/com.iboundiaye.newsreader I/Top Stories Id: 12707606
10-15 12:23:42.757 32635-32635/com.iboundiaye.newsreader I/Top Stories Id: 12712577
10-15 12:23:42.757 32635-32635/com.iboundiaye.newsreader I/Top Stories Id: 12709820
10-15 12:23:42.757 32635-32635/com.iboundiaye.newsreader I/Top Stories Id: 12712454
    10-15 12:23:45.109 32635-32635/com.iboundiaye.newsreader I/id: 1
    10-15 12:23:45.109 32635-32635/com.iboundiaye.newsreader I/article id: 12713089
    10-15 12:23:45.109 32635-32635/com.iboundiaye.newsreader I/title: KiCad: A commitment to freedom
    10-15 12:23:45.109 32635-32635/com.iboundiaye.newsreader I/url: https://giving.web.cern.ch/content/kicad-development-1
    10-15 12:23:45.109 32635-32635/com.iboundiaye.newsreader I/id: 2
    10-15 12:23:45.109 32635-32635/com.iboundiaye.newsreader I/article id: 12713249
    10-15 12:23:45.109 32635-32635/com.iboundiaye.newsreader I/title: What has happened down here is the winds have changed
    10-15 12:23:45.109 32635-32635/com.iboundiaye.newsreader I/url: http://andrewgelman.com/2016/09/21/what-has-happened-down-here-is-the-winds-have-changed/
    10-15 12:23:45.109 32635-32635/com.iboundiaye.newsreader I/id: 3
    10-15 12:23:45.109 32635-32635/com.iboundiaye.newsreader I/article id: 12711343
    10-15 12:23:45.109 32635-32635/com.iboundiaye.newsreader I/title: A single byte write opened a root execution exploit
    10-15 12:23:45.109 32635-32635/com.iboundiaye.newsreader I/url: https://daniel.haxx.se/blog/2016/10/14/a-single-byte-write-opened-a-root-execution-exploit/
    10-15 12:23:45.109 32635-32635/com.iboundiaye.newsreader I/id: 4
    10-15 12:23:45.109 32635-32635/com.iboundiaye.newsreader I/article id: 12711511
    10-15 12:23:45.109 32635-32635/com.iboundiaye.newsreader I/title: Books Programmers Don't Really Read (2008)
    10-15 12:23:45.109 32635-32635/com.iboundiaye.newsreader I/url: http://www.billthelizard.com/2008/12/books-programmers-dont-really-read.html
    10-15 12:23:45.109 32635-32635/com.iboundiaye.newsreader I/id: 5
    10-15 12:23:45.109 32635-32635/com.iboundiaye.newsreader I/article id: 12709220
    10-15 12:23:45.109 32635-32635/com.iboundiaye.newsreader I/title: Intel will add deep-learning instructions to its processors
    10-15 12:23:45.109 32635-32635/com.iboundiaye.newsreader I/url: http://lemire.me/blog/2016/10/14/intel-will-add-deep-learning-instructions-to-its-processors/
    10-15 12:23:45.109 32635-32635/com.iboundiaye.newsreader I/id: 6
    10-15 12:23:45.109 32635-32635/com.iboundiaye.newsreader I/article id: 12707606
    10-15 12:23:45.109 32635-32635/com.iboundiaye.newsreader I/title: Be Kind
    10-15 12:23:45.109 32635-32635/com.iboundiaye.newsreader I/url: https://www.briangilham.com/blog/2016/10/10/be-kind
    10-15 12:23:45.110 32635-32635/com.iboundiaye.newsreader I/id: 7
    10-15 12:23:45.110 32635-32635/com.iboundiaye.newsreader I/article id: 12712577
    10-15 12:23:45.110 32635-32635/com.iboundiaye.newsreader I/title: The Ops Identity Crisis
    10-15 12:23:45.110 32635-32635/com.iboundiaye.newsreader I/url: http://www.susanjfowler.com/blog/2016/10/13/the-ops-identity-crisis
    10-15 12:23:45.110 32635-32635/com.iboundiaye.newsreader I/id: 8
    10-15 12:23:45.110 32635-32635/com.iboundiaye.newsreader I/article id: 12709820
    10-15 12:23:45.110 32635-32635/com.iboundiaye.newsreader I/title: Easy Amazon EC2 Instance Comparison
    10-15 12:23:45.110 32635-32635/com.iboundiaye.newsreader I/url: http://www.ec2instances.info/
    10-15 12:23:45.110 32635-32635/com.iboundiaye.newsreader I/id: 9
    10-15 12:23:45.110 32635-32635/com.iboundiaye.newsreader I/article id: 12712454
    10-15 12:23:45.110 32635-32635/com.iboundiaye.newsreader I/title: 5900 online stores found skimming
    10-15 12:23:45.110 32635-32635/com.iboundiaye.newsreader I/url: https://gwillem.github.io/2016/10/11/5900-online-stores-found-skimming/
 

(В конце включена статья 10)

Комментарии:

1. если вставка не работает, вы получите некоторое исключение в журналах, вставьте это

2. Спасибо за ответ, на самом деле это не так, он просто возвращает базу данных с null в столбцах title и url

3. значит, первичный ключ генерируется автоматически? и вы хотите вставить в ту же строку, т.е. Вы хотите обновить (первую строку вставки) во второй вставке или вставить другую новую строку?

4. Да, первичный ключ генерируется автоматически. И после того, как я вставил articleId в первую строку, используя postExecute первой AsyncTask, я хочу вставить заголовок и URL-адрес в ту же строку, что и articleId, который был вставлен в первую AsyncTask, используя postExecute второй AsyncTask.

Ответ №1:

Попробуйте это: открытый класс MainActivity расширяет AppCompatActivity {

 DownloadIdList idTask;
DownloadArticle articleTask;
SQLiteDatabase newsReaderDB;

ListView listView;
ArrayList<String> articlesList = new ArrayList<String>();
ArrayList<String> idList = new ArrayList<String>();
ArrayAdapter<String> arrayAdapter;
int i=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    idTask = new DownloadIdList();
    listView = (ListView) findViewById(R.id.listView);
    arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, articlesList);
    listView.setAdapter(arrayAdapter);

    try {

        newsReaderDB = this.openOrCreateDatabase("News", MODE_PRIVATE, null);

        newsReaderDB.execSQL("CREATE TABLE IF NOT EXISTS topStories (id INTEGER PRIMARY KEY, articleId INT(10), title VARCHAR, url VARCHAR)");

        //newsReaderDB.execSQL("DROP TABLE topStories");

        //Toast.makeText(getApplicationContext(),"Database deleted", Toast.LENGTH_LONG).show();

    }   catch (Exception e) {

        Toast.makeText(getApplicationContext(), "Can't create or open Database On Create", Toast.LENGTH_LONG).show();

    }


    try {

        idTask.execute("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty");

    }   catch (Exception e) {
            e.printStackTrace();
        Toast.makeText(getApplicationContext(),"Can't download URL", Toast.LENGTH_LONG).show();

    }
}

public class DownloadIdList extends AsyncTask<String, Void, String>    {

    @Override
    protected String doInBackground(String... urls) {

        String result = "";

        URL url;

        HttpURLConnection urlConnection = null;

        try {

            url = new URL(urls[0]);

            urlConnection = (HttpURLConnection) url.openConnection();

            InputStream inputStream = urlConnection.getInputStream();

            InputStreamReader reader = new InputStreamReader(inputStream);

            int data = reader.read();

            while (data != -1)  {

                char current = (char) data;

                result  = current;

                data = reader.read();

            }

            return resu<

        }catch (Exception e)    {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(),"Can't get Top Stories Id's" ,Toast.LENGTH_LONG).show();

        }

        return null;
    }


    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        try {

            JSONArray idArray = new JSONArray(result);

            for (int i=0; i < 10; i  )    {

                int value = idArray.getInt(i);
                Log.i("Top Stories Id", String.valueOf(value));
                String id = String.valueOf(value);
                idList.add(id);
              /*  articleTask = new DownloadArticle();

                    try {
                        articleTask.execute("https://hacker-news.firebaseio.com/v0/item/"   id   ".json?print=pretty");


                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(getApplicationContext(),"can't get article info from id",Toast.LENGTH_LONG).show();

                    }*/
            }
for(int l=0;l<idList.size();l  ){
    articleTask = new DownloadArticle();
i = l;
                    try {
                        articleTask.execute("https://hacker-news.firebaseio.com/v0/item/"   id   ".json?print=pretty");


                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(getApplicationContext(),"can't get article info from id",Toast.LENGTH_LONG).show();

                    }
}
        }catch (JSONException e)    {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(),"Can't get JSON Object",Toast.LENGTH_LONG).show();
        }


    }
}

public class DownloadArticle extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {

        String content = "";

        URL url;

        HttpURLConnection urlConnection = null;

        try {

            url = new URL(urls[0]);

            urlConnection = (HttpURLConnection) url.openConnection();

            InputStream inputStream = urlConnection.getInputStream();

            InputStreamReader reader = new InputStreamReader(inputStream);

            int data = reader.read();

            while (data != -1) {

                char current = (char) data;

                content  = current;

                data = reader.read();

            }

            return content;

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "Can't get Articles after retrieving the id", Toast.LENGTH_LONG).show();

        }

        return null;
    }

    @Override
    protected void onPostExecute(String content) {
        super.onPostExecute(content);

        try {

            JSONObject jsonObject = new JSONObject(content);

            int idInfo = jsonObject.getInt("id");
            String title = String.valueOf(jsonObject.getString("title"));
            title = title.replaceAll("'","''");
            String urlien = String.valueOf(jsonObject.getString("url"));


            //newsReaderDB = openOrCreateDatabase("News", MODE_PRIVATE, null);
            newsReaderDB.execSQL("INSERT INTO topStories (articleId, title, url) VALUES("   idInfo   ", '"   title   "','"   urlien   "');");
            if(i==(idList.size()-1){//last row is inserted in db
                 showData();
            }



        }catch (JSONException   e)  {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "Can't get Article", Toast.LENGTH_LONG).show();

        }
    }
}

/*public void showDatabase()  {

    try {

        newsReaderDB = this.openOrCreateDatabase("News", MODE_PRIVATE, null);

        Cursor c = newsReaderDB.rawQuery("SELECT * FROM topStories", null);

        c.moveToFirst();

        int idIndex = c.getColumnIndex("id");

        int a_idIndex = c.getColumnIndex("articleId");

        int titleIndex = c.getColumnIndex("title");

        int urlIndex = c.getColumnIndex("url");

        c.moveToFirst();

        while (c != null ) {

            Log.i("Id", String.valueOf(c.getInt(idIndex)));
            Log.i("Article id", String.valueOf(c.getInt(a_idIndex)));
            Log.i("Title", c.getString(titleIndex));
            Log.i("Url Link", c.getString(urlIndex));

            c.moveToNext();
        }

    }   catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(getApplicationContext(), "Unable to List Database", Toast.LENGTH_LONG).show();
    }
}*/

public void showData()  {
try {
    Cursor cursor = newsReaderDB.rawQuery("SELECT * FROM topStories", null);
    if (cursor.moveToFirst()) {
        do {
            String id = String.valueOf(cursor.getInt(cursor.getColumnIndex("id")));
            String a_id = String.valueOf(cursor.getInt(cursor.getColumnIndex("articleId")));
            String title = cursor.getString(cursor.getColumnIndex("title"));
            String url = cursor.getString(cursor.getColumnIndex("url"));

            Log.i("id", id);
            Log.i("article id", a_id);
            Log.i("title", title);
            Log.i("url", url);
        } while (cursor.moveToNext());
    } cursor.close();
}catch (Exception e)    {

    e.printStackTrace();
}

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}
 

Комментарии:

1. Спасибо, так действительно имеет смысл! Но это все равно не позволит мне сохранить URL-адрес сейчас: я добавил e.printStackTrace() в catch инструкции now UPDATE . Но он показывает это errororg.json.JSONException: нет значения для url

2. Спасибо, так действительно имеет смысл! Но это все равно не позволит мне сохранить URL-адрес сейчас: я добавил e.printStackTrace() в catch инструкции now UPDATE . Но он показывает эту ошибку «org.json.JSONException: нет значения для URL». Значение в этом URL равно » petapixel.com/2016/10/11 /… «. Это из-за знаков плюс в ссылке? должен ли я избегать их?

3. Вы можете сохранить его в виде строки вместо URL-адреса и также вставить запрос на обновление

4. Совет, который вы мне дали по поводу ОБНОВЛЕНИЯ, помог мне многое понять: — Мне не нужно использовать курсор в цикле for первого postExecute. — На данный момент мне не нужно сохранять идентификатор статьи:

5. newsReaderDB.ExecSQL(«ВСТАВИТЬ В ЗНАЧЕНИЯ topStories (articleId) (» id «)»);