Android onResume崩溃
问题描述:
我做了一个应用程序,它使用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();
}
}
}
答
您正试图访问已关闭的游标。 1)尝试在onDestroy和onPause中关闭该游标,这是正确的方法。 2)并尝试在onResume中打开它。