Creating DialogFragment with EditText - java

I'm new to android, started it about a month ago, and now I'm trying to make a "Shopping List" app for the sake of practice. In this app I have a ListView, where user can insert items via EditText above that ListView. When user longClick on item, ContextMenu with "Edit", "Delete" and "Mark" fields appears. I have already made "Delete" button work, but I still have problems with "Edit" function. To make this function work I created DialogFragment class, so when user presses the "Edit" button, this DialogFragment appears. This DF has EditText field, where we enter data we want to change. Here is DialogFragment class code:
public class AlertEdit extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder bd = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
bd.setView(inflater.inflate(R.layout.alert, null))
.setTitle("Edit")
.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((MyActivity)getActivity()).doPositiveClick();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((MyActivity)getActivity()).doNegativeClick();
}
});
return bd.create();
}
as you can see, we have positive button here, which calls doPositiveClick method from MyActivity, which appears to be the main activity.
.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((MyActivity)getActivity()).doPositiveClick();
}
So, here is the MyActivity class code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
lw = (ListView) findViewById(R.id.listView);
edtxt = (EditText) findViewById(R.id.editText);
alertEd = (EditText) findViewById(R.id.alertEdit);
goods = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, goods);
lw.setAdapter(adapter);
lw.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v,
int position, long id) {
}
});
registerForContextMenu(lw);
edtxt.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction()== KeyEvent.ACTION_DOWN) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
goods.add(0, edtxt.getText().toString());
adapter.notifyDataSetChanged();
edtxt.setText("");
return true;
}
}
return false;
}
});
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo info){
super.onCreateContextMenu(menu, v, info);
getMenuInflater().inflate(R.menu.actions, menu);
}
public boolean onContextItemSelected(MenuItem item) {
position = (int) info.id;
switch (item.getItemId()) {
case R.id.cnt_mnu_delete:
goods.remove(position);
adapter.notifyDataSetChanged();
return true;
case R.id.cnt_mnu_edit:
}
return super.onContextItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void doPositiveClick()
{
}
public void doNegativeClick()
{
}
public void showDialog()
{
DialogFragment frag = new AlertEdit();
frag.show(getFragmentManager(), "edit");
}
}
My problem is that I have no idea how to create that Edit function. I tryied to use AdapterContextMenuInfo, but it works only in onContextItemSelected method, because it requires and Item to work with. Hope you help me and sorry for the possible lack of information, ask me any additional questions please.
P.S. I'm trying to make this dialog for almost two weeks already and I'm really frustrated because of that.

I'm using this method - it's simple and you may adapt it to your needs:
First of all make an interface to handle your result, for example:
public interface OnDialogResultListener {
public void onDialogResult(String result);
}
Then use your dialog with additional view, like this:
public void showDialogAndGetResult(final int title, final String message, final String initialText, final OnDialogResultListener listener) {
// additional View - use appropriate View to your needs:
final EditText editText = new EditText(this);
editText.setText(initialText);
new AlertDialog.Builder(MainActivity.this)//
.setTitle(title)//
.setMessage(message)//
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (listener != null) {
listener.onDialogResult(editText.getText().toString());
}
}
})//
.setNegativeButton(android.R.string.cancel, null)//
.setView(editText)//
.show();
}
At last implement this interface in your activity:
public class YourActivity Extends Activity implements OnDialogResultListener{
...
#Override
public void onDialogResult(String result) {
//do what you need
}
...
}
Edit:
You may replace EditText by any View, including Layouts.
Still you may use the same scheme to return result from your DialogFragment descendant - just pass OnDialogResultListener in constructor or initializing method. I would say AlertDialog is more lightweight and DialogFragment allows more control and you may use both according to your needs.

Related

Placement of Dialog box in android studio main activity of Android

I want to delete the recycler view item by long press methode and on long press , a dialog box should appear with yes and no. As i click on yes, the item should be delete.. My code for dialog box...
public static class DialogBox extends DialogFragment {
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
builder.setTitle("Do you want to delete it?").setMessage("Confirmation Dialog")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder.create();
}
}
}
My code for delete button of dialog box
public void onDeleteItem(int position) {
DialogBox dialogBox=new DialogBox();
dialogBox.show(getSupportFragmentManager(),"Example Dialog");
removeItem(position);
}
});
Here what should I do that I can easily remove the item by placing the code at right position
You can use this Alternative.
In this scenario You can long press the item and you will get the delete option if you press delete thn it will delete the item else you can press out side of that item to cancel.
#Override
public void onBindViewHolder(EmployeeListAdapter.ViewHolder holder, final int position) {
holder.cardClick.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
#Override
public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
MenuItem delete = contextMenu.add(0, position, 0, "Delete");
delete.setOnMenuItemClickListener(onDeleteMenu);
}
});
}
/*
* Delete Menu
* */
private final MenuItem.OnMenuItemClickListener onDeleteMenu = new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
deleteTaskApi(IdList.get(item.getItemId() ));
return true;
}
};

How to save a listview using shared preference

I've made a simple shopping list app where the user can add items to the listview. My problem is when I leave the app the items do not save. I think I need to use a shared preference but haven't had much look implementing it (I'm fairly new to coding) If anyone knows how to implement the shared preference so my items will save it would be much appreciated.
My code:
public class CreateAList extends AppCompatActivity {
//ArrayList for data
private ArrayList<String> list = new ArrayList<>();
ListView list_view;
ArrayAdapter arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_alist);
//find view by id
list_view = findViewById(R.id.list_view);
arrayAdapter = new ArrayAdapter(CreateAList.this, android.R.layout.simple_list_item_1,list);
list_view.setAdapter(arrayAdapter);
list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> adapterView, View view, final int i, long l) {
//Inflating is the process of adding a view(.xml) to activity on runtime
PopupMenu popupMenu = new PopupMenu(CreateAList.this,view);
popupMenu.getMenuInflater().inflate(R.menu.pop_up_menu,popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.item_update:
//function for update
AlertDialog.Builder builder = new AlertDialog.Builder(CreateAList.this);
View v = LayoutInflater.from(CreateAList.this).inflate(R.layout.item_dialog,null,false);
builder.setTitle("Update Item");
final EditText editText = v.findViewById(R.id.editItem);
editText.setText(list.get(i));
//set custom view to dialog
builder.setView(v);
builder.setPositiveButton("Update", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
if (!editText.getText().toString().isEmpty()){
list.set(i, editText.getText().toString().trim());
arrayAdapter.notifyDataSetChanged();
Toast.makeText(CreateAList.this, "Item Updated", Toast.LENGTH_SHORT).show();
}else{
editText.setError("add item here!");
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
dialog.dismiss();
}
});
builder.show();
break;
case R.id.item_delete:
//function for delete
Toast.makeText(CreateAList.this, "Item Deleted", Toast.LENGTH_SHORT).show();
list.remove(i);
arrayAdapter.notifyDataSetChanged();
break;
}
return true;
}
});
popupMenu.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.add_item:
//function to add
addItem();
break;
}
return true;
}
//method for adding item
private void addItem() {
AlertDialog.Builder builder = new AlertDialog.Builder(CreateAList.this);
builder.setTitle("Add new Item");
View v = LayoutInflater.from(CreateAList.this).inflate(R.layout.item_dialog,null,false);
builder.setView(v);
final EditText editItem = v.findViewById(R.id.editItem);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (!editItem.getText().toString().isEmpty()){
list.add(editItem.getText().toString().trim());
arrayAdapter.notifyDataSetChanged();
}else{
editItem.setError("Add Item Here!");
}
}
});
}
It would be a good idea to go through a tutorial for shared preference. This way you will learn more. Also look for SQLite database that Android provides to store data. I think that will be much better approach if you have simple objects in your list view.
Here is a good tutorial : https://medium.com/#evancheese1/shared-preferences-saving-arraylists-and-more-with-json-and-gson-java-5d899c8b0235
void putSharedPreferencesStringSet(String key, Set value)
{
SharedPreferences.Editor edit = getContext().getSharedPreferences("SHARED_PREFERENCE_NAME", 0).edit();
edit.putStringSet(key, value);
edit.apply();
}
void putSharedPreferencesStringSet(String key, String value)
{
SharedPreferences.Editoredit = getContext().getSharedPreferences("SHARED_PREFERENCE_NAME", 0).edit();
edit.putString(key, value);
edit.apply();
}
String getSharedPreferencesString(String key)
{
SharedPreferences prefs = AppConstants.appContext.getSharedPreferences(AppConstants.SHARED_PREFERENCE_NAME, 0);
return prefs.getString(key, 0);
}
void removeSharedPreferencesString(String key)
{
SharedPreferences edit = AppConstants.appContext.getSharedPreferences(AppConstants.SHARED_PREFERENCE_NAME, 0);
edit.remove(key);
edit.apply();
}
//the above functions are about add , get and remove sharedPrefrences
Another way if you need to use database when ever you add items in to your cart

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
package 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 {
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 {
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 {
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:
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-
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. Change the update() method to -
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).
Change the code for delete() method to-
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 -
I have updated your Home activity class so that it will work perfectly for db refresh. You try to notice the differences basically in the following area-
refresh() -> updated, loaddatainlist() -> removed, createAdapter() -> added, refreshListFromDb() -> added, onCreate() updated, onReume() -> added.
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-
#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.
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.
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)**:-
holder.lv.setOnItemLongClickListener(new OnItemLongClickListener() {
//your code here.i.e updating the database
}

Recyclerview sqllite update only works on first item on the list

I have a list of items that are displayed in a recylcerview in my adapter class i implmented a onlongclick method, when used it opens up a new alertdialog, when i press on the selected item in the alterdialog im calling updateList() function that is supposed to update the selected item the problem is this only works for the first item displayed in my list, so in exmaple if i pressed the 10th item on the list said item wont update.
Update function
public boolean updateList(long rowId, String stanje) {
ContentValues newValues = new ContentValues();
newValues.put(TABELA_STOLPEC_STANJE,stanje);
return db.update(TABELA_IME,newValues,TABELA_STOLPEC_ID+"="+rowId,null)>0;
}
OnlongClickListener this method is in my fragment class.
mmAdapter.setOnLongClick(new ToDoRecyclerViewAdapter.OnLongClickListener_() {
#Override
public void onLongClick(long i,String item) {
if(item.equals("doing")) {
boolean update_1 = db.updateList(i, item);
if(update_1) {
android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(TodoFragment.this).attach(TodoFragment.this).commit();
Toast.makeText(getContext(), "Dodano v bazo.!", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getContext(), "Prislo je do napake!", Toast.LENGTH_SHORT).show();
}
}
}
});
onlongclicklistener implementation in my adapter class
holder.mView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
AlertDialog.Builder adb = new AlertDialog.Builder(v.getContext());
CharSequence meni[] = new CharSequence[] {"DOING"};
adb.setItems(meni, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0) {
mValues.get(i).setStanje("doing");
clickLinster_.onLongClick(mValues.get(position).getId_(),mValues.get(position).getStanje());
}
}
});
AlertDialog alertDialog = adb.create();
alertDialog.setCancelable(true);
alertDialog.show();
return true;
}
});
public interface OnLongClickListener_ {
void onLongClick(long i, String item);
}
The reason is simple, you are updating wrong row with index, correct solution:
#Override
public void onBindViewHolder(#NonNull final CustomViewHolder holder, int position) {
//Rest of onBindViewHolder code
holder.mView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
final int pos = holder.getAdapterPosition();
AlertDialog.Builder adb = new AlertDialog.Builder(v.getContext());
CharSequence meni[] = new CharSequence[] {"DOING"};
adb.setItems(meni, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0) {
mValues.get(pos).setStanje("doing");
clickLinster_.onLongClick(mValues.get(pos).getId_(),mValues.get(pos).getStanje());
}
}
});
AlertDialog alertDialog = adb.create();
alertDialog.setCancelable(true);
alertDialog.show();
return true;
}
});
}

ListView OnItemClickListener not being triggered in bottom sheet

I have created a bottom sheet using the newly updated support library. Basically, whenever an item in my recyclerview is long-clicked, a bottom sheet is shown (containing a linearlayout which contains a listview). But whenever I tap the items in the listview nothing happens. I added toasts and it is never triggered when I tap on the sheet items. Any ideas? Thanks in advance!
Here is the listview initialization method:
public void initSheet() {
bottomSheet = findViewById(R.id.list_sheet);
ListAdapter adapter = new ListAdapter(this, R.layout.custom_sheet_row, getSheetInfo(), "Sheet");
list = (ListView) findViewById(R.id.list_sheet_list);
list.setAdapter(adapter);
behavior = BottomSheetBehavior.from(bottomSheet);
behavior.setHideable(true);
}
Here is the recyclerview long click:
#Override
public void onLongClick(View view, int position) {
final String itemText = ((TextView) view.findViewById(R.id.textRow)).getText().toString();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(ListActivity.this, "sdjakfjs", Toast.LENGTH_SHORT).show();
switch (position) {
case 0:
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(Intent.EXTRA_TEXT, itemText);
startActivity(Intent.createChooser(sharingIntent, "Share the item"));
break;
case 1:
final ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setPrimaryClip(ClipData.newPlainText("New", itemText));
break;
case 2:
editText(itemText, position);
break;
case 3:
listAdapter.deleteItem(position);
break;
}
behavior.setState(BottomSheetBehavior.STATE_HIDDEN);
}
});
behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
}
try this.
implement custom clicklistener it will work pefectly.
// creating interface to handle clicks for Recycler view items
public interface ClickListener
{
void onClick(View view,int position);
void onLongClick(View view,int position);
}
public static class CustomRecyclerTouchListener implements RecyclerView.OnItemTouchListener
{
private GestureDetector gestureDetector;
private MainActivity.ClickListener clickListener;
public CustomRecyclerTouchListener(Context context,final RecyclerView recyclerView,final MainActivity.ClickListener clickListener)
{
this.clickListener=clickListener;
gestureDetector=new GestureDetector(context,new GestureDetector.SimpleOnGestureListener()
{
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child=recyclerView.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clickListener !=null)
{
clickListener.onLongClick(child,recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
View child=recyclerView.findChildViewUnder(motionEvent.getX(),motionEvent.getY());
if(child!=null && clickListener!=null && gestureDetector.onTouchEvent(motionEvent))
{
clickListener.onClick(child,recyclerView.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean b) {
}
}
}
Then implement like this.
recyclerView.addOnItemTouchListener(new CustomRecyclerTouchListener(getApplicationContext(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
User user=users.get(position);
Toast.makeText(MainActivity.this,user.getName()+" is clicked",Toast.LENGTH_SHORT).show();
}
#Override
public void onLongClick(View view, int position) {
User user=users.get(position);
Toast.makeText(MainActivity.this,user.getName()+" is long clicked",Toast.LENGTH_SHORT).show();
}
}));
For more details refer here:- http://coderzpassion.com/android-working-with-recycler-view/
Ok, what I ended up doing was creating 4 textviews inside of the linear layout instead of using the listview. Then I just added an onclick listener for all of the textviews to do their respective commands

Categories

Resources