如何在longpress上的列表视图中更新和删除数据

时间:2019-08-05 06:48:39

标签: java android sqlite

我在列表视图中有一些记录,当我长按列表的特定项目时,我想更新和删除这些记录。 Like this structure DBHelper1 DBHelper2 DBHelper3 DBHelper4 DBHelper5 DBHelper6

包com.example.loginproject.model; 公共课记录{

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;

}}

公共类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;
}

}

公共类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());
        }
    });
}

}

公共类更新扩展了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);

}
 }

我显示了所有存储在数据库中的记录,但无法更新。

2 个答案:

答案 0 :(得分:0)

我要逐堂上课,以使事情容易理解。

DatabaseHelper类: 我不确定您为什么在onCreate()方法中使用了以下部分:

enter image description here

如果没有特定目的,则可以将其删除(您可以对其进行评论)。

现在,使用在“客户”表中使用的所有字段来完成“记录”模型。如果没有,也使该类序列化。所以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;
        .
        .
        .
    }
    ..
}

返回db类。 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;
}

getAllData()方法中填充“记录模型”列表,在更新的Record模型中(如上面提到的添加字段),对所有字段(例如SNO等)进行伪造。

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;
}   

将数据库类中的getalldata()方法更新为-

enter image description here

我已经更新了您的Home活动类,以便它可以完美地用于数据库刷新。您尝试在以下方面基本上注意到差异-

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);

像这样在Update活动中获取记录对象-

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

现在通过从记录模型中获取诸如

,在更新活动中填充名称,移动设备等字段
editTextMobile.setText(record.getMobile());

一旦用户单击“更新”按钮,就使用来自字段的编辑值(例如-

)更新记录模型
record.setMobile(editTextMobile.getText().toString());
....

并调用数据库帮助程序类的updateClientInfo(record)

希望细节能够帮助您满足要求。

注意:是我的建议,为变量和方法使用合适的名称,例如DB类中的getingData()到getUserRecord(),insertData()到insertClientInfo()等等。 / p>

答案 1 :(得分:-1)

尝试:-

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

如果要在适配器项上设置onLongClick,则只需执行此操作**(在适配器的onBindViewHolder方法中)**:-

    holder.lv.setOnItemLongClickListener(new OnItemLongClickListener() {

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

    }