Java 无法从Android版my note app中的列表和数据库中删除便笺

Java 无法从Android版my note app中的列表和数据库中删除便笺,java,android,sqlite,Java,Android,Sqlite,在我的Android便笺应用程序中,如果我长按某个便笺,然后选择“删除”删除该便笺,则该便笺仍存在于列表中,然后在我关闭该应用程序并返回该应用程序后,该便笺将消失 提示:我正在使用onContextItemSelected方法显示“删除”选项 如何从列表和数据库中删除注释 MainActivity类,其中包含onContextItemSelected方法: package com.twitter.i_droidi.mynotes; import android.app.AlertD

在我的Android便笺应用程序中,如果我长按某个便笺,然后选择“删除”删除该便笺,则该便笺仍存在于列表中,然后在我关闭该应用程序并返回该应用程序后,该便笺将消失

  • 提示:我正在使用
    onContextItemSelected
    方法显示“删除”选项
如何从列表和数据库中删除注释

MainActivity类,其中包含
onContextItemSelected
方法:

    package com.twitter.i_droidi.mynotes;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;

public class MainActivity extends ActionBarActivity implements AdapterView.OnItemClickListener {

    ListView lv;
    NotesDataSource nDS;
    List<NotesModel> notesList;

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

        nDS = new NotesDataSource(this);
        lv = (ListView) findViewById(R.id.lv);

        nDS.open();
        notesList = nDS.getAllNotes();
        nDS.close();

        String[] notes = new String[notesList.size()];

        for (int i = 0; i < notesList.size(); i++) {
            notes[i] = notesList.get(i).getTitle();
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,
                android.R.id.text1, notes);
        lv.setAdapter(adapter);

        registerForContextMenu(lv);
        lv.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent nView = new Intent(this, Second2.class);
        nView.putExtra("id", notesList.get(position).getId());
        nView.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(nView);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_delete, menu);
        super.onCreateContextMenu(menu, v, menuInfo);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.delete:
                nDS.open();
                nDS.deleteNote("id"); // Check...!!!
                nDS.close();
                Toast nDelete = Toast.makeText(this, R.string.deleted, Toast.LENGTH_LONG);
                nDelete.show();
        }
        return super.onContextItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.mainMenuNewNote:
                Intent nNote = new Intent(this, Second.class);
                startActivity(nNote);
                return true;

            case R.id.mainMenuAbout:
                AlertDialog.Builder aboutDialog = new AlertDialog.Builder(this);
                aboutDialog.setTitle(getString(R.string.about_title));
                aboutDialog.setMessage(R.string.about_body);
                aboutDialog.setIcon(R.drawable.my_notes);
                aboutDialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface aboutDialog, int witch) {
                        // Do Not Do Anything.
                    }
                });

                aboutDialog.show();
                return true;

            case R.id.mainMenuExit:
                AlertDialog.Builder exDialog = new AlertDialog.Builder(this);
                exDialog.setTitle(R.string.exit_title);
                exDialog.setMessage(R.string.exit_body);
                exDialog.setIcon(R.drawable.my_notes);
                exDialog.setNegativeButton(R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface exDialog, int which) {
                        finish();
                    }
                });
                exDialog.setPositiveButton(R.string.no, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface exDialog, int which) {
                        // Do Not Do Anything.
                    }
                });

                exDialog.show();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
NotesDataSource类

    package com.twitter.i_droidi.mynotes;

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

public class DB extends SQLiteOpenHelper {

    private static final String DB_NAME = "MyNotes";
    private static final int DB_VERSION = 1;

    public static final String TABLE_NAME = "MyNotes";
    public static final String ID = "id";
    public static final String TITLE = "title";
    public static final String BODY = "body";

    private static final String DB_CREATE = "create table " + TABLE_NAME + " (" + ID + " integer primary key autoincrement, " +
            TITLE + " text not null, " + BODY + " text not null)";

    public DB(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(DB_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }
}
    package com.twitter.i_droidi.mynotes;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;

public class NotesDataSource {

    DB myDB;
    SQLiteDatabase sql;

    String[] getAllColumns = new String[]{DB.ID, DB.TITLE, DB.BODY};

    public NotesDataSource(Context context) {
        myDB = new DB(context);
    }

    public void open() {
        try {
            sql = myDB.getWritableDatabase();
        } catch (Exception ex) {
            Log.d("Error in your database!", ex.getMessage());
        }
    }

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

    public void createNote(String title, String body) {
        ContentValues note = new ContentValues();
        note.put(myDB.TITLE, title);
        note.put(myDB.BODY, body);
        sql.insert(myDB.TABLE_NAME, null, note);
    }

    public NotesModel getNote(int id) {
        NotesModel note = new NotesModel();

        Cursor cursor = sql.rawQuery("SELECT * FROM " + DB.TABLE_NAME + " WHERE " + DB.ID + " = ?", new String[]{id + ""});

        if (cursor.getCount() > 0) {
            cursor.moveToFirst();
            note.setId(cursor.getInt(0));
            note.setTitle(cursor.getString(1));
            note.setBody(cursor.getString(2));
            cursor.close();
        }
        return note;
    }

    public void updateNote(int id, String title, String body) {
        ContentValues note = new ContentValues();
        note.put(myDB.TITLE, title);
        note.put(myDB.BODY, body);
        sql.update(myDB.TABLE_NAME, note, myDB.ID + " = " + id, null);
    }

    public void deleteNote(Object id) {
        sql.delete(myDB.TABLE_NAME, myDB.ID + " = " + id, null);
    }

    public List<NotesModel> getAllNotes() {
        List<NotesModel> notesList = new ArrayList<NotesModel>();

        StringBuffer selectQuery = new StringBuffer();
        selectQuery.append("SELECT * FROM "+ myDB.TABLE_NAME +"");

        Cursor cursor = sql.rawQuery(selectQuery.toString(), null);

        if(cursor != null && cursor.moveToFirst()) {
            do {
                NotesModel notes = new NotesModel();
                notes.setId(cursor.getInt(0));
                notes.setTitle(cursor.getString(1));
                notes.setBody(cursor.getString(2));

                notesList.add(notes);

            } while (cursor.moveToNext());
        }
        cursor.close();
        return notesList;
    }
}
package com.twitter.i_droidi.mynotes;
导入android.content.ContentValues;
导入android.content.Context;
导入android.database.Cursor;
导入android.database.sqlite.SQLiteDatabase;
导入android.util.Log;
导入java.util.ArrayList;
导入java.util.List;
公共类NotesDataSource{
数据库myDB;
sqlitesql数据库;
String[]getAllColumns=新字符串[]{DB.ID,DB.TITLE,DB.BODY};
public NotesDataSource(上下文){
myDB=新DB(上下文);
}
公开作废{
试一试{
sql=myDB.getWritableDatabase();
}捕获(例外情况除外){
Log.d(“数据库中的错误!”,例如getMessage());
}
}
公众假期结束(){
sql.close();
}
public void createNote(字符串标题、字符串正文){
ContentValues注释=新的ContentValues();
注.put(myDB.TITLE,TITLE);
注:put(myDB.BODY,BODY);
insert(myDB.TABLE_NAME,null,note);
}
public notes模型getNote(int-id){
NotesModel note=新的NotesModel();
Cursor Cursor=sql.rawQuery(“从“+DB.TABLE_NAME+”中选择*,其中“+DB.ID+”=?”,新字符串[]{ID+”});
if(cursor.getCount()>0){
cursor.moveToFirst();
注.setId(cursor.getInt(0));
注.setTitle(cursor.getString(1));
注.setBody(cursor.getString(2));
cursor.close();
}
退货单;
}
public void updateNote(int-id、字符串标题、字符串正文){
ContentValues注释=新的ContentValues();
注.put(myDB.TITLE,TITLE);
注:put(myDB.BODY,BODY);
更新(myDB.TABLE_名称,注释,myDB.ID+“=”+ID,null);
}
公共void deleteNote(对象id){
sql.delete(myDB.TABLE_NAME,myDB.ID+“=”+ID,null);
}
公共列表getAllNotes(){
List notesList=new ArrayList();
StringBuffer selectQuery=新建StringBuffer();
selectQuery.append(“SELECT*FROM”+myDB.TABLE_NAME+”);
Cursor Cursor=sql.rawQuery(selectQuery.toString(),null);
if(cursor!=null&&cursor.moveToFirst()){
做{
NotesModel notes=新的NotesModel();
notes.setId(cursor.getInt(0));
notes.setTitle(cursor.getString(1));
notes.setBody(cursor.getString(2));
注释列表。添加(注释);
}while(cursor.moveToNext());
}
cursor.close();
返回票据列表;
}
}

从数据库中删除项目后 从中删除已删除的项目

String[] notes
利用

notes.remove(position);
nd呼叫

adapter.notifyDataSetChanged();

从数据库中删除项后 从中删除已删除的项目

String[] notes
利用

notes.remove(position);
nd呼叫

adapter.notifyDataSetChanged();

您使用StringBuffer的方式不值得使用它。也就是说:
deletfromdb
,然后
重新加载ListView
。你能解释更多吗?!我是初学者!:(需要一个StringBuilder来避免多个字符串连接(代价高昂)。但对于少量的连接,更不用说每个连接(+)需要一个
append
。您没有正确使用它。此外,您连接了一个完全无用的空字符串。此外,当您将其转换回字符串时,CPU还需要一些其他解压工作。实际上,您是在强调CPU没有用。您使用StringBuffer的方式不值得使用它。也就是说:
delete fromm db
,然后
重新加载ListView
。你能解释更多吗?!我是一个初学者!:(需要一个StringBuilder来避免几个字符串的串联(代价很高)。但不是为了少量的串联,而且是每一个串联(+)需要一个
append
。您没有正确使用它。此外,您连接了一个完全无用的空字符串。此外,当您将其转换回字符串时,CPU还需要一些其他解装箱工作。实际上,您是在强调CPU没有用。这不会从数据库中删除。从数据库中删除后,您必须删除从notes中删除它。您看到整个MainActivity类了吗?!在那里我可以调用
remove(position);
?!还有
notifyDataSetChanged();
?!这不会从数据库中删除。从数据库中删除后,您必须从notes中删除它。您看到整个MainActivity类了吗?!在那里我可以调用
remove(position);
?!以及
notifyDataSetChanged();
?!