更新行,而不是创建新条目的数据库的android [英] updating rows instead of creating new entries database android

查看:270
本文介绍了更新行,而不是创建新条目的数据库的android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力从Android的食谱配方,利用存储事件的数据库。当前code允许我补充新的项目,但我不能修改任何添加的条目。我需要的是具有行(48)predefined号码数据库通过相应的EditText字段更新这些行的功能。谁能帮我修改以下code来实现这一目标吗?我是新来的Andr​​oid编码和我需要开始使用该数据库。

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.

下面是我的MyDB文件:

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

}

下面是我的MyDBhelper文件:

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




}

下面是我的常量文件:

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

最后,这里是我DisplayDiaries文件返回创建日记在ListView:

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

正如我前面提到的,这个code运行允许创建新的日记,并把它们放在一个列表视图时。我需要的是修改此code所以数据库有predefined 48行(使用默认空内容)和日志文件可以通过相应的48的EditText字段修改行。任何帮助,上面会非常多AP preciated。我期待着你的学习。欢呼声中,帕特里克

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

由于我与创建​​默认在我的表48行,然后写code更新每行对应的EditText一个绝对的初学者,我仍然有问题。也许有一些有用的灵魂,可以算出这个对我?

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?

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

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

我已经更新了我的MyDBhelper onCreate方法与你的code是这样的:

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

但在日记的onCreate一个新行创建,而不是更新现有的行...我在做什么错在这里?我相信,我把code在错误的地方或者我错过了什么东西......

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...

推荐答案

我把这个循环语句:

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

在我的onCreate文件MyDBhelper()方法,这样的:

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

    }

}

有关无济于事新行没有被创建。是不是因为一个已经创建的数据库和应用程序后,重新启动该code不运行的事实?如果是的话,我能做些什么来删除数据库,并再次运行此code?

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

我找到了解决办法: 改变方法签名采取SQLiteDatabase作为参数的工作。

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)

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

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

placed within onCreate() method in MyDBhelper file

在创建数据库创建行解决的问题。现在我需要找到一种方法来填充的EditText的与新创建的行数据给用户一个机会来保存或更改数据。 任何帮助将是AP preciated。

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.

这篇关于更新行,而不是创建新条目的数据库的android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆