2016-06-13 206 views
0

我的ListView沒有顯示任何東西。ListView沒有顯示任何東西

我從下載黑客新聞的頭條新聞API並且把它們放在我的應用程序。我想把這些故事的標題放在我的列表視圖中(它們超過100)。

我下載它們,並將它們存儲在永久存儲數據庫,然後將它們添加到我的列表視圖,但沒有什麼是顯示在我的應用程序了。任何人都可以向我解釋爲什麼?

更新:我得到一個CursorIndexOutOfBoundException問題。 (指數350出的350)

public class MainActivity extends AppCompatActivity { 

    ListView listView; 
    private SQLiteDatabase myDatabase; 
    private Cursor cursor; 

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

     listView = (ListView) findViewById(R.id.listView); 

     DownloadIDs ids = new DownloadIDs(); 
     String URL = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty"; 
     ids.execute(URL); 

     try { 

      ArrayList<String> titles = new ArrayList<String>(); 
      ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, titles); 
      listView.setAdapter(arrayAdapter); 

      myDatabase = this.openOrCreateDatabase("HackerNews", MODE_PRIVATE, null); 

      Cursor cursor1 = myDatabase.rawQuery("SELECT * FROM ids", null); 
      int index = cursor1.getColumnIndex("urlID"); 
      cursor1.moveToFirst(); 
      while (cursor1 != null) { 
       String newUrl = "https://hacker-news.firebaseio.com/v0/item/" + cursor1.getString(index) + ".json?print=pretty"; 
       new DownloadContent().execute(newUrl); 
       cursor1.moveToNext(); 
      } 

      Cursor cursor2 = myDatabase.rawQuery("SELECT * FROM content", null); 
      int titleIndex = cursor2.getColumnIndex("title"); 
      cursor2.moveToFirst(); 
      titles.add("Hello"); 
      while(cursor2 != null){ 
       titles.add(cursor2.getString(titleIndex)); 
       arrayAdapter.notifyDataSetChanged(); 
       cursor2.moveToNext(); 
      } 

     }catch (Exception e){ 
      e.printStackTrace(); 
     } 
    } 

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

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

      String result = ""; 
      URL url; 
      HttpURLConnection urlConnection = null; 
      try { 
       url = new URL(params[0]); 
       urlConnection = (HttpURLConnection) url.openConnection(); 
       InputStream inputStream = urlConnection.getInputStream(); 
       InputStreamReader reader = new InputStreamReader(inputStream); 
       int data = reader.read(); 

       while (data >= 0) { 
        char current = (char) data; 
        result += current; 
        data = reader.read(); 
       } 

       return result; 

      } catch (Exception e) { 
       e.printStackTrace(); 
       return null; 
      } 
     } 

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

      try { 
       myDatabase.execSQL("CREATE TABLE IF NOT EXISTS ids (id INTEGER PRIMARY KEY, urlID VARCHAR)"); 
       cursor = myDatabase.rawQuery("SELECT COUNT(*) FROM ids", null); 
       cursor.moveToFirst(); 
       int count = cursor.getInt(0); 

       if (!(count > 0)) { 

        JSONArray ids = new JSONArray(s); 
        for (int i = 0; i < ids.length(); i++) { 
         myDatabase.execSQL("INSERT INTO ids (urlID) VALUES ('" + ids.getString(i) + "')"); 
        } 
       } 

      }catch (Exception e){ 
       e.printStackTrace(); 
      } 
     } 
    } 

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

     @Override 
     protected String doInBackground(String... params) { 
      String result = ""; 
      URL url; 
      HttpURLConnection urlConnection = null; 
      try { 
       url = new URL(params[0]); 
       urlConnection = (HttpURLConnection) url.openConnection(); 
       InputStream inputStream = urlConnection.getInputStream(); 
       InputStreamReader reader = new InputStreamReader(inputStream); 
       int data = reader.read(); 

       while (data >= 0) { 
        char current = (char) data; 
        result += current; 
        data = reader.read(); 
       } 

       return result; 

      } catch (Exception e) { 
       e.printStackTrace(); 
       return null; 
      } 
     } 

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

      try { 
       myDatabase.execSQL("CREATE TABLE IF NOT EXISTS content(id INTEGER PRIMARY KEY, title VARCHAR, url VARCHAR)"); 
       cursor = myDatabase.rawQuery("SELECT COUNT(*) FROM content", null); 
       cursor.moveToFirst(); 
       int count = cursor.getInt(0); 

       if (!(count > 0)) { 

        JSONObject jsonObject = new JSONObject(s); 
        String title = jsonObject.getString("title"); 
        Log.i("title", title); 
        String url = jsonObject.getString("url"); 
        Log.i("url", url); 

        myDatabase.execSQL("INSERT INTO content (title, url) VALUES('" + title + "','" + url + "')"); 

       } 

      }catch(Exception e){ 
       e.printStackTrace(); 
      } 
     } 
    } 
} 
+0

在哪一行,你得到的異常? –

+0

對不起。我在onCreate方法的兩個while循環上都得到它。 –

回答

1

明白了!我修好了它。我只是減少了新聞量(我決定選擇前20名),並決定在我的應用上只運行一個ASyncTask。

下面是編輯的代碼:

PD:感謝@ cafebabe1991,因爲他給了我如何解決它的提示。謝謝!

public class MainActivity extends AppCompatActivity { 

    ListView listView; 
    private SQLiteDatabase myDatabase; 
    ArrayList<String> titles; 
    ArrayList<String> urls; 
    ArrayAdapter arrayAdapter; 

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

     listView = (ListView) findViewById(R.id.listView); 
     titles = new ArrayList<>(); 
     urls = new ArrayList<>(); 
     arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, titles); 
     listView.setAdapter(arrayAdapter); 

     try { 
      myDatabase = this.openOrCreateDatabase("HackerNews", MODE_PRIVATE, null); 
      DownloadTask downloadTask = new DownloadTask(); 
      String URL = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty"; 
      downloadTask.execute(URL); 

      Cursor cursor = myDatabase.rawQuery("SELECT * FROM content", null); 
      int titleIndex = cursor.getColumnIndex("title"); 
      int urlIndex = cursor.getColumnIndex("url"); 
      cursor.moveToFirst(); 
      while(cursor!=null){ 
       titles.add(cursor.getString(titleIndex)); 
       urls.add(cursor.getString(urlIndex)); 
       cursor.moveToNext(); 
      } 
      arrayAdapter.notifyDataSetChanged(); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 

       Intent intent = new Intent(getApplicationContext(), MainActivity2.class); 
       MainActivity2.url = urls.get(position); 
       startActivity(intent); 
      } 
     }); 
    } 

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

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

      String articleInfo = ""; 
      URL url; 
      HttpURLConnection urlConnection = null; 
      try { 
       url = new URL(params[0]); 
       urlConnection = (HttpURLConnection) url.openConnection(); 
       InputStream inputStream = urlConnection.getInputStream(); 
       InputStreamReader reader = new InputStreamReader(inputStream); 
       int data = reader.read(); 

       while (data >= 0) { 
        char current = (char) data; 
        articleInfo += current; 
        data = reader.read(); 
       } 

       //myDatabase.execSQL("CREATE TABLE IF NOT EXISTS ids (id INTEGER PRIMARY KEY, urlID VARCHAR)"); 
       myDatabase.execSQL("CREATE TABLE IF NOT EXISTS content (id INTEGER PRIMARY KEY, title VARCHAR, url VARCHAR)"); 
       myDatabase.delete("content", null, null); 
       JSONArray ids = new JSONArray(articleInfo); 

       for (int i = 0; i < 20; i++) { 
        //myDatabase.execSQL("INSERT INTO ids (urlID) VALUES ('" + ids.getString(i) + "')"); 

        String articleInfo2 = ""; 
        URL url2 = new URL("https://hacker-news.firebaseio.com/v0/item/" + ids.getString(i) + ".json?print=pretty"); 
        HttpURLConnection urlConnection2 = (HttpURLConnection) url2.openConnection(); 
        InputStream inputStream2 = urlConnection2.getInputStream(); 
        InputStreamReader reader2 = new InputStreamReader(inputStream2); 
        int data2 = reader2.read(); 

        while (data2 >= 0) { 
         char current2 = (char) data2; 
         articleInfo2 += current2; 
         data2 = reader2.read(); 
        } 

        JSONObject jsonObject = new JSONObject(articleInfo2); 

        String title = "'" + jsonObject.getString("title").replaceAll("'", "") + "'"; 
        String articleURL = "'" + jsonObject.getString("url") + "'"; 

        myDatabase.execSQL("INSERT INTO content (title, url) VALUES (" + title + "," + articleURL + ")"); 

       } 

       return null; 

      } catch (Exception e) { 
       e.printStackTrace(); 
       return null; 
      } 
     } 

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

     } 
    } 
} 
0

問題就出在這個代碼

1)

Cursor cursor1 = myDatabase.rawQuery("SELECT * FROM ids", null); 
     int index = cursor1.getColumnIndex("urlID"); 
     cursor1.moveToFirst(); 
     while (cursor1 != null) { 
      String newUrl = "https://hacker-news.firebaseio.com/v0/item/" + cursor1.getString(index) + ".json?print=pretty"; 
      new DownloadContent().execute(newUrl); 
      cursor1.moveToNext(); 
     } 

如何?

您說要光標爲您獲取列索引,並從中獲取項目標識,但是當數據庫爲空時,值將爲空。因此,API將不會返回響應。此外,您也可以使用下面提到的光標執行相同的錯誤。

2)

int titleIndex = cursor2.getColumnIndex("title"); 
     cursor2.moveToFirst(); 
     titles.add("Hello"); 
     while(cursor2 != null){ 
      titles.add(cursor2.getString(titleIndex)); 
      arrayAdapter.notifyDataSetChanged(); 
      cursor2.moveToNext(); 
     } 

如何?

您將光標說移動到(moveToFirst()),如果當前沒有記錄存在哪些的第一個記錄。如果遊標爲空,則此方法返回false。所以確保這個方法返回true然後繼續。

OR

做到這一點(更好的方法)...

while(cursor.moveToNext()) { 
    //If inside , that means you are on the next record.Fetch the column values here 
} 

參考文獻: Cursor methods

Discussion about best ways to iterate a cursor

For loading data into the listview from the database

+0

另外,您正在使用cursor2來獲取標題,之後您將看到它是否爲空。這很糟糕...空檢查是多餘的。 – cafebabe1991

+0

我很確定它是否爲空,我的錯誤會說索引0 out of 0,而不是350 out of 350。我嘗試了你所說的,它仍然是一樣的。沒有什麼顯示在我的列表視圖 –

+0

嘗試一個接一個的調試....首先看看對api的請求是否成功。打印迴應,看看是否工作正常,然後我們轉移到驗證你的邏輯的第二步 – cafebabe1991