我有一个 zip 文件,我必须从中提取可以获取特定信息的信息。提取信息的过程大约需要 0.7 秒的估计时间。我所做的是在我的 ListAdapter 中添加一个异步类(为了创建多个线程,以便它也可以加载其他类似的线程),现在在我的异步类中它创建了多个线程,这导致数据库将信息添加到其预先存在的信息中。
现在我的问题是“如何在 listadapter 上创建异步线程而不导致数据库重复?”
这是代码:
Map<TextView, String> authorViews=Collections.synchronizedMap(new WeakHashMap<TextView, String>());
Map<TextView, String> dateViews=Collections.synchronizedMap(new WeakHashMap<TextView, String>());
private class PresentInformation extends AsyncTask<Context, Void, Void>{
private TextView Tauthor;
private TextView Tlabel;
String position;
String date = null;
String author = null;
public PresentInformation(TextView author, TextView label, String Position) {
// TODO Auto-generated constructor stub
this.Tauthor = author;
this.Tlabel = label;
this.position = Position;
}
@Override
protected Void doInBackground(Context... params) {
// TODO Auto-generated method stub
Boolean addToDB;
if(author_exist(Tauthor)){
author = getAuthorFName(position);
addToDB = false;
}else{
//Declare an action to test if author does exist
authorViews.put(Tauthor, position);
author = getAuthor(position);
addToDB = true;
}
dateViews.put(Tlabel, position);
if(date_exist(Tlabel)){
date = db.getDate(position);
addToDB = false;
}else{
dateViews.put(Tlabel, position);
date = date/time();
addToDB = true;
}
if(addToDB){//Adds to database if they don't exist
db.addDatabase(new Database(position, author, date));
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
if(author == null){
author = "Author not found!";
}
if(date == null){
date = "Date not found!";
}
Tlabel.setText(date);
Tlabel.setText(author);
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
Tauthor.setText("Loading author please wait...");
Tlabel.setText("Loading date please wait...");
}
public Boolean author_exist(TextView tv){
String temp = authorViews.get(tv);
if(temp ==null)
return true;
return false;
}
public Boolean date_exist(TextView tv){
String temp = dateViews.get(tv);
if(temp ==null)
return true;
return false;
}
}
public class IconicAdapter extends ArrayAdapter<String>{
IconicAdapter() {
super(main.this, R.layout.bookselection_row, R.id.Book_Title, bookLocation);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = null;
if(row == null)
row = super.getView(position, convertView, parent);
icon=(ImageView)row.findViewById(R.id.icon);
author = (TextView)row.findViewById(R.id.book_Author);
date_label = (TextView)row.findViewById(R.id.label);
String path = bookLocation.get(position);
// Collections(path, position, author, date_label);
new PresentInformation(author, date_label, path).execute(main.this);
try{
Log.i("BookString input", bookLocation.get(position));
loadImage.Uploader(bookLocation.get(position), icon);
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return row;
}
}