简体   繁体   中英

Unfortunately, Organitza't (my app) has stopped

I am getting error message when I start another activity named Task. The application have 4 image buttons (the other buttons image open correctly. When I click "TaskViewer"(ImageButton2) appears the error.

The activity that attempts to open: (ViewTask)

public class ViewTask extends Activity {
protected TaskerDbHelper db;
List<Task> list;
MyAdapter adapt;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_task);
    db = new TaskerDbHelper(this);
    list = db.getAllTasks();
    adapt = new MyAdapter(this, R.layout.list_inner_view, list);
    ListView listTask = (ListView) findViewById(R.id.listView1);
    listTask.setAdapter(adapt);
}

public void addTaskNow(View v) {
    EditText t = (EditText) findViewById(R.id.editText1);
    String s = t.getText().toString();
    if (s.equalsIgnoreCase("")) {
        Toast.makeText(this, "enter the task description first!!",
                Toast.LENGTH_LONG);
    } else {
        Task task = new Task(s, 0);
        db.addTask(task);
        Log.d("tasker", "data added");
        t.setText("");
        adapt.add(task);
        adapt.notifyDataSetChanged();
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_view_task, menu);
    return true;
}

private class MyAdapter extends ArrayAdapter<Task> {

    Context context;
    List<Task> taskList = new ArrayList<Task>();
    int layoutResourceId;

    public MyAdapter(Context context, int layoutResourceId,
            List<Task> objects) {
        super(context, layoutResourceId, objects);
        this.layoutResourceId = layoutResourceId;
        this.taskList = objects;
        this.context = context;
    }

    /**
     * This method will DEFINe what the view inside the list view will
     * finally look like Here we are going to code that the checkbox state
     * is the status of task and check box text is the task name
     */
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        CheckBox chk = null;
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.list_inner_view,
                    parent, false);
            chk = (CheckBox) convertView.findViewById(R.id.chkStatus);
            convertView.setTag(chk);

            chk.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    CheckBox cb = (CheckBox) v;
                    Task changeTask = (Task) cb.getTag();
                    changeTask.setStatus(cb.isChecked() == true ? 1 : 0);
                    db.updateTask(changeTask);
                    Toast.makeText(
                            getApplicationContext(),
                            "Clicked on Checkbox: " + cb.getText() + " is "
                                    + cb.isChecked(), Toast.LENGTH_LONG)
                            .show();
                }

            });
        } else {
            chk = (CheckBox) convertView.getTag();
        }
        Task current = taskList.get(position);
        chk.setText(current.getTaskName());
        chk.setChecked(current.getStatus() == 1 ? true : false);
        chk.setTag(current);
        Log.d("listener", String.valueOf(current.getId()));
        return convertView;
    }

}
}

The main activity:

public class MainActivity extends Activity {

private Context activity;

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

private void entrarboton() {
    ImageButton accionentrar = (ImageButton) findViewById(R.id.imageButton0);
    accionentrar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.android.calendar");
            startActivity(LaunchIntent);


        }
    });
    ImageButton accionentrar2 = (ImageButton) findViewById(R.id.imageButton3);
    accionentrar2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(MainActivity.this,Notes.class));

        }
    });
    ImageButton accionentrar3 = (ImageButton) findViewById(R.id.imageButton2);
    accionentrar3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(MainActivity.this,ViewTask.class));
        }
    });
    ImageButton accionentrar4 = (ImageButton) findViewById(R.id.imageButton4);
    accionentrar4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(MainActivity.this,Altres.class));
        }
    });

    AutoCompleteTextView auto = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);

    String[] noms = getResources() . getStringArray(R.array.noms_array);

    ArrayAdapter<String> adapter;
    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, noms);

    auto.setThreshold(1);

    auto.setAdapter(adapter);


}

}

Android Manifest:

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.dppalvaplicacio.app.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="com.dppalvaplicacio.app.Calendari"
        android:label="@string/title_activity_calendari" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
    <activity
        android:name="com.dppalvaplicacio.app.Notes"
        android:label="@string/title_activity_notes" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
    <activity
        android:name="com.dppalvaplicacio.app.ViewTask"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
    <activity
        android:name="com.dppalvaplicacio.app.Altres"
        android:label="@string/title_activity_altres" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
</application>

Logcat

Caused by: java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/data/com.dppalvaplicacio.app/databases/taskerManager
at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)
at android.database.sqlite.SQLiteDatabase.endTransaction(SQLiteDatabase.java:520)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:263)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at com.dppalvaplicacio.app.TaskerDbHelper.getAllTasks(TaskerDbHelper.java:70)
at com.dppalvaplicacio.app.ViewTask.onCreate(ViewTask.java:33)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)

TaskDbHelper

public class TaskerDbHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "taskerManager";

// tasks table name
private static final String TABLE_TASKS = "tasks";

// tasks Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TASKNAME = "taskName";
private static final String KEY_STATUS = "status";

public TaskerDbHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {

    String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_TASKS + " ( "
            + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_TASKNAME
            + " TEXT, " + KEY_STATUS + " INTEGER)";
    db.execSQL(sql);

    db.close();
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_TASKS);
    // Create tables again
    onCreate(db);
}

// Adding new task
public void addTask(Task task) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_TASKNAME, task.getTaskName()); // task name
    // status of task- can be 0 for not done and 1 for done
    values.put(KEY_STATUS, task.getStatus());

    // Inserting Row
    db.insert(TABLE_TASKS, null, values);
    db.close(); // Closing database connection
}

public List<Task> getAllTasks() {
    List<Task> taskList = new ArrayList<Task>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_TASKS;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Task task = new Task();
            task.setId(cursor.getInt(0));
            task.setTaskName(cursor.getString(1));
            task.setStatus(cursor.getInt(2));
            // Adding contact to list
            taskList.add(task);
        } while (cursor.moveToNext());
    }

    // return task list
    return taskList;
}

public void updateTask(Task task) {
    // updating row
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_TASKNAME, task.getTaskName());
    values.put(KEY_STATUS, task.getStatus());
    db.update(TABLE_TASKS, values, KEY_ID + " = ?",new String[] {String.valueOf(task.getId())});
    db.close();
}

}

The problem is in your TaskDBHelper class, and more specifically the onCreate method. This method is called automatically when you try to do work on the database, but the database is not created yet. So it first calls the onCreate method and then the method, that does work on it, in your case - getAllTasks . The problem is that you are closing your db in the onCreate method, preventing any further operations on the database within this class instance. Your method should look like this:

public void onCreate(SQLiteDatabase db) {

    String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_TASKS + " ( "
            + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_TASKNAME
            + " TEXT, " + KEY_STATUS + " INTEGER)";
    db.execSQL(sql);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM