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.
Related
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.
**I need help to do a simple click in a listview to start a new activity using onclicklistener.I am using JSON to parse the data.Below is my code
**
public class MainActivity extends Activity {
private CategoryAdapter adapter;
private CategoriesBean cb;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv = (ListView) findViewById(R.id.list);
cb = callCategory();
List<Category> catList = new ArrayList<Category>();
adapter = new CategoryAdapter(this, cb.getCategoryBn());
lv.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mif = getMenuInflater();
mif.inflate(R.menu.actionbar_menu, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.share:
return true;
case R.id.settings:
Intent in = new Intent(MainActivity.this, AppSettings.class);
startActivity(in);
case R.id.feedback:
return true;
case R.id.about:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private CategoriesBean callCategory() {
CategoriesBean cb = new CategoriesBean();
NetworkClass netClass = NetworkClass.getInstance(MainActivity.this);
cb = netClass.callCategory();
return cb;
}
private void showData() {
DbAdapter1 helper = DbAdapter1.getInstance(MainActivity.this);
Cursor cur = helper.fetchQuery("select * from jokes");
}
public class CategoryAdapter extends BaseAdapter {
Context context;
List<Category> catList = new ArrayList<Category>();
TextView categoryName;
TextView categoryCount;
public CategoryAdapter(Context context, List<Category> items) {
this.context = context;
this.catList = items;
}
public int getCount() {
return catList.size();
}
public Object getItem(int position) {
return catList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position,View convertView,ViewGroup parent)
{
if(convertView==null)
{
LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=vi.inflate(R.layout.inflate_categoryrow,null);
}
categoryName = (TextView)convertView.findViewById(R.id.categoryname);
categoryName.setText(catList.get(position).getCatName());
categoryCount=(TextView)convertView.findViewById(R.id.categorycount);
categoryCount.setText(catList.get(position).getCatCount());
convertView.setOnClickListener(new OnClickListener() {
something should be within this onClick method to get the position of the list and start a new activity
#Override
public void onClick(View v) {
Intent i=new Intent(MainActivity.this,CategoryDetail.class);
startActivity(i);
}
});
return convertView;
}
}
}
To send the position to the other activity:
Intent i=new Intent(MainActivity.this,CategoryDetail.class);
Bundle bundle = new Bundle();
bundle.putInt("Position", position); //position is one of the method arguments
i.putExtras(bundle);
startActivity(i);
To retrieve this info within the other activity set this line on the onCreate method:
int position = getIntent().getExtras().getInt("Position");
You can set a onItemClickListener for your listview, Like this:
listview.setOnItemClickListener(new onItemClickListener(){
#Override
protected void onListItemClick(ListView parent, View v, int position, long id){
//Do stuff
}
});
Since your position variable is final you can use it in your onClick block:
#Override
public void onClick(View v) {
//In case you need the object at the position
Object objectAtPosition = getItem(position);
Bundle bundle = new Bundle();
bundle.putInt("YOUR_POSITION_EXTRA", position);
Intent i=new Intent(MainActivity.this,CategoryDetail.class);
i.putExtras(bundle);
startActivity(i);
}
Don't see any problem there. If this is not the solution could you try to be more specific what your problem is?
Im setting up a main activity with a ListView object, however, the ListView will not respond to touch, onItemClick and onContextItemSelected are not reachable, i have set up setOnItemClickListener and registerForContextMenu, and i dont see my error, here is my code:
public class MainActivity extends Activity implements OnClickListener, OnItemClickListener {
long selectedMovieId;
DbHandler dbhandler;
Movie selectedMovie;
MovieAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn_setting = (Button) findViewById(R.id.page_main_setting);
Button btn_add = (Button) findViewById(R.id.page_main_add);
ListView lv = (ListView) findViewById(R.id.list);
btn_add.setOnClickListener(this);
btn_setting.setOnClickListener(this);
lv.setOnItemClickListener(this);
dbhandler = new DbHandler(this);
registerForContextMenu(lv);
Cursor c = dbhandler.queryAll();
startManagingCursor(c);
adapter = new MovieAdapter(this, c);
lv.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_options, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.main_options_exit:
finish();
return true;
case R.id.main_option_delete_all:
dbhandler.deleteAll();
refresh();
return true;
}
return false;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.main_context, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
Log.d("context menu", "clicked");
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
selectedMovieId = info.id;
switch (item.getItemId()) {
case R.id.main_context_edit:
Intent intent = new Intent(this, AddEditActivity.class);
intent.putExtra(DbConstants.FROM_CONTEXT, selectedMovie+"");
startActivity(intent);
return true;
case R.id.main_context_delete:
dbhandler.deleteMovie(selectedMovieId);
refresh();
return true;
}
return false;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.page_main_setting:
openOptionsMenu();
break;
case R.id.page_main_add:
DialogInterface.OnClickListener listenerInternet = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getBaseContext(),
InternetEditActivity.class);
startActivity(intent);
}
};
DialogInterface.OnClickListener listenerManual = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getBaseContext(),AddEditActivity.class);
intent.putExtra(DbConstants.MANUAL, DbConstants.MANUAL);
startActivity(intent);
}
};
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Please choose an adding method")
.setCancelable(false).setNegativeButton("Cancel", null)
.setNeutralButton("via internet", listenerInternet)
.setPositiveButton("Manual", listenerManual).create();
dialog.show();
break;
}
}
class MovieAdapter extends CursorAdapter /*implements OnTouchListener*/ {
public MovieAdapter(Context context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// inflate the view:
return getLayoutInflater().inflate(R.layout.main_list_layout,
parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// bind the data
// get the data from the cursor
String subject = cursor.getString(cursor.getColumnIndex(DbConstants.DB_SUBJECT));
String body = cursor.getString(cursor.getColumnIndex(DbConstants.DB_BODY));
String internal_location = cursor.getString(cursor.getColumnIndex(DbConstants.DB_INTERNAL_LOCATION));
int year = cursor.getInt(cursor.getColumnIndex(DbConstants.DB_YEAR));
int status = cursor.getInt(cursor.getColumnIndex(DbConstants.DB_STATUS));
int rating = cursor.getInt(cursor.getColumnIndex(DbConstants.DB_RATING));
TextView subjectText = (TextView) view.findViewById(R.id.list_main_subject);
TextView bodyText = (TextView) view.findViewById(R.id.list_main_body);
TextView yearText = (TextView) view.findViewById(R.id.list_main_year);
TextView statusText = (TextView) view.findViewById(R.id.list_main_status);
ImageView image = (ImageView) view.findViewById(R.id.list_main_imgae);
//RatingBar ratingBar = (RatingBar) view.findViewById(R.id.list_main_ratingBar1);
//ratingBar.setOnTouchListener(this);
subjectText.setText(subject);
bodyText.setText(body);
yearText.setText(String.valueOf(year));
//ratingBar.setRating(rating);
Log.d("status in main", status+"");
Log.d("rating in main", rating+"");
if (status==0){
statusText.setText("watched");
} else if (status==1){
statusText.setText("Not watched");
}
Log.d("ternal loction", internal_location+"!");
if (internal_location!=null){
File imgFile = new File(internal_location);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
image.setImageBitmap(myBitmap);
}
}
}
/*#Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}*/
} //Movie Adapter close
public void refresh(){
Cursor newCursor = dbhandler.queryAll();
Cursor oldCursor = adapter.getCursor();
adapter.changeCursor(newCursor);
startManagingCursor(newCursor);
stopManagingCursor(oldCursor);
oldCursor.close();
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long id) {
Log.d("list menu", "clicked");
Intent intent = new Intent(this, AddEditActivity.class);
intent.putExtra(DbConstants.FROM_LISTVIEW, id);
startActivity(intent);
}
} //Main Activity close
it has to be somthing to do with the layout of the list, a simple list inserted next to it worked
OnItemClick event is now intercepted by RatingBar.
Add onTouchEvent listener to your RatingBar and return false to say to system that RatingBar does not handle this events.
#Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(MotionEvent event)
return false;
}
Edit: above answer is for subclassing RatingBar.
But you already have onTouchEvent just return false instead of true.
The problem was that there was a Scroll view object in the layout of the adapter, remove it and the problem will be fixed
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
I am trying to add a button to each line on a ListView. The button will then copy the row (that has been clicked) from the table and insert the row into another table. What I need to know is how to assign the clicked row rowId to my button method as I need to pass that over to the copyData method. Here is my main code and the button method is at the bottom.
public class Favourites extends ListActivity {
private static final int ACTIVITY_CREATE=0;
private static final int ACTIVITY_EDIT=1;
private static final int INSERT_ID = Menu.FIRST;
private static final int DELETE_ID = Menu.FIRST + 1;
private FavouritesDbAdapter mDbHelper;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favourites_list);
mDbHelper = new FavouritesDbAdapter(this);
mDbHelper.open();
fillData();
registerForContextMenu(getListView());
}
private void fillData() {
Cursor notesCursor = mDbHelper.fetchAllNotes();
startManagingCursor(notesCursor);
// Create an array to specify the fields we want to display in the list
String[] from = new String[]{FavouritesDbAdapter.KEY_TITLE,FavouritesDbAdapter.KEY_ROWID};
// and an array of the fields we want to bind those fields to
int[] to = new int[]{R.id.text1,R.id.text2};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.favourites_row, notesCursor, from, to);
setListAdapter(notes);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, INSERT_ID, 0, R.string.menu_insert);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()) {
case INSERT_ID:
createNote();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, R.string.menu_delete);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
mDbHelper.deleteNote(info.id);
fillData();
return true;
}
return super.onContextItemSelected(item);
}
private void createNote() {
Intent i = new Intent(this, FavouritesEdit.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, Favourites.class);
Intent i1 = new Intent(this, FavouritesEdit.class);
i1.putExtra(FavouritesDbAdapter.KEY_ROWID, id);
i.putExtra(FavouritesDbAdapter.KEY_ROWID, id);
startActivityForResult(i1, ACTIVITY_EDIT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
fillData();
}
public void button(View view) {
mDbHelper.copyData(#ROWID of CLICKED BUTTON TO BE PASSED OVER#);
fillData();
}
}
I've done it something like this before:
ListView list_Builds = (ListView)findViewById(R.id.list_Builds);
list_Builds.setAdapter(adapter);
list_Builds.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView parent, View view, int position, long id)
{
// BuildID is my primary key in the table
TextView lbl_BuildID = (TextView)view.findViewById(R.id.lbl_BuildID);
String buildID = (String)lbl_BuildID.getText();
TextView lbl_BuildName = (TextView)view.findViewById(R.id.lbl_BuildName);
String buildName = (String)lbl_BuildName.getText();
TextView lbl_BuildDescription = (TextView)view.findViewById(R.id.lbl_BuildDescription);
String buildDescription = (String)lbl_BuildDescription.getText();
// I passed it on to a new intent. But here you could call your database
Intent i = new Intent(getBaseContext(), ViewBuild.class);
i.putExtra("BuildID", buildID);
i.putExtra("BuildName", buildName);
i.putExtra("BuildDescription", buildDescription);
startActivity(i);
}
catch(Exception ex)
{
Log.println(1, "item-click-event", ex.getMessage());
}
}
});
Basically, when I bind to the the list view, I have a hidden "BuildID" TextView that contains the primary key ID of that row from the database.