Question

I have been working on recipe from Android recipe book to utilize a database for storing events. Current code allows me to add new entries but I am unable to modify any of the added entries. What I need is a database with predefined number of rows(48) with functionality of updating these rows through corresponding edittext fields. Can anyone help me to modify the following code to achieve this please? I am new to android coding and I need to start with this database.

Here is my MyDB file:

package com.cookbook.data;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.util.Log;

public class MyDB {
    private SQLiteDatabase db;
    private final Context context;
    private final MyDBhelper dbhelper;
    // Initializes MyDBHelper instance
    public MyDB(Context c){
        context = c;
        dbhelper = new MyDBhelper(context, Constants.DATABASE_NAME, null,
                                            Constants.DATABASE_VERSION);
    }
    // Closes the database connection
    public void close()
    {
        db.close();
    }
    // Initializes a SQLiteDatabase instance using MyDBhelper
    public void open() throws SQLiteException
    {
        try {
            db = dbhelper.getWritableDatabase();
        } catch(SQLiteException ex) {
            Log.v("Open database exception caught", ex.getMessage());
            db = dbhelper.getReadableDatabase();
        }
    }
    // Saves a diary entry to the database as name-value pairs in ContentValues instance
    // then passes the data to the SQLitedatabase instance to do an insert
    public long insertdiary(String title, String content)
    {
        try{
            ContentValues newTaskValue = new ContentValues();
            newTaskValue.put(Constants.TITLE_NAME,  title);
            newTaskValue.put(Constants.CONTENT_NAME, content);
            newTaskValue.put(Constants.DATE_NAME,     java.lang.System.currentTimeMillis());            
            return db.insert(Constants.TABLE_NAME,  null, newTaskValue);
        } catch(SQLiteException ex) {
            Log.v("Insert into database exception caught",
                    ex.getMessage());
            return -1;
        }
    }


    // Reads the diary entries from database, saves them in a Cursor class and returns     it from the method
    public Cursor getdiaries()
    {
        Cursor c = db.query(Constants.TABLE_NAME, null, null,
                            null, null, null, null);
        return c;
    }

}

Here is my MyDBhelper file:

package com.cookbook.data;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


public class MyDBhelper extends SQLiteOpenHelper{


    private static final String CREATE_TABLE="create table "+
    Constants.TABLE_NAME+" ("+
    Constants.KEY_ID+" integer primary key autoincrement, "+
    Constants.TITLE_NAME+" text not null, "+
    Constants.CONTENT_NAME+" text not null, "+
    Constants.DATE_NAME+" long);";
    // database initialization
    public MyDBhelper(Context context, String name, CursorFactory factory,
                        int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.v("MyDBhelper onCreate","Creating all the tables");
        try {
            db.execSQL(CREATE_TABLE);
        } catch(SQLiteException ex) {
            Log.v("Create table exception", ex.getMessage());
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion,
                            int newVersion) {
        Log.w("TaskDBAdapter", "Upgrading from version "+oldVersion
                                +" to "+newVersion
                                +", which will destroy all     old data");
        db.execSQL("drop table if exists "+Constants.TABLE_NAME);
        onCreate(db);
    }




}

Here is my Constants file:

package com.cookbook.data;

public class Constants {
    public static final String DATABASE_NAME="datastorage";
    public static final int DATABASE_VERSION=1;
    public static final String TABLE_NAME="diaries";
    public static final String TITLE_NAME="title";
    public static final String CONTENT_NAME="content";
    public static final String DATE_NAME="recorddate";
    public static final String KEY_ID="_id";
    public static final String TABLE_ROW="row_id";
}

Here is my Diary file that creates new entries into a database:

package com.example.classorganizer;

import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.cookbook.data.MyDB;
import com.cookbook.data.MyDBhelper;
public class Diary extends Activity {
    EditText titleET1,contentET1;
    EditText titleET2,contentET2;
    Button submitBT;
    MyDB dba;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.diary);
        dba = new MyDB(this);
        dba.open();
        titleET1 = (EditText)findViewById(R.id.diary1);
        contentET1 = (EditText)findViewById(R.id.diarycontentText1);
        titleET2 = (EditText)findViewById(R.id.diary2);
        contentET2 = (EditText)findViewById(R.id.diarycontentText2);
        submitBT = (Button)findViewById(R.id.submitButton);
        submitBT.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                try {
                    saveItToDB();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


        });
    }



    public void saveItToDB() {
        dba.insertdiary(titleET1.getText().toString(),     contentET1.getText().toString());
        dba.insertdiary(titleET2.getText().toString(),     contentET2.getText().toString());
        dba.close();
        titleET1.setText("");
        contentET1.setText("");
        titleET2.setText("");
        contentET2.setText("");
        Intent i = new Intent(Diary.this, DisplayDiaries.class);
        startActivity(i);
    }
    /** Called when the user clicks the Back button */
    public void visitMonday(View view) {
        Intent intent = new Intent(this, Monday.class);
        startActivity(intent);
    }
}

And finally here is my DisplayDiaries file which returns created diaries in a listview:

package com.example.classorganizer;


import java.util.Date;
import java.text.DateFormat;
import java.util.ArrayList;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.cookbook.data.Constants;
import com.cookbook.data.MyDB;




public class DisplayDiaries extends ListActivity {
    MyDB dba;
    DiaryAdapter myAdapter;
    private class MyDiary{
        public MyDiary(String t, String c, String r){
            title=t;
            content=c;
            recorddate=r;

        }
        public String title;
        public String content;
        public String recorddate;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        dba = new MyDB(this);
        dba.open();
        setContentView(R.layout.diaries);

        super.onCreate(savedInstanceState);
        myAdapter = new DiaryAdapter(this);
        this.setListAdapter(myAdapter);
    }

    private class DiaryAdapter extends BaseAdapter {
        private LayoutInflater mInflater;
        private ArrayList<MyDiary> diaries;
        public DiaryAdapter(Context context) {
            mInflater = LayoutInflater.from(context);
            diaries = new ArrayList<MyDiary>();
            getdata();
        }

        public void getdata(){
            Cursor c = dba.getdiaries();
            startManagingCursor(c);
            if(c.moveToFirst()){
                do{
                    String title =
                            c.getString(c.getColumnIndex(Constants.TITLE_NAME));
                    String content =
                            c.getString(c.getColumnIndex(Constants.CONTENT_NAME));
                    DateFormat dateFormat =
                            DateFormat.getDateTimeInstance();
                    String datedata = dateFormat.format(new
                            Date(c.getLong(c.getColumnIndex(
                                    Constants.DATE_NAME))).getTime());
                    MyDiary temp = new MyDiary(title,content,datedata);
                    diaries.add(temp);
                } while(c.moveToNext());
            }
        }

        @Override
        public int getCount() {return diaries.size();}
        public MyDiary getItem(int i) {return diaries.get(i);}
        public long getItemId(int i) {return i;}
        public View getView(int arg0, View arg1, ViewGroup arg2) {
            final ViewHolder holder;
            View v = arg1;
            if ((v == null) || (v.getTag() == null)) {
                v = mInflater.inflate(R.layout.diaryrow, null);
                holder = new ViewHolder();
                holder.mTitle = (TextView)v.findViewById(R.id.name);
                holder.mDate = (TextView)v.findViewById(R.id.datetext);

                v.setTag(holder);
            } else {
                holder = (ViewHolder) v.getTag();
            }

            holder.mdiary = getItem(arg0);
            holder.mTitle.setText(holder.mdiary.title);
            holder.mDate.setText(holder.mdiary.recorddate);

            v.setTag(holder);

            return v;
        }

        public class ViewHolder {
            MyDiary mdiary;
            TextView mTitle;
            TextView mDate;

        }

    }
    /** Called when the user clicks the Back button */
    public void visitDiary(View view) {
        Intent intent = new Intent(this, Diary.class);
        startActivity(intent);
    }
}

As I mentioned before, this code when run allows creation new diaries and puts them in a listview. What I need is modify this code so the database has the predefined 48 rows (with default empty content) and diary file allows to modify rows through corresponding 48 edittext fields. Any help with the above will be very much appreciated. I look forward to learning from you. Cheers, Patrick

edit--------------------------------------------------------------------------------------

Since I am an absolute beginner I am still having problem with creating default 48 rows in my table and then writing code for updating each row with corresponding edittext. Maybe there is some helpful soul that could figure this out for me?

edit 2 -----------------------------------------------------------------------------------

I have updated my MyDBhelper onCreate method with your code like this:

@Override
    public void onCreate(SQLiteDatabase db) {
        Log.v("MyDBhelper onCreate","Creating all the tables");

        ContentValues cv=new ContentValues();
        cv.put(Constants.KEY_ID, 1);
        cv.put(Constants.TITLE_NAME,  "My App");
        db.insert( Constants.TABLE_NAME, null, cv);

        String Updatetable= "update" + Constants.TABLE_NAME + 
                "Set" + Constants.CONTENT_NAME + " = " + 1 + 
                "Where" +Constants.KEY_ID +" = " + R.id.diary1;

        try {
            db.execSQL(CREATE_TABLE);
        } catch(SQLiteException ex) {
            Log.v("Create table exception", ex.getMessage());
        }
    }

but upon Diary's onCreate a new row is created instead of updating the existing rows... What am I doing wrong here? I believe that I put the code in the wrong place or I missed something else...

Was it helpful?

Solution 3

I put this loop statement:

for(int i=1; i <= 48; i++) { insertdiary("", ""); } 

in my MyDBhelper file in onCreate() method as this:

@Override
public void onCreate(SQLiteDatabase db) {
    Log.v("MyDBhelper onCreate","Creating all the tables");



    try {
        db.execSQL(CREATE_TABLE);


        for(int i=1; i <= 48; i++) { insertdiary("", ""); } 
    }

    catch(SQLiteException ex) {
        Log.v("Create table exception", ex.getMessage());

    }

}

For no avail new rows are not being created. Is it due to the fact that database is already created and this code is not running upon app restart? If so, what can I do to delete database and run this code again?

EDIT--------------------------------------------------------------------------------------

I found the solution: Changing the method signature to take a SQLiteDatabase as a parameter worked.

public long insertdiary(SQLiteDatabase db, String title, String content)

together with:

for(int i=1; i <= 48; i++) { insertdiary(db, "free",""); }

placed within onCreate() method in MyDBhelper file

Problem of creating rows upon database creation solved. Now I need to find a way to populate edittext's with data from newly created rows to give a user a chance to save or change data. Any help would be appreciated.

OTHER TIPS

I am not sure how do you manuplate the 48 edit text but below example will give you an idea of writing the update query.

String Updatetable= "update " + Constants.TABLE_NAME  + "Set " + Constants.CONTENT_NAME + " = " + your value + "Where " +Constants.KEY_ID +" = " + <<May be your edit text value>> +

write the above query where you want to update the values

Edit--------------------------------------------------------------------------------------------

First thing you need to have data on what should those rows contain, Then you have multiple ways to insert data into data.

  1. Using Content Values

    ContentValues cv=new ContentValues(); cv.put(Constants.KEY_ID, 1); cv.put(Constants.TITLE_NAME, "My App"); db.insert( Constants.TABLE_NAME,null,cv);

  2. Write a query as above (Update Query) and use any of the methods rawquery, execsql

    db.rawQuery(<<your insert query>>,null)

in the same way execsql aswell

To get more info check android documention avaialable. link

This could be an example on how to update a row in your db:

 public boolean updateDiaryEntry(String title,String content, long date, long rowId){
        ContentValues newValue = new ContentValues();
        newValue.put(Constants.TITLE_NAME, title);
        newValue.put(Constants.CONTENT_NAME, content);
        newValue.put(Constants.DATE_NAME, date);
        return db.update(DATABASE_TABLE, newValue, Constants.KEY_ID + "=" + rowId, null)>0;

    }

You should put this code in your MyDB file and use it whenever you need to update the values of a specific raw in your db.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top