简体   繁体   English

Android从数据库获取数据到编辑文本视图时出现问题

[英]Android trouble in getting data from Database to Edit Text View

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. 我从数据库调用getMsg()方法来显示文本。 Please have look on my code... 请查看我的代码......

MainActivity.java 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 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) ;

    }

    } 

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. 我建议你必须使用SharedPreferences而不是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
   -------------------------------------
            }
        });

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);

    }

You are using SQLiteDatabase db = this.getReadableDatabase(); 您正在使用SQLiteDatabase db = this.getReadableDatabase(); in updateMSg 在updateMSg中

You should use SQLiteDatabase db = this.getWritableDatabase(); 你应该使用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 正如您在短语中所使用的那样:其中“+ 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 如果数据库为空,则调用insertContact on button,如果不为空,则调用updateMsg

you can find out your database is empty or not by calling getAllContact function and checking the size of returned arrayItem. 你可以通过调用getAllContact函数并检查返回的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); call insertContact(conItems); if database empty, else updateMsg(message.gettext()); 如果数据库为空,则为updateMsg(message.gettext());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM