Android 从作为响应从服务器url接收的项目生成Listview
我正在制作一个门户类的应用程序。我使用了一个api来接收我在listview中推送的更新。但随着每一次新的更新,我都失去了先前回复中的新闻报道。因此,我创建了一个数据库来存储以前的新闻条目。现在的问题是,我得到了重复的副本,因为如果api的更新没有更改,数据库会再次存储响应。我是Android的初学者。有人能帮我解决吗。 下面是我的代码: 主要片段Android 从作为响应从服务器url接收的项目生成Listview,android,listview,Android,Listview,我正在制作一个门户类的应用程序。我使用了一个api来接收我在listview中推送的更新。但随着每一次新的更新,我都失去了先前回复中的新闻报道。因此,我创建了一个数据库来存储以前的新闻条目。现在的问题是,我得到了重复的副本,因为如果api的更新没有更改,数据库会再次存储响应。我是Android的初学者。有人能帮我解决吗。 下面是我的代码: 主要片段 语境; 新闻项目新闻项目; ArrayList newslist=新建ArrayList(); 列表视图列表视图; 自定义适配器; Progress
语境;
新闻项目新闻项目;
ArrayList newslist=新建ArrayList();
列表视图列表视图;
自定义适配器;
ProgressDialog;
@凌驾
公共void-onAttach(上下文){
this.context=上下文;
super.onAttach(上下文);
}
@可空
@凌驾
CreateView上的公共视图(布局、充气机、视图组容器、捆绑包保存状态){
视图v=充气机。充气(R.layout.fragment_类别,容器,错误);
listView=(listView)v.findViewById(R.id.list);
新建GetContacts().execute();
返回v;
}
@凌驾
ActivityCreated上的公共无效(@Nullable Bundle savedinStateCState){
super.onActivityCreated(savedInstanceState);
getActivity().setTitle(“娱乐”);
//新建GetContacts().execute();
//setAdapter(customAdapter);
}
@凌驾
已创建视图上的公共void(视图,捆绑保存状态){
super.onViewCreated(视图,savedInstanceState);
}
私有类GetContacts扩展异步任务{
DatabaseHandlerNewsItems DBHandler=新的DatabaseHandlerNewsItems(getContext());
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=newprogressdialog(getContext());
setMessage(“请稍候…”);
pDialog.setCancelable(假);
pDialog.show();
}
@凌驾
受保护的Void doInBackground(Void…arg0){
httphandler sh=新的httphandler();
字符串jsonStr=sh.makeServiceCall(“https://newsapi.org/v1/sources?apiKey=7494e8d897474ddc9a4c13dcec8f78b1&category=entertainment");
Log.e(“响应”,“来自url的响应:+jsonStr”);
if(jsonStr!=null){
试一试{
JSONObject jsonObj=新的JSONObject(jsonStr);
JSONArray jsonarr=jsonObj.getJSONArray(“源”);
//字符串first_news=DBHandler.getcontact(0.getNews_description();
for(int i=0;i
数据库处理程序
NewsItem数据库NewsItem;
私有静态最终int数据库版本=1;
私有静态最终字符串DataBaseName=“NewsDataBase2”;
私有静态最终字符串TableName=“Newslist”;
私有静态最终字符串ColumnTitle=“news\u description”;
私有静态最终字符串ColumnImage=“Name”;
私有静态最终字符串ColumnId=“\u id”;
私有静态最终字符串列\u url=“url”;
公共数据库HandlerNewsItems(上下文){
super(上下文、数据库名、null、数据库版本);
}
@凌驾
public void onCreate(SQLiteDatabase db){
String CREATE=“CREATE TABLE”+TableName+”(“
+ColumnTitle+“TEXT,”+ColumnId+“整型主键自动递增,”+Column_url+“TEXT,”+ColumnImage+“TEXT”
+ ");";
execSQL(创建);
}
@凌驾
public void onUpgrade(SQLiteDatabase db,int-oldVersion,int-newVersion){
//String drop=“drop TABLE IF EXIST”+TableName;
//db.execSQL(drop);
onCreate(db);
}
public void addContact(新闻项表){
SQLiteDatabase dB=this.getWritableDatabase();
ContentValues ContentValues=新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\u IGNORE);
dB.close();
}
公共阵列列表getallcontacts(){
ArrayList news=新的ArrayList();
SQLiteDatabase db=this.getWritableDatabase();
String query=“SELECT*FROM”+表名;
Cursor Cursor=db.rawQuery(查询,空);
cursor.getCount();
if(cursor.moveToFirst()){
做{
NewsItem NewsItem=新的NewsItem();
newsItem.setNews_描述(cursor.getString(0));
setUrl(cursor.getString((2));
字符串url=cursor.getString(3);
InputStream=null;
试一试{
is=(InputStream)新URL(URL).getContent();
}捕获(IOE异常){
e、 printStackTrace();
}
Drawable d=Drawable.createFromStream(为“”);
新闻项目.setD(d);
news.add(新闻项);
}
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);
}