Я пытаюсь создать приложение для чтения новостей, в котором содержимое новостей извлекается из api с использованием JSON и хранится в ListView, чтобы пользователи могли видеть разные заголовки статей. Я создал 2 AsyncTask:Просматривая базу данных с помощью курсоров, что-то не хватает?
Первый из них используется для извлечения списка идентификаторов статей из Top Stories из JSONArray.I извлекает каждый отдельный идентификатор статьи, используя цикл for, который выполняется 10 раз, чтобы получить 10 идентификаторов статьи ,
Вторая AsyncTask вызывается внутри первой. Мне нужно передать другой url во второй AsyncTask, используя специальный идентификатор статьи, чтобы получить текст статьи, заголовок и ссылку, которые я хочу добавить в столбец «articleId» и «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 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, но по какой-то причине он считает его нулевым, поэтому он пропускает один комплект и показывает до тех пор, пока не будет приведена статья 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, включенной в конце)
если вставка не работает, то вы получите некоторое исключение в журналах вставить что –
Спасибо за ответ, на самом деле он просто возвращает базу данных с нулевым значением в заголовке и столбцах url – Ibou92
так что первичный ключ сгенерирован автоматически? и вы хотите вставить в ту же строку, то есть хотите обновить (сначала вставить строку) во вторую вставку или вставить другую новую строку? –