java - 数据库不会更新编辑文本更改android

标签 java android database sqlite

好的,我是android开发的新手

Also i went through some already asked questions but i could not solve my issue.

所以我正在学习 android 开发,为了练习,我正在创建一个笔记应用程序,它还没有完成,我正在使用 SQLite 来存储标题和笔记本身等信息

我在项目中有三个 Activity ,即 HomeActivity、MainActivity 和 EditorActivity,我将在下面附加其代码。

所以我认为数据库没有更新和存储新标题。

该应用程序的预期工作方式: 只有在您第一次运行该应用程序时,ma​​inactivity 会向您显示有关如何使用该应用程序以及设置数据库的说明,之后,无论何时打开该应用程序,您都会直接被带到homeactivity 将在 ListView 中显示数据库内容。每当单击此 ListView 中的项目时,noteID 都会发送到 editoractivity,它有两个 EditText,一个用于标题,一个用于注释本身 (目前只处理标题) 每当更改标题时,都应更新数据库,但事实并非如此。有人可以帮我弄这个吗 ?

代码:

主要 Activity .java

    package com.dharamshi.noteitdownv2;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.support.constraint.ConstraintLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    int mInstructionsID = 1;

    ConstraintLayout mConstraintLayout;
    Button mForwardButton;
    Button mBackButton;
    Button mLetsGo;
    LinearLayout mButtonLayout;

    SharedPreferences mSharedPreferences;

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

        mSharedPreferences = this.getSharedPreferences(getPackageName(), MODE_PRIVATE );

        boolean firstTimeSetup = mSharedPreferences.getBoolean("FirstTimeSetup", false);

        if(firstTimeSetup == false) {


            initDatabase();

            mConstraintLayout = findViewById(R.id.mainLayout);
            mForwardButton = findViewById(R.id.forwardButton);
            mBackButton = findViewById(R.id.backButton);
            mButtonLayout = findViewById(R.id.buttonLayout);
            mLetsGo = findViewById(R.id.letsGo);

            mLetsGo.setVisibility(View.INVISIBLE);
            mButtonLayout.setVisibility(View.VISIBLE);

            updateInstructions();
            Toast.makeText(this, "Click on the right side of the screen to continue", Toast.LENGTH_LONG).show();

            mForwardButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mInstructionsID <= 4) {
                        mInstructionsID++;
                        updateInstructions();
                    }

                }
            });

            mBackButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mInstructionsID > 1) {
                        mInstructionsID--;
                        updateInstructions();
                    }
                }
            });

            mLetsGo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {


                    mSharedPreferences.edit().putBoolean("FirstTimeSetup", true).apply();


                    Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
                    startActivity(intent);
                    finish();

                }
            });

        }else{
            Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
            startActivity(intent);
            finish();
        }

    }



    public void updateInstructions(){

        switch (mInstructionsID){

            case 1: mConstraintLayout.setBackgroundResource(R.drawable.noteitdownbgone);
                    break;

            case 2: mConstraintLayout.setBackgroundResource(R.drawable.noteitdownbgtwo);
                    break;

            case 3: mConstraintLayout.setBackgroundResource(R.drawable.noteitdownbgthree);
                    break;

            case 4: mConstraintLayout.setBackgroundResource(R.drawable.noteitdownbgfour);
                    break;


        }

        if(mInstructionsID > 4)
            mInstructionsID = 4;

        if(mInstructionsID == 4){

            mButtonLayout.setVisibility(View.INVISIBLE);
            mLetsGo.setVisibility(View.VISIBLE);

        }


    }

    public void initDatabase(){

        try{
            SQLiteDatabase myDatabase = openOrCreateDatabase("Notes", MODE_PRIVATE, null);

            myDatabase.execSQL("CREATE TABLE IF NOT EXISTS notes (id INT PRIMARY KEY, title TEXT, message TEXT)");

            myDatabase.execSQL("INSERT INTO notes (title, message) VALUES ('Introduction', 'This is a introduction')");

            Toast.makeText(this, "Database Created!", Toast.LENGTH_SHORT).show();

        }catch (Exception e)
        {
            new AlertDialog.Builder(this)
                    .setTitle("Error")
                    .setMessage(e.getMessage())
                    .setNegativeButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            finish();
                        }
                    }).show();
        }


    }
}

HomeActivity.java

package com.dharamshi.noteitdownv2;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

public class HomeActivity extends AppCompatActivity {

    ConstraintLayout mainLayout;

    public static ArrayList<String> titleList = new ArrayList<>();
    public static ArrayList<String> notesList = new ArrayList<>();
    public static ArrayList<Integer> idList = new ArrayList<>();

    public static ArrayAdapter sArrayAdapter;

    ListView notesListView;

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

        titleList.clear();
        notesList.clear();
        idList.clear();

        mainLayout = findViewById(R.id.constraintLayout);
        notesListView = findViewById(R.id.notesList);

        SQLiteDatabase sqLiteDatabase = openOrCreateDatabase("Notes" , MODE_PRIVATE, null);

        Cursor c = sqLiteDatabase.rawQuery("SELECT * FROM notes", null);

        int titleIndex = c.getColumnIndex("title");
        int idIndex = c.getColumnIndex("id");
        int messageIndex = c.getColumnIndex("message");


        c.moveToFirst();

        if (c != null) {
            do {
                //Log.i("id", Integer.toString(c.getInt(idIndex)));
                idList.add(c.getInt(idIndex));
                //Log.i("Title", c.getString(titleIndex));
                titleList.add(c.getString(titleIndex));
                //Log.i("Message", c.getString(messageIndex));
                notesList.add(c.getString(messageIndex));

            }while(c.moveToNext());
        }

        sArrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, titleList);

        notesListView.setAdapter(sArrayAdapter);

        notesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                Intent intent = new Intent(getApplicationContext(), EditorActivity.class);
                intent.putExtra("noteID", i);

                startActivity(intent);

            }
        });

    }

}

EditorActivity.java

package com.dharamshi.noteitdownv2;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.Toast;

public class EditorActivity extends AppCompatActivity {

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

        Intent intent = getIntent();

        final SQLiteDatabase sqLiteDatabase = openOrCreateDatabase("Notes", MODE_PRIVATE, null);

        EditText editTitle = findViewById(R.id.editTitle);
        EditText editNote = findViewById(R.id.editNote);

        final int noteID =intent.getIntExtra("noteID", -1);

        if(noteID != -1)
        {

            editTitle.setText(HomeActivity.titleList.get(noteID));
            editNote.setText(HomeActivity.notesList.get(noteID));

        }

        editTitle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                sqLiteDatabase.execSQL("UPDATE notes SET title = '" + charSequence.toString() + "' WHERE id = "+ HomeActivity.idList.get(noteID));
                Toast.makeText(EditorActivity.this, "UPDATE notes SET title = '" + charSequence.toString() + "' WHERE id = "+ HomeActivity.idList.get(noteID), Toast.LENGTH_SHORT).show();
                HomeActivity.titleList.set(noteID, charSequence.toString());
                HomeActivity.sArrayAdapter.notifyDataSetChanged();

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

    }


}

另外,我已经在这里上传了整个包:

https://drive.google.com/open?id=1Bc18Bbu0dodXFAQj_MeUrxsHEzCX09zp

编辑: 我在 HomeActivity 中添加了一个刷新按钮来验证数据库是否正在更新。结果证明,没有。数据库未更新。

public void refreshList(View view){

        idList.clear();
        notesList.clear();
        titleList.clear();

        SQLiteDatabase sqLiteDatabase = openOrCreateDatabase("Notes" , MODE_PRIVATE, null);

        Cursor c = sqLiteDatabase.rawQuery("SELECT * FROM notes", null);

        int titleIndex = c.getColumnIndex("title");
        int idIndex = c.getColumnIndex("id");
        int messageIndex = c.getColumnIndex("message");


        c.moveToFirst();

        if (c != null) {
            do {
                //Log.i("id", Integer.toString(c.getInt(idIndex)));
                idList.add(c.getInt(idIndex));
                //Log.i("Title", c.getString(titleIndex));
                titleList.add(c.getString(titleIndex));
                //Log.i("Message", c.getString(messageIndex));
                notesList.add(c.getString(messageIndex));

            }while(c.moveToNext());
        }

        sArrayAdapter.notifyDataSetChanged();

    }

最佳答案

您的问题与使用 id 列有关。首先是它的定义方式,然后是您如何尝试将 id 从 HomeActivity 传递到 EditorActivity。

问题 1

将列定义为 id INT PRIMARY KEY 将不会得到分配唯一 ID 所期望的结果(1,然后可能是 2,然后可能是 3 等)。

您必须非常具体并使用 id INTEGER PRIMARY KEY,这会将列定义为 rowid 的别名,如果未指定值,则这将是一个唯一的 ID。

要解决此问题,请更改:-

myDatabase.execSQL("CREATE TABLE IF NOT EXISTS notes (id INT PRIMARY KEY, title TEXT, message TEXT)");

到:-

myDatabase.execSQL("CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, title TEXT, message TEXT)");
  • 注意要使此更改生效,您需要删除应用程序的数据卸载应用程序,然后重新运行应用程序。

第 2 期

第二个问题是,在 HomeActivity 的 onItemClick 中,您要传递项目在列表中的位置,然后检索该值,就好像它是 id 一样。如果问题 1 没有解决,所有行的 id 都将为 null,位置永远不会匹配 null,因此您永远不会更新行。

但是,即使 id 已更正,位置也不会与单击的行/项目的 id 匹配。即第一个分配的 id 将是 1,第一行是位置 0,然后依此类推。

好消息是您拥有三个 ArrayList,因此 position 将等于 idList 的第 n 个元素,因此修复相对简单。你只需要改变:-

intent.putExtra("noteID", i);

到:-

intent.putExtra("noteID", idList.get(i));

其他问题。

问题 3

使用:-

    your_cursor.moveToFirst();
    if (your_cursor != null) {
        .....
    }

可能会导致问题,因为 your_cursor 不会为空。游标可能为空,在这种情况下 getCount() 方法将返回 0 或任何 moveTo??? 方法将返回 false。

我建议更换:-

    Cursor c = sqLiteDatabase.rawQuery("SELECT * FROM notes", null);


    int titleIndex = c.getColumnIndex("title");
    int idIndex = c.getColumnIndex("id");
    int messageIndex = c.getColumnIndex("message");


    c.moveToFirst(); // <<<< NO

    if (c != null) { // <<<< Cursor will not be null does nothing to check
        do {
            //Log.i("id", Integer.toString(c.getInt(idIndex)));
            idList.add(c.getInt(idIndex));
            //Log.i("Title", c.getString(titleIndex));
            titleList.add(c.getString(titleIndex));
            //Log.i("Message", c.getString(messageIndex));
            notesList.add(c.getString(messageIndex));

        }while(c.moveToNext());
    }

更紧凑:-

    Cursor c = sqLiteDatabase.rawQuery("SELECT * FROM notes", null);
    while(c.moveToNext()) {
        idList.add(c.getInt(c.getColumnIndex("id")));
        titleList.add(c.getString(c.getColumnIndex("title")));
        notesList.add(c.getString(c.getColumnIndex("message")));
    }

第 4 期

You are updating the database every time a a change is made (i.e. every time a character is typed or removed). You may find this rather intensive (especially with a Toast).

请注意,在此阶段更改不会立即反射(reflect)出来,但如果您重新启动应用程序,您应该会看到数据已更新。

更多内容......

下面是完整的代码,它实现了在编辑项目后列表不变的解决方案。 :-

首页 Activity .java

这会将 id 传递给 EditorActivity 并使用 onResume 方法重建列表。

public class HomeActivity extends AppCompatActivity {

    ConstraintLayout mainLayout;

    public static ArrayList<String> titleList = new ArrayList<>();
    public static ArrayList<String> notesList = new ArrayList<>();
    public static ArrayList<Integer> idList = new ArrayList<>();
    public static ArrayAdapter sArrayAdapter;

    SQLiteDatabase sqLiteDatabase; //<<<< ADDED
    ListView notesListView;

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

        titleList.clear();
        notesList.clear();
        idList.clear();

        mainLayout = findViewById(R.id.constraintLayout);
        notesListView = findViewById(R.id.notesList);
        sqLiteDatabase = openOrCreateDatabase("Notes" , MODE_PRIVATE, null); // <<<< CHANGED

        Cursor c = sqLiteDatabase.rawQuery("SELECT * FROM notes", null);
        /*
        int titleIndex = c.getColumnIndex("title");
        int idIndex = c.getColumnIndex("id");
        int messageIndex = c.getColumnIndex("message");
        c.moveToFirst(); // <<<< NO
        if (c != null) { // <<<< Cursor will not be null does nothing to check
            do {
                //Log.i("id", Integer.toString(c.getInt(idIndex)));
                idList.add(c.getInt(idIndex));
                //Log.i("Title", c.getString(titleIndex));
                titleList.add(c.getString(titleIndex));
                //Log.i("Message", c.getString(messageIndex));
                notesList.add(c.getString(messageIndex));
            }while(c.moveToNext());
        }
        */

        while(c.moveToNext()) {
            idList.add(c.getInt(c.getColumnIndex("id")));
            titleList.add(c.getString(c.getColumnIndex("title")));
            notesList.add(c.getString(c.getColumnIndex("message")));
        }
        sArrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, titleList);

        notesListView.setAdapter(sArrayAdapter);

        notesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                Intent intent = new Intent(getApplicationContext(), EditorActivity.class);
                //intent.putExtra("noteID", i); // <<<< i is the position not the ID of the row
                intent.putExtra("noteID", idList.get(i)); //<<<< ADDED
                startActivity(intent);
            }
        });
    }

    //<<<<<<<<<< Added to rebuild the Arrays and to notify the adapter of the changed data
    protected void onResume() {
        super.onResume();
        Cursor c = sqLiteDatabase.rawQuery("SELECT * FROM notes", null);
        idList.clear();
        notesList.clear();
        titleList.clear();
        while(c.moveToNext()) {
            idList.add(c.getInt(c.getColumnIndex("id")));
            titleList.add(c.getString(c.getColumnIndex("title")));
            notesList.add(c.getString(c.getColumnIndex("message")));
        }
        sArrayAdapter.notifyDataSetChanged();
    }
}

EditorActivity.java

这有相当大的变化,包括方法 setEditTexts 根据传递的 id 获取值。此外,许多变量的范围已更改为类级别。

public class EditorActivity extends AppCompatActivity {

    SQLiteDatabase sqLiteDatabase; //<<<< ADDED
    EditText editTitle, editNote; //<<<< ADDED
    int noteID; //<<<< ADDED

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

        Intent intent = getIntent();
        sqLiteDatabase = openOrCreateDatabase("Notes", MODE_PRIVATE, null); //<<<< CHANGED
        editTitle = findViewById(R.id.editTitle); //<<<< CHANGED
        editNote = findViewById(R.id.editNote); //<<<< CHANGED
        noteID =intent.getIntExtra("noteID", -1); //<<<<CHANGED

        if(noteID != -1)
        {
            setEditTexts(noteID); //<<<< ADDED
            //editTitle.setText(HomeActivity.titleList.get(noteID)); //<<<< DELETED
            //editNote.setText(HomeActivity.notesList.get(noteID)); //<<<< DELETED
        }

        editTitle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                String sql = "UPDATE notes SET title = '" + charSequence.toString() + "' WHERE id="+ String.valueOf(noteID); //<<<< CHANGED
                sqLiteDatabase.execSQL(sql); //<<<< CHANGED
                Toast.makeText(EditorActivity.this, sql, Toast.LENGTH_SHORT).show(); //<<<< CHANGED
                //HomeActivity.titleList.set(noteID, charSequence.toString()); //<<<<DELETED done in onResume of HomeActivity
                //HomeActivity.sArrayAdapter.notifyDataSetChanged(); //<<<<DELETED done in onResume of HomeActivity
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    //<<<<<<<<<< ADDED
    private void setEditTexts(int id) {
        String whereclasue = "id=?";
        String[] whereargs = new String[]{String.valueOf(id)};
        Cursor c = sqLiteDatabase.query(
                "notes",
                null,
                whereclasue,
                whereargs,
                null,null,null,null
        );
        if (c.moveToFirst()) {
            editTitle.setText(c.getString(c.getColumnIndex("title")));
            editNote.setText(c.getString(c.getColumnIndex("message")));
        }
    }
}

关于java - 数据库不会更新编辑文本更改android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51252194/

相关文章:

MySQL 在一次连接中只能使用 61 个表;如何绕过以下查询的此错误?

java - 无法在 Java 中解析 httpClientBuilder

java - 如何使用方法 Object.wait(long timeout, int nanos)

android - Google Play 上的应用程序始终显示 "Update"而不是打开

android - DailogFragment - getArguments/setArguments - 为什么要在包中传递参数?

mysql - 在触发器Mysql 5.0中打印消息

database - SAS:从多个数据集创建多个文件

java - Maven java maven-antrun-plugin

java - 打印机驱动程序在java中的实现

android - 在自定义内容提供程序中调用删除方法