0

みなさん、sqlite dbにデータを挿入しようとしていますが、挿入ボタンをクリックしても、強制終了、エラー、成功/失敗のトーストメッセージは何も起こりません.そして、db情報の表示ボタンをクリックすると、データは挿入されません以前にこれを行って問題はありませんでしたが、今回はどこが間違っていたのかわかりません。助けてください。よろしくお願いします。


主な活動

package com.example.sql;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

    Button insert,viewd;
    EditText name,age;

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

        name = (EditText)findViewById(R.id.etname);
        age = (EditText) findViewById(R.id.etage);

        insert = (Button)findViewById(R.id.btninsert);
        viewd = (Button)findViewById(R.id.btnview);

        insert.setOnClickListener(this);
        viewd.setOnClickListener(this);

    }


    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

final MediaPlayer mpButtonClick = MediaPlayer.create(this, R.raw.buttonclick);

        switch (v.getId()) {

        case R.id.btninsert:

            boolean status = true;

            try{

            String name1 = name.getText().toString();
            String age1 = age.getText().toString();

            SQLActivity entry = new SQLActivity(MainActivity.this);
            entry.open();

            entry.passDataToEntry(name1,age1);
            entry.close();

            mpButtonClick.start();

            }
            catch (Exception e) {
                // TODO: handle exception
                status=false;

                String error = e.toString();

                Log.e("Exception found ",error);

            }
            finally{
                if(status)
                {
                    Toast.makeText(getApplicationContext(), "Successfully Inserted", Toast.LENGTH_SHORT).show();

                }
            }

            break;

        case R.id.btnview:
            Intent i = new Intent("com.example.sql.VIEW");
            startActivity(i);
            break;
        }

    }   
}

SQLアクティビティ

package com.example.sql;

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

public class SQLActivity {

    public static final String KEY_ROWID = "_id";
    public static final String KEY_NAME = "p_name";
    public static final String KEY_AGE = "p_age";


    private static final String DATABASE_NAME = "SQLDB";
    private static final String DATABASE_TABLE = "data_table";
    private static final int DATABASE_VERSION = 1;


    private DbHelper ourHelper;
    private final Context ourContext;
    private SQLiteDatabase ourDatabase;

    private static class DbHelper extends SQLiteOpenHelper
    {

        public DbHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
                    + " INTEGER PRIMARY KEY AUTOINCREMENT , " + KEY_NAME + " TEXT NOT NULL , "
                    + KEY_AGE + " TEXT NOT NULL);" 
                      );

            String y = "CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
                    + " INTEGER PRIMARY KEY AUTOINCREMENT , " + KEY_NAME + " TEXT NOT NULL , "
                    + KEY_AGE + " TEXT NOT NULL);";

            //System.out.println("query" + y);
            Log.d("query", y);


        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
            Log.w("TaskDBAdapter", "Upgrading from version " +
                    oldVersion + " to " +
                    newVersion + ", which will destroy all old data");

            db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

            onCreate(db);

        }

    }

    public SQLActivity(Context c)
    {
        ourContext = c;
    }

    public SQLActivity open() throws SQLException
    {
        ourHelper = new DbHelper(ourContext);
        ourDatabase = ourHelper.getWritableDatabase();
        return this;
    }

    public void close()
    {
        ourHelper.close();
    }


    public long passDataToEntry(String name1, String age1) {
        // TODO Auto-generated method stub

        ContentValues cv = new ContentValues();
        cv.put(KEY_NAME, name1);
        cv.put(KEY_AGE, age1);
        int i = (int)ourDatabase.insert(DATABASE_TABLE, null, cv);
        String MY_TAG="";
        Log.d(MY_TAG,"Value= "+i);
        return ourDatabase.insert(DATABASE_TABLE, null, cv);


    }

    public String getData() {
        // TODO Auto-generated method stub
        String[] columns = new String[]{KEY_NAME,KEY_AGE};
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
        String result = "";

        int iRow = c.getColumnIndex(KEY_ROWID);
        int iName = c.getColumnIndex(KEY_NAME);
        int iAge = c.getColumnIndex(KEY_AGE);

        for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
        {
            result = result + c.getString(iName) + " " + c.getString(iAge) + "\n";
        }

        return result;
    }





}

activity_main.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="28dp"
        android:text="Name"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/etname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="14dp"
        android:ems="10"
        android:inputType="textPersonName" />

    <TextView
        android:id="@+id/tvinfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="40dp"
        android:text="Age"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/etage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="number" />

    <Button
        android:id="@+id/btninsert"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="130dp"
        android:text="Insert" />

    <Button
        android:id="@+id/btnview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="View" />

</LinearLayout>

ログキャット

04-18 22:43:50.625: E/Zygote(33): setreuid() failed. errno: 2
04-18 22:43:56.095: E/Zygote(33): setreuid() failed. errno: 17
04-18 22:43:56.985: E/BatteryService(59): usbOnlinePath not found
04-18 22:43:56.985: E/BatteryService(59): batteryVoltagePath not found
04-18 22:43:56.985: E/BatteryService(59): batteryTemperaturePath not found
04-18 22:43:56.995: E/SurfaceFlinger(59): Couldn't open /sys/power/wait_for_fb_sleep or /sys/power/wait_for_fb_wake
04-18 22:44:01.455: E/EventHub(59): could not get driver version for /dev/input/mouse0, Not a typewriter
04-18 22:44:01.455: E/EventHub(59): could not get driver version for /dev/input/mice, Not a typewriter
04-18 22:44:02.105: E/System(59): Failure starting core service
04-18 22:44:02.105: E/System(59): java.lang.SecurityException
04-18 22:44:02.105: E/System(59):   at android.os.BinderProxy.transact(Native Method)
04-18 22:44:02.105: E/System(59):   at android.os.ServiceManagerProxy.addService(ServiceManagerNative.java:146)
04-18 22:44:02.105: E/System(59):   at android.os.ServiceManager.addService(ServiceManager.java:72)
04-18 22:44:02.105: E/System(59):   at com.android.server.ServerThread.run(SystemServer.java:184)
04-18 22:44:02.665: E/SoundPool(59): error loading /system/media/audio/ui/Effect_Tick.ogg
04-18 22:44:02.675: E/SoundPool(59): error loading /system/media/audio/ui/KeypressStandard.ogg
04-18 22:44:02.675: E/SoundPool(59): error loading /system/media/audio/ui/KeypressSpacebar.ogg
04-18 22:44:02.675: E/SoundPool(59): error loading /system/media/audio/ui/KeypressDelete.ogg
04-18 22:44:02.675: E/SoundPool(59): error loading /system/media/audio/ui/KeypressReturn.ogg
04-18 22:44:03.755: E/ThrottleService(59): Could not open GPS configuration file /etc/gps.conf
04-18 22:44:05.005: E/logwrapper(147): executing /system/bin/tc failed: No such file or directory
04-18 22:44:05.045: E/logwrapper(148): executing /system/bin/tc failed: No such file or directory
04-18 22:44:05.065: E/logwrapper(149): executing /system/bin/tc failed: No such file or directory
04-18 22:44:10.423: E/HierarchicalStateMachine(59): TetherMaster - unhandledMessage: msg.what=3

アクティビティを見る

package com.example.sql;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ViewActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view);

        TextView tv = (TextView)findViewById(R.id.tvinfo);
        SQLActivity info = new SQLActivity(this);
        info.open();
        info.getData();
    }



}

view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Data...." />

    <TextView
        android:id="@+id/tvinfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="DB Info" />

</LinearLayout>
4

2 に答える 2

1

これが単純な SQLite データベースです。これを試して、これをシナリオに合わせてください。

RegistrationAdapter.java

package com.example.registrationform;
        import android.content.ContentValues;
        import android.content.Context;
        import android.database.Cursor;
        import android.database.sqlite.SQLiteDatabase;

    public class RegistrationAdapter {
        SQLiteDatabase database_ob;
        RegistrationOpenHelper openHelper_ob;
        Context context;

        public RegistrationAdapter(Context c) {
            context = c;
        }

        public RegistrationAdapter opnToRead() {
            openHelper_ob = new RegistrationOpenHelper(context,
                    openHelper_ob.DATABASE_NAME, null, openHelper_ob.VERSION);
            database_ob = openHelper_ob.getReadableDatabase();
            return this;

        }

        public RegistrationAdapter opnToWrite() {
            openHelper_ob = new RegistrationOpenHelper(context,
                    openHelper_ob.DATABASE_NAME, null, openHelper_ob.VERSION);
            database_ob = openHelper_ob.getWritableDatabase();
            return this;

        }

        public void Close() {
            database_ob.close();
        }

        public long insertDetails(String fname, String lname) {
            ContentValues contentValues = new ContentValues();
            contentValues.put(openHelper_ob.FNAME, fname);
            contentValues.put(openHelper_ob.LNAME, lname);
            opnToWrite();
            long val = database_ob.insert(openHelper_ob.TABLE_NAME, null,
                    contentValues);
            Close();
            return val;

        }

        public Cursor queryName() {
            String[] cols = { openHelper_ob.KEY_ID, openHelper_ob.FNAME,
                    openHelper_ob.LNAME };
            opnToWrite();
            Cursor c = database_ob.query(openHelper_ob.TABLE_NAME, cols, null,
                    null, null, null, null);

            return c;

        }

        public Cursor queryAll(int nameId) {
            String[] cols = { openHelper_ob.KEY_ID, openHelper_ob.FNAME,
                    openHelper_ob.LNAME };
            opnToWrite();
            Cursor c = database_ob.query(openHelper_ob.TABLE_NAME, cols,
                    openHelper_ob.KEY_ID + "=" + nameId, null, null, null, null);

            return c;

        }

        public long updateldetail(int rowId, String fname, String lname) {
            ContentValues contentValues = new ContentValues();
            contentValues.put(openHelper_ob.FNAME, fname);
            contentValues.put(openHelper_ob.LNAME, lname);
            opnToWrite();
            long val = database_ob.update(openHelper_ob.TABLE_NAME, contentValues,
                    openHelper_ob.KEY_ID + "=" + rowId, null);
            Close();
            return val;
        }

        public int deletOneRecord(int rowId) {
            // TODO Auto-generated method stub
            opnToWrite();
            int val = database_ob.delete(openHelper_ob.TABLE_NAME,
                    openHelper_ob.KEY_ID + "=" + rowId, null);
            Close();
            return val;
        }

    }

openhelper.java

package com.example.registrationform;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class RegistrationOpenHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "REGISTRATION_DB";
    public static final String TABLE_NAME = "REGISTRATION_TABLE";
    public static final String TABLE_NAME_ONE = "REGISTRATION_TABLE_ONE";
    public static final int VERSION = 1;
    public static final String KEY_ID = "_id";
    public static final String FNAME = "F_NAME";
    public static final String PKEY_ID = "pid";
    public static final String PROFILE = "profile";
    public static final String LNAME = "L_NAME";
    public static final String SCRIPT = "create table " + TABLE_NAME + " ("
            + KEY_ID + " integer primary key autoincrement, " + FNAME
            + " text not null, " + LNAME + " text not null );";

    public static final String PROFILE_TABLE = "create table " + TABLE_NAME_ONE + " ("
            + PKEY_ID + " integer primary key autoincrement, " + PROFILE
            + " text not null, );";

  /* public static final String PROFILE_TABLE="create table profiletable(profileid integer primary key autoincrement,profilename text null);";
   public static final String VALUE_TABLE="create table valuetable(id integer primary key autoincrement,value text null,delay );";
   */


    public RegistrationOpenHelper(Context context, String name,
            CursorFactory factory, int version) {
        super(context, name, factory, version);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(SCRIPT);
        db.execSQL(PROFILE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("drop table " + TABLE_NAME);
        db.execSQL("drop table "+TABLE_NAME_ONE);
        onCreate(db);
    }

}

登録アクティビティ.java

package com.example.registrationform;



import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class RegistrationActivity extends Activity {
    RegistrationAdapter adapter;
    RegistrationOpenHelper helper;
    EditText fnameEdit, lnameEdit;
    Button submitBtn, resetBtn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        fnameEdit = (EditText) findViewById(R.id.et_fname);
        lnameEdit = (EditText) findViewById(R.id.et_lname);
        submitBtn = (Button) findViewById(R.id.btn_submit);
        resetBtn = (Button) findViewById(R.id.btn_reset);
        adapter = new RegistrationAdapter(this);

        submitBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                String fnameValue = fnameEdit.getText().toString();
                String lnameValue = lnameEdit.getText().toString();
                long val = adapter.insertDetails(fnameValue, lnameValue);
                // Toast.makeText(getApplicationContext(), Long.toString(val),
                // 300).show();
                finish();
            }
        });
        resetBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                fnameEdit.setText("");
                lnameEdit.setText("");
            }
        });

    }
}

MainActivity.java

package com.example.registrationform;

    import android.app.Activity;
    import android.content.Intent;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.os.Bundle;
    import android.support.v4.widget.SimpleCursorAdapter;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.Button;
    import android.widget.ListView;

    public class MainActivity extends Activity {
        RegistrationAdapter adapter_ob;
        RegistrationOpenHelper helper_ob;
        SQLiteDatabase db_ob;
        ListView nameList;
        Button registerBtn;
        Cursor cursor;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            nameList = (ListView) findViewById(R.id.lv_name);
            registerBtn = (Button) findViewById(R.id.btn_register);
            adapter_ob = new RegistrationAdapter(this);

            String[] from = { helper_ob.FNAME, helper_ob.LNAME };
            int[] to = { R.id.tv_fname, R.id.tv_lname };
            cursor = adapter_ob.queryName();
            SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this,
                    R.layout.row, cursor, from, to);
            nameList.setAdapter(cursorAdapter);
            nameList.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView arg0, View arg1, int arg2,
                        long arg3) {
                    // TODO Auto-generated method stub
                    Bundle passdata = new Bundle();
                    Cursor listCursor = (Cursor) arg0.getItemAtPosition(arg2);
                    int nameId = listCursor.getInt(listCursor
                            .getColumnIndex(helper_ob.KEY_ID));
                    passdata.putInt("keyid", nameId);
                    Intent passIntent = new Intent(MainActivity.this,
                            EditActivity.class);
                    passIntent.putExtras(passdata);
                    startActivity(passIntent);
                }
            });
            registerBtn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    Intent registerIntent = new Intent(MainActivity.this,
                            RegistrationActivity.class);
                    startActivity(registerIntent);
                }
            });

        }

        @Override
        public void onResume() {
            super.onResume();
            cursor.requery();

        }

    }

EditActivity.java

package com.example.registrationform;


    import android.app.Activity;
    import android.database.Cursor;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;

    public class EditActivity extends Activity {
        RegistrationAdapter regadapter;
        RegistrationOpenHelper openHelper;
        int rowId;
        Cursor c;
        String fNameValue, lNameValue;
        EditText fname, lname;
        Button editSubmit, btnDelete;

        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.editregister);
            fname = (EditText) findViewById(R.id.et_editfname);
            lname = (EditText) findViewById(R.id.et_editlname);
            editSubmit = (Button) findViewById(R.id.btn_update);
            btnDelete = (Button) findViewById(R.id.btn_delete);

            Bundle showData = getIntent().getExtras();
            rowId = showData.getInt("keyid");
            // Toast.makeText(getApplicationContext(), Integer.toString(rowId),
            // 500).show();
            regadapter = new RegistrationAdapter(this);

            c = regadapter.queryAll(rowId);

            if (c.moveToFirst()) {
                do {
                    fname.setText(c.getString(1));
                    lname.setText(c.getString(2));

                } while (c.moveToNext());
            }

            editSubmit.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    regadapter.updateldetail(rowId, fname.getText().toString(),
                            lname.getText().toString());
                    finish();
                }
            });
            btnDelete.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    regadapter.deletOneRecord(rowId);
                    finish();
                }
            });
        }
    }
于 2013-09-12T12:06:07.570 に答える