尝试使用SqLiteDatabase

时间:2018-06-03 23:14:59

标签: java android sql sqlite

我有 editText1,editText2和EditText3 。用户需要在此区域撰写个人信息。当他们放置保存按钮时, editText1,editText2和EditText3 必须保存。他们应该在他们想要的时候找到他们写的东西。但是当我尝试保存 3个(editText1,editText2和EditText3)时,这不会发生。 我只能保存editText1 。或者我可以在editText1中保存3个空格区域。例如, 我在editText1“hello”中写道,在editText2“listen”中,在editText3“伙伴”中,我保存了这个,当我在保存区域中打开时,我可以看到3次“监听”。其他人不保存。 你能帮助我吗?我应该改变什么?

MainActivity:

 into INA.member
(mem_id,mem_insertaddress,address_type,effective_date,end_date,adress,city,zip_code,phone_number,last_name,first_name)
values
(19889218,191166765,'Z2','01-AUG-2013','07-MAY-2016','45 NEWYORK','ATLANTIC','NY',011101,2012922341,'BOB','GUY');

Main2Activity

public class MainActivity extends AppCompatActivity {

    static ArrayList<Bitmap> newImage;


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.add_new, menu);

        return super.onCreateOptionsMenu(menu);
    }

    @Override //Menüyü seçersek ne olacak onu belirler.
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == R.id.add_new) {

            Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
            intent.putExtra("info", "new"); //Bu satırda amaç eğer yeni bir resimmi yoksa eski resimmi görentülenmek isteniyor onu anlamak
            startActivity(intent);
        }

        return super.onOptionsItemSelected(item);
    }

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

        ListView listView = (ListView) findViewById(R.id.listView);

        //Databaseden çektiğimiz dataları kaydedeceğimiz bir arraylist oluşturalım ve listview ile bağlayalım
        final ArrayList<String> newName = new ArrayList<String>();
        final ArrayList<String> newName2 = new ArrayList<String>();
        final ArrayList<String> newName3 = new ArrayList<String>();
        newImage = new ArrayList<Bitmap>();

        ArrayAdapter arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,newName);
        listView.setAdapter(arrayAdapter);

        //uygulama ilk açıldığında database'de kayıtlı bir şey varmı bakmasını istiyoruz aşağıdaki aşamalarda

        try {

            Main2Activity.database = this.openOrCreateDatabase("Yeni", MODE_PRIVATE, null);
            Main2Activity.database.execSQL("CREATE TABLE IF NOT EXISTS yeni (name VARCHAR, name2 VARCHAR, name3 VARCHAR, image BLOB)");

            Cursor cursor = Main2Activity.database.rawQuery("SELECT * FROM yeni", null); //Data çekmek için cursoru kullanıyoruz

            int nameIx = cursor.getColumnIndex("name");
            int name2Ix = cursor.getColumnIndex("name2");
            int name3Ix = cursor.getColumnIndex("name3");
            int imageIx = cursor.getColumnIndex("image");

            cursor.moveToFirst();

            while (cursor != null) {

                newName.add(cursor.getString(nameIx)); //Kullanıcının girdği ismi newName'in içine ekle
                newName2.add(cursor.getString(name2Ix));
                newName3.add(cursor.getString(name3Ix));

                byte[] byteArray = cursor.getBlob((imageIx));
                Bitmap image = BitmapFactory.decodeByteArray(byteArray,0,byteArray.length);
                newImage.add(image); //newImage'in içine ekle diyoruz

                cursor.moveToNext();

                arrayAdapter.notifyDataSetChanged();//Eğer bir datayı değiştirdiysek hemen güncelleyen bir konut
            }

        } catch (Exception e) {

        }

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent (getApplicationContext(), Main2Activity.class);
                intent.putExtra("info", "old");
                intent.putExtra("name", newName.get(position));
                intent.putExtra("name2", newName2.get(position));
                intent.putExtra("name3", newName3.get(position));
                intent.putExtra("position", position);

                startActivity(intent);

            }
        });
    }

}

2 个答案:

答案 0 :(得分:1)

问题1 是您尝试定义同一个表但有4列(onCreate方法MainActivity),然后是2列(在{{ 1}} save的方法,第二个不会创建表,因为它已经创建了,因此看起来将存在4列版本(如果它不存在并且表格被创建)然后,当您返回Main2Activity时,由于两列(MainActivityname2)不存在而导致找不到name3时未找到列,因此您最终会遇到问题

第二个问题是您尝试插入2个值,但有4个值作为参数,即int name2Ix = cursor.getColumnIndex("name2"); 2个值INSERT INTO yeni (name,image) .... 4个参数。

第3期是指您没有检测到插入的成功或失败,而只是假设它会起作用(当它没有时)。在SQLiteDatabase方法中使用try / catch也不是一个好主意,因为它们经常会处理很多情况,只有在出现问题时才会崩溃(并且你想要崩溃)。

第4期是您可以点击“保存”按钮(假设您在布局中使用了VALUES(?, ?, ? ,?)android:onClick="save"可能为空。

第5期是指在完成selectedImage后,您尝试启动Main2Activity,这将启动另一项活动,而不是通过完成{{1 }}。目前,这对您有利,因为ListView列出了新插入的行。但是,你最终会有很多活动,按下后退按钮会逐渐返回一堆活动,并且会非常混乱。

修复第5个问题,即完成MainActivity引入第6个问题,即列表未刷新,它仍然是插入新行之前的状态

修复第6个问题需要进行大量代码更改,但最终通过重新构建List的源来覆盖Main2Activity方法来刷新List(清除ArrayList,然后将所有元素添加到它)。

第4期的临时修复。

忽略第一个问题,这个问题不会引起问题,因为它似乎首先创建了具有4列的表(当然是在测试中)。 而且最初也忽略了第二和第三期。但使用: -

Main2Activty

onResume的{​​{1}}方法和输入测试,测试和测试中的3个EditText,然后单击按钮会返回MainActivity但没有任何内容显示。但是,日志会显示预期的 if (info.equalsIgnoreCase("new")) { // UNCHANGED Bitmap background = BitmapFactory.decodeResource( getApplicationContext().getResources(), android.R.drawable.ic_dialog_alert //<<<< Use a stock Android image for testing ); //Kullanıcı resim seçerkenki aşama selectedImage = background; //<<<< ADDED to overcome null pointer exception imageView.setImageBitmap(background); //<<<< UNCHANGED //........ rest of the code : -

Main2Activity

第二和第三期的主要修复

主要问题的建议修复,插入不插入记录,可以是以下内容,它使用SQLiteDatabase insert convenience method: -

onCreate

修复第6期(需要在修复第5期之前)

这需要进行相当多的代码更改,但基本上需要通过 E/SQLiteLog: (1) 4 values for 2 columns

中的06-03 22:13:09.895 2647-2647/yeni.yeni E/SQLiteLog: (1) 4 values for 2 columns 06-03 22:13:09.895 2647-2647/yeni.yeni W/System.err: android.database.sqlite.SQLiteException: 4 values for 2 columns (code 1): , while compiling: INSERT INTO yeni (name, image) VALUES (?, ?, ?, ?) at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method) at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887) at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498) at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588) at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58) at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31) at android.database.sqlite.SQLiteDatabase.compileStatement(SQLiteDatabase.java:994) at yeni.yeni.Main2Activity.save(Main2Activity.java:145) at java.lang.reflect.Method.invoke(Native Method) at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384) at android.view.View.performClick(View.java:5198) at android.view.View$PerformClick.run(View.java:21147) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 方法来刷新列表
public void save (View view) {

    String newName = editText.getText().toString(); //Kullanıcının kardettiği isme bu şekilde ulaştık
    String newName2 = editText2.getText().toString();
    String newName3 = editText3.getText().toString();
    //image'ler bytearray şeklinde kaydedilir!!!!!!!!!!

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); //selectedImage'i compress etmeliyiz kaydetme aşamalarından biri
    selectedImage.compress(Bitmap.CompressFormat.PNG,50,outputStream); //bu şekilde ziplemiş olduk resmi
    byte[] byteArray = outputStream.toByteArray(); //Bu outpuSteam'i al array'e çevir dedik! ve resmimiz kaydedilebilir oldu

    ContentValues cv = new ContentValues();
    cv.put("name",newName);
    cv.put("name2",newName2);
    cv.put("name3",newName3);
    cv.put("image",byteArray);
    long new_row_id = database.insert("yeni",null,cv);
    //<<<< ADDED TO ISSUE TOAST WITH THE RESULT
    if (new_row_id > 0) {
        Toast.makeText(this,"Row Insereted.",Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(this,"Row NOT Inserted",Toast.LENGTH_SHORT).show();
    }
    /*
    try { //Tüm bu alttaki aşamalarda kullanıcının girdiği isim ve resmi database'imize işlemiş olduk!
        Log.d("SAVE","Attempting OPEN Or CREATE DATABASE");
        database = this.openOrCreateDatabase("Yeni", MODE_PRIVATE, null);
        Log.d("SAVE","Attempting CREATE OF TABLE yeni");
        database.execSQL("CREATE TABLE IF NOT EXISTS yeni (name VARCHAR, image BLOB)");

        String sqlString = "INSERT INTO yeni (name, image) VALUES (?, ?, ?, ?)";
        SQLiteStatement statement =database.compileStatement(sqlString);
        statement.bindString(1,newName);
        statement.bindString(3,newName2);
        statement.bindString(4,newName3);
        statement.bindBlob(2,byteArray);
        Log.d("SAVE","Attempting EXECUTION of the SQL INSERT using :- " + statement.toString());
        statement.execute();

    } catch (Exception e) {
        e.printStackTrace();
    }
    */
    Intent intent = new Intent(getApplicationContext(), MainActivity.class); //kaydet'e bastığında anasayfaya yönlendirilsin
    startActivity(intent);

    //this.finish(); //<<<< Should not start a parent activity you should return to it by finishing the child activity
}
  • 注意为方便起见,而不是使用按钮的菜单。
    • 要使用该菜单,请删除为按钮使用而注释的代码并取消注释 使用菜单的代码。

最后修复第5期

onResume中删除2行: -

MainActivity

然后添加以下行: -

public class MainActivity extends AppCompatActivity {

    static ArrayList<Bitmap> newImage;
    ArrayList<String> nameList;
    ArrayList<String> name2List;
    ArrayList<String> name3List;
    ArrayAdapter<String> arrayadpater;
    ListView listView;

    Button addbutton; //<<<< Instead of menu for my convenience
    //<<<<<<<<<< Code Commented out for convenience of using button >>>>>>>>>
    /*
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.add_new, menu);

        return super.onCreateOptionsMenu(menu);
    }

    @Override //Menüyü seçersek ne olacak onu belirler.
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == R.id.add_new) {

            Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
            intent.putExtra("info", "new"); //Bu satırda amaç eğer yeni bir resimmi yoksa eski resimmi görentülenmek isteniyor onu anlamak
            startActivity(intent);
        }

        return super.onOptionsItemSelected(item);
    }
    */

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

        listView = (ListView) findViewById(R.id.listview); //<<<< CHANGED as declared as class variable

        //<<<<<<<<<< Code below for the conveince of using a button instead of Menu >>>>>>>>>>
        addbutton = (Button) findViewById(R.id.addnew);
        addbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
                intent.putExtra("info", "new"); //Bu satırda amaç eğer yeni bir resimmi yoksa eski resimmi görentülenmek isteniyor onu anlamak
                startActivity(intent);
            }
        });
        //<<<<<<<<<< End of code for Button handling >>>>>>>>>>

        setupListView();

        //<<<<<<<<<< NOTE commented out Code >>>>>>>>>>
        /*
        //Databaseden çektiğimiz dataları kaydedeceğimiz bir arraylist oluşturalım ve listview ile bağlayalım
        final ArrayList<String> newName = new ArrayList<String>();
        final ArrayList<String> newName2 = new ArrayList<String>();
        final ArrayList<String> newName3 = new ArrayList<String>();
        newImage = new ArrayList<Bitmap>();

        ArrayAdapter arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,newName);
        listView.setAdapter(arrayAdapter);

        //uygulama ilk açıldığında database'de kayıtlı bir şey varmı bakmasını istiyoruz aşağıdaki aşamalarda

        try {

            Main2Activity.database = this.openOrCreateDatabase("Yeni", MODE_PRIVATE, null);
            Main2Activity.database.execSQL("CREATE TABLE IF NOT EXISTS yeni (name VARCHAR, name2 VARCHAR, name3 VARCHAR, image BLOB)");

            Cursor cursor = Main2Activity.database.rawQuery("SELECT * FROM yeni", null); //Data çekmek için cursoru kullanıyoruz

            int nameIx = cursor.getColumnIndex("name");
            int name2Ix = cursor.getColumnIndex("name2");
            int name3Ix = cursor.getColumnIndex("name3");
            int imageIx = cursor.getColumnIndex("image");

            cursor.moveToFirst();

            while (cursor != null) {

                newName.add(cursor.getString(nameIx)); //Kullanıcının girdği ismi newName'in içine ekle
                newName2.add(cursor.getString(name2Ix));
                newName3.add(cursor.getString(name3Ix));

                byte[] byteArray = cursor.getBlob((imageIx));
                Bitmap image = BitmapFactory.decodeByteArray(byteArray,0,byteArray.length);
                newImage.add(image); //newImage'in içine ekle diyoruz

                cursor.moveToNext();

                arrayAdapter.notifyDataSetChanged();//Eğer bir datayı değiştirdiysek hemen güncelleyen bir konut
            }

        } catch (Exception e) {
        }
        */
    }
    //<<<< ADDED to handle return from child >>>>
    @Override
    public void onResume() {
        super.onResume();
        setupListView();
    }

    //<<<< ADDED to utilise a single refreshable ListView
    private void setupListView() {
        getListsFromDatabase();
        if (arrayadpater == null) {
            arrayadpater = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,nameList);
            listView.setAdapter(arrayadpater);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    Intent intent = new Intent (getApplicationContext(), Main2Activity.class);
                    intent.putExtra("info", "old");
                    intent.putExtra("name", nameList.get(position));
                    intent.putExtra("name2", name2List.get(position));
                    intent.putExtra("name3", name3List.get(position));
                    intent.putExtra("position", position);
                    startActivity(intent);
                }
            });
        } else {
            arrayadpater.notifyDataSetChanged();
        }
    }

    //<<<< Added to build/rebuild the Arraylist's used by the ListView
    private void getListsFromDatabase() {
        // Get the database (and set the databse for Main2Acticity)
        SQLiteDatabase db = openOrCreateDatabase(
                "Yeni",
                MODE_PRIVATE,
                null
        );
        db.execSQL("CREATE TABLE IF NOT EXISTS yeni (name VARCHAR, name2 VARCHAR, name3 VARCHAR, image BLOB)");
        Main2Activity.database = db;

        // Initialise or clear the array lists
        if (nameList == null) {
            nameList = new ArrayList<>();
        } else {
            nameList.clear();
        }
        if (name2List == null) {
            name2List = new ArrayList<>();
        } else {
            name2List.clear();
        }
        if (name3List == null) {
            name3List = new ArrayList<>();
        } else {
            name3List.clear();
        }
        if (newImage == null) {
            newImage = new ArrayList<>();
        } else {
            newImage.clear();
        }
        // get the
        Cursor cursor = db.query("yeni",
                null,
                null,
                null,
                null,
                null,
                null
        );
        while (cursor.moveToNext()) {
            nameList.add(cursor.getString(cursor.getColumnIndex("name")));
            name2List.add(cursor.getString(cursor.getColumnIndex("name2")));
            name3List.add(cursor.getString(cursor.getColumnIndex("name3")));
            byte[] b = cursor.getBlob(cursor.getColumnIndex("image"));
            Bitmap bmp = BitmapFactory.decodeByteArray(b,0,b.length);
            newImage.add(bmp);
        }
        cursor.close();
    }
}

结果

首次开始时: -

enter image description here

单击“添加”(相当于从菜单中选择“添加”): -

enter image description here

在点击Save(Hit Me)按钮之前: -

enter image description here

单击Save(Hit Me)按钮(即返回MainActivity)

enter image description here

点击列表中的项目(进行更新)

enter image description here

答案 1 :(得分:0)

检查你的logcat! 也许这句话有问题!

String sqlString = "INSERT INTO yeni (name, image) VALUES (?, ?, ?, ?)"

您选择了两列但是要插入4个值。