所以,我不想删除删除按钮所在的listview项目。现在,当我按下按钮时,我的第一个项目被删除了。有谁能够帮我?
Locatie
package com.buysse.roan.findyourstuff;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class Locatie extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, OnClickListener {
private Button buttonSave;
private Button buttonDelete;
private EditText editTextName;
private EditText editTextLocation;
MySQLiteHelper db = new MySQLiteHelper(this);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_locatie);
try{filList();
List<Item> list = db.getAllItems();}
catch( IndexOutOfBoundsException e){ System.out.println("caught");}
//add all items to list
//if(i>0){
//filList();
//List<Item> list = db.getAllItems();
//db.deleteItem(list.get(0));}
/**
* CRUD Operations
*
*/
//buttonpress
buttonSave = (Button) findViewById(R.id.buttonAddUser);
buttonSave.setOnClickListener(this);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextLocation = (EditText) findViewById(R.id.editTextLocation);
// add item
// get all items
// get all items
//db.getAllItems();
///new activity remove
//toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.locatie, 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();
return super.onOptionsItemSelected(item);
}
//change links
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_Locatie) {
Intent Locatie = new Intent(this, Locatie.class);
startActivity(Locatie);
} else if (id == R.id.nav_objects) {
Intent Object = new Intent(this, Object.class);
startActivity(Object);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onResume() {
super.onResume();
}
// onclick add to array + refresh list
@Override
public void onClick(View view) {
if (view.getId() == R.id.buttonAddUser) {
db.addItem(new Item(editTextName.getText().toString(), editTextLocation.getText().toString()));
/////Make Method
try{filList();}
catch( IndexOutOfBoundsException e){ System.out.println("caught");}
}
}
public void filList(){
MyAdapter adapter = new MyAdapter(this, db.getAllItems());
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}
//list delete
public void deleteItem (View view ){
List<Item> list = db.getAllItems();
ArrayList items = db.getAllItems();
db.deleteItem(list.get(0));
try{filList();}
catch( IndexOutOfBoundsException e){ System.out.println("caught");}//
}
}
content_locatie
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.buysse.roan.findyourstuff.Locatie"
tools:showIn="@layout/app_bar_locatie"
android:weightSum="1">
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:stretchColumns="1"
android:id="@+id/tableLayout">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@string/textViewNameText"
android:id="@+id/textViewName" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editTextName" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
</TableRow>
</TableLayout>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listView"
android:layout_below="@+id/buttonAddUser"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:longClickable="true"
android:choiceMode="multipleChoice" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/buttonAddText"
android:id="@+id/buttonAddUser"
android:layout_span="2"
android:layout_below="@+id/tableLayout"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="54dp"
android:layout_toStartOf="@+id/editTextLocation"
android:layout_alignRight="@+id/listView"
android:layout_alignEnd="@+id/listView"
android:layout_toLeftOf="@+id/editTextLocation" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textViewLocation"
android:layout_alignBottom="@+id/editTextLocation"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:text="@string/textViewLocation"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editTextLocation"
android:layout_below="@+id/tableLayout"
android:layout_alignRight="@+id/tableLayout"
android:layout_alignEnd="@+id/tableLayout"
android:layout_toEndOf="@+id/textViewLocation"
android:layout_toRightOf="@+id/textViewLocation" />
行自定义布局列表视图
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/Name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Study cursors"
android:textAppearance="?android:attr/textAppearanceLarge"
android:longClickable="true"
android:layout_alignRight="@+id/button"
android:layout_alignEnd="@+id/button" />
<TextView
android:id="@+id/Location"
android:layout_width="388dp"
android:layout_height="wrap_content"
android:text="3"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_weight="0.07"
android:longClickable="true"
android:layout_below="@+id/Name"
android:layout_toLeftOf="@+id/button"
android:layout_toStartOf="@+id/button" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete"
android:id="@+id/button"
android:onClick="deleteItem"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</LinearLayout>
Sqlitehelper +在Locatie中删除的方法(被问到)
//list delete
public void deleteItem (View view ){
List<Item> list = db.getAllItems();
ArrayList items = db.getAllItems();
db.deleteItem(list.get(0));
try{filList();}
catch( IndexOutOfBoundsException e){ System.out.println("caught");}}}
/////////////////////////////////////////////// ////////////////////////////////////////////////// ////////////////////////////////////////////////// //////////
package com.buysse.roan.findyourstuff;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.ListView;
import java.lang.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* Created by roanb on 10/08/2016.
*/
public class MySQLiteHelper extends SQLiteOpenHelper { // Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "ItemDB";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// SQL statement to create book table
String CREATE_ITEM_TABLE = "CREATE TABLE items ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"name TEXT, "+
"location TEXT )";
// create items table
db.execSQL(CREATE_ITEM_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older items if existed
db.execSQL("DROP TABLE IF EXISTS items");
// create fresh items table
this.onCreate(db);
}
//sql statements
// items table name
private static final String TABLE_ITEMS = "items";
// items Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_LOCATION = "location";
private static final String[] COLUMNS = {KEY_ID,KEY_NAME,KEY_LOCATION};
public void addItem (Item item){
//for logging
Log.d("addItem", item.toString());
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put(KEY_NAME, item.getName()); // get name
values.put(KEY_LOCATION, item.getLocation()); // get author
// 3. insert
db.insert(TABLE_ITEMS, // table
null, //nullColumnHack
values); // key/value -> keys = column names/ values = column values
// 4. close
db.close();
}
public Item getItem(int id){
// 1. get reference to readable DB
SQLiteDatabase db = this.getReadableDatabase();
// 2. build query
Cursor cursor =
db.query(TABLE_ITEMS, // a. table
COLUMNS, // b. column names
" id = ?", // c. selections
new String[] { String.valueOf(id) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit
// 3. if we got results get the first one
if (cursor != null)
cursor.moveToFirst();
// 4. build item object
Item item = new Item();
item.setId(Integer.parseInt(cursor.getString(0)));
item.setName(cursor.getString(1));
item.setLocation(cursor.getString(2));
//log
Log.d("geItem("+id+")", item.toString());
// 5. return book
return item;
}
public ArrayList<Item> getAllItems() {
ArrayList<Item> items = new ArrayList<>();
// 1. build the query
String query = "SELECT * FROM " + TABLE_ITEMS;
// 2. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
// 3. go over each rowl, build item and add it to list
Item item = null;
if (cursor.moveToFirst()) {
do {
item = new Item();
item.setId(Integer.parseInt(cursor.getString(0)));
item.setName(cursor.getString(1));
item.setLocation(cursor.getString(2));
// Add item to items
items.add(item);
} while (cursor.moveToNext());
}
Log.d("getAllItems()", items.toString());
// return items
return items;
}
public int updateItem(Item item) {
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put("name", item.getName()); // get title
values.put("location", item.getLocation()); // get author
// 3. updating rowl
int i = db.update(TABLE_ITEMS, //table
values, // column/value
KEY_ID+" = ?", // selections
new String[] { String.valueOf(item.getId()) }); //selection args
// 4. close
db.close();
return i;
}
public void deleteItem(Item item) {
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. delete
db.delete(TABLE_ITEMS, //table name
KEY_ID+" = ?", // selections
new String[] { String.valueOf(item.getId()) }); //selections args
// 3. close
db.close();
//log
Log.d("deleteItem",item.toString());
}
}
MyAdapter
private final Context context;
private final ArrayList<Item> itemsArrayList;
public MyAdapterL(Context context, ArrayList<Item> itemsArrayList) {
super(context, R.layout.rowl, itemsArrayList);
this.context = context;
this.itemsArrayList = itemsArrayList;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// 1. Create inflater
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// 2. Get rowView from inflater
View rowView = inflater.inflate(R.layout.rowl, parent, false);
// 3. Get the two text view from the rowView
TextView labelView = (TextView) rowView.findViewById(R.id.Location);
TextView valueView = (TextView) rowView.findViewById(R.id.Name);
// 4. Set the text for textView
labelView.setText(itemsArrayList.get(position).getName());
valueView.setText(itemsArrayList.get(position).getLocation());
// 5. retrn rowView
return rowView;
}
}
答案 0 :(得分:0)
使用ListView类不是最佳选择,每次数据集更改时都不应重建MyAdapter。您需要修改后备数据集,在您的情况下是DB,然后调用:adapter.notifyDataSetChanged()。
至于第一个被删除的数据项,我会说这是因为你总是索引第0项:
db.deleteItem(list.get(0));
您不会从ListView中删除数据,使用SQL查询从数据库中删除所需数据,然后更新适配器。
答案 1 :(得分:0)
首先,只要名称是唯一的,使用name从SQLite表中删除数据就不是理想的方法。
使适配器成为全局变量。
在MyAdapter中传递活动而不是上下文。
在适配器的getView中,将setOnClickListener添加到删除按钮。在onClick中调用活动的deleteItem(id)函数。
在deleteItem(id)函数中,最后添加myAdapter.notifyDataSetChanged()。
由于