从另一个活动导航后,MainActivity不恢复

时间:2019-03-02 12:15:47

标签: android

我有以下2个活动:

  1. MainActivity
  2. TempActivity

临时活动

public class TempActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_temp);
    }
}

MainActivity 中,我有以下代码:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    TextView textView = (TextView) findViewById(R.id.textView);
    textView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

                List<Sms> lst = getAllSms();
                Intent iti=new Intent(getBaseContext(),TempActivity.class);
                startActivity(iti);

            }


        }
    });
}


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;
}

因此,在单击按钮(textView)时,我正在从设备读取短信,完成后,我将启动TempActivity。这项工作正常,并启动了活动。但是当我在TempActivity中按下后退按钮时,应用程序崩溃,并且出现以下错误:

Unable to resume activity {com.myProject/com.myProject.MainActivity}: android.database.StaleDataException: Attempted to access a cursor after it has been closed.

2 个答案:

答案 0 :(得分:2)

尝试删除此行

this.startManagingCursor(c)

此方法在API级别11中已弃用,我认为问题是此行,您根本不需要此函数。这种方法尝试管理您的游标,但它不知道生命周期和崩溃的发生

最好不要使用FLAG_ACTIVITY_CLEAR_TOPBaseContext

代替此用途

Intent iti=new Intent(MainActivity.this,TempActivity.class);
iti.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

答案 1 :(得分:0)

在关闭光标后尝试将其设置为null。

c.close();
c=null;