如何删除列表和sqlite文件中的listview项

时间:2016-08-11 17:07:07

标签: android sqlite listview

我以为我找到了一个简单的删除方法的解决方案,它引用了MySQLiteHelper,但我不知道db.deleteItem(list.get(0))中的列表是什么;是指。

我的位置文件

package com.buysse.roan.findyourstuff;

import android.content.ClipData;
import android.content.Intent;
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 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);


        //add all items to list

        filList();

        /**
         * 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
        List<Item> list = db.getAllItems();

        // delete one book
        db.deleteItem(list.get(0));

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

        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 (){
    //            db.deleteItem(list.get(0));
   // }


}

适配器

    package com.buysse.roan.findyourstuff;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;

/**
 * Created by roanb on 10/08/2016.
 */
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class MyAdapter extends ArrayAdapter<Item> {

    private final Context context;
    private final ArrayList<Item> itemsArrayList;

    public MyAdapter(Context context, ArrayList<Item> itemsArrayList) {

        super(context, R.layout.row, 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.row, parent, false);

        // 3. Get the two text view from the rowView
        TextView labelView = (TextView) rowView.findViewById(R.id.Name);
        TextView valueView = (TextView) rowView.findViewById(R.id.Location);

        // 4. Set the text for textView
        labelView.setText(itemsArrayList.get(position).getName());
        valueView.setText(itemsArrayList.get(position).getLocation());

        // 5. retrn rowView
        return rowView;
    }
}

MySQLiteHelper

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.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 iems 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("addBook", 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 row, 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 row
        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());

    }

}

Content_locatie.xml

<?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" />

    <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" />

</RelativeLayout>

2 个答案:

答案 0 :(得分:0)

将您从db获取的活动中的列表存储并将其传递给适配器 ArrayList items = db.getAllItems() 从此列表中删除项目(您只从数据库中删除) items.remove(0); 然后在适配器

上调用notifyDataSetChanged

答案 1 :(得分:0)

我建议您使用CursorAdapter ListView。网上有很多关于如何做到这一点的教程。