简体   繁体   中英

how to get data from android database into an arraylist

I'm very new at android programming and this is my first question on stack overflow ever. I am having trouble understanding where i have gone wrong in my code implementation. I'm trying to store data in a database and then extract it into an arraylist.

This is the class where i add data into the database in the button onclicklistener:

public class KarmaDescription extends AppCompatActivity {

Button button;
TasksDBHandler dbHandler;
int tId = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_karma_desc2min);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle("Overview");

    button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MyTasksGS myTask = new MyTasksGS(tId, "New Task Title", 2);
            dbHandler.addTask(myTask);
            Toast.makeText(KarmaDescription.this, "Task Added", Toast.LENGTH_SHORT).show();
        }
    });

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    if (id == android.R.id.home) {
        onBackPressed();
    }

    return super.onOptionsItemSelected(item);
}

}

This is the class which manages the database:

public class TasksDBHandler extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "tasks.db";
public static final String TABLE_TASKS = "tasks";
public static final String COLUMN_ID = "id";
public static final String COLUMN_TASKNAME = "taskname";
public static final String COLUMN_DAYSLEFT = "daysleft";

public TasksDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {

    String query = "CREATE TABLE " + TABLE_TASKS + "(" +
            COLUMN_ID + " INTEGER PRIMARY KEY," +
            COLUMN_TASKNAME + " TEXT," +
            COLUMN_DAYSLEFT + " INTEGER" +
            ")";
    db.execSQL(query);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    db.execSQL("DROP TABLE IF EXISTS " + TABLE_TASKS);
    onCreate(db);
}

//Add a new row to the database
public void addTask(MyTasksGS myTask) {

    ContentValues values = new ContentValues();
    values.put(COLUMN_ID, myTask.getId());
    values.put(COLUMN_TASKNAME, myTask.getTitle());
    values.put(COLUMN_DAYSLEFT, myTask.getDaysRemaining());
    SQLiteDatabase db = getWritableDatabase();
    db.insert(TABLE_TASKS, null, values);
    db.close();
}


//Delete row from the database
public void deleteTask(String taskID) {

    SQLiteDatabase db = getWritableDatabase();
    db.execSQL("DELETE FROM " + TABLE_TASKS + " WHERE " + COLUMN_ID + "=\"" + taskID + "\";");
}


//To put data into an arraylist
public List<MyTasksGS> getDataFromDB()
{
    int id, daysRemaining;
    String title;

    List<MyTasksGS> tasksList = new ArrayList<MyTasksGS>();
    String query = "SELECT * FROM " + TABLE_TASKS;

    SQLiteDatabase db = getReadableDatabase();
    Cursor cursor = db.rawQuery(query, null);

    cursor.moveToFirst();
    while (cursor.moveToNext())
    {
        id = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_ID));
        title = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_TASKNAME));
        daysRemaining = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_DAYSLEFT));
        MyTasksGS myTask = new MyTasksGS(id, title, daysRemaining);
        tasksList.add(myTask);
    }

    return tasksList;
}

}

I'm trying to copy the arraylist data which is returned from the above class(using getDataFromDB function) into myTaskList here and im getting this error:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.example.prateek.karma.TasksDBHandler.getDataFromDB()' on a null object reference

public class MyTasksFragment extends Fragment {

Button taskComplete;
RecyclerView RVMyTasks;
static MyTasksAdapter mtAdapter;
List<MyTasksGS> myTaskList = new ArrayList<>();
TasksDBHandler dbHandler;


public MyTasksFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_my_tasks, container, false);

    taskComplete = (Button) view.findViewById(R.id.taskComplete);

    RVMyTasks = (RecyclerView) view.findViewById(R.id.RVMyTasks);
    mtAdapter = new MyTasksAdapter(myTaskList);
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
    RVMyTasks.setLayoutManager(mLayoutManager);
    RVMyTasks.setItemAnimator(new DefaultItemAnimator());
    RVMyTasks.setAdapter(mtAdapter);

    myTaskList = dbHandler.getDataFromDB();
    mtAdapter.notifyDataSetChanged();

    return view;
}

}

And this is the MyTasksGS class:

public class MyTasksGS {
String title;
int daysRemaining;
int id;

public MyTasksGS() {

}

public MyTasksGS(int id, String title, int daysRemaining) {
    this.title = title;
    this.daysRemaining = daysRemaining;
    this.id = id;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public int getDaysRemaining() {
    return daysRemaining;
}

public void setDaysRemaining(int daysRemaining) {
    this.daysRemaining = daysRemaining;
}

}

I may have made a very silly mistake somewhere but im not able to find it. Any help is appreciated

You need to instantiate the dbHandler, you are trying to use it without a valid instance. It causes the NullPointerException.

In your on onCreateView before myTaskList = dbHandler.getDataFromDB();

add : dbHandler = new TasksDBHandler(getActivity());

use your class property DATABASE_NAME and DATABASE_VERSION instead of pass in constructor.

Change your TaskDBHandler constructor like this

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

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