So i am preety new with this SQLite i finaly managed to create base and work with it etc. Now i created ContextMenu thath you will be able to delete item from listView on which context menu was opened. Here is my current code.
import java.util.List;
import java.util.Random;
import android.app.ListActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.view.MenuItem;
public class Ann extends ListActivity{
private CommentsDataSource datasource;
EditText edit;
ListView bump;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ann);
datasource = new CommentsDataSource(this);
datasource.open();
List<Comment> values = datasource.getAllComments();
ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
registerForContextMenu(getListView());
}
public void onClick(View view) {
#SuppressWarnings("unchecked")
ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) getListAdapter();
Comment comment = null;
switch (view.getId()) {
case R.id.add:
edit = (EditText)findViewById(R.id.editTxt);
Editable txt=(Editable)edit.getText();
String vnos = txt.toString();
comment = datasource.createComment(vnos);
adapter.add(comment);
edit.setText("");
break;
}
adapter.notifyDataSetChanged();
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
}
Now i know thath i need to make method for public boolean onContextItemSelected(MenuItem item)
but how to manage now to delete item which was selected.
Can I ask why you don't use a SimpleCursorAdapter to create the list? It looks like you're getting a cursor and turning into an array... why take that extra step? It's useful in that if you make an addition/deletion to the database, you can simply use the requery() method to regenerate/update the list.
Anyway, should you decide to go with a SimpleCursorAdapter, onContextItemSelected(MenuItem item) would be the way to go. An example from one of my projects:
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
if (item.getTitle() == "Delete Member") {
mDbHelper.deleteMember(info.id);
mMemberCursor.requery();
return true;
}
return super.onContextItemSelected(item);
}
Note that I created my menu view programatically, so you may need to change the if statement to something that will work better for your set-up with an inflated menu resource.
info.id is the row id from the database that represents the line of the list you clicked.
mDbHelper.deleteMember() is a method from my database helper for deleting records.
Hope this helps!
The context menu is not listItem specific, ie. id does not know which item was clicked.
Go for an onItemClicked or onItemLongClick version.
To do the latter implement the onItemLongClick interface on you activity
public class Ann extends ListActivity implements OnItemLongClickListener
and add the onItemLongClick method
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// do something with your datasource and the position
return false;
}
Related
I am creating a spinner given in the code as follow. How can i connect it to another activity(say Bangalore.java). I tried the something available on stackoverflow but its not working.
package com.example.searchbox;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import com.example.searchbox.run;
import com.example.searchbox.ArrayList;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] cityNames = {"Jaipur","Bangalore","Agra"};
setContentView(R.layout.activity_main);
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
cityNames));
/*how can i connect activity of the spinner to another activity*/
}
#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, menu);
return true;
}
}
You can do something like this:
MyOnItemSelectedListener myonitemselectedlistener =new MyOnItemSelectedListener (savedRoomNames);
YOURSPINNER.setOnItemSelectedListener(myonitemselectedlistener);
And then:
private class MyOnItemSelectedListener implements OnItemSelectedListener{
AdapterView<?> arg0;
View arg1;
int arg2;
long arg3;
public MyOnItemSelectedListener(String[] gespeicherteRaeume) {
this.savedRooms=gespeicherteRaeume;
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
this.arg0=arg0;
this.arg1=arg1;
this.arg2=arg2;
this.arg3=arg3;
//here you have to look which item is arg2 and then if == yyour item start your new activity via intent
}
public void onNothingSelected(AdapterView<?> arg0) {
}
I would use an OnItemSelectedListener and then start the activity once the correct item has been caught.
So I have a weird problem. I have 2 Activities I'm working on. One of the Activities displays a ListView whose data is grabbed via a long Extra I use to fetch the results via a WHERE clause in the database.query. The other Activity is called when a ListView item is clicked, allowing someone to add something to the database for the ListView.
The activity names are DaysActivity.java (the activity with the listview) and DayAddActivity.java (the Activity that allows someone to add a day, which then shows up in the DaysActivity.java ListView).
The problem I'm having is, when I finish() DayAddActivity.java it goes back to DaysActivity and the ListView is still there fully populated. However, if I hit the back button in DayAddActivity.java (the button to the left of the title in the action bar with my app icon), when it goes back to DaysActivity.java, the ListView is empty/gone.
Heres the code for both:
DaysActivity.java:
package com.gauvion.gfit;
import android.annotation.SuppressLint;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class DaysActivity extends ListActivity {
private DaysDataSource datasource;
private SimpleCursorAdapter dataAdapter;
private boolean isEditing = false;
private Toast toast_deleted;
private String[] columns = new String[] { MySQLiteHelper.COLUMN_NAME, MySQLiteHelper.COLUMN_DAY };
private int[] to;
private long routineDataID;
private String routineDataName;
#SuppressLint("ShowToast")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_days);
routineDataID = getIntent().getLongExtra("routineDataID", 0);
routineDataName = getIntent().getStringExtra("routineDataName");
setTitle(routineDataName);
toast_deleted = Toast.makeText(this, "", Toast.LENGTH_SHORT);
datasource = new DaysDataSource(this);
datasource.open();
Cursor cursor = datasource.fetchAllDays(routineDataID);
to = new int[] { R.id.listitem_day_name, R.id.listitem_day_day };
dataAdapter = new SimpleCursorAdapter(this, R.layout.listitem_day, cursor, columns, to, 0);
setListAdapter(dataAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_days, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Cursor cursor = datasource.fetchAllDays(routineDataID);
switch (item.getItemId()) {
case R.id.button_days_add:
Intent startDayAdd = new Intent(this, DayAddActivity.class);
startDayAdd.putExtra("routineDataID", routineDataID);
this.startActivity(startDayAdd);
return true;
case R.id.button_days_edit:
to = new int[] { R.id.listitem_day_edit_name, R.id.listitem_day_edit_day };
dataAdapter = new SimpleCursorAdapter(this, R.layout.listitem_day_edit, cursor, columns, to, 0);
setListAdapter(dataAdapter);
isEditing = true;
invalidateOptionsMenu();
return true;
case R.id.button_days_edit_done:
to = new int[] { R.id.listitem_day_name, R.id.listitem_day_day };
dataAdapter = new SimpleCursorAdapter(this, R.layout.listitem_day, cursor, columns, to, 0);
setListAdapter(dataAdapter);
isEditing = false;
invalidateOptionsMenu();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.findItem(R.id.button_days_edit).setVisible(!isEditing);
menu.findItem(R.id.button_days_edit_done).setVisible(isEditing);
return true;
}
#Override
protected void onResume() {
datasource.open();
Cursor cursor = datasource.fetchAllDays(routineDataID);
dataAdapter.changeCursor(cursor);
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
}
DayAddActivity.java:
package com.gauvion.gfit;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
public class DayAddActivity extends Activity {
private RoutinesDataSource datasource;
private EditText dayName;
private Spinner dayDay;
private Button saveButton;
private long routineDataID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_day_add);
routineDataID = getIntent().getLongExtra("routineDataID", 0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_day_add, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void cancelDay(View view) {
this.finish();
}
}
The cancelDay() function is called when a "Cancel" button is clicked in activity_day_add.xml. Like I said, when I click the "Cancel" button inside of DayAddActivity.java, it goes back to DaysActivity.java and the ListView is fine. All data is there. However, if I press the back button in the action bar (the button containing a back arrow and my app icon beside the title of the Activity) the ListView for DaysActivity.java is empty/gone, and the title is also empty (because this is also generated through an Extra String value).
Your cursors are not managed by the activity, this can cause a memory leak or even ANR. You should consider using a loader to populate a list using a cursor. You can find an example here :http://developer.android.com/guide/components/loaders.html.
Loaders work better as they don't freeze the app when the connexion to the database is obtained and they will be passed from one instance of your activity to another, preventing memory leaks and reusing resources.
But again, as in your previous post : Extras seem to be lost onResume(), you should understand the link between onSaveInstanceState and onCreate to pass arguments to the future self of your activity. Look at this post, the answer with the biggest score : onSaveInstanceState () and onRestoreInstanceState ().
It seems like your Context has some problems in "this.startActivity(startDayAdd);" line. try using "DaysActivity.this.startActivity(startDayAdd);". if it doesnot work then use breakpoints to see line by line execution.
on my application i want to click the list item and make some changes like deleting or updating the item.but i could not implemented the other codes to my code.so little help will be useful. here is my code
package com.example.todolist;
import java.util.ArrayList;
import java.util.Collection;
import android.os.Bundle;
import android.provider.Contacts;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity implements OnClickListener,OnKeyListener,OnInitListener {
EditText txtitem;
ListView listitem;
TextToSpeech talker;
ArrayList<String> todolist;
ArrayAdapter<String> arrayadapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtitem = (EditText) findViewById(R.id.txtitem);
listitem = (ListView) findViewById(R.id.listitem);
talker = new TextToSpeech(this, this);
txtitem.setOnKeyListener(this);
todolist = new ArrayList<String>();
arrayadapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,todolist);
listitem.setAdapter(arrayadapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main, menu);
MenuItem toAdd = menu.add("AddItem");
MenuItem toDelete = menu.add("DeleteItem");
MenuItem toSave = menu.add("SaveItem");
MenuItem toExit = menu.add("ExitItem");
MenuItem toUpdate = menu.add("UpdateItem");
return true;
}
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
return false;
}
#Override
public void onClick(DialogInterface dialog, int which) {
}
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
if(item.getTitle().equals("AddItem")){
todolist.add(txtitem.getText().toString());
arrayadapter.notifyDataSetChanged();
txtitem.setText("");
}
if(item.getTitle().equals("DeleteItem")){
String x = txtitem.getText().toString();
int y = Integer.parseInt(x);
todolist.remove(y-1);
arrayadapter.notifyDataSetChanged();
txtitem.setText("");
}
if(item.getTitle().equals("SaveItem")){
say("Save Complete");
arrayadapter.notifyDataSetChanged();
}
if (item.getTitle().equals("ExitItem")){
talker.speak("Are you sure you want to close this activity?",TextToSpeech.QUEUE_FLUSH,null);
onBackPressed();
}
if(item.getTitle().equals("UpdateItem")){
String x = txtitem.getText().toString();
int y = Integer.parseInt(x);
arrayadapter.notifyDataSetChanged();
txtitem.setText(todolist.get(y-1));
todolist.remove(y-1);
}
return true;
}
public void say(String text2say){
talker.speak(text2say, TextToSpeech.QUEUE_FLUSH, null);
}
#Override
public void onInit(int status) {
}
#Override
public void onDestroy() {
if (talker != null) {
talker.stop();
talker.shutdown();
}
super.onDestroy();
}
}
#Override
public void onBackPressed()
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Closing Activity")
.setMessage("Are you sure you want to close this activity?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
runOnUiThread(new Runnable() {
#Override
public void run() {
say("Bye");
}
});
}
})
.setNegativeButton("No", null)
.show();
}
this code takes the list's elemnt number and delete's it.but i want to click and delete or update.son little help will be useful.thank you already
To remove the desired item from the list using the remove() method of your ArrayAdapter.
A possible way to do that would be:
Object toRemove = arrayAdapter.getItem([POSITION]);
arrayAdapter.remove(toRemove);
Another way would be to modify the ArrayList and call notifyDataSetChanged() on the ArrayAdapter.
arrayList.remove([INDEX]);
arrayAdapter.notifyDataSetChanged();
To Add items you can do something like this :
on a click of button take text from edittext and add it as an item on list
/** Reference to the button of the layout main.xml */
Button btn = (Button) findViewById(R.id.btnAdd);
/** Defining the ArrayAdapter to set items to ListView */
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
/** Defining a click event listener for the button "Add" */
OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
EditText edit = (EditText) findViewById(R.id.txtItem);
list.add(edit.getText().toString());
edit.setText("");
adapter.notifyDataSetChanged();
}
};
/** Setting the event listener for the add button */
btn.setOnClickListener(listener);
Read official android docs here 1 and 2 for handling click of menu items ...
What you want to do is set the itemClickListener(). This is done by something like this:
list.setOnItemClickListner(new OnItemClickListener(){
onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//Do stuff here.
}
});
From that block, you just need to call your delete statement. Alternatively, you could have your class use the AdapterView.OnItemClickListener interface, and put the routine there, then changing the command to list.setOnItemClickListner(this);
I'm pritty new to Android and I've got a little question.
I've got a Problem with my ContextMenu. I have filled my ListView with my database entries, now i wand if i longclick it, that the ContextMenu pops up and there i want to delete or to edit my databaseentries:
But I don't get how I can find out what entrie it is.
Here's my Code..
package de.retowaelchli.filterit.stats;
import de.retowaelchli.filterit.R;
import de.retowaelchli.filterit.database.ADFilterDBAdapter;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleCursorAdapter;
public class CreatedADFilters extends ListActivity {
//Variablen deklaration
private ADFilterDBAdapter mDbHelper;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
//Kontext-Menu registrieren
registerForContextMenu(findViewById(R.layout.list_layout));
//Hier wir die Datenbank aufgerufen
mDbHelper = new ADFilterDBAdapter(this);
mDbHelper.open();
fillData();
}
private void fillData() {
// Get all of the notes from the database and create the item list
Cursor c = mDbHelper.getAllADFilter();
startManagingCursor(c);
String[] from = new String[] { ADFilterDBAdapter.NAME, ADFilterDBAdapter.ROW_ID };
int[] to = new int[] { R.id.label };
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter adname =
new SimpleCursorAdapter(this, R.layout.list_layout, c, from, to);
setListAdapter(adname);
mDbHelper.close();
}
//ContextMenu erstellen und definieren
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
if (v.getId() == R.layout.list_layout) {
getMenuInflater().inflate(R.menu.createdadmenu, menu);
}
super.onCreateContextMenu(menu, v, menuInfo);
}
public boolean onContextItemSelected(MenuItem item) {
final AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.delete_adfilter: {
deleteAD();
return true;
}
case R.id.edit_adfilter:{
editAD();
return true;
}
return super.onContextItemSelected(item);
}
}
// THIS IS THE PART I DONT KNOW HOW TO REALIZE
private void deleteAD(){
}
private void editAD(){
}
}
Thx for you Help in Advance!
best regards
safari
Your info local variable in onContextItemSelected() has an id data member which contains the _ID value from your Cursor. Here is a sample project demonstrating how to use that to delete an item based on a ListView context menu.
hey all.. i have been looking at other questions to get help and answers without luck..
my problem is that i want to open different class from my listView. according to the specific name in the listView. . the names are in lv_arr[] ..
If anybody can give a detailed answer i will be very thankfull and happy..
Im new in android and not the best in java :-(
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class StatusActivity extends Activity implements OnItemClickListener {
public ListView lv1;
public String lv_arr[]= {"John", "Andrew","alex","alice","bob","bla bla"};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabview);
lv1=(ListView)findViewById(R.id.ListView01);
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr));
lv1.setOnItemClickListener(this);
}
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(getApplication())
.inflate(R.menu.menu, menu);
return(super.onPrepareOptionsMenu(menu));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.close:
super.finish();
break;
case R.id.icontext:
Intent i = new Intent(this, InfoActivity.class);
startActivity(i);
break;
}
return true;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
if(position == 0){
//Intent w = new Intent (this, Seekbar.class);
//startActivity(w);
Toast.makeText(this, "You pressed the first item in the list", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "You pressed all other items in the list", Toast.LENGTH_SHORT).show();
}
}
}
try this....if you have doubts add comment.
edited:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabview);
lv1=(ListView)findViewById(R.id.ListView01);
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr));
lv1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
if(position==0){
Intent i = new Intent(this, InfoActivity.class);
startActivity(i);
} else if(position==1){
start another activity here...
}
}
});
}
hope it helps..
well i think you want to know basically the flow of how it is possible.
If all the classes which should be opened are more likely the same with just text and image changes and same layout then you dont need to create separate class file for each and every item clicked.
Just create one class file and one xml file and on item click pass on the bundle to the class file which will just changes the content on different item clicks and will workk as a charm as with this flow you will have only one class file and one xml file for all the list items you have
If you dont want to keep the same layout then you can obviously make the some views gone, visible or invisible at runtime
try something like this
public String lv_class_names[]= {Activity1.class.getName(), Activity2.class.getName(), Activity3.class.getName(), .....};
In the onItemClick method write
Intent i = new Intent(this, Class.forName(lv_class_name[position]));
startActivity(i);
for more details see this