I'm making small to-do app, and I got stuck.
The idea is:
Save the data into the DB -> Retrieve it in a ListView.
At the moment, my app crashes right after I press the "BUILD!" Button, even though I think it should just say "SAVED!" (To make sure the data is saved into the db).
Some hints on how to display that data in ListView would be much appreciated.
P.S.: It's my first app, so don't be harsh
Code:
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
}