如何更新列表视图中的记录以及android中的数据库

Posted

技术标签:

【中文标题】如何更新列表视图中的记录以及android中的数据库【英文标题】:How to update record in listview as well as Database in android 【发布时间】:2018-09-06 08:26:56 【问题描述】:

当我单击列表项时,我希望在 SQL 中保存的所有编辑文本内容都显示在编辑账单活动中,但我只能检索名称并在意图中再次显示它。如果我在 editbills_activity 中再次保存现有记录,它应该使用新数据更新记录,而不是保存另一个数据。这是我的 DBAdapter.java

package com.example.dhruv.bills;
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 DBAdapter 
public static final String KEY_ROWID = "id";
public static final String KEY_NAME = "name";
public static final String KEY_AMOUNT = "amount";
public static final String KEY_DUEDATE = "duedate";
private static final String TAG = "DBAdapter";

private static final String DATABASE_NAME = "billsdb";
private static final String DATABASE_TABLE = "bills";
private static final int DATABASE_VERSION = 2;



private static final String DATABASE_CREATE =
        "create table if not exists assignments (id integer primary key autoincrement, "
                + "name VARCHAR not null, amount VARCHAR, duedate date );";

// Replaces DATABASE_CREATE using the one source definition
private static final String TABLE_CREATE =
        "CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE + "(" +
                KEY_ROWID + " INTEGER PRIMARY KEY, " + // AUTOINCREMENT NOT REQD
                KEY_NAME + " DATE NOT NULL, " +
                KEY_AMOUNT + " VARCHAR ," +
                KEY_DUEDATE + " DATE " +
                ")";

private final Context context;

private DatabaseHelper DBHelper;
private SQLiteDatabase db;

public DBAdapter(Context ctx)

    this.context = ctx;
    DBHelper = new DatabaseHelper(context);


private static class DatabaseHelper extends SQLiteOpenHelper

    DatabaseHelper(Context context)
    
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    

    @Override
    public void onCreate(SQLiteDatabase db)
    
        db.execSQL(TABLE_CREATE); // NO need to encapsulate in try clause
    

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS contacts"); //????????
        db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
        onCreate(db);
    


//---opens the database---
public DBAdapter open() throws SQLException

    db = DBHelper.getWritableDatabase();
    return this;


//---closes the database---
public void close()

    DBHelper.close();


//---insert a record into the database---
public long insertRecord(String name, String amount, String duedate)

    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_NAME, name);
    initialValues.put(KEY_AMOUNT, amount);
    initialValues.put(KEY_DUEDATE, duedate);
    //return db.insert(DATABASE_TABLE, null, initialValues);
    // Will return NULL POINTER EXCEPTION as db isn't set
    // Replaces commented out line
    return DBHelper.getWritableDatabase().insert(DATABASE_TABLE,
            null,
            initialValues
    );


//---deletes a particular record---
public boolean deleteContact(long rowId)

    return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;


//---retrieves all the records--- SEE FOLLOWING METHOD
public Cursor getAllRecords()
SQLiteDatabase db = DBHelper.getWritableDatabase();
    String query ="SELECT * FROM " + DATABASE_TABLE;
    Cursor data = db.rawQuery(query,null);
    return data;



//As per getAllRecords but using query convenience method
public Cursor getAllAsCursor() 
    return DBHelper.getWritableDatabase().query(
            DATABASE_TABLE,
            null,null,null,null,null,null
    );

public void deleteName(int id, String name)
    SQLiteDatabase db = DBHelper.getWritableDatabase();
    String query = "DELETE FROM " + DATABASE_TABLE + " WHERE "
            + KEY_ROWID + " = '" + id + "'" +
            " AND " + KEY_NAME + " = '" + name + "'";
    Log.d(TAG, "deleteName: query: " + query);
    Log.d(TAG, "deleteName: Deleting " + name + " from database.");
    db.execSQL(query);

public Cursor getItemID(String name) 
    SQLiteDatabase db = DBHelper.getWritableDatabase();
    String query = "SELECT " + KEY_ROWID + " FROM " + DATABASE_TABLE +
            " WHERE " + KEY_NAME + " = '" + name + "'";
    Cursor data = db.rawQuery(query, null);
    return data;

//---retrieves a particular record--- THIS WILL NOT WORK - NO SUCH TABLE
/* public Cursor getRecord()
String query1 ="SELECT * FROM" + KEY_TITLE;
    Cursor mCursor = db.rawQuery(query1,null);
    if (mCursor != null) 
        mCursor.moveToFirst();
    
    return mCursor;
*/

// Retrieve a row (single) according to id
public Cursor getRecordById(long id) 
    return DBHelper.getWritableDatabase().query(
            DATABASE_TABLE,
            null,
            KEY_ROWID + "=?",
            new String[]String.valueOf(id),
            null,null,null
    );



//---updates a record---
/* public boolean updateRecord(long rowId, String name, String amount, String duedate)

    ContentValues args = new ContentValues();
    args.put(KEY_NAME, name);
    args.put(KEY_AMOUNT, amount);
    args.put(KEY_DUEDATE, duedate);
    String whereclause = KEY_ROWID + "=?";
    String[] whereargs = new String[]String.valueOf(rowId);
    // Will return NULL POINTER EXCEPTION as db isn't set
    //return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    // Replaces commented out line
    return DBHelper.getWritableDatabase().update(DATABASE_TABLE,
            args,
            whereclause,
            whereargs
    ) > 0;
*/

这是我的 Bills.java (MainActivity)

问题:Bills.java 的列表视图在列表视图中的项目被单击时显示意图,但它没有输入金额和日期或更新记录。相反,它会保存另一条记录。

解决方案:我想检索它并显示所有(名称、金额、到期日期),而不是保存另一条记录,它应该更新它。

package com.example.dhruv.bill;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

import java.util.ArrayList;

public class bills extends AppCompatActivity 
DBAdapter dbAdapter;
ListView mrecycleview;
private static final String TAG ="assignments";

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bills);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    mrecycleview =(ListView) findViewById(R.id.mRecycleView);
    dbAdapter = new DBAdapter(this);
    // mlistview();
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab1);
    fab.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View view) 
            Intent i = new Intent(getApplicationContext(),Editbills.class);
            startActivity(i);
        
    );
    mlistview();


@Override
public boolean onCreateOptionsMenu(Menu menu) 
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_bills, menu);
    return true;


@Override
public boolean onOptionsItemSelected(MenuItem item) 
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) 
        return true;
    

    return super.onOptionsItemSelected(item);

private void mlistview()
    Log.d(TAG,"mlistview:Display data in listview");
    Cursor mCursor = dbAdapter.getAllRecords();
    ArrayList<String> listData = new ArrayList<>();
    while (mCursor.moveToNext())
        listData.add(mCursor.getString(1));
    
    ListAdapter adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,listData);
    mrecycleview.setAdapter(adapter);
    mrecycleview.setOnItemClickListener(new AdapterView.OnItemClickListener() 
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) 
            String name = adapterView.getItemAtPosition(i).toString();
            Log.d(TAG, "onItemClick: You Clicked on " + name);
            Cursor data = dbAdapter.getItemID(name); //get the id associated with that name
            int itemID = -1;
            while(data.moveToNext())
                itemID = data.getInt(0);
            
            if(itemID > -1)
                Log.d(TAG, "onItemClick: The ID is: " + itemID);
                Intent editScreenIntent = new Intent(bills.this, Editbills.class);
                editScreenIntent.putExtra("id",itemID);
                editScreenIntent.putExtra("name",name);
                startActivity(editScreenIntent);

            
            else

            
        
    );




这是我的 editbills.java 代码

package com.example.dhruv.bill;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Editbills extends AppCompatActivity 
Button button;
private static final String Tag= "assignments";
DBAdapter db = new DBAdapter(this);
private String selectedName;
private int selectedID;
DBAdapter dbAdapter;
private EditText editText,editText2,editText3;
@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_editbills);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    button=(Button)findViewById(R.id.button);
    editText =(EditText)findViewById(R.id.editText);
    editText2=(EditText)findViewById(R.id.editText2);
    editText3 =(EditText)findViewById(R.id.editText3);
    //get the intent extra from the ListDataActivity
    Intent receivedIntent = getIntent();

    //now get the itemID we passed as an extra
    selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value

    //now get the name we passed as an extra
    selectedName = receivedIntent.getStringExtra("name");

    //set the text to show the current selected name
    editText.setText(selectedName);
    button.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View view) 
            Log.d("test", "adding");
            db.open();
            long id = db.insertRecord(editText.getText().toString(), editText2.getText().toString(), editText3.getText().toString());
            db.close();
            Toast.makeText(Editbills.this," Added", Toast.LENGTH_LONG).show();
            Intent q = new Intent(getApplicationContext(),bills.class);
            startActivity(q);

        
    );

@Override
public boolean onCreateOptionsMenu(Menu menu) 
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_bills, menu);
    return true;


@Override
public boolean onOptionsItemSelected(MenuItem item) 
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_Delete) 
        db.deleteName(selectedID,selectedName);
        editText.setText("");
        Toast.makeText(this, "Deleted", Toast.LENGTH_SHORT).show();
        Intent p = new Intent(getApplicationContext(),bills.class);
        startActivity(p);
        return true;

    

    return super.onOptionsItemSelected(item);



【问题讨论】:

【参考方案1】:

而不是 DBHelper.getWritableDatabase().insert(DATABASE_TABLE, null, initialValues); 在 DBHelper 的 insertRecord 函数中,应该是 DBHelper.getWritableDatabase().update("markers", valores, where, whereArgs);

【讨论】:

***.com/questions/50162920/…@Mashal_Rashid 请帮忙

以上是关于如何更新列表视图中的记录以及android中的数据库的主要内容,如果未能解决你的问题,请参考以下文章

Android ViewPager,ListFragments以及更新列表中的元素时更新

如果可扩展列表视图android中的孩子为空,如何单击组

Android Studio 中的动态 ListView:选择随机元素并更新列表视图

如何从firebase检索多个数据到android中的列表视图?

长按列表视图后的操作(Android Studio)

如何将最新数据附加到android中的自定义基本适配器列表视图?