onLongClick show menu options - android

Its my first time here, I'm looking the answer for this question for 2 days and nothing works.
Here is, I want to show the MenuOptions (edit,delete) when users hold the selected item, long press.
My code:
public class ProjetoProTelefoneActivity extends ListActivity {
public final static String ID_EXTRA = "br.com.DaniloDeLuca.ProjetoProTelefone._ID";
Cursor modelo = null;
RestaurantAdapter adapter = null;
RestauranteHelper helper=null;
SharedPreferences prefs=null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
helper = new RestauranteHelper(this);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
initList();
prefs.registerOnSharedPreferenceChangeListener(prefListener);
}
public void onDestroy(){
super.onDestroy();
helper.close();
}
public void onListItemClick(ListView list, View view,
int position,long id){
Intent i=new Intent(ProjetoProTelefoneActivity.this, DetailForm.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
}
public void onListItemLongClic( View view,int position,Menu menu){
new MenuInflater(this).inflate(R.menu.option,menu);
super.onCreateOptionsMenu(menu);
}
//hook into menu button for activity
public boolean onCreateOptionsMenu(Menu menu){
new MenuInflater(this).inflate(R.menu.option,menu);
return(super.onCreateOptionsMenu(menu));
}
/// when menu button option selected
public boolean onOptionsItemSelected(MenuItem item){
if(item.getItemId()==R.id.add){
startActivity(new Intent(ProjetoProTelefoneActivity.this, DetailForm.class));
return(true);
}
else if(item.getItemId()==R.id.prefs){
startActivity(new Intent(this, EditPreferences.class));
return(true);
}
return(super.onOptionsItemSelected(item));
}
private SharedPreferences.OnSharedPreferenceChangeListener prefListener=
new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if(key.equals("sort_order")){
initList();
}
}
};
private void initList(){
if(modelo!=null){
stopManagingCursor(modelo);
modelo.close();
}
modelo =helper.getAll(prefs.getString("sort_order","nome DESC"));
startManagingCursor(modelo);
adapter = new RestaurantAdapter(modelo);
setListAdapter(adapter);
}
class RestaurantAdapter extends CursorAdapter {
RestaurantAdapter(Cursor c) {
super(ProjetoProTelefoneActivity.this, c);
}
public void bindView(View row, Context ctxt,
Cursor c) {
RestaurantHolder holder=(RestaurantHolder)row.getTag();
holder.populateFrom(c, helper);
}
public View newView(Context ctxt, Cursor c,
ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.row, parent, false);
RestaurantHolder holder=new RestaurantHolder(row);
row.setTag(holder);
return(row);
}
}
static class RestaurantHolder {
private TextView name=null;
private TextView address=null;
private ImageView icon=null;
RestaurantHolder(View row) {
name=(TextView)row.findViewById(R.id.title);
address=(TextView)row.findViewById(R.id.address);
icon=(ImageView)row.findViewById(R.id.icon);
}
void populateFrom(Cursor r,RestauranteHelper helper) {
name.setText(helper.getNome(r));
address.setText(helper.getEnd(r));
if (helper.getTipo(r).equals("casa")) {
icon.setImageResource(R.drawable.casa_icon);
}
else if (helper.getTipo(r).equals("apartamento")) {
icon.setImageResource(R.drawable.apartamento_icon);
}
else {
icon.setImageResource(R.drawable.comercio_ico);
}
}
}
}
Thats work only when I choose the MenuButton. but I want to make the "MenuButton" activity to be the LongPress action, I dont know if its clear.

What you want is to registerForContextMenu, that is register your ListView against the Activity so that on a long press on it a new menu will be created and shown to the user. See
http://developer.android.com/reference/android/app/Activity.html#registerForContextMenu%28android.view.View%29

Related

Context menu android on Listview item with CustomAdapter doesn't show

I'm quite new at Android developing and I was trying to put a a context menu on my Listview that uses a CursorAdapter, I followed this examples https://www.youtube.com/watch?v=Pq9YQl0nfEk Using contextmenu with listview in android but the menu doesn't appear and I don't no why, appearently everything's OK.
These is the code of my activity
public class ProductsView extends AppCompatActivity {
private FloatingActionButton botonAnadir;
private ListView lvProducts;
SetOfProductList mylist;
private ProductAdapter productAdapter;
Cursor cursor;
private ProductList productList;
private Long idProductList;
private DBManager dbManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
if (bundle != null){
productList = bundle.getParcelable("productList");
setTitle(getResources().getString(R.string.show_products) + " " + productList.getName());
}
setContentView(R.layout.products_view);
initialize();
}
private void initialize(){
botonAnadir = (FloatingActionButton)findViewById(R.id.button_add_product);
lvProducts = (ListView)findViewById(R.id.listViewProducts);
dbManager = new DBManager(getApplicationContext());
loadProducts();
registerForContextMenu(lvProducts);
botonAnadir.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
creaNuevaLista();
}
});
lvProducts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Product aux = getProduct(position);
goToNewProduct(aux);
}
});
lvProducts.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// markAsPurchased(position);
return true;
}
});
}
private void markAsPurchased(int position){
Product p = getProduct(position);
TextView item = (TextView) findViewById(R.id.textview_product_name);
if (p.getPurchased() == 0){
p.setPurchased(1); //mark as a purchased
item.setPaintFlags(item.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
else{
p.setPurchased(0); //mark as a purchased
item.setPaintFlags(item.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
}
editProduct(p); //makes de update
loadProducts();
}
private void editProduct(Product product){
dbManager.updateProduct(product);
}
private void goToNewProduct(Product p){
Intent intent = new Intent(this,NewProductActivity.class);
Bundle b = new Bundle();
b.putBoolean("editMode",true);
b.putParcelable("product", p);
intent.putExtras(b);
startActivity(intent);
}
private void creaNuevaLista(){
Intent i = new Intent(this,NewProductActivity.class);
Bundle b = new Bundle();
b.putParcelable("productList", productList);
i.putExtras(b);
startActivityForResult(i, 0);
}
private void loadProducts(){
cursor = dbManager.getAllProductsWithCursor(productList);
productAdapter = new ProductAdapter(this,cursor);
lvProducts.setAdapter(productAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId() == R.id.listViewProducts){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.prodcut_view_context_menu,menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()){
case R.id.delete_id:
return true;
default:
return super.onContextItemSelected(item);
}
}
}
And this is the adapter that I'm using
public class ProductAdapter extends CursorAdapter {
private LayoutInflater inflater;
//Constructor
public ProductAdapter(Context context, Cursor cursor) {
super(context, cursor,false);
}
// The newView method is used to inflate a new view and return it,
// you don't bind any data to the view at this point.
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.layout_product_row,parent,false);
return view;
}
// The bindView method is used to bind all data to a given view
// such as setting the text on a TextView.
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView tv_product_name = (TextView) view.findViewById(R.id.textview_product_name); // Find fields to populate in inflated template
String product_name = cursor.getString(cursor.getColumnIndexOrThrow("name"));// Extract properties from cursor
// Populate fields with extracted properties
tv_product_name.setText(product_name);
if (cursor.getInt(cursor.getColumnIndexOrThrow("purchased")) == 1){
tv_product_name.setPaintFlags(tv_product_name.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
}
public Product getProduct(int position, Cursor cursor) {
Product p=null;
if(cursor.moveToPosition(position)) {
Log.e("PRODUCTLISTADAPTER","nombre es: "+cursor.getString(cursor.getColumnIndex("name")));
p = new Product (cursor.getLong(cursor.getColumnIndex("_id")),cursor.getString(cursor.getColumnIndex("name")),
cursor.getString(cursor.getColumnIndex("unit_type")),cursor.getDouble(cursor.getColumnIndex("value")),cursor.getInt(cursor.getColumnIndex("purchased")),cursor.getLong(cursor.getColumnIndex("id_pl")));
}
return p;
}
}
Can anyone exaplin me why it isn't working? isn't it necessary to make something on the LongClickListener ? because I don't see that the menu is being created.
Thanks in advance.
You've set an OnItemLongClickListener for the ListView, which will run before the context Menu is created. Returning true from its onItemLongClick() method indicates that the long click is being consumed there, so the Menu will not be created.
If you don't actually need the OnItemLongClickListener, you can remove the relevant code. If you do need it as well, for some reason, you can return false from onItemLongClick(), and your Menu will then show.

My filter for the listview suddenly stopped working, and I don't know why

I've made an Edittext with a listview, and a filter, that worked smoothly, but suddenly it stopped working. I've searched for a solution both on Google and Stackoverflow, but the code should be correct. I get the list content from an Arraylist ´then I put in a Customlistadapter which I put in a Listview. Then in onTextChanged I filter the list with the input from the edittext, but when I something in the edittext, the list becomes empty, and when I don't anything there is something, why does this happen?
public class Sogeresultater extends AppCompatActivity implements Liste{
CustomListAdapter listAdapter;
EditText filterText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
ArrayList<Annonce> søgeresultater = (ArrayList<Annonce>) getIntent().getExtras().getSerializable("søg");
filterText = (EditText)findViewById(R.id.password);
ListView itemList = (ListView)findViewById(R.id.listView);
listAdapter = new CustomListAdapter (this, søgeresultater);
itemList.setAdapter(listAdapter);
itemList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent intent = new Intent(Sogeresultater.this, AnnonceDisplay.class);
intent.putExtra("annonce", (Serializable) adapterView.getItemAtPosition(position));
startActivity(intent);
}
});
filterText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Sogeresultater.this.listAdapter.getFilter().filter(s);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.Forside) {
Intent intent = new Intent(this, Forside.class);
startActivity(intent);
}
else if (id == R.id.Logud){
Intent intent = new Intent(this, LogInd.class);
startActivity(intent);
}
return true;
}
}
Customlistadapter:
public class CustomListAdapter extends ArrayAdapter<Annonce>{
private final Activity context;
LayoutInflater inflater;
public CustomListAdapter(Activity context, ArrayList<Annonce> annoncer) {
super(context, R.layout.mylist, annoncer);
this.context=context;
}
public View getView(int position,View view,ViewGroup parent) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null) view = inflater.inflate(R.layout.mylist, null);
TextView txtTitle = (TextView) view.findViewById(R.id.item);
ImageView imageView = (ImageView) view.findViewById(R.id.icon);
TextView extratxt = (TextView) view.findViewById(R.id.textView1);
Annonce currentItem = getItem(position);
txtTitle.setText(currentItem.getItemname());
imageView.setImageResource(currentItem.getImgid());
extratxt.setText(currentItem.getDescription());
return view;
}
}

ListView does not load data from Curstom array adapter situated in separate java file

I made two activities, one for listing the data and second activity is form for entering the data. For this, I used List and custom ArrayAdapter as I did it when putting the two displays in same activity. When the two displays are in same window, there is no problem. After I separated activities, I put the List and custom ArrayAdapter in separate java file so that I can access them from 2 activities.
I saved the data by calling static function
"addRestaurant(Restaurant r)"
from DetailForm.java. Custom Adapter RestaurantAdapter is made static so that it can fit in addRestaurant(Restaurant).After doing this, the data is saved but the ListView does not display them. Can any one help me here ?
/*************************MainActivity.java **************************/
public class MainActivity extends ActionBarActivity {
public final static String ID_EXTRA="apt.tutorial._ID";
RestaurantList restaurantlist = null;
ListView list = null;
#Override protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
restaurantlist = new RestaurantList(MainActivity.this);
list = (ListView) findViewById(R.id.list);
restaurantlist.setlistadapter(list);
}
#Override public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override public boolean onOptionsItemSelected(MenuItem item){
if (item.getItemId() == R.id.option) {
Intent intent = new Intent(MainActivity.this, DetailForm.class);
startActivity(intent);
return (true);
}
return true;
}
}
/*******************************DetailForm.Java ********************/
public class DetailForm extends ActionBarActivity {
EditText name=null;
EditText address=null;
EditText notes=null;
RadioGroup types=null;
String restaurantId=null;
Restaurant current = null;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_form);
name=(EditText)findViewById(R.id.name);
address=(EditText)findViewById(R.id.addr);
notes=(EditText)findViewById(R.id.notes);
types=(RadioGroup)findViewById(R.id.types);
Button save=(Button)findViewById(R.id.save);
save.setOnClickListener(onSave);
restaurantId = getIntent().getStringExtra(MainActivity.ID_EXTRA);
}
public View.OnClickListener onSave=new View.OnClickListener(){
public void onClick(View v) {
String type=null;
current = new Restaurant();
String newname = name.getText().toString();
String newaddr = address.getText().toString();
current.setName(newname);
current.setAddress(newaddr);
current.setNotes(notes.getText().toString());
switch (types.getCheckedRadioButtonId()) {
case R.id.sit_down:
current.setType("sit_down");
break;
case R.id.take_out:
current.setType("take_out");
break;
case R.id.delivery:
current.setType("delivery");
break;
}
RestaurantList.addRestaurant(current); //adapter.add(current); // add values
name.setText("");
address.setText("");
notes.setText("");
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_LONG).show();
}
};
#Override public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option, menu);
return true;
}
#Override public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.ViewList) {
Intent intent = new Intent(DetailForm.this, MainActivity.class);
startActivity(intent);
return (true);
}
return true;
}
}
/*************************RestaurantList.java ***********************/
public class RestaurantList {
List<Restaurant> model;
static RestaurantAdapter adapter;
public RestaurantList(Context context) {
model = new ArrayList<Restaurant>();
adapter = new RestaurantAdapter(context);
}
public void setlistadapter(ListView listview){
listview.setAdapter(adapter);
}
public static void addRestaurant(Restaurant r){
adapter.add(r);
}
public class RestaurantAdapter extends ArrayAdapter<Restaurant> {
Context mycontext;
RestaurantAdapter(Context context){
super(context, R.layout.row, model);
mycontext = context;
}
#Override public View getView(int position, View convertView, ViewGroup parent){
View row = convertView;
RestaurantHolder holder = null;
if (row == null){
LayoutInflater inflater = ((Activity)mycontext).getLayoutInflater();
row = inflater.inflate(R.layout.row, parent, false);
holder = new RestaurantHolder(row);
row.setTag(holder);
} else {
holder = (RestaurantHolder)row.getTag();
}
holder.populateFrom(model.get(position));
return (row);
}
}
public static class RestaurantHolder{
private TextView name=null;
private TextView address=null;
private ImageView icon=null;
RestaurantHolder(View row) {
name=(TextView)row.findViewById(R.id.title);
address=(TextView)row.findViewById(R.id.address);
icon=(ImageView)row.findViewById(R.id.icon);
}
void populateFrom(Restaurant r){
name.setText(r.getName());
address.setText(r.getAddress());
if (r.getType().equals("sit_down")) {
icon.setImageResource(R.drawable.ball_red);
}
else if (r.getType().equals("take_out")) {
icon.setImageResource(R.drawable.ball_yellow);
}
else {
icon.setImageResource(R.drawable.ball_green);
}
}
}
}
List<Restaurant> modelis always empty that is why you are not able to see the listView
public class DetailForm extends AppCompatActivity implements View.OnClickListener {
EditText etName;
EditText etAddress;
EditText etNote;
Button save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etName= (EditText) findViewById(R.id.name);
etAddress= (EditText) findViewById(R.id.address);
etNote = (EditText) findViewById(R.id.place);
save= (Button) findViewById(R.id.save);
save.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String name =etName.getText().toString();
String address=etName.getText().toString();
String notes= etNote.getText().toString();
Restaurant restaurant=new Restaurant(name,address,notes);
RestaurantList.addRestaurant(restaurant);
Intent intent=new Intent(this, ListingActivity.class);
startActivity(intent);
}
}
Listing Activity
public class ListingActivity extends AppCompatActivity{
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
listView= (ListView) findViewById(R.id.listView);
listView.setAdapter(new RestaurantAdapter(this,RestaurantList.getRestaurentsList()));
}
}
Restaurant
public class Restaurant {
String name;
String address;
String notes;
public Restaurant(String name, String address, String notes) {
this.name = name;
this.address = address;
this.notes = notes;
}
}
RestaurantAdapter
public class RestaurantAdapter extends ArrayAdapter {
List<Restaurant> mRestaurants;
private LayoutInflater mLayoutInflater;
public RestaurantAdapter(Context context, List restorentsList) {
super(context, R.layout.row, restorentsList);
mRestaurants = restorentsList;
mLayoutInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
RestaurantHolder holder = new RestaurantHolder();
if (convertView == null) {
convertView = mLayoutInflater.inflate(R.layout.row, parent, false);
holder.name= (TextView) convertView.findViewById(R.id.name);
holder.address= (TextView) convertView.findViewById(R.id.address);
holder.note= (TextView) convertView.findViewById(R.id.note);
convertView.setTag(holder);
} else {
holder = (RestaurantHolder) convertView.getTag();
}
final Restaurant restaurant = mRestaurants.get(position);
holder.name.setText(restaurant.name);
holder.address.setText(restaurant.address);
holder.note.setText(restaurant.notes);
return (convertView);
}
public static class RestaurantHolder {
private TextView name;
private TextView address;
private TextView note;
}
}
RestaurantList
public class RestaurantList {
private static List<Restaurant> restaurants=new ArrayList<>();
public static void addRestaurant(Restaurant restaurant) {
restaurants.add(restaurant);
}
public static List<Restaurant> getRestaurentsList()
{
return restaurants;
}
}
I have provided the snippens for all the operations hope this helps
The problem is you start a "new MainActivity" when you click on ViewList in your menu instead of back to the "original MainActivity" (if don't get it, press back button after Saved :) ). If you really want to make the least changes to see the result, change your onOptionsItemSelected() in DetailForm:
#Override public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.ViewList) {
finish();
}
return true;
}

How to refresh view after updating sql row while using OnItemLongClick?

The problem is as follows: When I click on the row, dialog opens where I enter new row value and click ok to save changes. The row is updated, but I need to exit view and go back again to see changes. How can I refresh view automatically when the sava button is clicked?
Here is my code for Dialog:
class EditListItemDialog extends Dialog implements View.OnClickListener {
MyDB dba;
private View editText;
private DiaryAdapter adapter;
private SQLiteDatabase db;
public EditListItemDialog(Context context) {
super(context);
dba = new MyDB(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
dba.open();
}
private List<String> fragment_monday;
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Position is the number of the item clicked
//You can use your adapter to modify the item
adapter.getItem(position); //Will return the clicked item
}
public EditListItemDialog(Context context, DiaryAdapter adapter, int position) {
super(context);
this.fragment_monday = new ArrayList<String>();
this.adapter = adapter;
dba = new MyDB(context);
}
#Override
public void onClick(View v) {
fragment_monday.add(((TextView) v).getText().toString());//here is your updated(or not updated) text
dismiss();
try {
saveItToDB();
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveItToDB() {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), 2);
dba.close();
((TextView) editText).setText("");
}
}
And here is the code where I want to refresh view instead of doing it manually:
public class Monday extends ListActivity {
private SQLiteDatabase db;
private static final int MyMenu = 0;
MyDB dba;
DiaryAdapter myAdapter;
private class MyDiary{
public MyDiary(String t, String c){
title=t;
content=c;
}
public String title;
public String content;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
dba = new MyDB(this);
dba.open();
setContentView(R.layout.fragment_monday);
super.onCreate(savedInstanceState);
myAdapter = new DiaryAdapter(this);
this.setListAdapter(myAdapter);
}
public class DiaryAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<MyDiary> fragment_monday;
public DiaryAdapter(Context context) {
mInflater = LayoutInflater.from(context);
fragment_monday = new ArrayList<MyDiary>();
getdata();
ListView list = getListView();
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(Monday.this, null, position).show();
return true;
}
});
}
public void getdata(){
Cursor c = dba.getdiaries();
startManagingCursor(c);
if(c.moveToFirst()){
do{
String title =
c.getString(c.getColumnIndex(Constants.TITLE_NAME));
String content =
c.getString(c.getColumnIndex(Constants.CONTENT_NAME));
MyDiary temp = new MyDiary(title,content);
fragment_monday.add(temp);
} while(c.moveToNext());
}
}
#Override
public int getCount() {return fragment_monday.size();}
public MyDiary getItem(int i) {return fragment_monday.get(i);}
public long getItemId(int i) {return i;}
public View getView(int arg0, View arg1, ViewGroup arg2) {
final ViewHolder holder;
View v = arg1;
if ((v == null) || (v.getTag() == null)) {
v = mInflater.inflate(R.layout.diaryrow, null);
holder = new ViewHolder();
holder.mTitle = (TextView)v.findViewById(R.id.name);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.mdiary = getItem(arg0);
holder.mTitle.setText(holder.mdiary.title);
v.setTag(holder);
return v;
}
public class ViewHolder {
MyDiary mdiary;
TextView mTitle;
}
}
/** Called when the user clicks the Edit button */
public void visitDiary(View view) {
Intent intent = new Intent(this, Diary.class);
startActivity(intent);
}
/** Called when the user clicks the back button */
public void visitSchedule(View view) {
Intent intent = new Intent(this, DisplayScheduleScreen.class);
startActivity(intent);
}
}
I hope it's clear enough what I am looking for. Where my list is, I want the list to be refreshed automatically after updating row so the new content of the row shows up immediately instead of navigating to other view and going back. I will be appreciated for your help.
At some point, after you call EditListItemDialog and it finishes, you need to run NotifyDataSetChanged() on your listview adapter. onResume() is a good place to do it,

Activity finish() refresh the ListActiviyt

i want to refresh/update afeter i select the "delete" ContextItem, it deletes but dont "refresh" the listview
see on code ListActivity:
public class ProjetoProTelefoneActivity extends ListActivity {
public final static String ID_EXTRA = "br.com.DaniloDeLuca.ProjetoProTelefone._ID";
Cursor modelo = null;
RestaurantAdapter adapter = null;
RestauranteHelper helper=null;
SharedPreferences prefs=null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
helper = new RestauranteHelper(this);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
initList();
prefs.registerOnSharedPreferenceChangeListener(prefListener);
registerForContextMenu(getListView());
}
public void onDestroy(){
super.onDestroy();
helper.close();
}
//*********************************************************************************************************************************
// Long Press menu
//*********************************************************************************************************************************
public void onCreateContextMenu(ContextMenu menu,View v,ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo info;
try {
info = (AdapterView.AdapterContextMenuInfo) menuInfo;
} catch (ClassCastException e) {
return;
}
Cursor cursor = (Cursor) getListAdapter().getItem(info.position);
if (cursor == null) {
return;
}
new MenuInflater(this).inflate(R.menu.option_item,menu);
super.onCreateContextMenu(menu,v,menuInfo);
}
public boolean onContextItemSelected(MenuItem item)
{
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
int index = info.position;
View view = info.targetView;
long id = info.id;
if(item.getItemId()==R.id.edit){
Intent i=new Intent(ProjetoProTelefoneActivity.this, DetailForm.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
return(true);
}
else if(item.getItemId()==R.id.remove){
Intent i=new Intent(ProjetoProTelefoneActivity.this, DeleteItemList.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
return(true);
}
return super.onContextItemSelected(item);
}
//*********************************************************************************************************************************
// Fim Long Press menu
//*********************************************************************************************************************************
public void onListItemClick(ListView list, View view,
int position,long id){
Intent i=new Intent(ProjetoProTelefoneActivity.this, DetailForm.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
}
//hook into menu button for activity
public boolean onCreateOptionsMenu(Menu menu){
new MenuInflater(this).inflate(R.menu.option,menu);
return(super.onCreateOptionsMenu(menu));
}
/// when menu button option selected
public boolean onOptionsItemSelected(MenuItem item){
if(item.getItemId()==R.id.add){
startActivity(new Intent(ProjetoProTelefoneActivity.this, DetailForm.class));
return(true);
}
else if(item.getItemId()==R.id.prefs){
startActivity(new Intent(this, EditPreferences.class));
return(true);
}
return(super.onOptionsItemSelected(item));
}
private SharedPreferences.OnSharedPreferenceChangeListener prefListener=
new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if(key.equals("sort_order")){
initList();
}
}
};
private void initList(){
if(modelo!=null){
stopManagingCursor(modelo);
modelo.close();
}
modelo =helper.getAll(prefs.getString("sort_order","nome DESC"));
startManagingCursor(modelo);
adapter = new RestaurantAdapter(modelo);
setListAdapter(adapter);
}
class RestaurantAdapter extends CursorAdapter {
RestaurantAdapter(Cursor c) {
super(ProjetoProTelefoneActivity.this, c);
}
public void bindView(View row, Context ctxt,
Cursor c) {
RestaurantHolder holder=(RestaurantHolder)row.getTag();
holder.populateFrom(c, helper);
}
public View newView(Context ctxt, Cursor c,
ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.row, parent, false);
RestaurantHolder holder=new RestaurantHolder(row);
row.setTag(holder);
return(row);
}
}
static class RestaurantHolder {
private TextView name=null;
private TextView address=null;
private ImageView icon=null;
RestaurantHolder(View row) {
name=(TextView)row.findViewById(R.id.title);
address=(TextView)row.findViewById(R.id.address);
icon=(ImageView)row.findViewById(R.id.icon);
}
void populateFrom(Cursor r,RestauranteHelper helper) {
name.setText(helper.getNome(r));
address.setText(helper.getEnd(r));
if (helper.getTipo(r).equals("casa")) {
icon.setImageResource(R.drawable.casa_icon);
}
else if (helper.getTipo(r).equals("apartamento")) {
icon.setImageResource(R.drawable.apartamento_icon);
}
else {
icon.setImageResource(R.drawable.comercio_ico);
}
}
}
}
Now my DeleteItemList:
public class DeleteItemList extends Activity{
RestauranteHelper helper = null;
String restauranteId= null;
public void onCreate(Bundle savedInstaceState){
super.onCreate(savedInstaceState);
helper= new RestauranteHelper(this);
restauranteId=getIntent().getStringExtra(ProjetoProTelefoneActivity.ID_EXTRA);
helper.delete(restauranteId);
finish();
}
public void onDestroy(){
super.onDestroy();
helper.close();
}
}
RestauranteHelper.delete:
public void delete(String id){
String[] args = {id};
getWritableDatabase().delete("restaurantes", "_ID =?", args);
}
idk if its clear what i want to do... i want to refresh the list, afeter selecting "Remove" option.
=D
After changing the items in the list call the notifyDatasetChanged on your list adapter. That will do it.
Here is how the ListView will work.
After you initialize the list, set the items in the list adapter.
Now call listview.setAdapter method to set the adapter.
Now when ever you make any changes in the items, change them on the list that you have passed to the adapter.
Then call the notofyDatasetChanged on your adapter.
That should work. If that is not working, then something else is wrong and try to debug each step of your code.
** In your case you are calling the delete on the database helper, but your cursor or adapter does not update when you change your stuff on the database. You need to remove that item from the cursor or query the database again and then pass it to the adapter.

Categories

Resources