我有来电记录应用。每次我调用它都会获取数字并将其保存在数据库中,然后将其添加到列表中,然后列表又添加到列表视图中。但我有一个问题,那就是它从不检查旧值,它会向数据库添加重复的数字,有什么办法可以避免这种情况吗?这是我的尝试。
public class Incoming_call_history extends Activity {
private ListView lv;
private ArrayAdapter<String> adapter;
private ArrayList<String>list;
DataSourceCall DS;
boolean duplicated=false;
String temp="";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_incoming_call_history);
DS= new DataSourceCall(this);
DS.open();
lv=(ListView)findViewById(R.id.callHistory);
registerForContextMenu(lv);
list=(ArrayList<String>) DS.getAllCalls();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
@SuppressWarnings("deprecation")
Cursor mCursor = managedQuery(CallLog.Calls.CONTENT_URI, null, null,
null, null);
int number = mCursor.getColumnIndex(CallLog.Calls.NUMBER);
int date = mCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = mCursor.getColumnIndex(CallLog.Calls.DURATION);
int type = mCursor.getColumnIndex(CallLog.Calls.TYPE);
while (mCursor.moveToNext()) {
String num = mCursor.getString(number);
String dur = mCursor.getString(duration);
String datee = mCursor.getString(date);
String calltype = mCursor.getString(type);
Date d = new Date(Long.valueOf(datee));
String callTypeStr = "";
switch (Integer.parseInt(calltype)) {
case CallLog.Calls.MISSED_TYPE:
callTypeStr = "Missed";
break;
case CallLog.Calls.OUTGOING_TYPE:
callTypeStr = "Outgoing";
break;
case CallLog.Calls.INCOMING_TYPE:
callTypeStr = "Incoming";
break;
}
boolean found = false;
for (int ndx = 0; ndx < list.size(); ndx++)
{
if (num.equals(list.contains(num)))
{
found = true;
DS.deleteCall(num);
adapter.notifyDataSetChanged();
break;
}
}
if (!found)
{
DS.createCall(num);
temp=num;
Log.d("added succesfuly ", num);
}
// list.add("Phone number: "+num+"\n"+"Duration: " + dur+"\n"+"Type: " + callTypeStr+"\n"+"Call date: " + d+"\n");
}
mCursor.close();
adapter.notifyDataSetChanged();
}}
答案 0 :(得分:1)
如果您不想在表格中插入已插入的手机号码,请检查手机号码是否已插入
public int isUserAvailable(int number)
{
int numberCount = 0;
Cursor c = null;
try
{
c = db.rawQuery("select p_number from user_table where p_number = ?", new String[] {String.valueOf(number)});
if(c.getCount() != 0)
numberCount = c.getCount();
}
catch(Exception e) {
e.printStackTrace();
} finally {
if(c!=null) c.close();
}
return numberCount ;
}
如果不符合您的要求,请告诉我,我会尝试提供其他解决方案。