I am making an android application that uses a listview. I want to get the index number of an item once an item has been pressed(single-click). I've gone through several tutorials, but none seemed to help. How can i get the index number and pass it to a String. I do then want to delete it, but i'll manage that part my self. I only need the index number and pass it to a string. The code where i'll get the index number is straigt after the onCreate method. Please help and thanks in advance! This is the code that i am using:
public class NotesActivity extends ListActivity implements OnClickListener {
/** Called when the activity is first created. */
List<String> myList = new ArrayList<String>();
EditText AddItemToListViewEditText;
Button AddItemToListView, AddItemToListViewButton, CancelButton, DeleteButton;
LinearLayout AddItemToListViewLinearLayout, DeleteItemFromListViewLinearLayout;
public String DeleteIndexNumber;
static final String[] COUNTRIES = new String[] {
"Matte på A1 med Ole", "Engelsk på klasserommet", "Film på A1 etter friminuttet"
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notes);
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES));
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, myList));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), "Note: " + ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
//This is where i need the index number to be passed to the string "DeleteIndexNumber"
DeleteItemFromListViewLinearLayout = (LinearLayout)findViewById(R.id.DeleteItemFromListViewLinearLayout);
DeleteItemFromListViewLinearLayout.setVisibility(View.VISIBLE);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu meny) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.listviewmenubuttons, meny);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.AddItemToListView:
AddItemToListViewButton = (Button)findViewById(R.id.AddItemToListViewButton);
CancelButton = (Button)findViewById(R.id.CancelButton);
DeleteButton = (Button)findViewById(R.id.DeleteButton);
CancelButton.setOnClickListener(this);
DeleteButton.setOnClickListener(this);
AddItemToListViewLinearLayout = (LinearLayout)findViewById(R.id.AddItemToListViewLinearLayout);
AddItemToListViewButton.setOnClickListener(this);
AddItemToListViewLinearLayout.setVisibility(View.VISIBLE);
break;
}
return true;
}
public void onClick(View src) {
switch(src.getId()) {
case R.id.AddItemToListViewButton:
AddItemToListViewEditText = (EditText)findViewById(R.id.AddItemToListViewEditText);
myList.add(AddItemToListViewEditText.getText().toString());
((ArrayAdapter)getListView().getAdapter()).notifyDataSetChanged();
AddItemToListViewEditText.setText("");
AddItemToListViewEditText.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput (InputMethodManager.SHOW_FORCED, InputMethodManager.RESULT_HIDDEN);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
AddItemToListViewLinearLayout.setVisibility(View.GONE);
break;
case R.id.CancelButton:
DeleteItemFromListViewLinearLayout = (LinearLayout)findViewById(R.id.DeleteItemFromListViewLinearLayout);
DeleteItemFromListViewLinearLayout.setVisibility(View.INVISIBLE);
break;
case R.id.DeleteButton:
break;
}
}
}
notice the parameters for the onItemClick method
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
position will give you the index you desire..
Isn't it position parameter in onItemClick ?
The position parameter in onItemClick will give you the index of the clicked Item in the list.
Related
I have a simple context menu and I want to make a Toast to display a short message.
The problem is I can't get the item Position to display the specific detail I want because the Position of the adapter is out of scope.
This is my code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ArrayAdapter<Product> adapter;
private ListView listView;
private ContextMenu menu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1);
listView.setAdapter(adapter);
registerForContextMenu(listView);
adapter.add(new Product("shoe", 150));
adapter.add(new Product("T shirt", 80));
adapter.add(new Product("pants", 100));
adapter.add(new Product("lamp", 300));
adapter.add(new Product("ball", 20));
adapter.add(new Product("egg", 1));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
Toast.makeText(MainActivity.this, adapter.getItem(position) + ": " + adapter.getItem(position).getPrice(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onClick(View v) {
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("choose what to do");
menu.add(1, 0, 0, "product details");
menu.add(1,1,1,"delete");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()){
case 0:
Toast.makeText(MainActivity.this, adapter... + ": " + adapter..., Toast.LENGTH_SHORT).show();
break;
}
return true;
}
}
I assume because it seems like you wanted to know which item has been long pressed by the user and wanted to know the item position so that you can get the value from Adapter Or List.
If I understand you correct PFB solution
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
info.position;//This is your desired position.
now you have the value and you can play with it. Njoy!
Happy Coding!!!
I'm trying to delete the selected item in listview through Context menu.
here is my code.
public class MainActivity extends AppCompatActivity
{
EditText editText;
Button add;
ListView listView;
final DBFunctions db=new DBFunctions(MainActivity.this);
ArrayAdapter<String> adapter;
String[] values;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText= (EditText) findViewById(R.id.editText);
add= (Button) findViewById(R.id.button);
listView= (ListView) findViewById(R.id.listView);
values=db.getAlldata();
adapter=new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,values);
listView.setAdapter(adapter);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = editText.getText().toString();
if (!name.equals("")) {
editText.setText("");
long check = db.insertData(name);
if (check < 0) {
Toast.makeText(MainActivity.this, "Error in insert query", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, name + " inserted", Toast.LENGTH_SHORT).show();
}
adapter.notifyDataSetChanged();
} else {
editText.setError("this field is empty");
}
}
});
registerForContextMenu(listView);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
getMenuInflater().inflate(R.menu.menu_main, menu);
super.onCreateContextMenu(menu, v, menuInfo);
}
#Override
public boolean onContextItemSelected(MenuItem item)
{
int position=listView.getSelectedItemPosition();
String data=values[position]; //error line
Log.e("Value ", data );
Log.e("Position ", position+"" );
switch (item.getItemId())
{
case R.id.delete_name:
long check=db.deleteData(data);
if(check<0)
{
Toast.makeText(MainActivity.this,"Error in query",Toast.LENGTH_SHORT).show();
}
else
{
adapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this,data+" deleted",Toast.LENGTH_SHORT).show();
}
return true;
default :
return super.onContextItemSelected(item);
}
}
}
when i run above code i get following error:
java.lang.ArrayIndexOutOfBoundsException: length=3; index=-1
at pack.madhan.listviewdemo.MainActivity.onContextItemSelected(MainActivity.java:72)
at android.app.Activity.onMenuItemSelected(Activity.java:2628)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:353)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:144)
at android.support.v7.internal.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:99)
at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:3864)
at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:741)
is it possible to delete selected item in listview via context menu ?
please help me on this.
finally i found an answer
Error Code:
int position=listView.getSelectedItemPosition();
String data=values[position];
Updated Code:
AdapterView.AdapterContextMenuInfo info= (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
String data=values[info.position];
where info.position gives the position of item in listView.
To refer click here
Based on the logstack, your function listView.getSelectedItemPosition() returns -1.
int position=listView.getSelectedItemPosition();
java.lang.ArrayIndexOutOfBoundsException: length=3; index=-1
-1 is not a correct index, and is the cause of this OutOfBoundsException.
I've never tried to keep track of the latest element selected in a list, but you could do as follow :
Add a variable at the begining of your MainActivity to keep track of the selectedItem;
// First item of the list is selected by defaul to avoid out of bound
int selectedItem = 0;
And update this variable with the onItemClickListener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
selectedItem = id;
}
});
I started a small Android project to re-learn a bit of Android development, and I'm already stuck...
I do not know how to implement the deletetion of an element of my ListView!
Here is the project: https://github.com/gdurelle/Listify
Right now it aims at showing a list of lists of elements.
I use a custom CursorAdapter to show my list of elements, and I already have a (ugly) destroy button, but I do not know how to make it delete an actual element from the list (and the database).
I use ActiveAndroid to manage the database in the ActiveRecord way.
Plus: I'm not sure wether or not to use getView(), bindView(), and/or newView()...
I created an issue to remember this and reference this question here: https://github.com/gdurelle/Listify/issues/1
public class ListifyCursorAdapter extends CursorAdapter {
public String content;
public ListifyCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
// 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) {
return LayoutInflater.from(context).inflate(R.layout.element_line, parent, false);
}
// 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) {
// Find fields to populate in inflated template
TextView tvBody = (TextView) view.findViewById(R.id.element_content);
// Extract properties from cursor
content = cursor.getString(cursor.getColumnIndexOrThrow("content"));
// Populate fields with extracted properties
tvBody.setText(content);
}
}
And in my MainActivity :
Cursor cursor = ListifyElement.fetchResultCursor();
adapter = new ListifyCursorAdapter(this, cursor);
listView.setAdapter(adapter);
I was thinking maybe about a:
Button delete_button = (Button) listView.findViewById(R.id.delete_button);
with something like ListifyElement.load(ListifyElement.class, the_id_of_the_element).delete(); where the_id_of_the_element would be the DB's id of the element retrieived somehow from the click on it's delete_button in the UI...
UPDATE:
#Override
public void bindView(View view, Context context, final Cursor cursor) {
// Find fields to populate in inflated template
TextView tvBody = (TextView) view.findViewById(R.id.element_content);
// Extract properties from cursor
content = cursor.getString(cursor.getColumnIndexOrThrow("content"));
// Populate fields with extracted properties
tvBody.setText(content);
Button delete_button = (Button) view.findViewById(R.id.delete_button);
delete_button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
System.out.println(cursor.getColumnName(0)); // Id
System.out.println(cursor.getColumnName(1)); // ListifyContainer
System.out.println(cursor.getColumnName(2)); // content
System.out.println(cursor.getColumnIndexOrThrow("Id")); // 0
ListifyElement.load(ListifyElement.class, cursor.getColumnIndexOrThrow("Id")).delete();
notifyDataSetChanged();
}
});
I get this error when I click the delete button:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.gdurelle.listify.models.ListifyElement.delete()' on a null object reference
If you want a Button in each row, you should add it to your xml which you inflate in the newView(). After that, you should set OnClickListener to your Button inside bindView(). Something like that:
public void bindView(View view, Context context, Cursor cursor) {
// Find fields to populate in inflated template
TextView tvBody = (TextView) view.findViewById(R.id.element_content);
Button delete_button = (Button) view.findViewById(R.id.delete_button);
delete_button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
//As you're using ActiveAndroid
new Delete().from(ListfyElement.class).where("yourCondition=?",yourCondition).execute();
notifyDataSetChanged();
}
});
// Extract properties from cursor
content = cursor.getString(cursor.getColumnIndexOrThrow("content"));
// Populate fields with extracted properties
tvBody.setText(content);
}
Use below code to perform this--
ListView lv;
ArrayList<String> arr = new ArrayList<String>();
ArrayAdapter adapter;
int position;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.extra);
for(int i=0;i<5;i++)arr.add("Hi # "+i);
lv = (ListView) findViewById(R.id.listViewBirthday);
lv.setOnItemLongClickListener(this);
adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, arr);
lv.setAdapter(adapter);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
MenuItem it1=menu.add("Delete");
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int p, long arg3)
{
position = p;
registerForContextMenu(lv);
return false;
}
#Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if(item.getTitle().equals("Delete"))
{
arr.remove(position);
adapter.notifyDataSetChanged();
Toast.makeText(getBaseContext(), "deleted", Toast.LENGTH_SHORT).show();
}
return true;
}
The context menu is relatively simple to implement on a listview. It (context menu) is activated on a long press of the item. My tip is to add an intent to the menu item so you can preserve the item id from your custom adapter and use it to perform whatever you want.
public class MainActionBarTabListFragment extends ListFragment {
#Override
public void onActivityCreated(Bundle savedState) {
super.onActivityCreated(savedState);
registerForContextMenu(getListView());
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
String name = adapter2.getItem(info.position).get_name();
menu.setHeaderTitle(name);
MenuInflater inflater = this.getActivity().getMenuInflater();
inflater.inflate(R.menu.menulistitem, menu);
MenuItem mi = menu.findItem(R.id.action_context_delete);
Intent i = new Intent();
i.putExtra("id", adapter2.getItem(info.position).get_id());
mi.setIntent(i);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_context_delete:
Intent i = item.getIntent();
if (i != null) {
Bundle b = i.getExtras();
if (b != null) {
int id = b.getInt("id");
Uri deleteIdUri = ContentUris.withAppendedId(
RidesDatabaseProvider.CONTENT_URI, id);
context.getContentResolver()
.delete(deleteIdUri, null, null);
return true;
}
}
}
return super.onContextItemSelected(item);
}
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
<item
android:id="#+id/action_context_delete"
android:icon="#drawable/action_about"
android:orderInCategory="100"
android:showAsAction="ifRoom"
android:title="delete"
yourapp:showAsAction="ifRoom"/>
</menu>
lets start from the beginning, why do you need to use ActiveAndroid? I suggest to avoid such things, IMHO. You've mixed your logic, adapter should not change your database. Set a listener to adapter (i.e. IDeleteListener with single method onDeleteRequested(long rowId)). Next you need to pass rowId, something like:
delete_button.setTag(cursor.getLong(0));
delete_button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
listener.onDeleteRequested((Long)v.getTag());
}
});
In your fragment/activity class you should set a listener to adapter and work with your database. I suggest you to use LoaderManager this will automatically re-query your db on delete and handle life cycle of activity.
Hope that helps!
I would suggest you to use an ArrayAdapter instead. Then you are just using an ArrayList (or any other array) and edit it, and call adapter.notifyDataSetChanged();, and the content of the ListView will update.
Declare the ArrayAdapter like this:
ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, yourStringArray);
where the variable called yourStringArray is just an ArrayListof Strings.
Then, add the adapter to the ListView, like this:
yourListView.setAdapter(adapter);
Then, you can modify the contents of the list, by editing the yourStringArray list, and calling adapter.notifyDataSetChanged();. Here is a simple example:
list.add("Hello!");
adapter.notifyDataSetChanged();
Finally, to remove the selected item when the button is clicked, you can do something like this:
int selectedItemIndex = 0;
yourArrayList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedItemIndex = position;
}
});
yourDestroyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yourStringArray.remove(selectedItemIndex);
adapter.notifyDataSetChanged();
}
});
The whole onCreate method would look something like this:
// Called when the activity is created
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> yourStringArray = new ArrayList<>();
ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, yourStringArray);
int selectedItemIndex = 0;
ListView yourListView = (ListView) findViewById(R.layout.yourListViewID);
yourListView.setAdapter(adapter);
yourListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedItemIndex = position;
}
});
yourDestroyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yourStringArray.remove(selectedItemIndex);
adapter.notifyDataSetChanged();
}
});
}
I've been trying to create a clickable listview that takes in a string array and a few images and presents them in a textview style. So far I have managed to create a listview with each of the strings and images, however I am unsure how to use the onClick method so as to make the textviews clickable to start new activities etc.
Here is my code so far (Excluding XML):
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public MySimpleArrayAdapter(Context context, String[] values) {
super(context, R.layout.activity_test2, values);
this.context = context;
this.values = values;
}
/* Print a toast when a list item is clicked, don't know what to do */
public void onClick() {
switch (list item) {
case 0:
Toast.makeText(this.context, "Pressed!", Toast.LENGTH_LONG).show()
break;
}
case 1:
etc....
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.activity_test2, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
textView.setText(values[position]);
String s = values[position];
if (s.startsWith("Report a Road Delay")) {
imageView.setImageResource(R.drawable.ic_menu_compose);
} else if (s.startsWith("View Reported Delays")) {
imageView.setImageResource(R.drawable.ic_menu_view);
} else if (s.startsWith("Search a Road for Delays")) {
imageView.setImageResource(R.drawable.ic_menu_search);
} else if (s.startsWith("Update a Delay Report")) {
imageView.setImageResource(R.drawable.ic_menu_edit);
} else if (s.startsWith("Validate a Delay Report")) {
imageView.setImageResource(R.drawable.ic_menu_mark);
}
return rowView;
}
}
public class MainActivity extends ListActivity {
public void onCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
String[] values = new String[] { "Report a Road Delay",
"View Reported Delays", "Search a Road for Delays",
"Update a Delay Report", "Validate a Delay Report" };
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this, values);
setListAdapter(adapter);
}
}
This is how it looks so far:
All I basically don't understand is the onClick method; what parameters it takes it, and how to determine which item was clicked. Any help would be appreciated.
Try this:
ListView list1 = getListView();
list1.setOnItemClickListener(
new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {
//Take action here.
}
}
);
You are looking for an OnItemClickListener and not an OnClickListener
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// DO SOMETHING WITH CICK EVENT HERE
}
}
Now only to discus the params:
parent The AdapterView where the click happened.
view The view within the AdapterView that was clicked
position The position of the view in the adapter.
id The row id of the item that was clicked.
I got the last part from android reference
You could use this code:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
long id) {
// We know the View is a <extView so we can cast it
TextView clickedView = (TextView) view;
Toast.makeText(MainActivity.this, "Item with id ["+id+"] - Position ["+position+"] - Planet ["+clickedView.getText()+"]", Toast.LENGTH_SHORT).show();
}
});
// we register for the contextmneu
registerForContextMenu(lv);
}
where lv is the listView.
If you want to add a context menu:
// We want to create a context Menu when the user long click on an item
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo aInfo = (AdapterContextMenuInfo) menuInfo;
// We know that each row in the adapter is a Map
Planet planet = aAdpt.getItem(aInfo.position);
menu.setHeaderTitle("Options for " + planet.getName());
menu.add(1, 1, 1, "Details");
menu.add(1, 2, 2, "Delete");
}
// This method is called when user selects an Item in the Context menu
#Override
public boolean onContextItemSelected(MenuItem item) {
int itemId = item.getItemId();
AdapterContextMenuInfo aInfo = (AdapterContextMenuInfo) item.getMenuInfo();
planetsList.remove(aInfo.position);
aAdpt.notifyDataSetChanged();
return true;
}
If you want to have more information give a look on my blog here and here
I am making an android application that needs to save listview items to the sdcard. I am using a dynamic listview that the users can delete items from and add items to. I want the listview to save the items if the application gets destroyed or if the user hits the back button. Basically when the activity is destroyed. Please help and thanks SO much in advance! I am using this code so far:
public class NotesActivity extends ListActivity implements OnClickListener {
/** Called when the activity is first created. */
List<String> myList = new ArrayList<String>();
EditText AddItemToListViewEditText;
Button AddItemToListView, AddItemToListViewButton, CancelButton, DeleteButton,CancelButton2, DeleteAllButton;
LinearLayout AddItemToListViewLinearLayout, DeleteItemFromListViewLinearLayout, DeleteAllItemsFromListViewLinearLayout;
public int DeleteIndexNumber;
static final String[] COUNTRIES = new String[] {
"Matte på A1 med Ole", "Engelsk på klasserommet", "Film på A1 etter friminuttet"
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notes);
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES));
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, myList));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), "Note: " + ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
DeleteIndexNumber = position;
DeleteItemFromListViewLinearLayout = (LinearLayout)findViewById(R.id.DeleteItemFromListViewLinearLayout);
DeleteItemFromListViewLinearLayout.setVisibility(View.VISIBLE);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu meny) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.listviewmenubuttons, meny);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.AddItemToListView:
AddItemToListViewButton = (Button)findViewById(R.id.AddItemToListViewButton);
CancelButton = (Button)findViewById(R.id.CancelButton);
DeleteButton = (Button)findViewById(R.id.DeleteButton);
CancelButton.setOnClickListener(this);
DeleteButton.setOnClickListener(this);
AddItemToListViewLinearLayout = (LinearLayout)findViewById(R.id.AddItemToListViewLinearLayout);
AddItemToListViewButton.setOnClickListener(this);
AddItemToListViewLinearLayout.setVisibility(View.VISIBLE);
break;
case R.id.DeleteAllNotes:
DeleteAllItemsFromListViewLinearLayout = (LinearLayout)findViewById(R.id.DeleteAllItemsFromListViewLinearLayout);
DeleteAllItemsFromListViewLinearLayout.setVisibility(View.VISIBLE);
CancelButton2 = (Button)findViewById(R.id.CancelButton2);
DeleteAllButton = (Button)findViewById(R.id.DeleteAllButton);
CancelButton2.setOnClickListener(this);
DeleteAllButton.setOnClickListener(this);
break;
}
return true;
}
public void onClick(View src) {
switch(src.getId()) {
case R.id.AddItemToListViewButton:
AddItemToListViewEditText = (EditText)findViewById(R.id.AddItemToListViewEditText);
myList.add(AddItemToListViewEditText.getText().toString());
((ArrayAdapter)getListView().getAdapter()).notifyDataSetChanged();
AddItemToListViewEditText.setText("");
AddItemToListViewEditText.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput (InputMethodManager.SHOW_FORCED, InputMethodManager.RESULT_HIDDEN);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
AddItemToListViewLinearLayout.setVisibility(View.GONE);
break;
case R.id.CancelButton:
DeleteItemFromListViewLinearLayout = (LinearLayout)findViewById(R.id.DeleteItemFromListViewLinearLayout);
DeleteItemFromListViewLinearLayout.setVisibility(View.INVISIBLE);
break;
case R.id.DeleteButton:
myList.remove(DeleteIndexNumber);
((ArrayAdapter)getListView().getAdapter()).notifyDataSetChanged();
DeleteItemFromListViewLinearLayout = (LinearLayout)findViewById(R.id.DeleteItemFromListViewLinearLayout);
DeleteItemFromListViewLinearLayout.setVisibility(View.INVISIBLE);
break;
case R.id.DeleteAllButton:
myList.removeAll(myList);
((ArrayAdapter)getListView().getAdapter()).notifyDataSetChanged();
DeleteAllItemsFromListViewLinearLayout = (LinearLayout)findViewById(R.id.DeleteAllItemsFromListViewLinearLayout);
DeleteAllItemsFromListViewLinearLayout.setVisibility(View.INVISIBLE);
break;
case R.id.CancelButton2:
DeleteAllItemsFromListViewLinearLayout = (LinearLayout)findViewById(R.id.DeleteAllItemsFromListViewLinearLayout);
DeleteAllItemsFromListViewLinearLayout.setVisibility(View.INVISIBLE);
break;
}
}
}
You can have a look at the official guide for data storage. Since your ListView content is large, you can store it into SQLite database. The link for the guide is below:-
http://developer.android.com/guide/topics/data/data-storage.html