【问题标题】:How to update my item in listview in the same activity where i add item into listview如何在我将项目添加到列表视图的同一活动中更新我在列表视图中的项目
【发布时间】:2019-07-12 17:26:11
【问题描述】:

我有 2 个按钮,添加和编辑。添加按钮有效,项目被添加到列表视图并存储在 sqlite 数据库中。但是我的编辑按钮不起作用,当我按下编辑时,列表视图中的项目没有更新。我用谷歌搜索,但所有代码都使用 2 个活动或对话,这不是我想要的。我想在同一个主要活动中添加和编辑。

这是我的 sqlite 数据库

public class GetFitHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "restaurantlist.db";
    private static final int SCHEMA_VERSION = 1;

    public GetFitHelper(Context context) {
        super(context, DATABASE_NAME, null, SCHEMA_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // Will be called once when the database is not created
        db.execSQL("CREATE TABLE food_table ( _id INTEGER PRIMARY KEY 
            AUTOINCREMENT, addFood TEXT, addCalories TEXT);");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int 
newVersion) {
    // Will not be called until SCHEMA_VERSION increases
    // Here we can upgrade the database e.g. add more tables
    }

    /* Read all records from food_table */
    public Cursor getAll() {
        return (getReadableDatabase().rawQuery(
                "SELECT _id, addFood, addCalories FROM food_table ORDER 
BY addFood", null));
    }

/* Read a particular record from food_table with id provided */
    public Cursor getById(String id) {
        String[] args = {id};
        return (getReadableDatabase().rawQuery(
                "SELECT _id, addFood, addCalories FROM food_table WHERE 
_ID = ?", args));
    }

    /* Write a record into food_table */
    public void insert(String addFood, String addCalories) {
        ContentValues cv = new ContentValues();

        cv.put("addFood", addFood);
        cv.put("addCalories", addCalories);


        getWritableDatabase().insert("food_table", "addFood", cv);
    }

    /* Update a particular record in food_table with id provided */
    public void update(String id,String addFood, String addCalories) {
        ContentValues cv = new ContentValues();
        String[] args = {id};
        cv.put("addFood", addFood);
        cv.put("addCalories", addCalories);

        getWritableDatabase().update("food_table", cv, " _ID = ?", args);
    }

    /* Read a record id value from food_table */
    public String getID(Cursor c) {
        return (c.getString(0));
    }
    public String getAddFood(Cursor c) {
        return (c.getString(1));
    }

    public String getAddCalories(Cursor c) {
        return (c.getString(2));
    }
}

这是我的编辑按钮代码

  private View.OnClickListener onEdit = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String foodStr = addFood.getText().toString();
            String caloriesStr = addCalories.getText().toString();           
            helper.update(foodID,foodStr,caloriesStr);
        }
    };

【问题讨论】:

  • 我建议在helper.update(foodID,foodStr,caloriesStr); 行之前添加行Log.d("ONCLCKUPDT","You clicked FoodID = " + String.valueOf(foodID) + "FoodStr = " + foodStr + " caloriesStr = " + caloriesStr);。我猜想 foodId 不是合适的值。不可能知道该值的来源,但它不太可能是正确的值。

标签: sqlite android-studio


【解决方案1】:

这是一个基于您的其他代码假设的工作示例。

ListView 的布局(示例中为 mylistview_item.xml):-

<TextView
    android:id="@+id/editfood"
    android:layout_width="0dp"
    android:layout_weight="3"
    android:layout_height="wrap_content" />
<TextView
    android:id="@+id/editcalories"
    android:layout_width="0dp"
    android:layout_weight="1"
    android:layout_height="wrap_content" />
<Button
    android:id="@+id/edit"
    android:layout_width="0dp"
    android:layout_weight="2"
    android:layout_height="wrap_content"
    android:text="UPDATE"
    android:onClick="onclick"/>
<TextView
    android:id="@+id/cheat"
    android:layout_width="0dp"
    android:layout_weight="0"
    android:layout_height="wrap_content"
    android:visibility="gone"/>
  • 注意 TextView 的 id(隐藏)称为作弊 (不是真正的作弊,而是使用 CursorAdapter 解决的方法)

  • 注意按钮的 onCLick="onclick"。

  • 否则假定这与您所拥有的相似。

GetFitHelper.java 没有改变。

活动的布局activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <EditText
        android:id="@+id/editfood"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="New Food Name"/>
    <EditText
        android:id="@+id/editcalories"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number"/>
    <ListView
        android:id="@+id/mylistview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </ListView>

</LinearLayout>

调用活动,在本例中为 MainActivity.java

public class MainActivity extends AppCompatActivity {

    GetFitHelper helper;
    EditText addFood,addCalories;
    ListView mylistview;
    Cursor mCsr;
    SimpleCursorAdapter mSCA;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        addFood = this.findViewById(R.id.editfood);
        addCalories = this.findViewById(R.id.editcalories);
        mylistview = this.findViewById(R.id.mylistview);
        helper = new GetFitHelper(this);

        addSomeDataIfNone();
        manageListView();

    }

    private void addSomeDataIfNone() {
        if(DatabaseUtils.queryNumEntries(helper.getWritableDatabase(),"food_table") > 0) return;
        helper.insert("Food1","100");
        helper.insert("Food2","150");
        helper.insert("Food2","300");
    }

    private void manageListView() {
        mCsr = helper.getAll();
        if (mSCA == null) {
            mSCA = new SimpleCursorAdapter(
                    this,
                    R.layout.mylistview_item,mCsr,
                    new String[]{"addFood","addCalories","_id"},
                    new int[]{R.id.editfood,R.id.editcalories,R.id.cheat},
                    0
            );
            mylistview.setAdapter(mSCA);
        } else {
            mSCA.swapCursor(mCsr);
        }
    }

    public void onclick(View v) {
        String foodStr = addFood.getText().toString();
        String caloriesStr = addCalories.getText().toString();
        TextView editbtn = ((View) v.getParent()).findViewById(R.id.cheat); 
        String foodID = editbtn.getText().toString();
        Log.d("ONCLCKUPDT","You clicked FoodID = " + String.valueOf(foodID) + "FoodStr = " + foodStr + " caloriesStr = " + caloriesStr);
        helper.update(foodID,foodStr,caloriesStr);
    }
}

修复的关键是 cheat TextView 具有相应行的 _id 列值。这是通过使用 findViewById 从父视图(LinearLayout)获取 TextView 从 TextView 中提取的。

结果

当应用程序第一次运行时,它是:-

输入 MyNewFood21500 然后点击 Food2 按钮,然后:-

日志包含以下行:-

D/ONCLCKUPDT: You clicked FoodID = 2FoodStr = MyNewFood2 caloriesStr = 1500

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    • 2015-06-22
    • 2018-09-06
    相关资源
    最近更新 更多