更新行而不是创建新条目数据库android

时间:2014-04-06 11:28:38

标签: android mysql sql database row

我一直在研究Android食谱书中的食谱,以利用数据库存储事件。当前代码允许我添加新条目,但我无法修改任何添加的条目。我需要的是一个具有预定义行数(48)的数据库,其功能是通过相应的edittext字段更新这些行。任何人都可以帮我修改下面的代码来实现这个目标吗?我是android编码的新手,我需要从这个数据库开始。

这是我的MyDB文件:

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

}

这是我的MyDBhelper文件:

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




}

这是我的常量文件:

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";
}

这是我的日记文件,它在数据库中创建新条目:

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

最后这是我的DisplayDiaries文件,它在列表视图中返回创建的日记:

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

正如我之前提到的,运行时此代码允许创建新日记并将它们放在listview中。我需要修改此代码,以便数据库具有预定义的48行(具有默认的空内容),日记文件允许通过相应的48个edittext字段修改行。任何有关上述的帮助将非常感谢。我期待着向你学习。干杯,帕特里克

编辑---------------------------------------------- ----------------------------------------

由于我是一个绝对的初学者,我仍然遇到在我的表中创建默认48行然后编写代码以使用相应的edittext更新每一行的问题。也许有一些有用的灵魂可以解决这个问题吗?

编辑2 --------------------------------------------- --------------------------------------

我已使用您的代码更新了我的MyDBhelper onCreate方法:

@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());
        }
    }

但是在Diary的onCreate上创建了一个新行而不是更新现有的行...我在这里做错了什么?我相信我把代码放在错误的地方或者我错过了其他的东西......

3 个答案:

答案 0 :(得分:1)

这可能是如何更新数据库中的行的示例:

 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;

    }

您应该将此代码放在MyDB文件中,并在需要更新数据库中特定原始值的值时使用它。

答案 1 :(得分:1)

我不知道你如何编写48个编辑文本,但是下面的例子将为你提供编写更新查询的想法。

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

将上述查询写在您想要更新值的位置

编辑---------------------------------------------- ----------------------------------------------

首先,你需要获得这些行包含的数据,然后你有多种方法将数据插入到数据中。

  1. 使用内容值

    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. 按上述方式撰写查询(Update Query),并使用rawqueryexecsql

    中的任何一种方法

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

  3. 以同样的方式execsql以及

    要获取更多信息,请检查android documentmention avaialable。 link

答案 2 :(得分:0)

我把这个循环语句:

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

在我的MyDBhelper文件中的onCreate()方法中:

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

    }

}

无效但未创建新行。是否由于数据库已经创建并且此代码在应用程序重启时未运行?如果是这样,我该怎么做才能删除数据库并再次运行此代码?

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

我找到了解决方案: 更改方法签名以将SQLiteDatabase作为参数工作。

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

与:

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

放在MyDBhelper文件中的onCreate()方法

解决了在创建数据库时创建行的问题。现在我需要找到一种方法来使用新创建的行中的数据填充edittext,以便用户有机会保存或更改数据。 任何帮助,将不胜感激。