数据库不会在编辑文本更改android

时间:2018-07-09 18:47:47

标签: java android database sqlite

好吧,我是android开发的新手

  

我也遇到了一些已经问过的问题,但我无法解决问题。

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

我在项目中有三个活动,分别是HomeActivity,MainActivity和EditorActivity,它们的代码我将在下面附加。

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

该应用的预期运行方式: 只有在您第一次运行该应用程序时, mainactivity 才会向您显示有关如何使用该应用程序以及如何设置数据库的说明,此后,无论何时打开该应用程序,您都将直接进入 > homeactivity ,它将在列表视图中显示数据库内容。每当单击此列表视图中的项目时,便会将noteID发送到 editoractivity ,该活动具有两个EditText,一个用于标题,一个用于注释本身。 (目前仅处理标题) 每当标题更改时,都应该更新数据库,但这没有发生。有人可以帮我弄这个吗 ?

代码:

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

    }

2 个答案:

答案 0 :(得分:3)

您的问题与使用 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)");
  • 注意,要使此更改生效,您需要删除该应用程序的数据卸载该应用程序,然后重新运行该应用程序。< / li>

问题2

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

但是,即使ID的位置更正,该行也不会与所单击的行/项目的ID相匹配。也就是说,分配的第一个id将为1,第一行的位置为0,依此类推。

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

intent.putExtra("noteID", i);

至:-

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

其他问题。

问题3

使用:-

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

可能会导致出现问题,因为您的光标不会为空。游标可能为空,在这种情况下,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).

请注意,此阶段的更改不会立即反映出来,但是如果您重新启动应用程序,则应该看到数据已更新。

更多……..

以下是用于实现解决方案的完整代码,该解决方案在项目被编辑后不会更改。 :-

HomeActivity.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")));
        }
    }
}

答案 1 :(得分:0)

尝试更改此行:

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