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
Related
I am looking for a way to have a Snackbox pop up at the bottom of the display when the user deletes an item from the database using the caseR.id.delete:. Below I have attached code from the fragment. If you need more of my code from different areas, please let me know.
/**
* A simple {#link Fragment} subclass.
*/
public class MainActivityListFragment extends ListFragment {
private ArrayList<Note> notes;
private NoteAdapter noteAdapter;
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
/*
String[] values = new String[] {"Android", "iPhone", "Windows", "WebOS", "Android", "iPhone", "Windows", "WebOS" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
*/
NotesDbAdapter dbAdapter = new NotesDbAdapter(getActivity().getBaseContext());
dbAdapter.open();
notes = dbAdapter.getAllNotes();
dbAdapter.close();
noteAdapter = new NoteAdapter(getActivity(), notes);
setListAdapter(noteAdapter);
getListView().setDivider(null);
getListView().setDividerHeight(0);
registerForContextMenu(getListView());
}
#Override
public void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
launchNoteDetailActivity(MainActivity.FragmentToLaunch.VIEW, position);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater menuInflater = getActivity().getMenuInflater();
menuInflater.inflate(R.menu.long_press_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item){
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int rowPosition = info.position;
Note note = (Note) getListAdapter().getItem(rowPosition);
switch (item.getItemId()){
case R.id.edit:
launchNoteDetailActivity(MainActivity.FragmentToLaunch.EDIT, rowPosition);
Log.d("menu clicks", "we pressed edit");
return true;
case R.id.delete:
NotesDbAdapter dbAdapter = new NotesDbAdapter(getActivity().getBaseContext());
dbAdapter.open();
dbAdapter.deleteNote(note.getId());
notes.clear();
notes.addAll(dbAdapter.getAllNotes());
noteAdapter.notifyDataSetChanged();
dbAdapter.close();
}
return super.onContextItemSelected(item);
}
private void launchNoteDetailActivity(MainActivity.FragmentToLaunch ftl, int position){
Note note = (Note) getListAdapter().getItem(position);
Intent intent = new Intent(getActivity(), NoteDetailActivity.class);
intent.putExtra(MainActivity.NOTE_TITLE_EXTRA, note.getTitle());
intent.putExtra(MainActivity.NOTE_MESSAGE_EXTRA, note.getMessage());
intent.putExtra(MainActivity.NOTE_CATEGORY_EXTRA, note.getCategory());
intent.putExtra(MainActivity.NOTE_DATE_EXTRA, note.getDate());
intent.putExtra(MainActivity.NOTE_ID_EXTRA, note.getId());
switch(ftl){
case VIEW:
intent.putExtra(MainActivity.NOTE_FRAGMENT_TO_LOAD_EXTRA, MainActivity.FragmentToLaunch.VIEW);
break;
case EDIT:
intent.putExtra(MainActivity.NOTE_FRAGMENT_TO_LOAD_EXTRA, MainActivity.FragmentToLaunch.EDIT);
}
startActivity(intent);
}
}
In your build.gradle add latest design library.
compile 'com.android.support:design:X.X.X' // where X.X.X version
And then, in your fragment do:
Snackbar
.make(view, "Item deleted",Snackbar.LENGTH_SHORT)
.show();
The parameter view could be the fragment's root layout. You just need it's reference.
For more information see http://www.materialdoc.com/snackbar/
Add design Lib
Compile 'com.android.support:design:X.X.X'
Code:
case R.id.delete:
NotesDbAdapter dbAdapter = new NotesDbAdapter(getActivity().getBaseContext());
dbAdapter.open();
dbAdapter.deleteNote(note.getId());
notes.clear();
notes.addAll(dbAdapter.getAllNotes());
noteAdapter.notifyDataSetChanged();
dbAdapter.close();
// Show SNACK Bar
mRoot = (RelativeLayout) view.findViewById(R.id.mainrl);
Snackbar snackbar = Snackbar.make(mRoot , "Item Deleted", Snackbar.LENGTH_LONG);
snackbar.show();
here mRoot is your main root layout of your fragment.
Why is this code not working? is there any problem with switch case?
I have 2 spinners (of branch and semester). When a branch is selected it must show a Toast of selected branch and same with the semester.
public class MainActivity extends Activity implements OnItemSelectedListener, OnClickListener{
Spinner branch, semester;
Button go;
TextView branchText, semText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
branch = (Spinner) findViewById(R.id.spinner1);
semester = (Spinner) findViewById(R.id.spinner2);
go = (Button) findViewById(R.id.button1);
ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.Branch, android.R.layout.simple_spinner_item);
branch.setAdapter(adapter);
branch.setOnItemSelectedListener(this);
ArrayAdapter adapter1 = ArrayAdapter.createFromResource(this, R.array.Semester, android.R.layout.simple_spinner_item);
semester.setAdapter(adapter1);
semester.setOnItemSelectedListener(this);
go.setOnClickListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
switch (view.getId())
{
case R.id.spinner1:
branchText = (TextView) view;
Toast.makeText(this, branchText.getText(), Toast.LENGTH_SHORT).show();
break;
case R.id.spinner2:
semText = (TextView) view;
Toast.makeText(this, semText.getText(), Toast.LENGTH_SHORT).show();
break;
}
}
You should get the id of selected item by "AdapterView parent" not "View view".
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
switch (parent.getId()){
case R.id.spinner1:
branchText = (TextView) view;
Toast.makeText(this, branchText.getText(), Toast.LENGTH_SHORT).show();
break;
case R.id.spinner2:
semText = (TextView) view;
Toast.makeText(this, semText.getText(), Toast.LENGTH_SHORT).show();
break;
}
}
Change Toast.makeText(this, branchText.getText(), Toast.LENGTH_SHORT).show(); to Toast.makeText(this, branchText.getText().tostring(), Toast.LENGTH_SHORT).show();
change all branchText.getText() to branchText.getText().tostring()
Reference branch array and use position to retrieve branch text:
String[] branchArr = getResources().getStringArray(R.array.Branch);
case R.id.spinner1:
Toast.makeText(this, branchArr[position], Toast.LENGTH_SHORT).show();
break;
I'm using predefined listview layout to show all the native messaging sms into my application.Code i defined in onCreate method:
lvInb = (ListView) findViewById(R.id.lvInb);
lvInb.setOnCreateContextMenuListener(this);
data = fetchInbox();
if(data!=null)
{
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1 , data);
lvInb.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lvInb.setAdapter(adapter);
}
for fetchInbox() I've created another method:
public ArrayList<String> fetchInbox()
{
ArrayList<String> sms = new ArrayList<String>();
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor cr = getContentResolver().query(uriSms, new String[]{"_id", "address", "date", "body"},null,null,null);
cr.moveToFirst();
while (cr.moveToNext())
{
sms.add(cr.getString(1)+"\n"+cr.getString(3)+"\n");
}
cr.close();
return sms;
}
code to delete row item in listview is:
private void openDelete() {
removeListViewItem();
}
public void removeListViewItem() {
if(intListViewItemPosition != -1){
lvInb.removeViewAt(intListViewItemPosition);
adapter.notifyDataSetInvalidated();
intListViewItemPosition = -1;
}else{
Toast.makeText(this, "No item selected", Toast.LENGTH_SHORT).show();
}
}
code in activity:
ListView lvInb;
ArrayAdapter<String> adapter;
int intListViewItemPosition = -1;
ArrayList<String> data;
Outside onCreate method:
#Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, view, menuInfo);
CreateMenu (menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
MenuChoice(item);
return true;
}
private void CreateMenu(Menu menu)
{
MenuItem mnu1 = menu.add(0,0,0,"Delete");
{
mnu1.setIcon(R.drawable.ic_launcher);
}}
private boolean MenuChoice(MenuItem item)
{
switch (item.getItemId()) {
case 0:
removeListViewItem();
break;
}
return false;
}
public void removeListViewItem() {
intListViewItemPosition = lvInb.getSelectedItemPosition();
if(intListViewItemPosition != -1){
//lvInb.removeViewAt(intListViewItemPosition);
data.remove(intListViewItemPosition);
adapter.notifyDataSetInvalidated();
intListViewItemPosition = -1;
}else{
Toast.makeText(this, "No item selected", Toast.LENGTH_SHORT).show();
}
}
delete option i've provided in menu options. but when i select a row item and click on delete option it shows No item selected
Hey in where you are assigning the selected Item position value into "intListViewItemPosition"
If not used please implement this in your listview OnItemClickListener,
intListViewItemPosition= listView.getSelectedItemPosition();
You are trying to remove the selected Item from the listview right ?? for that you have clicked your listview item from the lisview, so you need to implement onClickListener for your listview
your code should be like this,
your_listView_name.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
intListViewItemPosition= listView.getSelectedItemPosition();
}
});
thats it..
first thing call fetchIndex only once:
declare an ArrayList of string in activity:
ArrayList<String> data;
ArrayAdapter<String> adapter
and in onCreate:
lvInb = (ListView) findViewById(R.id.lvInb);
lvInb.setOnCreateContextMenuListener(this);
data= fetchInbox();
if(data!=null)
{
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1 , data);
lvInb.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lvInb.setAdapter(adapter);
}
now change change removeListViewItem to:
public void removeListViewItem() {
intListViewItemPosition= lvInb.getSelectedItemPosition();
if(intListViewItemPosition != -1){
//lvInb.removeViewAt(intListViewItemPosition);
data.remove(intListViewItemPosition);
adapter.notifyDataSetInvalidated();
intListViewItemPosition = -1;
}else{
Toast.makeText(this, "No item selected", Toast.LENGTH_SHORT).show();
}
}
also have class level variable for adapter so that you can access it in removeListViewItem.
ArrayAdapter<String> adapter;
and in onCreate just say:
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1 , data);
If you declare it again in onCreate the class level one would be null and you might get null pointer when your removeListViewItem will get called.
so far i have an android app which can save data (Simple text) into a sqlite database and display it in to a list view. I would like to be able to add images as well but i dont know how.
here is the class which creates the rows everytime i add some text:
public class TestDatabaseActivity extends ListActivity {
private CommentsDataSource datasource;
int holanumero;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_database);
datasource = new CommentsDataSource(this);
datasource.open();
List<Comment> values = datasource.getAllComments();
// use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this, android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
final ListView listadeutiles = (ListView) findViewById(android.R.id.list);
//
listadeutiles.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
holanumero = position;
}});
}
// Will be called via the onClick attribute
// of the buttons in main.xml
public void onClick(View view) {
#SuppressWarnings("unchecked")
ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) getListAdapter();
Comment comment = null;
switch (view.getId())
{
case R.id.add:
EditText texto1 = (EditText) findViewById(R.id.editText1);
String palabra1 = texto1.getText().toString();
EditText texto2 = (EditText) findViewById(R.id.editText2);
String palabra2 = texto2.getText().toString();
String palabra3 = palabra1 + palabra2;
comment = datasource.createComment(palabra3);
adapter.add(comment);
texto1.setText("");
texto2.setText("");
break;
case R.id.delete:
if (getListAdapter().getCount() > 0) {
comment = (Comment) getListAdapter().getItem(holanumero);
datasource.deleteComment(comment);
adapter.remove(comment);
}
break;
}
adapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
Saving images in the database is rarely I good idea. You should store the file path to the image in the sd card, and then load that image in your getView() method in the ListView's adapter.
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.