如何使用“标题”更新列表视图

时间:2019-07-30 12:40:10

标签: java android sqlite android-studio listview

我正在尝试在Udemy“完成Android N开发人员课程”之后实施Newsreader应用程序。使用列表视图。

按照我正确遵循的说明进行操作,但是在执行以下主要活动时,尽管需要用标题更新列表项,但列表视图中什么都没有显示。即使在Android Monitor中也没有错误。

请找到问题的任何建议。

谢谢!

public class MainActivity extends AppCompatActivity {

    ArrayList<String > titles = new ArrayList<>();
    ArrayList<String> content = new ArrayList<>();
    ArrayAdapter arrayAdapter;
    SQLiteDatabase articleDB ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView listView = (ListView) findViewById(R.id.listView );
        arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,titles);
        listView.setAdapter(arrayAdapter);
        articleDB = this.openOrCreateDatabase("articles",MODE_PRIVATE,null);
        articleDB.execSQL("CREATE TABLE IF NOT EXISTS articles (id INTEGER PRIMARY KEY, articleID INTEGER,title VARCHAR,content VARCHAR)");
        updateListView();
        DownloadTask task = new DownloadTask();
        try {
            task.execute("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty");
        }catch(Exception e){
           e.printStackTrace();
        }
    }
    //update table
    public void updateListView(){
        Cursor c = articleDB.rawQuery("SELECT * FROM articles", null);
        int contentIndex = c.getColumnIndex("content");
        int titleIndex = c.getColumnIndex("title");
        if(c.moveToFirst()){
            titles.clear();
            content.clear();
            do{
                titles.add(c.getString(titleIndex));
                content.add(c.getString(contentIndex));
            }while (c.moveToNext());
            arrayAdapter.notifyDataSetChanged();
        }
    }
    public class DownloadTask extends AsyncTask<String, Void, String>{
        @Override
        protected String doInBackground(String... strings) {
            String result = "";
            URL url;
            HttpsURLConnection urlConnection = null;
            try {
                url = new URL (strings[0]);
                urlConnection = (HttpsURLConnection) url.openConnection();
                InputStream in = urlConnection.getInputStream();
                InputStreamReader reader = new InputStreamReader(in);
                int data = reader.read();
                while (data != -1){
                    char current = (char) data;
                    result += current;
                    data = reader.read();
                }
                //Log.i("URLContent",result);

                JSONArray jsonArray = new JSONArray(result);
                int numberOfItems = 20;
                if(jsonArray.length() <20){
                    numberOfItems = jsonArray.length();
                }
                //to clear the table before add data
                articleDB.execSQL("DELETE FROM articles"); //will clear everything and add a new data
                for (int i=0;i<numberOfItems;i++ ){
                    //Log.i("JSONItem",jsonArray.getString(i));
                    String articleId = jsonArray.getString(i);
                    url = new URL("https://hacker-news.firebaseio.com/v0/item/"+articleId+".json?print=pretty");
                    urlConnection = (HttpsURLConnection) url.openConnection();
                    in = urlConnection.getInputStream();
                    reader = new InputStreamReader(in);
                    data = reader.read();
                    String articleInfo = "";
                    while (data!= -1){
                        char current = (char) data;
                        articleInfo += current;
                        data = reader.read();
                    }
                    //Log.i("ArticleInfo",articleInfo);
                    //separate title and URL
                    JSONObject jsonObject = new JSONObject(articleInfo);
                    if (!jsonObject.isNull("title") && !jsonObject.isNull("url")){
                        String articleTitle = jsonObject.getString("title");
                        String articleURL = jsonObject.getString("url");
                        //Log.i("info",articleTitle + articleURL);
                        url = new URL(articleURL);
                        urlConnection = (HttpsURLConnection) url.openConnection();
                        in = urlConnection.getInputStream();
                        reader = new InputStreamReader(in);
                        data = reader.read();
                        String articleContent = "";
                        while (data!= -1){
                            char current = (char) data;
                            articleContent += current;
                            data = reader.read();
                        }
                        //Log.i("articleContent",articleContent);

                        String sql = "INSERT INTO articles(articleID,title,content) VALUES(? , ? , ?)";
                        SQLiteStatement statement = articleDB.compileStatement(sql);
                        statement.bindString(1,articleId);
                        statement.bindString(2,articleTitle);
                        statement.bindString(3,articleContent);
                        statement.execute();
                    }
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            //run when the download task is completed
            updateListView();
        }
    }
}

2 个答案:

答案 0 :(得分:0)

我不认为您的问题是基于SQLite的,而是问题在于数据的检索。

问题可能是:-

  1. 您没有相应的权限。因此,您需要检查清单是否具有权限,以及您是否已请求运行时权限。参见Request App Permissions

    • 下面的测试通过使用API​​ 24之前的设备(模拟器)来规避运行时权限。
  2. 在检索时未使用适当的连接类型,即将HTTP URL切换为HTTP连接。请参见下面的代码以获取修复(可能是更好的选择)。

测试1

例如,修改您的代码(从中注释代码)以跳过数据检索,并添加用于测试的数据插入会显示插入的数据。

例如:-

body.style.backgroundColor = `rgb(${rrr},${ggg},${bbb}`;

结果:-

enter image description here

  • 这与预期的一样,即仅显示标题

测试2

删除注释掉的代码,最初会导致 protected String doInBackground(String... strings) { String result = ""; URL url; HttpsURLConnection urlConnection = null; HttpURLConnection xurlConnection = null; //ADDED for stage 2 testing /* <<<<<<<<<<< COMMENT OUT DATA RETRIEVAL >>>>>>>>>> try { url = new URL (strings[0]); urlConnection = (HttpsURLConnection) url.openConnection(); InputStream in = urlConnection.getInputStream(); InputStreamReader reader = new InputStreamReader(in); int data = reader.read(); while (data != -1){ char current = (char) data; result += current; data = reader.read(); } //Log.i("URLContent",result); JSONArray jsonArray = new JSONArray(result); int numberOfItems = 20; if(jsonArray.length() <20){ numberOfItems = jsonArray.length(); } //to clear the table before add data articleDB.execSQL("DELETE FROM articles"); //will clear everything and add a new data for (int i=0;i<numberOfItems;i++ ){ //Log.i("JSONItem",jsonArray.getString(i)); String articleId = jsonArray.getString(i); url = new URL("https://hacker-news.firebaseio.com/v0/item/"+articleId+".json?print=pretty"); urlConnection = (HttpsURLConnection) url.openConnection(); in = urlConnection.getInputStream(); reader = new InputStreamReader(in); data = reader.read(); String articleInfo = ""; while (data!= -1){ char current = (char) data; articleInfo += current; data = reader.read(); } //Log.i("ArticleInfo",articleInfo); //separate title and URL JSONObject jsonObject = new JSONObject(articleInfo); if (!jsonObject.isNull("title") && !jsonObject.isNull("url")){ String articleTitle = jsonObject.getString("title"); String articleURL = jsonObject.getString("url"); //Log.i("info",articleTitle + articleURL); url = new URL(articleURL); xurlConnection = (HttpURLConnection) url.openConnection(); in = xurlConnection.getInputStream(); reader = new InputStreamReader(in); data = reader.read(); String articleContent = ""; while (data!= -1){ char current = (char) data; articleContent += current; data = reader.read(); } //Log.i("articleContent",articleContent); String sql = "INSERT INTO articles(articleID,title,content) VALUES(? , ? , ?)"; SQLiteStatement statement = articleDB.compileStatement(sql); statement.bindString(1,articleId); statement.bindString(2,articleTitle); statement.bindString(3,articleContent); statement.execute(); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } <<<<<<<<<< END OF COMMENTED OUT CODE >>>>>>>>>> */ ContentValues cv = new ContentValues(); cv.put("articleID",1); cv.put("title","Title"); cv.put("content","Some content"); articleDB.insert("articles",null,cv); return null; }

测试3

使用API​​ 24之前的设备(为了不必请求运行时权限)并将清单更改为包含Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)

结果

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

第117行为 Caused by: java.lang.ClassCastException: com.android.okhttp.internal.huc.HttpURLConnectionImpl cannot be cast to javax.net.ssl.HttpsURLConnection at aso.aso57271930listview.MainActivity$DownloadTask.doInBackground(MainActivity.java:117) at aso.aso57271930listview.MainActivity$DownloadTask.doInBackground(MainActivity.java:67)

测试4

在第117行添加一个断点并以调试模式运行会导致:-

enter image description here

  • URL不是https而是http

测试5

根据:-

添加行
urlConnection =  (HttpsURLConnection) url.openConnection();

然后更改为使用:-

protected String doInBackground(String... strings) {
        String result = "";
        URL url;
        HttpsURLConnection urlConnection = null;
        HttpURLConnection xurlConnection = null; //<<<<<<<<<< ADDED for stage 2 testing

结果:-

enter image description here

答案 1 :(得分:-1)

您的表未在db中创建,请更改

articleDB.execSQL("CREATE TABLE IF NOT EXISTS articles (id INTEGER PRIMARY KEY, articleID INTEGER,title VARCHAR,content VARCHAR)");

articleDB.execSQL("CREATE TABLE IF NOT EXISTS articles (id INTEGER PRIMARY KEY, articleID INTEGER,title TEXT,content TEXT)");