2016-08-12 8 views
0

削除ボタンがあるリストビュー項目を削除することはできません。今すぐ、ボタンを押すと、最初のアイテムが削除されます。誰か助けてくれますか?リストビュー項目をsqliteテーブルの名前で削除する方法

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> 

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

に削除する +メソッドSqlitehelper ///////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////// ////////////////////////////////

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

は、アイテムを削除しようとしているコードを追加します。 – Abbas

+0

アイテムを削除するコードを追加しました –

+0

アクティビティやプロジェクト全体ではなく、必要なコード(ケースコードとリストビューコード)を追加し、インポートステートメントの投稿を避けてください。 – user392117

答えて

0

ListViewクラスの使用が最適ではないため、データセットが変更されるたびにMyAdapterを再構築しないでください。あなたはDBの場合はバッキングデータセットを変更してから、adapter.notifyDataSetChanged()を呼び出す必要があります。

db.deleteItem(list.get(0)); 

あなたはリストビューからデータを削除しないでください、あなたはから必要なデータを削除します。

は常に削除される最初のデータ項目については、私はあなたが常に索引項目0からだと言うだろうDB、SQLクエリを使用して、アダプタを更新します。

+0

ええ、ごめんなさい。私は十分にはっきりしていなかった。 'db.deleteItem(list.get(0)); 'のために私は常に最初の項目を削除することを知っていますが、削除ボタンが置かれている項目を削除する方法を知りたいとは思っていません。それを 'db.deleteItem(list.get(0));'(またはそのようなもの)に入れてください。 –

+0

これで、各ListViewの行にボタンがあり、 –

+0

カスタムMyAdapterクラスのコードを追加します。 –

0

名前を使用してSQLiteテーブルからデータを削除することは、名前が一意である限り理想的な方法ではありません。

  1. あなたのアクティビティでは、deleteItem(id(またはname))のパブリック関数を作成できます。
  2. アダプタをグローバル変数にします。

  3. コンテキストではなくMyAdapterでアクティビティを渡します。

  4. アダプタのgetViewで、setOnClickListenerを削除ボタンに設定します。 onClickでは、あなたのアクティビティのdeleteItem(id)関数を呼び出します。

  5. deleteItem(id)関数で、最後にmyAdapter.notifyDataSetChanged()を追加します。

おかげ

関連する問題