0

JSON을 사용하여 API의 내용을 검색하고 사용자가 기사의 다른 제목을 볼 수 있도록 ListView에 저장되는 뉴스 리더 앱을 만들려고합니다. 나는 2 AsyncTask를 만들었습니다 :커서를 사용하여 데이터베이스를 탐색하는 중 누락 된 것이 있습니까?

첫 번째 것은 JSONArray에서 Top Stories의 기사 ID 목록을 검색하는 데 사용됩니다. 10 회 실행되는 for 루프를 사용하여 개별 기사 ID를 검색합니다. .

두 번째 AsyncTask는 첫 번째 AsyncTask 내부에서 호출됩니다. 나는 articleId, 제목 및 내 테이블의 "articleId" "title"및 "url"열에 INSERT 할 링크를 얻기 위해 기사의 특정 ID를 사용하여 두 번째 AsyncTask에 다른 URL을 전달해야합니다.

테이블 내용을 표시하는 데 문제가 있습니다. 내가 목표로하는 것은 AsynTask 덕분에 10 개의 행이 채워진 후에야 내 테이블의 내용을 한 번 표시한다는 것입니다.

이 내 코드는 지금 모습입니다 :

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 result; 

     }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까지 줄 것입니다 그러나 무엇인가의 이유로, 그것은 1 세트 건너 뛰고 기사 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/ 

+0

삽입하면 로그에 일부 예외를 얻을 것이다 작동하지 않는 경우가 있음을 붙여 –

+0

답장을 보내 주셔서 감사합니다. 실제로는 제목과 URL 열 – Ibou92

+0

에 null이있는 데이터베이스 만 반환하므로 기본 키가 자동으로 생성됩니까? 동일한 행, 즉 두 번째 삽입에서 업데이트 (첫 번째 행 삽입)하거나 다른 새 행 삽입을 원하십니까? –

답변

0

(끝 부분에 포함 기사 (10)와 함께)이 시도 : 공용 클래스 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 result; 

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

} 
+0

감사합니다.이 방법이 더 의미가 있습니다! 하지만 지금도 URL을 저장할 수는 없습니다. 지금 UPDATE 문에서 e.printStackTrace()를 추가했습니다. 하지만이 errororg.json.JSONException을 보여줍니다 : URL 값이 없습니다 – Ibou92

+0

감사합니다,이 방법은 더 이해가 돼! 하지만 여전히 URL을 저장할 수는 없습니다. 이제 UPDATE 문에서 e.printStackTrace()를 추가했습니다. 하지만이 오류는 "org.json.JSONException : URL에 대한 값 없음"을 표시합니다. 해당 URL의 값은 "http://petapixel.com/2016/10/11/cooled-nikon-d5500a-chills-sensor-clearer-star-photos/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%25253A+PetaPixel+ % 252528PetaPixel % 252529 ". 링크의 더하기 기호 때문입니까? 내가 그들을 벗어나야합니까? – Ibou92

+0

U URL 대신 문자열로 저장하고 업데이트 쿼리를 붙여 넣을 수 있습니다. –

관련 문제