【问题标题】:how to add button in custom row listview i want to delete database selected entry in listview如何在自定义行列表视图中添加按钮我想删除列表视图中的数据库选定条目
【发布时间】:2015-01-22 06:00:55
【问题描述】:

用于保存数据库的xml请帮助我##我想在按下按钮时在列表视图的每一行中添加删除按钮从列表视图和数据库中删除该数据##

这是第一个xml文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F3CAE5"
android:orientation="vertical"
android:padding="5dp" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/frst_txtV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="First name"
        android:textColor="#000" />

    <EditText
        android:id="@+id/frst_editTxt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/frst_txtV" />
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/lst_txtV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Last name"
        android:textColor="#000" />

    <EditText
        android:id="@+id/last_editTxt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_toRightOf="@+id/lst_txtV" />
</LinearLayout>

<Button
    android:id="@+id/save_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="10dp"
    android:text="Save"
    android:textColor="#000" />

</LinearLayout>

display_activty.xml 列表视图 xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#B58897"
android:gravity="center_horizontal" >

<Button
    android:id="@+id/btnAdd"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_marginRight="10dp"
    android:layout_marginTop="10dp"
    android:text="Add" />

<View
    android:id="@+id/a"
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:layout_below="@+id/btnAdd"
    android:background="#8DB3E1" />

<ListView
    android:id="@+id/List"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/a"
    android:divider="#8DB3E1"
    android:dividerHeight="2dp" />

</RelativeLayout>

displayadapter.java 在这里我添加按钮,如果我按下按钮,那么记录将从数据库以及列表视图中删除

public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private SQLiteDatabase dataBase;
private ArrayList<String> firstName;
private ArrayList<String> lastName;



public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname) {
    this.mContext = c;

    this.id = id;
    this.firstName = fname;
    this.lastName = lname;
}

public int getCount() {
    // TODO Auto-generated method stub
    return id.size();
}

public Object getItem(int position) {
    // TODO Auto-generated method stub
    return null;
}

public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
}

public View getView(final int pos, View child, ViewGroup parent) {
    Holder mHolder;
    LayoutInflater layoutInflater;
    if (child == null) {
        layoutInflater = (LayoutInflater)     mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        child = layoutInflater.inflate(R.layout.listcell, null);
        mHolder = new Holder();
        mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
        mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);

        mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
        mHolder.btn = (Button) child.findViewById(R.id.Button1);

        child.setTag(mHolder);
    } else {
        mHolder = (Holder) child.getTag();
    }
    mHolder.txt_id.setText(id.get(pos));
    mHolder.txt_fName.setText(firstName.get(pos));
    mHolder.txt_lName.setText(lastName.get(pos));
    mHolder.btn.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) 
        {

        }
    });


    return child;
}

public class Holder {
    TextView txt_id;
    TextView txt_fName;
    TextView txt_lName;
    Button btn;

    //ImageView img;
}
}

listcell.xml 这是显示自定义列表视图 xml 文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F3CAE5"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="8dp" >

<TextView
    android:id="@+id/txt_id"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:textColor="#000" />

<TextView
    android:id="@+id/txt_fName"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="2"
    android:textColor="#000" />

<TextView
    android:id="@+id/txt_lName"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="2"
    android:textColor="#000" />

<Button android:text="Button"
    android:id="@+id/Button1"
    android:focusable="false"

    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />

</LinearLayout>

DisplayActivty.java 这里是listview添加类

public class DisplayActivity extends Activity {

private DbHelper mHelper;
private SQLiteDatabase dataBase;


private ArrayList<String> userId = new ArrayList<String>();
private ArrayList<String> user_fName = new ArrayList<String>();
private ArrayList<String> user_lName = new ArrayList<String>();

private ListView userList;

private AlertDialog.Builder build;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.display_activity);

    userList = (ListView) findViewById(R.id.List);


    mHelper = new DbHelper(this);


    //add new record
    findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() 
    {

        public void onClick(View v) {

            Intent i = new Intent(getApplicationContext(),
                    AddActivity.class);
            i.putExtra("update", false);
            startActivity(i);

        }
    });

    //click to update data
    userList.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {

            Intent i = new Intent(getApplicationContext(),
                    AddActivity.class);
            i.putExtra("Fname", user_fName.get(arg2));
            i.putExtra("Lname", user_lName.get(arg2));
            i.putExtra("ID", userId.get(arg2));
            i.putExtra("update", true);
            startActivity(i);


        }
    });
}

@Override
protected void onResume() {
    displayData();
    super.onResume();
}

/**
 * displays data from SQLite
 */
private void displayData() {
    dataBase = mHelper.getWritableDatabase();
    Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
            + DbHelper.TABLE_NAME, null);

    userId.clear();
    user_fName.clear();
    user_lName.clear();
    if (mCursor.moveToFirst()) {
        do {
              userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
            user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
            user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));

        } while (mCursor.moveToNext());
    }
    DisplayAdapter disadpt = new DisplayAdapter(DisplayActivity.this,userId, user_fName, user_lName);
    userList.setAdapter(disadpt);
    mCursor.close();
}

}

Addactivty.java 添加数据库类

public class AddActivity extends Activity implements OnClickListener {
private Button btn_save;
private EditText edit_first,edit_last;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private String id,fname,lname;
private boolean isUpdate;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_activity);

    btn_save=(Button)findViewById(R.id.save_btn);
    edit_first=(EditText)findViewById(R.id.frst_editTxt);
    edit_last=(EditText)findViewById(R.id.last_editTxt);

   isUpdate=getIntent().getExtras().getBoolean("update");
    if(isUpdate)
    {
        id=getIntent().getExtras().getString("ID");
        fname=getIntent().getExtras().getString("Fname");
        lname=getIntent().getExtras().getString("Lname");
        edit_first.setText(fname);
        edit_last.setText(lname);

    }

     btn_save.setOnClickListener(this);

     mHelper=new DbHelper(this);

}

// saveButton click event 
public void onClick(View v) {
    fname=edit_first.getText().toString().trim();
    lname=edit_last.getText().toString().trim();
    if(fname.length()>0 && lname.length()>0)
    {
        saveData();
    }
    else
    {
        AlertDialog.Builder alertBuilder=new     AlertDialog.Builder(AddActivity.this);
        alertBuilder.setTitle("Invalid Data");
        alertBuilder.setMessage("Please, Enter valid data");
        alertBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();

            }
        });
        alertBuilder.create().show();
    }

}

/**
 * save data into SQLite
 */
private void saveData(){
    dataBase=mHelper.getWritableDatabase();
    ContentValues values=new ContentValues();

    values.put(DbHelper.KEY_FNAME,fname);
    values.put(DbHelper.KEY_LNAME,lname );

    System.out.println("");
    if(isUpdate)
    {    
        //update database with new data 
        dataBase.update(DbHelper.TABLE_NAME, values, DbHelper.KEY_ID+"="+id, null);
    }
    else
    {
        //insert data into database
        dataBase.insert(DbHelper.TABLE_NAME, null, values);
    }
    //close database
    dataBase.close();
    finish();


  }

}

【问题讨论】:

    标签: android sqlite delete-row


    【解决方案1】:

    像这样创建自定义数组适配器

    public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        if(convertView==null)
            vi = inflater.inflate(R.layout.inflatelistview, null);
    
        TextView text=(TextView)vi.findViewById(R.id.textView1);
        ImageView image=(ImageView)vi.findViewById(R.id.imageView1);
        Button btn=(Button)vi.findViewById(R.id.button1);
        btn.setTag(position);
        btn.setOnClickListener(new View.OnClickListener() {
    
            @Override
            public void onClick(View v) {
                Integer index = (Integer) v.getTag();
                //items.remove(index.intValue());  
                data.remove(position);
                notifyDataSetChanged();
    
            }
        });
        text.setText("item "+position);
        imageLoader.DisplayImage(data.get(position), image);
        return vi;
    }
    

    【讨论】:

    • 它只从列表视图中删除,如果我重新启动应用程序或重新启动 mainactivty 数据又回来了,所以也必须从数据库中删除数据
    • 对于 ArrayAdapter,notifyDataSetChanged 只有在适配器上使用 add()、insert()、remove() 和 clear() 时才有效。构造 ArrayAdapter 时,它保存对传入的 List 的引用。如果您要传入一个作为 Activity 成员的 List,然后更改该 Activity 成员,则 ArrayAdapter 仍然持有对原名单。 Adapter 不知道你更改了 Activity 中的 List。
    【解决方案2】:

    当你 inserting (Addactivty.java 添加数据库类) 和 fetching (DisplayActivty.java 这里是添加列表视图class) 数据库中的数据同样可以删除。

    例如:

    public static boolean Delete(Context context, int id) {
        SQLiteDatabase db = new MyDataBase(context).getWritableDatabase();
    
        int res = db.delete(CATEGORY, ID + " = " + id, null);
    
        if (db.isOpen())
            db.close();
    
        return (res == 0 ? false : true);
    }
    

    你需要在点击监听器中从数据库和listView中删除数据,比如:

    mHolder.btn.setOnClickListener(new View.OnClickListener() {
    
        public void onClick(View v) 
        {
            //1. get the clicked item's *ID* 
            //   (as you did id.get(pos), in your adapter class).
            //2. delete data from database using this *ID*.
            //   (see above function).
            //3. remove position from your list. 
            //   list.remove(position);
            //   (in your case you've multiple lists remove position from all)
            //4. notifyDataSetChanged();
        }
    });
    

    帮助链接:

    【讨论】:

      【解决方案3】:

      您的选择是:

      Use the functions of the ArrayAdapter to modify the underlying List (add(), insert(), remove(), clear(), etc.)
      Re-create the ArrayAdapter with the new List data. (Uses a lot of resources and garbage collection.)
      Create your own class derived from BaseAdapter and ListAdapter that allows changing of the underlying List data structure.
      Use the notifyDataSetChanged() every time the list is updated. To call it on the UI-Thread, use the runOnUiThread() of Activity. Then, notifyDataSetChanged() will work.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多