简体   繁体   English

如何在Longpress上更新和删除ListView中的数据

[英]How can I update and delete data in listview on longpress

I have some records in list view, I want to update and delete these records when I long press on particular item of list. 我在列表视图中有一些记录,当我长按列表中的特定项目时,我想更新和删除这些记录。 Like this structure DBHelper1 DBHelper2 DBHelper3 DBHelper4 DBHelper5 DBHelper6 像这样的结构 DBHelper1 DBHelper2 DBHelper3 DBHelper4 DBHelper5 DBHelper6

package com.example.loginproject.model; 包com.example.loginproject.model; public class Record { 公开课记录{

String lead;
String name;
String mobile;
public Record(String lead, String name, String mobile) {
    this.lead = lead;
    this.name = name;
    this.mobile = mobile;
}
public String getLead() {
    return lead;
}
public Record(){}
public void setLead(String lead) {
    this.lead = lead;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getMobile() {
    return mobile;
}
public void setMobile(String mobile) {
    this.mobile = mobile;

}} }}

public class MyAdapter extends BaseAdapter { 公共类MyAdapter扩展BaseAdapter {

Context context;
ArrayList<Record> arrayList;

public  MyAdapter(Context context,ArrayList<Record>arrayList){

    this.context=context;
    this.arrayList=arrayList;
}

@Override
public int getCount() {
    return this.arrayList.size();
}

@Override
public Object getItem(int position) {
    return arrayList.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater layoutInflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView= layoutInflater.inflate(R.layout.custom_list_view,null);
        TextView textView1 =(TextView)convertView.findViewById(R.id.textview_leads);
        TextView textView2 =(TextView)convertView.findViewById(R.id.textview_names);
        TextView textView3 =(TextView)convertView.findViewById(R.id.textview_company);


        Record record=arrayList.get(position);
        textView1.setText(record.getLead());
        textView2.setText(record.getName());
        textView3.setText(record.getMobile());

    return convertView;
}

} }

public class Home extends AppCompatActivity { 公共类Home扩展AppCompatActivity {

TextView Name;
Button refresh,addlead;
DatabaseHelper databaseHelper;
SQLiteOpenHelper sqLiteOpenHelper;
SQLiteDatabase db;
ListView listView;
MyAdapter myAdapter;
ArrayList<Record>arrayList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    Name=(TextView)findViewById(R.id.Name);
    addlead=(Button)findViewById(R.id.addlead);
    refresh=(Button)findViewById(R.id.viewlead);
    listView=(ListView)findViewById(R.id.list_view);
    sqLiteOpenHelper=new DatabaseHelper(this);
    db=sqLiteOpenHelper.getReadableDatabase();
    databaseHelper=new DatabaseHelper(this);
    arrayList=new ArrayList<>();
    loaddatainlist();
    registerForContextMenu(listView);

    Name.setText(getIntent().getStringExtra(MainActivity.user));
    refresh();
   add_lead();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
    return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.mybutton) {
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setMessage("Are you really want to Logout ?")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getApplicationContext(),"Logout Successfully",Toast.LENGTH_SHORT).show();
                        finish();
                        //startActivity(new Intent(Home.this,MainActivity.class));
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
        AlertDialog alertDialog=builder.create();
        alertDialog.show();

    }
    return super.onOptionsItemSelected(item);
}


public void add_lead()
{
    addlead.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
         startActivity(new Intent(Home.this,Registration.class));
        }
    });
}

  private void loaddatainlist()
  {
      arrayList=databaseHelper.getalldata();
     myAdapter=new MyAdapter(this,arrayList);
     listView.setAdapter(myAdapter);
     myAdapter.notifyDataSetChanged();

  }

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    getMenuInflater().inflate(R.menu.listoption,menu);
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId())
    {
        case R.id.editoption:
            {
            startActivity(new Intent(Home.this, Update.class));
        }
        case R.id.deleteoption:
            {
            Toast.makeText(this, "Delete", Toast.LENGTH_SHORT).show();
        }

       return true;
       default:
           return super.onContextItemSelected(item);
    }

}
public void refresh()
{
    refresh.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
            startActivity(getIntent());
        }
    });
}

} }

public class Update extends AppCompatActivity { 公共类更新扩展了AppCompatActivity {

EditText lead,name,company,mobile,address;
Button update;
DatabaseHelper databaseHelper;
SQLiteDatabase dataBase;
ImageButton getrecord;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_update);
    databaseHelper=new DatabaseHelper(this);

    lead=(EditText)findViewById(R.id.lead);
    name=(EditText)findViewById(R.id.updatename);
    company=(EditText)findViewById(R.id.updatecompany_name);
    address=(EditText)findViewById(R.id.updateaddress);
    mobile=(EditText)findViewById(R.id.updatemobile);
    update=(Button)findViewById(R.id.update_button);

}
 }

I displayed all the records which i stored in database but I can not update it. 我显示了所有存储在数据库中的记录,但无法更新。

I am going class by class to make the things easy to understand. 我要逐堂上课,使事情容易理解。

DatabaseHelper class: I am not sure why you have used below section in onCreate() method: DatabaseHelper类:我不确定为什么在onCreate()方法中使用了以下部分:

在此处输入图片说明

If there is no specific purpose then you can remove it (you can comment for it's use). 如果没有特定目的,则可以将其删除(可以对其进行评论)。

Now in Complete your Record model with all the fields which you have used in Client table. 现在,在“客户”表中使用所有字段完成“记录”模型。 Also make the class serialized if it is not. 如果没有,也使该类序列化。 So the Record class will look like- 所以Record类看起来像-

public class Record implements Serializable {
    ..
    public Record(String sno, lead, String name, String mobile, String companyName, ...) {
        this.sno = sno;
        this.lead = lead;
        this.name = name;
        this.mobile = mobile;
        this.companyName = companyName;
        .
        .
        .
    }
    ..
}

Back to db class. 回到db类。 Change the update() method to - update()方法更改为-

public boolean updateClientInfo(Record record) {
    SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
    //Updated code will be like
    ContentValues contentValues = new ContentValues();
    contentValues.put(Column21, record.getLead());
    .
    .
    .
    int count = sqLiteDatabase.update(Table2, contentValues, "SNO = ?", new String[] {record.getSno()});

    return count > 0 ? true : false;
}

In getAllData() method to populate Record model list, pupulate all fields such as SNO etc in the updated Record model (as mentioned above with added fields). 在用于填充记录模型列表的getAllData()方法中,对更新的Record模型中的所有字段(例如SNO等)进行伪装(如上所述,其中添加了字段)。

Change the code for delete() method to- delete()方法的代码更改为-

public boolean deleteClientInfo(Record record) {
    SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();

    //Updated code will be
    int count = sqLiteDatabase.update(Table2, "SNO = ?", new String[] {record.getSno()});

    return count > 0 ? true : false;
}   

Update getalldata() method in DB class to - 将数据库类中的getalldata()方法更新为-

在此处输入图片说明

I have updated your Home activity class so that it will work perfectly for db refresh. 我已经更新了您的Home活动类,以便它可以完美地用于数据库刷新。 You try to notice the differences basically in the following area- 您尝试在以下方面基本上注意到差异:

refresh() -> updated, loaddatainlist() -> removed, createAdapter() -> added, refreshListFromDb() -> added, onCreate() updated, onReume() -> added. refresh()->已更新,loaddatainlist()->已删除,createAdapter()->已添加,refreshListFromDb()->已添加,onCreate()已更新,onReume()->已添加。

public class Home extends AppCompatActivity {

    TextView Name;
    Button refresh, addlead;
    DatabaseHelper databaseHelper;
    SQLiteOpenHelper sqLiteOpenHelper;
    SQLiteDatabase db;
    ListView listView;
    MyAdapter myAdapter;
    ArrayList<Record> arrayList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        Name = (TextView) findViewById(R.id.Name);
        addlead = (Button) findViewById(R.id.addlead);
        refresh = (Button) findViewById(R.id.viewlead);
        listView = (ListView) findViewById(R.id.list_view);
        sqLiteOpenHelper = new DatabaseHelper(this);
        db = sqLiteOpenHelper.getReadableDatabase();
        databaseHelper = new DatabaseHelper(this);
        arrayList = new ArrayList<>();
        createAdapter();
        registerForContextMenu(listView);

        Name.setText(getIntent().getStringExtra(MainActivity.user));
        refresh();
        add_lead();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.mybutton) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Are you really want to Logout ?").setCancelable(false)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(getApplicationContext(), "Logout Successfully", Toast.LENGTH_SHORT).show();
                            finish();
                            // startActivity(new Intent(Home.this,MainActivity.class));
                        }
                    }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
            AlertDialog alertDialog = builder.create();
            alertDialog.show();

        }
        return super.onOptionsItemSelected(item);
    }

    public void add_lead() {
        addlead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Home.this, Registration.class));
            }
        });
    }

    private void createAdapter() {
        myAdapter = new MyAdapter(this, arrayList);
        listView.setAdapter(myAdapter);
    }

    private void refreshListFromDb() {
        arrayList = databaseHelper.getAllClientData(arrayList);
        myAdapter.notifyDataSetChanged();

    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        getMenuInflater().inflate(R.menu.listoption, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.editoption: {
            startActivity(new Intent(Home.this, Update.class));
        }
        case R.id.deleteoption: {
            Toast.makeText(this, "Delete", Toast.LENGTH_SHORT).show();
        }

            return true;
        default:
            return super.onContextItemSelected(item);
        }

    }

    public void refresh() {
        refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshListFromDb();
            }
        });
    }

    @Override
        public void onResume() {
            super.onResume();
            refreshListFromDb()
        }
}

When you are calling Update class after longpress call the Intent as-

Intent intent = new Intent(this, Update.class);
intent.putExtra("parcel_record", recordModel); // record model of the index from array list where longpress is made. 
startActivity(intent);

Fetch the record object in Update activity like this- 像这样在Update活动中获取记录对象-

@Override
protected void onCreate(Bundle savedInstanceState) {
    // Using getParcelableExtra(String key) method
    Record record = (Record) getIntent().getParcelableExtra("parcel_record");
    ....
}

Now populate the fields such as name, mobile in update activity by taking from record model such as 现在,通过从记录模型中获取诸如更新中的名称,移动等字段,

editTextMobile.setText(record.getMobile());

Once user click on Update button, update the record model with the edited value from field such as - 用户单击“更新”按钮后,使用字段中的编辑值更新记录模型,例如-

record.setMobile(editTextMobile.getText().toString());
....

and call updateClientInfo(record) of DB helper class. 并调用数据库帮助程序类的updateClientInfo(record)

Hope the detail will help you to get your requirement. 希望细节会帮助您达到要求。

Note: It's my suggestion, use a proper name for the variables and methods such as getingData() to getUserRecord() in DB class, insertData() to insertClientInfo() and so on. 注意:这是我的建议,为数据库类中的变量和方法使用适当的名称,例如getingData()到getUserRecord(),insertData()到insertClientInfo()等等。

try this:- 尝试这个:-

lv.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                    int pos, long id) {
                // TODO Auto-generated method stub

                Log.v("long clicked","pos: " + pos);

                return true;
            }
        }); 

if you want to set onLongClick on an adapter item.then just do this**(in onBindViewHolder method of adapter)**:- 如果要在适配器项上设置onLongClick,则只需执行**(在适配器的onBindViewHolder方法中)**:-

    holder.lv.setOnItemLongClickListener(new OnItemLongClickListener() {

        //your code here.i.e updating the database

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM