Как определить причину остановки приложения - PullRequest
0 голосов
/ 23 марта 2019

Мое приложение компилируется без проблем, кроме предупреждения об устаревании курсора, оно развертывается и работает правильно, но останавливается через несколько минут и запрашивает «снова открыть приложение?». Он открывается снова правильно.

Ниже приведен отчет о сбое, но я не знаю, как его интерпретировать. Приложение представляет собой простую базу данных, которая показывает свойства стального профиля. Любые предложения о том, с чего начать искать с благодарностью.

Код всех 3 видов деятельности здесь http://silverfernsolutions.com/Code_for_stackoverflow_55308480.txt

Мин. Код версии указан ниже. Я могу проверить это только на Studio AVD, открыв экран DisplaySectionProperties, а затем выключив и включив эмулятор. Дисплей возвращается к экрану ShowSelectedSource при включении и иногда вызывает сообщение об ошибке.

ОБНОВЛЕНО ОБНОВЛЕНО Проблема исчезает, когда строки

    c.close();
    mDbHelper.close(); 

в DisplaySectionProperties onCreate () удалены. Это подразумевает, что это проблема способа использования БД, и это другой вопрос.

  a java.lang.RuntimeException: 
  at android.app.ActivityThread.performResumeActivity (ActivityThread.java:3790)
  at android.app.ActivityThread.handleResumeActivity (ActivityThread.java:3830)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1746)
  at android.os.Handler.dispatchMessage (Handler.java:105)
  at android.os.Looper.loop (Looper.java:164)
  at android.app.ActivityThread.main (ActivityThread.java:6944)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.Zygote$MethodAndArgsCaller.run (Zygote.java:327)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1374)
Caused by: java.lang.IllegalStateException: 
  at android.app.Activity.performRestart (Activity.java:7322)
  at android.app.Activity.performResume (Activity.java:7353)
  at android.app.ActivityThread.performResumeActivity (ActivityThread.java:3765)

код

public class MainActivity extends AppCompatActivity{

String DB_NAME = "SteelSectionProperties";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    toolbar.setNavigationIcon(R.drawable.icon);
    setSupportActionBar(toolbar);
    // Display icon in the toolbar
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setDisplayUseLogoEnabled(true);

    deleteDatabase(DB_NAME);  //7Aug2011. Reload each time to pick up any upgrades

    DataBaseHelperReign myDbHelper;// = new DataBaseHelperReign(this);
    myDbHelper = new DataBaseHelperReign(this);

    try {
        myDbHelper.createDataBase();
    } catch (IOException ioe) {
        //Toast.makeText(MainActivity.this, "Unable to create DB", Toast.LENGTH_LONG).show();
        throw new Error("Unable to create database");
    }

    try {
        myDbHelper.openDataBase();
    } catch (SQLException sqle) {
        //Toast.makeText(MainActivity.this, "Unable to open DB", Toast.LENGTH_LONG).show();
        throw sqle;
    }
    myDbHelper.close();

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    String units = prefs.getString("displayunitskey", "1");
    if (units == "1") {
        //first use. Set mm as initial default setting
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("displayunitskey", "mm");
        editor.commit();
    }
}//end oncreate


public void onClick(View v) {
    // Perform action on click
    int Idx = 0;
    int id = v.getId();
    switch (id) {
        case R.id.btn0: Idx = 0; break;
        case R.id.btn1: Idx = 1; break;
        case R.id.btn2: Idx = 2; break;
        case R.id.btn3: Idx = 3; break;
        case R.id.btn4: Idx = 4; break;
        case R.id.btn5: Idx = 5; break;
        case R.id.btn6: Idx = 6; break;
        case R.id.btn7: Idx = 7; break;
    } //end switch
    runIntents(Idx);
}//end onClick

/**/
private void runIntents(int idx) {
    if (idx == 0) {
        //Intent i = new Intent(this, UserSectionInput.class);
        //startActivity(i);
    } else {
        Intent i = new Intent(this, ShowSelectedSource.class);
        i.putExtra("ButtonID", idx);
        startActivity(i);
    } //endif
}//end runintents
}



 public class ShowSelectedSource extends ListActivity{
    long mSelSectionID;
    String mSource, mSourceFile;
    String mTable;
    private SectionsDbAdapter mDbHelper;
    private SectionsUserDbAdapter mDbUserHelper;
    private int BtnId;
    TextView tv_section, lblListSection;
    ImageView imgListSection;
    ImageView imgIcon;
    Button btn6;  //Tee shape
    String mSorting ="DESC";  //ASC or DESC (default)
    String mShape="A";         //default

       @Override
       public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_selected_source);

        Bundle bundle = getIntent().getExtras();
        BtnId = bundle.getInt("ButtonID");
        lblListSection= findViewById(R.id.lblListSection);
        imgListSection= findViewById(R.id.imgListSection);
        btn6 =  findViewById(R.id.btn6);

        mDbHelper = new SectionsDbAdapter(this);
        mDbUserHelper = new SectionsUserDbAdapter(this);

        //Button clicked on opening screen
        switch (BtnId){
            case 0://custom, already gone in Main to section input screen
            case 1: mSource="CU"; mSourceFile="Saved user sections"; break; //user saved sections
            case 2: mSource="US"; mSourceFile="American   ";  break;
            case 3: mSource="AU"; mSourceFile="Australian  ";  break;
            case 4: mSource="UK"; mSourceFile="British   ";  break;
            case 5: mSource="EU"; mSourceFile="European   ";  break;
            case 6: mSource="JA"; mSourceFile="Japan   ";  break;
            case 7: mSource="TU"; mSourceFile="Tubes   ";  break;
        }//end switch

        if ( BtnId == 1){
            mTable="SectionUser";
            mDbUserHelper.open();
        }else{
            mTable="SectionProps";
            mDbHelper.open();
            btn6.setVisibility(View.GONE); //turn off Tee button
        }
        initialDisplay();

    } // end onCreate   ///////////////////////////////////////////////

    private void initialDisplay(){
        //open display
        lblListSection.setText(mSourceFile);
        Cursor c=null;
        try{
            if ( BtnId == 1){
                c = mDbUserHelper.fetchRecordsbySource(mTable, mSource);
            }else{
                c = mDbHelper.fetchRecordsbySourceReverse(mTable, mSource,mSorting);
            }
            startManagingCursor(c);
        } catch (SQLException e){
            e.printStackTrace();
        }

        String[] from = new String[] {SectionsDbAdapter.KEY_DESC };  //The column(s) that the data are from
        int[] to = new int[] { R.id.tv_full_width }; // int array containing references to the views that we'll bind the data into (the R.id.text1 TextView).

        SimpleCursorAdapter records =
                new SimpleCursorAdapter(this, R.layout.section_row_full_width, c, from, to);  //the .xml file containing the R.id.xxxx
        setListAdapter(records);
        //c.close();  don't close, it stuffs up the buttons for some reason
    }

   private void loadListView(){
        setImage();
        Cursor c=null;
        try{
            if (mShape.equals("A")){
                if ( BtnId == 1){
                    c = mDbUserHelper.fetchRecordsbySourceReverse(mTable, mSource,mSorting);
                }else{
                    c = mDbHelper.fetchRecordsbySourceReverse(mTable, mSource, mSorting);
                }
            }else{
                if ( BtnId == 1){
                    c = mDbUserHelper.fetchRecordsbySourceShapeReverse(mTable, mSource, mShape, mSorting);
                }else{
                    c = mDbHelper.fetchRecordsbySourceShapeReverse(mTable, mSource, mShape, mSorting);
                }
            }
            startManagingCursor(c);

            String[] from = new String[] {SectionsDbAdapter.KEY_DESC };  //The column(s) that the data are from
            int[] to = new int[] { R.id.tv_full_width }; // int array containing references to the views that we'll bind the data into (the R.id.text1 TextView).

            SimpleCursorAdapter records =
                    new SimpleCursorAdapter(this, R.layout.section_row_full_width, c, from, to);  //the .xml file containing the R.id.xxxx
            setListAdapter(records);
            //c.close();  don't close, it stuffs up the buttons for some reason

        } catch (SQLException e){
            e.printStackTrace();
        }

    }//end loadview

    //get button clicks for filtering
    public void onButtonClick(View v) {

        switch ( v.getId()) {
            case R.id.btn0: mShape="A" ;break; //all
            case R.id.btn1: mShape="I";break;
            case R.id.btn2: mShape="["; break;
            case R.id.btn3: mShape="[]"; break;
            case R.id.btn4: mShape="O";break;
            case R.id.btn5: mShape="L";break;
            case R.id.btn6: mShape="T";break;
            case R.id.btnsort:
                if (mSorting.equals("DESC")){
                    mSorting="ASC";
                } else {
                    mSorting="DESC";
                }
                break;
        } //end switch

        loadListView();
    }//end onClick buttons

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id); // Get the item that was clicked
        v.setBackgroundColor(Color.rgb(127, 255, 0));

        // next screen to display properties
        Intent i = new Intent(this, DisplaySectionProperties.class);
        i.putExtra("ButtonID",BtnId);
        i.putExtra("Table",mTable);
        i.putExtra("TablerowID", id);
        Log.e("in select, Tablerow", " id = " +id);
        startActivity(i);

    }// end onclick listview
}  //end class


    public class DisplaySectionProperties extends AppCompatActivity {

private String mTable;
private long mTablerowID;
private int mBtnId;

private String mShape;
private String mDescription;
private double mDepth, mtw,mb1, mt1, mb2, mt2;
private String mDisplayUnits; // the units the user wants displayed
private String mSectionUnits; //the units that mS is currently using
private TextView txtDescription;
private ImageView imgShape;

//The section object
private cSectionProperties mS;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_section_properties);
    Toolbar toolbar = findViewById(R.id.toolbar);
    toolbar.setNavigationIcon(R.drawable.icon);
    setSupportActionBar(toolbar);

    mS= new cSectionProperties();

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences (this);
    mDisplayUnits=prefs.getString("displayunitskey","1");

    txtDescription= findViewById(R.id.lblDisplaySection);
    imgShape= findViewById(R.id.imgDisplaySection);


    Bundle bundle = getIntent().getExtras();
    mBtnId = bundle != null ? bundle.getInt("ButtonID") : 0;
    mTable = bundle != null ? bundle.getString("Table") : null;
    mTablerowID= bundle.getLong("TablerowID");
    Toast.makeText(this, "Disp Sect TablerowID := " + mTablerowID, Toast.LENGTH_LONG) .show();

    if (mTablerowID == 0){
        //user input section
        mDescription=bundle.getString("Description");
        mDepth=bundle.getDouble("Depth");
        mtw=bundle.getDouble("tw");
        mb1=bundle.getDouble("B1");
        mt1=bundle.getDouble("T1");
        mb2=bundle.getDouble("B2");
        mt2=bundle.getDouble("T2");
        mShape=bundle.getString("Shape");
        mSectionUnits=bundle.getString("Units");
        //createUserSection();

    }else{

        Cursor c;
        try{

            if(mTable.equals("SectionUser") ){
                SectionsUserDbAdapter mDbHelper = new SectionsUserDbAdapter(this);
                mDbHelper.open();
                c = mDbHelper.fetchRecordbyID(mTable, mTablerowID+""); //convert int to string (v= v + "")= int V is now string
                startManagingCursor(c);
                mDescription= c.getString(c.getColumnIndex("Description"));
                mDepth= c.getDouble(c.getColumnIndex("Depth"));
                mtw = c.getDouble(c.getColumnIndex("tweb_wall"));
                mb1= c.getDouble(c.getColumnIndex("Bf1"));
                mt1= c.getDouble(c.getColumnIndex("Tf1"));
                mb2= c.getDouble(c.getColumnIndex("Bf2"));
                mt2= c.getDouble(c.getColumnIndex("Tf2"));
                mShape= c.getString(c.getColumnIndex("Shape"));
                mSectionUnits= c.getString(c.getColumnIndex("Units"));
                c.close();
                mDbHelper.close();

                //createUserSection();

            }else{
                // section from the standard DB, mSectionUnits will be mm
                SectionsDbAdapter mDbHelper = new SectionsDbAdapter(this);
                mDbHelper.open();
                c = mDbHelper.fetchRecordbyID(mTable, mTablerowID+""); //convert int to string (v= v + "")= int V is now string
                startManagingCursor(c);
                mDbHelper.close();
               // createSection(c);
                c.close();
            }
        } catch (SQLException e){
            e.printStackTrace();
        }
    }//endif

   // displayProperties();


} //end oncreate
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...