我正在制作小型待办事项应用程序,但我遇到了问题 这个想法是:
将数据保存到数据库中 - >在ListView中检索它。
此刻,我的应用程序在按下“BUILD”后立即崩溃按钮,即使我认为它应该只是说“保存!” (确保将数据保存到数据库中) 关于如何在ListView中显示数据的一些提示将非常受欢迎。
P.S。:这是我的第一个应用,所以不要苛刻
代码:
Mainactivity
package com.example.mrti.todo2;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
TaskDbHelper taskDbHelper;
SQLiteDatabase SQLdb;
ArrayAdapter<String> itemsAdapter;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lvItems = (ListView) findViewById(R.id.listView);
ArrayList<String> items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items);
lvItems.setAdapter(itemsAdapter);
}
// ADDING YOUR FUTURE GOALS!
public void onBuildButton (View view){
EditText dreamText = (EditText) findViewById(R.id.dreamText);
String task = dreamText.getText().toString();
//db
taskDbHelper = new TaskDbHelper(context);
SQLdb = taskDbHelper.getWritableDatabase();
taskDbHelper.insertData(task, SQLdb);
Toast.makeText(getBaseContext(), "Saved!", Toast.LENGTH_LONG).show();
taskDbHelper.close();
}
}
TaskDBHelper.java
public class TaskDbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "TASKS.db";
private static final int DB_VERSION = 1;
private static final String CREATE_QUERY =
"CREATE TABLE " + TaskContract.newTaskInfo.TABLE_NAME + " ( " +
TaskContract.newTaskInfo.TASK_NAME + " TEXT NOT NULL);";
public TaskDbHelper(Context context) {
super(context, DATABASE_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
Log.e("DB Operations", "Table created...");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TaskContract.newTaskInfo.TABLE_NAME);
onCreate(db);
}
// For adding new data to database
public void insertData(String task, SQLiteDatabase db){
ContentValues contentValues = new ContentValues();
contentValues.put(TaskContract.newTaskInfo.TASK_NAME, task);
db.insert(TaskContract.newTaskInfo.TABLE_NAME, null, contentValues);
Log.e("DB Operations", "1 record added...");
}
}
TaskContract.java
public class TaskContract {
public static abstract class newTaskInfo{
public static final String TASK_NAME = "task_name"; // Table field
public static final String TABLE_NAME = "task_info"; // Name of the table
}
答案 0 :(得分:0)
您的context
变量为null且不必要。
活动是上下文,所以请改用
taskDbHelper = new TaskDbHelper(MainActivity.this);