0

Like if I type some text on Edit Text View and press save button, the data is getting saved to database. Now I want, when I restarts the emulator, the saved text will remain there on the Edit Text View. I am calling getMsg() method from database for displaying the text. Please have look on my code...

MainActivity.java

public class MainActivity extends Activity implements LocationListener {
    String separator = "; ";
    private Button btn_cntct;
    private EditText message;
    LinearLayout linearLayoutSec;
    private Button GPSState;
    Button b_alert;
    Button b_save_message;
    public int REQUESTCODE = 1;
    int temp;
    ScrollView ScrView;
    Context c = MainActivity.this;
    Button AlertMessages;
    private static ArrayList<ContactItems> selectedContactList = new ArrayList<ContactItems>();
    static CustomAdapter adapter;
    public static String[] myvalue = new String[1];
    Spinner spinner;
    static String[] alert = { " ", "I am in danger", "Help Me", "Watch Out",
            "Look For Me", "Cover ME" };
    MySQLiteHelper dbHelper;
    String savedMessage;
    Button bsave;

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

                message = (EditText) findViewById(R.id.et_message);
        dbHelper = new MySQLiteHelper(this);
        String dis = dbHelper.getMsg();
        if (dis != null) {
            message.setText(dis);
        }

        bsave = (Button) findViewById(R.id.b_save);
        bsave.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String str = message.getText().toString();
                dbHelper.updateMsg(str);

            }
        });

MySQLiteHelper.java

public class MySQLiteHelper extends SQLiteOpenHelper {

      public static final String TABLE_NAME = "userdetails";
      public static final String TABLE_NAME_MSG = "usermessage";
      public static final String COLUMN_ID = "_id";
      public static final String COLUMN_NUMBER = "NUMBER";
      public static final String COLUMN_NAME = "name";
      public static final String COLUMN_TYPE = "type";
      public static final String COLUMN_ID_MSG = "_id";
      public static final String COLUMN_MSG = "message";
      private static final String DATABASE_NAME = "userInformation.db";

      private static final int DATABASE_VERSION = 1;
      private static final String LOG = "DatabaseHelper";

      // Database creation sql statement
      private static final String DATABASE_CREATE_TABLE_CONTACTS = "create table "
          + TABLE_NAME + "(" + COLUMN_ID
          + " integer primary key autoincrement, " + COLUMN_NAME
          + " text not null,"+COLUMN_NUMBER+"  text not null,"+COLUMN_TYPE+" text not null);";
      private static final String DATABASE_CREATE_TABLE_MSG = "create table "
              + TABLE_NAME_MSG + "(" + COLUMN_ID_MSG
              + " integer primary key autoincrement, " + COLUMN_MSG    + " text not null);";
      private static final String DATABASE_INSERT_MSG = "insert into  "
              + TABLE_NAME_MSG + "(" + COLUMN_MSG+") VALUES('enter your message');";


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

      @Override
      public void onCreate(SQLiteDatabase database) {
        database.execSQL(DATABASE_CREATE_TABLE_CONTACTS);
        database.execSQL(DATABASE_CREATE_TABLE_MSG);
        database.execSQL(DATABASE_INSERT_MSG);

      }

      @Override
      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(MySQLiteHelper.class.getName(),
            "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
      }

      public long insertContact(ContactItems contItem) {
            SQLiteDatabase db = this.getWritableDatabase();

            ContentValues values = new ContentValues();
            values.put(COLUMN_NAME, contItem.getName());
            values.put(COLUMN_NUMBER, contItem.getNumber());
            values.put(COLUMN_TYPE, contItem.getType());

            // insert row
            long result = db.insert(TABLE_NAME, null, values);

            // assigning tags to todo
            /*for (long tag_id : tag_ids) {
                createTodoTag(todo_id, tag_id);
            }*/

            return result;
        }


      public ArrayList<ContactItems> getAllContacts() {
          ArrayList<ContactItems> contactList = new ArrayList<ContactItems>();
            String selectQuery = "SELECT  * FROM " + TABLE_NAME;

            Log.e(LOG, selectQuery);

            SQLiteDatabase db = this.getReadableDatabase();
            Cursor c = db.rawQuery(selectQuery, null);

            // looping through all rows and adding to list
            if (c.moveToFirst()) {
                do {
                    ContactItems conItems = new ContactItems();
                    conItems.setName(c.getString((c.getColumnIndex(COLUMN_NAME))));
                    conItems.setNumber((c.getString(c.getColumnIndex(COLUMN_NUMBER))));
                    conItems.setType(Integer.parseInt(c.getString(c.getColumnIndex(COLUMN_TYPE))));

                    // adding to todo list
                    contactList.add(conItems);
                } while (c.moveToNext());
            }

            return contactList;
        }

    public void updateMsg(String msg) {
        // TODO Auto-generated method stub
        // String selectQuery = "update  " + TABLE_NAME_MSG+" set "+COLUMN_MSG+" = '"+msg+"' where "+COLUMN_ID_MSG+" = 1";
          ContentValues values = new ContentValues();
            values.put(COLUMN_MSG, msg);
          SQLiteDatabase db = this.getReadableDatabase();
         db.update(TABLE_NAME_MSG, values, null, null);

    }
    public String getMsg() {
        String message ="";
          String selectQuery = "SELECT  * FROM " + TABLE_NAME_MSG;

          SQLiteDatabase db = this.getReadableDatabase();
            Cursor c = db.rawQuery(selectQuery, null);
            if (c.moveToFirst()) {
                do {
                    message = c.getString(c.getColumnIndex(COLUMN_MSG));
                } while (c.moveToNext());
            }

        // TODO Auto-generated method stub
            Log.e(LOG, "message = "+message);
        return message;

    }

    public int removeData(String number) {
        // TODO Auto-generated method stub

          SQLiteDatabase db = this.getReadableDatabase();
           //db.drawQuery(deleteQuery, null);
          return db.delete(TABLE_NAME, COLUMN_NUMBER + "='" + number+"'", null) ;

    }

    } 
bhanu kaushik
  • 391
  • 1
  • 7
  • 30

3 Answers3

1

I think your query create new table everytime...

just change your query

private static final String DATABASE_CREATE_TABLE_CONTACTS = "create table if not exist "
          + TABLE_NAME + "(" + COLUMN_ID
          + " integer primary key autoincrement, " + COLUMN_NAME
          + " text not null,"+COLUMN_NUMBER+"  text not null,"+COLUMN_TYPE+" text not null);";
      private static final String DATABASE_CREATE_TABLE_MSG = "create table if not exist "
              + TABLE_NAME_MSG + "(" + COLUMN_ID_MSG
              + " integer primary key autoincrement, " + COLUMN_MSG    + " text not null);";

I suggest you that you have to use SharedPreferences instead of Database.

Check below code..

public class MainActivity extends Activity implements LocationListener {
    String separator = "; ";
    private Button btn_cntct;
    private EditText message;
    LinearLayout linearLayoutSec;
    private Button GPSState;
    Button b_alert;
    Button b_save_message;
    public int REQUESTCODE = 1;
    int temp;
    ScrollView ScrView;
    Context c = MainActivity.this;
    Button AlertMessages;
    private static ArrayList<ContactItems> selectedContactList = new ArrayList<ContactItems>();
    static CustomAdapter adapter;
    public static String[] myvalue = new String[1];
    Spinner spinner;
    static String[] alert = { " ", "I am in danger", "Help Me", "Watch Out",
            "Look For Me", "Cover ME" };
    MySQLiteHelper dbHelper;
    String savedMessage;
    Button bsave;

   -------------------------------------
   SharedPreferences sp; // edited
   -------------------------------------

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

         message = (EditText) findViewById(R.id.et_message);
   -------------------------------------
       sp=getSharedPreferences("user_data", Activity.MODE_PRIVATE); //Edited
       String saved_value=sp.getString("share_key","");
       message.setText(saved_value);
   -------------------------------------
        dbHelper = new MySQLiteHelper(this);
        //String dis = dbHelper.getMsg();
        //if (dis != null) {
        //    message.setText(dis);
       // }

        bsave = (Button) findViewById(R.id.b_save);
        bsave.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String str = message.getText().toString();
                //dbHelper.updateMsg(str);
   -------------------------------------
              sp.edit().putString("str", str1).commit(); /Edited
   -------------------------------------
            }
        });
Niranj Patel
  • 32,980
  • 10
  • 97
  • 133
  • actually, i was using SharedPreference only before the database. But my boss ordered me to use database. :( and i am having hard time in displaying the text on the edit text view on emulator restart – bhanu kaushik Feb 21 '14 at 06:46
  • @bhanukaushik first check your query successfully insert data or not? – Niranj Patel Feb 21 '14 at 07:18
  • @bhanukaushik check this [question](http://stackoverflow.com/questions/14142908/insert-or-update-in-sqlite-and-android-using-the-database-query) – Niranj Patel Feb 21 '14 at 07:21
1

Do not use "update". Use "Insert". Update will only change the already-existed-data in your database, but would not save the data.

    bsave.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String str = message.getText().toString();
            dbHelper.updateMsg(str);

        }
    });

    public void updateMsg(String msg) {
        // TODO Auto-generated method stub
        // String selectQuery = "update  " + TABLE_NAME_MSG+" set "+COLUMN_MSG+" = '"+msg+"' where "+COLUMN_ID_MSG+" = 1";
        ContentValues values = new ContentValues();
            values.put(COLUMN_MSG, msg);
        SQLiteDatabase db = this.getReadableDatabase();
        db.update(TABLE_NAME_MSG, values, null, null);

    }
Ethan J
  • 281
  • 1
  • 9
  • 2
    "dbHelper.updateMsg(str)"; ---That will only change the already-existed-data in your database, but would not save the data. – Ethan J Feb 21 '14 at 06:53
0

You are using SQLiteDatabase db = this.getReadableDatabase(); in updateMSg

You should use SQLiteDatabase db = this.getWritableDatabase(); As u are performing write operation on database.

update operation will be performed only when the there will be atleast one row in database. as you are using where phrase as : where "+COLUMN_ID_MSG+" = 1

So row is never inserted in database and you are getting blank in edit text every time.

call insertContact on button click if database is empty and if not empty then call updateMsg

you can find out your database is empty or not by calling getAllContact function and checking the size of returned arrayItem.

ContactItems conItems = new ContactItems();
conItems.setName(message.getText());
conItems.setNumber(1);
conItems.setType(1);   // I don't know what is this purpose for

call insertContact(conItems); if database empty, else updateMsg(message.gettext());

Hemant Patel
  • 3,160
  • 1
  • 20
  • 29