0
我做了一個應用程序,它使用runnable讀取特定類型的短信。 Everyhing正常工作。我收到了短信,從讀狀態移動閱讀,但它崩潰的onResume(),並給予下列錯誤:Android onResume崩潰
Unable to resume activity {com.android.testthread/com.android.testthread.MainActivity}: android.database.StaleDataException: Attempted to access a cursor after it has been closed.
如何解決這個問題?
public class MainActivity extends Activity {
boolean recieved = false;
private TextView text;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView1);
Runnable runnable = new Runnable() {
@Override
public void run() {
while (!recieved) {
doFakeWork();
text.post(new Runnable() {
@Override
public void run() {
List<Sms> list = getAllSms();
if (list.size() > 0) {
if (list.get(0).getAddress().equals("Engage") && list.get(0).getFolderName().equals("inbox") && list.get(0).getReadState().equals("0")) {
setReadMessage(list.get(0).getId());
text.setText("Got it");
Toast.makeText(MainActivity.this, list.get(0).getMsg(), Toast.LENGTH_SHORT).show();
recieved = true;
}
}
}
});
}
}
};
new Thread(runnable).start();
}
public void setReadMessage(String SmsMessageId){
ContentValues values = new ContentValues();
values.put("read",true);
getContentResolver().update(Uri.parse("content://sms/inbox"),values,
"_id="+SmsMessageId, null);
}
public List<Sms> getAllSms() {
List<Sms> lstSms = new ArrayList<Sms>();
Sms objSms = new Sms();
Uri message = Uri.parse("content://sms/");
ContentResolver cr = this.getContentResolver();
Cursor c = cr.query(message, null, null, null, null);
this.startManagingCursor(c);
int totalSMS = c.getCount();
if (c.moveToFirst()) {
for (int i = 0; i < totalSMS; i++) {
objSms = new Sms();
objSms.setId(c.getString(c.getColumnIndexOrThrow("_id")));
objSms.setAddress(c.getString(c
.getColumnIndexOrThrow("address")));
objSms.setMsg(c.getString(c.getColumnIndexOrThrow("body")));
objSms.setReadState(c.getString(c.getColumnIndex("read")));
objSms.setTime(c.getString(c.getColumnIndexOrThrow("date")));
if (c.getString(c.getColumnIndexOrThrow("type")).contains("1")) {
objSms.setFolderName("inbox");
} else {
objSms.setFolderName("sent");
}
lstSms.add(objSms);
c.moveToNext();
}
}
c.close();
return lstSms;
}
private void doFakeWork() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}