我正在制作门户网站类的应用。我使用api接收我在listview中推送的更新。但随着每一次新的更新,我都会失去以前回复的新闻。因此,我创建了一个存储以前新闻项的数据库。现在的问题是我得到了重复的副本,因为如果来自api的更新没有改变,数据库会再次存储响应。我是Android的初学者。有人可以帮助我解决它。 以下是我的代码:
主要片段
Context context;
NewsItem newsItem;
ArrayList<NewsItem> newslist = new ArrayList<>();
ListView listView;
Custom customAdapter;
ProgressDialog pDialog;
@Override
public void onAttach(Context context) {
this.context = context;
super.onAttach(context);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_categories, container, false);
listView = (ListView) v.findViewById(R.id.list);
new GetContacts().execute();
return v;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getActivity().setTitle("Entertainment");
// new GetContacts().execute();
// listView.setAdapter(customAdapter);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private class GetContacts extends AsyncTask<Void, Void, Void > {
DatabaseHandlerNewsItems DBHandler = new DatabaseHandlerNewsItems(getContext());
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getContext());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
HttpHandlder sh = new HttpHandlder();
String jsonStr = sh.makeServiceCall("https://newsapi.org/v1/sources?apiKey=7494e8d897474ddc9a4c13dcec8f78b1&category=entertainment");
Log.e("Response", "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray jsonarr = jsonObj.getJSONArray("sources");
// String first_news = DBHandler.getcontact(0).getNews_description();
for (int i = 0; i < jsonarr.length(); i++) {
JSONObject c = jsonarr.getJSONObject(i);
//if(c.getString("description").equals(first_news))
// break;
JSONObject object= c.getJSONObject("urlsToLogos");
String s = object.getString("medium");
String url =c.getString("url");
newsItem = new NewsItem(c.getString("description"), s,url);
DBHandler.addContact(newsItem);
//newslist.add(newsItem);
}
newslist = DBHandler.getallcontacts();
customAdapter = new Custom(getContext(), R.layout.fragment_listview_row, newslist);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("error", "Couldn't get json from server.");
}
return null;
}
@Override
protected void onPostExecute(Void avoid) {
super.onPostExecute(avoid);
pDialog.dismiss();
listView.setAdapter(customAdapter);
}
}
@Override
public void onDestroy() {
super.onDestroy();
if ( pDialog!= null) {
pDialog.dismiss();
pDialog = null;
}
}
数据库处理程序
NewsItem dbNewsItem;
private static final int DataBaseVersion = 1;
private static final String DataBaseName = "NewsDataBase2";
private static final String TableName = "Newslist";
private static final String ColumnTitle = "news_description";
private static final String ColumnImage = "Name";
private static final String ColumnId ="_id";
private static final String Column_url="url";
public DatabaseHandlerNewsItems(Context context) {
super(context, DataBaseName, null,DataBaseVersion);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE ="CREATE TABLE " + TableName + "("
+ ColumnTitle + " TEXT,"+ColumnId+ " INTEGER PRIMARY KEY AUTOINCREMENT," + Column_url + " Text,"+ColumnImage + " TEXT"
+ ");";
db.execSQL(CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//String drop = "DROP TABLE IF EXIST" + TableName;
//db.execSQL(drop);
onCreate(db);
}
public void addContact(NewsItem table) {
SQLiteDatabase dB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(ColumnTitle, table.getNews_description());
contentValues.put(ColumnImage, table.getUrl_of_icon());
contentValues.put(Column_url,table.getUrl());
dB.insertWithOnConflict(TableName, null, contentValues,SQLiteDatabase.CONFLICT_IGNORE);
dB.close();
}
public ArrayList<NewsItem> getallcontacts (){
ArrayList<NewsItem> news = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM "+ TableName;
Cursor cursor = db.rawQuery(query,null);
cursor.getCount();
if(cursor.moveToFirst()){
do {
NewsItem newsItem = new NewsItem();
newsItem.setNews_description(cursor.getString(0));
newsItem.setUrl(cursor.getString((2)));
String url = cursor.getString(3);
InputStream is = null;
try {
is = (InputStream) new URL(url).getContent();
} catch (IOException e) {
e.printStackTrace();
}
Drawable d = Drawable.createFromStream(is, "");
newsItem.setD(d);
news.add(newsItem);
} while (cursor.moveToNext());
}
return news;
}
public int getcount(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM "+ TableName;
Cursor cursor = db.rawQuery(query,null);
return cursor.getCount();
}
public NewsItem getcontact(int id ) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TableName, new String[]{ColumnTitle}, ColumnId + "=?" , new String[]{String.valueOf(id)}, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
NewsItem contact = new NewsItem(cursor.getString(0));
return contact;
}
自定义适配器
private ArrayList<NewsItem> objects;
private LayoutInflater inflater;
public TextView TextView_newsitem;
ImageView ImageView_newsicon;
NewsItem i;
ProgressDialog pDialog;
int position;
String url;
public Custom(Context context, int resource, ArrayList<NewsItem> objects) {
super(context, resource, objects);
this.objects = objects;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
this.position = position;
convertView = inflater.inflate(R.layout.fragment_listview_row, null);
TextView_newsitem = (TextView) convertView.findViewById(R.id.TextView_newsitem);
ImageView_newsicon = (ImageView) convertView.findViewById(R.id.ImageView_newsicon);
ImageView_newsicon.setOnClickListener(this);
i = objects.get(position);
TextView_newsitem.setText(i.getNews_description());
ImageView_newsicon.setImageDrawable(i.getD());
url = i.getUrl();
return convertView;
}
@Override
public void onClick(View v) {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
getContext().startActivity(intent);
}