I'm trying to make a SingleChoiceItems AlertDialog with an OK and Cancel button which gives the user the option on a onItemLongClick from a ListView to 1.view the user's profile 2.send the user a message and 3.delete the user from the friends list.
I haven't done option 1 and 2 yet but I'm trying to make option 3 right now in which I included the Database delete method and a toast that says "friend removed" but when I select Option 3 and hit ok that row does not get deleted or I see the Toast saying the user was deleted.Here is my code for the Activity I'm using the Dialog.
public class PlayAFriend extends ListActivity {
DBAdapter DBAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list_items);
final DBAdapter db = new DBAdapter(this);
DBAdapter = db.open();
ListView FriendLV = (ListView) findViewById(android.R.id.list);
final Cursor friendslist = db.GetAllFriends();
String[] from = new String[] { "FRIENDS" }; // your column/columns here
int[] to = new int[] { R.id.textview_friends };
#SuppressWarnings("deprecation")
ListAdapter cursorAdapter = new SimpleCursorAdapter(this,
R.layout.list_items, friendslist, from, to, 0);
FriendLV.setAdapter(cursorAdapter);
FriendLV.setLongClickable(true);
FriendLV.setOnItemLongClickListener(new OnItemLongClickListener() {
class CustomCursorAdapter extends CursorAdapter {
public CustomCursorAdapter(Context context, Cursor c, int flags) {
super(context, friendslist, flags);
// TODO Auto-generated constructor stub
inflater = LayoutInflater.from(context);
}
LayoutInflater inflater;
#Override
public void bindView(View view, Context context,
Cursor friendslist) {
// TODO Auto-generated method stub
int row_id = ((com.fullfrontalgames.numberfighter.DBAdapter) friendslist)
.get("_id");
}
#Override
public View newView(Context context, Cursor friendslist,
ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.list_items, parent,
false);
bindView(v, context, friendslist);
return v;
}
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
showDialog(arg2);
return false;
}
});
}
public void OnButtonClick(View view) {
startActivity(new Intent(
"com.fullfrontalgames.numberfighter.Fightattacker"));
}
String[] items = { "View Profile", "Send Message", "Remove Friend" };
#Override
public Dialog onCreateDialog(final int id) {
final DBAdapter db = new DBAdapter(this);
db.open();
switch (id) {
case 0:
return new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("Select an Option")
.setSingleChoiceItems(items, id,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int choice) {
// TODO Auto-generated method stub
}
}
)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int choice) {
// TODO Auto-generated method stub
if (choice == 0) {
Toast.makeText(getBaseContext(),
"Test", Toast.LENGTH_SHORT)
.show();
} else if (choice == 1) {
Toast.makeText(getBaseContext(),
"Test2", Toast.LENGTH_SHORT)
.show();
} else if (choice == 2) {
Toast.makeText(getBaseContext(),
"Friend Removed",
Toast.LENGTH_SHORT).show();
final TextView friends = (TextView) findViewById(R.id.textview_friends);
String deletedfriend = friends
.getText().toString();
db.DeleteFriends(deletedfriend);
}
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int choice) {
}
})
.create();
}
return null;
}
#Override
protected void onDestroy() {
super.onDestroy();
// Clear the database
DBAdapter.close();
}
}
You have to save the choice when select a radio button, the other int parameter in the button does not represent the choice.
Make int mChoice; a class member
public class PlayAFriend extends ListActivity {
DBAdapter DBAdapter;
int mChoice;
......
......
#Override
public Dialog onCreateDialog(final int id) {
final DBAdapter db = new DBAdapter(this);
db.open();
switch (id) {
case 0:
return new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("Select an Option")
.setSingleChoiceItems(items, id,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int choice) {
mChoice = choice; // save the choice
}
}
)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int choice) {
// TODO Auto-generated method stub
if (mChoice == 0) {
Toast.makeText(getBaseContext(),
"Test", Toast.LENGTH_SHORT)
.show();
} else if (mChoice == 1) {
Toast.makeText(getBaseContext(),
"Test2", Toast.LENGTH_SHORT)
.show();
} else if (mChoice == 2) {
Toast.makeText(getBaseContext(),
"Friend Removed",
Toast.LENGTH_SHORT).show();
final TextView friends = (TextView) findViewById(R.id.textview_friends);
String deletedfriend = friends
.getText().toString();
db.DeleteFriends(deletedfriend);
}
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int choice) {
}
})
.create();
}
return null;
}
Related
i have some problems with updating fragment view after item deleted. So i have one fragment which one showing all items added from another activity. And when im trying to delete item it's not updating view so i should restart fragment to see updated fragment.
There is my fragment
public class MyGarageFragment extends Fragment {
FloatingActionButton fab;
RecyclerView mRecyclerView;
DatabaseHelper databaseHelper;
RVAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_my_garage, null);
mRecyclerView = v.findViewById(R.id.recyclerView);
databaseHelper = new DatabaseHelper(getContext());
showRecord();
fab = v.findViewById(R.id.addFabButton);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// startActivity(new Intent(getContext(), AddRecordActivity.class));
Intent intent = new Intent(getContext(), AddAutoActivity.class);
intent.putExtra("editMode",false);
startActivity(intent);
}
});
return v;
}
private void showRecord() {
adapter = new RVAdapter(getContext(),databaseHelper.getAllData(Constants.C_ADD_TIMESTAMP + " DESC"));
mRecyclerView.setAdapter(adapter);
}
#Override
public void onResume(){
super.onResume();
showRecord();
}
also my Recyclerview Adapter
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.Holder> {
private Context context;
private ArrayList<Model> arrayList;
DatabaseHelper databaseHelper;
#NonNull
#Override
public Holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_my_garage,parent,false);
return new Holder(view);
}
public RVAdapter(Context context, ArrayList<Model> arrayList) {
this.context = context;
this.arrayList = arrayList;
databaseHelper = new DatabaseHelper(context);
}
#Override
public void onBindViewHolder(#NonNull Holder holder, int position) {
Model model = arrayList.get(position);
String id = model.getId();
String image = model.getImage();
String name = model.getName();
String age = model.getAge();
String phone = model.getPhone();
String addTimeStamp = model.getAddTimeStamp();
String updateTimeStamp = model.getUpdateTimeStamp();
holder.profileIv.setImageURI(Uri.parse(image));
holder.name.setText(name);
holder.age.setText(age);
holder.phone.setText(phone);
holder.editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(context, holder.editButton);
popupMenu.inflate(R.menu.popup_menu);
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit:
editDialog(
""+position,
""+id,
""+name,
""+age,
""+phone,
""+image,
""+addTimeStamp,
""+updateTimeStamp
);
break;
case R.id.action_delete:
deleteDialog(""+id);
break;
default:
break;
}
return false;
}
});
popupMenu.show();
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,"item " + id, Toast.LENGTH_SHORT).show();
}
});
}
private void deleteDialog(String id) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Delete");
builder.setMessage("Are you sure?");
builder.setCancelable(false);
builder.setIcon(R.drawable.ic_baseline_delete_24);
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
databaseHelper.deleteInfo(id);
((MyGarageFragment)context).onResume();
Toast.makeText(context, "Delete Success!", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.create().show();
}
private void editDialog(String position, String id, String name, String age, String phone, String image, String addTimeStamp, String updateTimeStamp) {
Intent intent = new Intent(context, EditAutoActivity.class);
intent.putExtra("ID",id);
intent.putExtra("NAME",name);
intent.putExtra("AGE",age);
intent.putExtra("PHONE",phone);
intent.putExtra("IMAGE",image);
intent.putExtra("ADD_TIMESTAMP",addTimeStamp);
intent.putExtra("UPDATE_TIMESTAMP",updateTimeStamp);
intent.putExtra("editMode",true);
context.startActivity(intent);
}
#Override
public int getItemCount() {
return arrayList.size();
}
class Holder extends RecyclerView.ViewHolder {
ImageView profileIv;
TextView name,age,phone;
ImageView editButton;
public Holder (#NonNull View itemView){
super(itemView);
profileIv = itemView.findViewById(R.id.profileIv);
name = itemView.findViewById(R.id.name);
age = itemView.findViewById(R.id.age);
phone = itemView.findViewById(R.id.phone);
editButton = itemView.findViewById(R.id.editBtn);
}
}
}
so what should i do in deleteDialog to delete cardview item and refresh ui?
private void deleteDialog(String id) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Delete");
builder.setMessage("Are you sure?");
builder.setCancelable(false);
builder.setIcon(R.drawable.ic_baseline_delete_24);
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
databaseHelper.deleteInfo(id);
((MyGarageFragment)context).onResume();
Toast.makeText(context, "Delete Success!", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.create().show();
}
I'm making a todo app and when an item is marked as finished an image should be displayed in front of the list item. But images are not visible in the list view even if the item status in the database is changed as finished.
This is my adapter class.
public class ToDoAdapter extends ArrayAdapter {
private Context context;
private int resource;
List<ToDoModel> todos;
public ToDoAdapter(#NonNull Context context, int resource, #NonNull List<ToDoModel> objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
this.todos = objects;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
//Inflate card view
LayoutInflater inflater = LayoutInflater.from(context);
View row = inflater.inflate(resource, parent, false);
TextView title = row.findViewById(R.id.title);
TextView description = row.findViewById(R.id.txtDescription);
ImageView img = (ImageView)row.findViewById(R.id.img_done);
img.setVisibility(View.VISIBLE);
//Set data in card view
ToDoModel todo = todos.get(position);
title.setText(todo.getTitle());
description.setText(todo.getDescription());
//Show done image
if(todo.getFinished() > 0){
img.setVisibility(View.VISIBLE);
}
return row;
}
}
This is MainActivity.
public class MainActivity extends AppCompatActivity {
private ListView todoList;
private TextView countTxt;
private Button addTodo;
private List<ToDoModel> toDos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
todoList = (ListView)findViewById(R.id.listViewToDo);
countTxt = (TextView)findViewById(R.id.txtCount);
addTodo = (Button)findViewById(R.id.btnAdd);
toDos = new ArrayList<>();
addTodo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Go to next activity
startActivity(new Intent(getApplicationContext(), AddToDO.class));
}
});
}
#Override
protected void onResume() {
super.onResume();
DBHandler dbh = new DBHandler(getApplicationContext());
//Set count
int count = dbh.getCountTODO();
countTxt.setText("You have " + count + " TODOs");
//Save list
toDos = dbh.getAllToDos();
//Set adapter to list
ToDoAdapter toDoAdapter = new ToDoAdapter(getApplicationContext(), R.layout.todo_cardview, toDos);
todoList.setAdapter(toDoAdapter);
//Add click listener to list element
todoList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Get clicked item
ToDoModel todo = toDos.get(position);
//Dialog box
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(todo.getTitle());
builder.setMessage(todo.getDescription());
//Buttons
builder.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dbh.deleteItem(todo.getId());
Toast.makeText(getApplicationContext(), "ToDo Deleted", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
builder.setPositiveButton("Finished", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
long time = System.currentTimeMillis();
//Update status
dbh.updateFinished(todo.getId(), time);
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
builder.setNeutralButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MainActivity.this, AddToDO.class);
intent.putExtra("id", todo.getId());
intent.putExtra("title", todo.getTitle());
intent.putExtra("description", todo.getDescription());
intent.putExtra("finished", todo.getFinished());
startActivity(intent);
}
});
builder.show();
}
});
}
}
Use Glide or Picasso Library to Displaying Image with any other Shape.
Glide Example:
Glide.with(mContext).load(responseList.getLogoUrl()).apply(RequestOptions.circleCropTransform()).into(holder.imageName);
Picasso Example:
Picasso.get().load(clsobjname.getLogoUrl())
.into(viewHolder.imagename);
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;
}
});
}
I have a listview implemented with its choice mode set to CHOICE_MODE_MULTIPLE_MODAL. Here is some of the code:
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
private int check = 0;
#Override
public boolean onPrepareActionMode(ActionMode arg0, Menu arg1) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onDestroyActionMode(ActionMode arg0) {
// TODO Auto-generated method stub
adapter.clearSelection();
}
#Override
public boolean onCreateActionMode(ActionMode arg0, Menu arg1) {
// TODO Auto-generated method stub
check = 0;
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, arg1);
return true;
}
#Override
public boolean onActionItemClicked(final ActionMode arg0,
MenuItem arg1) {
// TODO Auto-generated method stub
if ((PinPad.mMediaPlayer != null)
&& (!PinPad.mMediaPlayer.isPlaying())) {
switch (arg1.getItemId()) {
case R.id.item_delete:
LayoutInflater inflater = getLayoutInflater();
View dialogLayout = inflater.inflate(
R.layout.delete_confirmation, null);
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainListActivity.this);
alertDialogBuilder.setView(dialogLayout);
final AlertDialog confirmationDialog = alertDialogBuilder
.create();
confirmationDialog.show();
Button buttonNo = (Button) dialogLayout
.findViewById(R.id.buttonNo);
Button buttonYes = (Button) dialogLayout
.findViewById(R.id.buttonYes);
buttonNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
weGotTheTime.clear();
weGotTheType.clear();
weGotTheDays.clear();
weGotTheRings.clear();
weGotTheIDs.clear();
confirmationDialog.dismiss();
adapter.clearSelection();
adapter.notifyDataSetChanged();
refreshListView();
check = 0;
arg0.finish();
}
});
buttonYes
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
databaseData.open();
databaseData.deleteEntries(
weGotTheTime, weGotTheType,
weGotTheDays);
databaseData.close();
new AlarmTask(MainListActivity.this,
weGotTheIDs, weGotTheDays,
weGotTheRings, weGotTheType,
weGotTheTime).cancelAl();
weGotTheTime.clear();
weGotTheType.clear();
weGotTheDays.clear();
weGotTheRings.clear();
weGotTheIDs.clear();
confirmationDialog.dismiss();
adapter.clearSelection();
adapter.notifyDataSetChanged();
refreshListView();
check = 0;
arg0.finish();
}
});
break;
}
return true;
} else if (PinPad.mMediaPlayer == null) {
switch (arg1.getItemId()) {
case R.id.item_delete:
LayoutInflater inflater = getLayoutInflater();
View dialogLayout = inflater.inflate(
R.layout.delete_confirmation, null);
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainListActivity.this);
alertDialogBuilder.setView(dialogLayout);
final AlertDialog confirmationDialog = alertDialogBuilder
.create();
confirmationDialog.show();
Button buttonNo = (Button) dialogLayout
.findViewById(R.id.buttonNo);
Button buttonYes = (Button) dialogLayout
.findViewById(R.id.buttonYes);
buttonNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
weGotTheTime.clear();
weGotTheType.clear();
weGotTheDays.clear();
weGotTheRings.clear();
weGotTheIDs.clear();
confirmationDialog.dismiss();
adapter.clearSelection();
adapter.notifyDataSetChanged();
refreshListView();
check = 0;
arg0.finish();
}
});
buttonYes
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
databaseData.open();
databaseData.deleteEntries(
weGotTheTime, weGotTheType,
weGotTheDays);
databaseData.close();
new AlarmTask(MainListActivity.this,
weGotTheIDs, weGotTheDays,
weGotTheRings, weGotTheType,
weGotTheTime).cancelAl();
weGotTheTime.clear();
weGotTheType.clear();
weGotTheDays.clear();
weGotTheRings.clear();
weGotTheIDs.clear();
confirmationDialog.dismiss();
adapter.clearSelection();
adapter.notifyDataSetChanged();
refreshListView();
check = 0;
arg0.finish();
}
});
break;
}
return true;
} else {
Toast.makeText(
getApplicationContext(),
"Cannot delete alarm(s). Make sure no alarm is currently ringing.",
Toast.LENGTH_SHORT).show();
adapter.clearSelection();
check = 0;
arg0.finish();
return true;
}
}
#Override
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked) {
// TODO Auto-generated method stub
td = results.get(position).getDays();
if (checked) {
check++;
adapter.setNewSelection(position, checked);
weGotTheTime.add(results.get(position).getTime());
weGotTheType.add(results.get(position).getType());
weGotTheDays.add(results.get(position).getDays());
weGotTheIDs.add(results.get(position).getID());
weGotTheRings.add(results.get(position).getTitle());
} else {
check--;
adapter.removeSelection(position);
weGotTheTime.remove(results.get(position).getTime());
weGotTheType.remove(results.get(position).getType());
weGotTheDays.remove(results.get(position).getDays());
weGotTheIDs.remove(results.get(position).getID());
weGotTheRings.remove(results.get(position).getTitle());
}
mode.setTitle(check + " selected");
}
});
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
listView.setItemChecked(arg2, !adapter.isPositionChecked(arg2));
vibrator.vibrate(50);
return false;
}
});
This works great, long clicking a listview item highlights it and it works fine. However, once I change the device orientation from portrait to landscape and vice versa, the highlighting is gone and the Contextual Action Bar is still showing however it doesn't show anything is selected. Any help? I've tried making selectors and drawables and manually doing it that way and still no luck. I've spent weeks on this one issue and I'm wondering if somebody out there knows how to solve it.
Thanks.
See if you can using this helps:
android:configChanges="orientation|keyboardHidden"
For more info on complete implementation refer this:
http://developer.android.com/guide/topics/resources/runtime-changes.html
I'm trying to show a menu once the user longclick an entry in my ListActivity but I cant figure it out. Unfourtenatly lists have been always a hard nut for me to crack and I'm still learning.
package android.GUI;
public class Shifts extends ListActivity implements OnClickListener,
SimpleGestureListener {
private Typeface tf = Entry.tf, tf2 = Entry.tf2;
public static int count = 1;
int dbHourTime = 0;
private SimpleGestureFilter detector;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.shifts);
detector = new SimpleGestureFilter(this, this);
DBAdapter DB = new DBAdapter(this);
DB.open();
Cursor cursor = DB.getAllShifts();
startManagingCursor(cursor);
cursor.moveToLast();
count = cursor.getPosition();
int g = count;
cursor.moveToNext();
String[] columns = new String[] { DB.KEY_DATE, DB.KEY_HOURS,
DB.KEY_DAY, DB.KEY_ROWID, DB.KEY_START, DB.KEY_END };
int[] to = new int[] { R.id.dateDisp, R.id.shiftDisp, R.id.day,
R.id.rawId, R.id.start, R.id.finish };
ListView ls = getListView();
TextView SF = (TextView) findViewById(R.id.total);
SF.setTypeface(tf);
TextView sum = (TextView)findViewById(R.id.sum);
sum.setTypeface(tf);
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
R.layout.list_entry, cursor, columns, to);
this.setListAdapter(mAdapter);
}
#Override
protected void onListItemClick(ListView ls, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(ls, v, position, id);
CharSequence text = "Clicked";
final int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(this, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER, 0, 0);
toast.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.view_shifts_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.back:
finish();
return true;
case R.id.clear:
DBAdapter DB = new DBAdapter(this);
DB.open();
DB.deleteAll();
startActivity(getIntent());
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
public void onSwipe(int direction) {
Intent intent = new Intent();
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT:
intent.setClass(this, Main.class);
startActivity(intent);
break;
case SimpleGestureFilter.SWIPE_LEFT:
intent.setClass(this, Entry.class);
startActivity(intent);
break;
case SimpleGestureFilter.SWIPE_DOWN:
break;
case SimpleGestureFilter.SWIPE_UP:
break;
}
}
#Override
public boolean dispatchTouchEvent(MotionEvent me) {
this.detector.onTouchEvent(me);
return super.dispatchTouchEvent(me);
}
#Override
public void onDoubleTap() {
// TODO Auto-generated method stub
}
#Override
public void onListItemClick(ListActivity l, View v, int position, long id) {
// TODO Auto-generated method stub
}
}
This needs to be outside of your onCreate():
#Override // the error is with this method decleration
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(ls, v, position, id);
}
You're creating the onListItemClick method inside the onCreate method. Move it outside the onCreate method :)