Initially it shows the correct item selected...but after re-populating the list it shows the wrong item being selected...please help me find the mistake
Intially the list is populated in onCreate()
and is re-populated in onOptionsItemSelected(MenuItem item)
public class MainActivity extends Activity {
MyListActivity adapter;
ListView list;
String[] web = {
"jerry",
"walters"
} ;
Integer[] imageId = {
R.drawable.ic_launcher,
R.drawable.ic_launcher
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new MyListActivity(MainActivity.this, web, imageId);
list=(ListView)findViewById(R.id.listView1);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at " +web[+ position], Toast.LENGTH_SHORT).show();
}
});
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
String[] web2 = {
"walters",
"jerry"
} ;
adapter = new MyListActivity(MainActivity.this, web2, imageId);
list.setAdapter(adapter);
return true;
}
return false;
}
}
You have this
web[position]
// get string from web string array not from web2 based on position
Position is the index.
web[0] = "jerry"
web[1] ="walters"
You are re-populating your listview with a different array.
web and web2 are two different arrays.
If you want to update , update the web array and call notifyDataSetChanged on your adapter to refresh listview
your are not updating your web array:
public class MainActivity extends Activity {
MyListActivity adapter;
ListView list;
String[] web = {
"jerry",
"walters"
} ;
Integer[] imageId = {
R.drawable.ic_launcher,
R.drawable.ic_launcher
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new MyListActivity(MainActivity.this, web, imageId);
list=(ListView)findViewById(R.id.listView1);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at " +web[position], Toast.LENGTH_SHORT).show();
}
});
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
web = {//<--------------just update we array as well
"walters",
"jerry"
} ;
adapter = new MyListActivity(MainActivity.this, web, imageId);
list.setAdapter(adapter);
return true;
}
return false;
}
}
I guess it might because web and web2 have different order which leads to different answer?
String[] web = { "jerry", "walters"} ;
String[] web2 = {"walters", "jerry" } ;
Related
I need to remove selected by chechbox items from ListView using a button from Options Menu. After selecting items, I'm trying to click delete button on Options Menu and then my application crashes. When I'm using same code when button is at the same xml where the listview everything goes correctly, problem only happen when I'm trying to do same thing using Options Menu Item.
EDIT: I'm pasting my whole code
This is my code from main_activity.java
public class MainActivity extends AppCompatActivity {
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
private ListView lvItems;
private static final String TAG = "MainActivity";
Button delete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_main);
lvItems = (ListView) findViewById(id.lvItems);
lvItems.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this, layout.item_to_do, id.task_title, items);
lvItems.setAdapter(itemsAdapter);
items.add("Pierwsza rzecz");
items.add("Druga rzecz");
delete = (Button) findViewById(id.action_delete_task);
setupListViewListener();
}
public void onCheckboxClicked(View view) {
// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();
// Check which checkbox was clicked
switch (view.getId()) {
case id.task_delete:
if (checked)
break;
}
}
private void setupListViewListener() {
lvItems.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View view, int position, long id) {
items.remove(position);
itemsAdapter.notifyDataSetChanged();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case id.action_add_task:
final EditText taskEditText = new EditText(this);
taskEditText.setAllCaps(true);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add a new task");
builder.setMessage("What do you want to do next?");
builder.setView(taskEditText);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String task = String.valueOf(taskEditText.getText());
Log.d(TAG, "Task to add: " + task);
itemsAdapter.add(task);
Snackbar.make(findViewById(id.lvItems), string.add,
Snackbar.LENGTH_SHORT)
.show();
}
});
builder.setNegativeButton("Cancel", null);
AlertDialog dialog = builder.create();
dialog.show();
return true;
case id.action_delete_task:
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SparseBooleanArray checkedItemPositions = lvItems.getCheckedItemPositions();
int itemCount = lvItems.getCount();
for (int i = itemCount - 1; i >= 0; i--) {
if (checkedItemPositions.get(i)) {
itemsAdapter.remove(items.get(i));
}
}
checkedItemPositions.clear();
itemsAdapter.notifyDataSetChanged();
}
});
default:
return super.onOptionsItemSelected(item);
}
}
}
delete is menu item not a view in your layout so you will not set click listener on it.
Remove Button delete from your class
And Just do like below
case id.action_delete_task:
SparseBooleanArray checkedItemPositions = lvItems.getCheckedItemPositions();
int itemCount = lvItems.getCount();
for (int i = itemCount - 1; i >= 0; i--) {
if (checkedItemPositions.get(i)) {
itemsAdapter.remove(items.get(i));
}
}
checkedItemPositions.clear();
itemsAdapter.notifyDataSetChanged();
Also I can not see onCreateOption menu in your code. This is used to inflate menu in your activity.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.your_menu, menu);
return true;
}
My app has search feature in ActionBar that can filter listView in MainActivity. Unfortunately, after I filter listView and click on first element on the list, app opens activity of the first element on the list before filtering, instead of doing nothing (because I haven't created other activities yet). I would like to have maintain position from original listView. My code is specific:
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setIcon(R.mipmap.ic_launcher_round);
final ListView listView = (ListView)findViewById(R.id.listViewElements);
ArrayList<String> arrayElements = new ArrayList<>();
arrayElements.addAll(Arrays.asList(getResources().getStringArray(R.array.array_elements)));
adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, arrayElements);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (id == 0) {
Intent myIntent = new Intent(MainActivity.this, wodor.class);
startActivityForResult(myIntent, 0);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_search, menu);
MenuItem item = menu.findItem(R.id.menuSearch);
SearchView searchView = (SearchView)item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
I've got a context menu bar that has two icons...When I click the save icons I want to store all the the items I've checked in my list view in SharedPreferences and when I click the load icon, I want all those checked items to appear in the list as highlighted.
The icons are declared as menu items in the OnActionItemClicked.
Any ideas would be much appreciated.
My Class:
public class UserContacts extends ActionBarActivity {
SimpleCursorAdapter mAdapter;
MatrixCursor mMatrixCursor;
ListView listview;
int count = 0;
SharedPreferences prf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_contacts);
// The contacts from the contacts content provider is stored in this cursor
mMatrixCursor = new MatrixCursor(new String[] { "_id","name","photo","details"} );
// Adapter to set data in the listview
mAdapter = new SimpleCursorAdapter(getBaseContext(),
R.layout.lv_layout,
null,
new String[] { "name","photo","details"},
new int[] { R.id.tv_name,R.id.iv_photo,R.id.tv_details}, 0);
// Getting reference to listview
final ListView lstContacts = (ListView) findViewById(R.id.lst_contacts);
// Setting the adapter to listview
lstContacts.setAdapter(mAdapter);
// Creating an AsyncTask object to retrieve and load listview with contacts
ListViewContactsLoader listViewContactsLoader = new ListViewContactsLoader();
// Starting the AsyncTask process to retrieve and load listview with contacts
listViewContactsLoader.execute();
//Selecting and highlighting the elements in the listview
//Creating the context menu and the options for it
listview = (ListView) findViewById(R.id.lst_contacts);
listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listview.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
try
{
final int checkedCount = listview.getCheckedItemCount();
mode.setTitle("Contacts: " + checkedCount);
if (checked)
{
count = count+1;
listview.getChildAt(position).setBackgroundColor(Color.parseColor("#6DCAEC"));
}
else
{
count = checkedCount;
listview.getChildAt(position).setBackgroundColor(Color.parseColor("#E7E8E9"));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contact_context_menu, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.delete_id:
Toast.makeText(getBaseContext(), count + " Contacts Deselected", Toast.LENGTH_SHORT).show();
count = 0;
mode.finish();
case R.id.save_id:
Toast.makeText(getBaseContext(), count + " Contacts Saved", Toast.LENGTH_SHORT).show();
count = 0;
mode.finish();
case R.id.load_id:
Toast.makeText(getBaseContext(), count + " Contacts Loaded", Toast.LENGTH_SHORT).show();
count = 0;
mode.finish();
}
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
});
}
I have a android list layout. Basically it will list user's info on the screen. Please help me explain how the listView set the data. How the SimpleCursorAdapter links with Loader
Here's code :
public class ChatList extends ListActivity implements LoaderManager.LoaderCallbacks<Cursor>{
private SimpleCursorAdapter adapter;
private final int Adapter_AccountName = 1;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chatlist);
adapter = new SimpleCursorAdapter(this,
R.layout.main_list_item,
null,
new String[]{DataProvider.COL_NAME, DataProvider.COL_COUNT,DataProvider.PROFILE_COL_LASTMSGAT,DataProvider.PROFILE_COL_IMAGE},
new int[]{R.id.text1, R.id.text2,R.id.text3,R.id.avatar},
0);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
switch(view.getId()) {
// here can add one more line in the main page for each account
case R.id.text2:
int count = cursor.getInt(columnIndex);
if (count > 0) {
((TextView)view).setText(String.format("%d new message%s", count, count==1 ? "" : "s"));
}
return true;
case R.id.text3:
String lastUpdate = cursor.getString(columnIndex);
Date d = DbDatetimeUtility.getDate(cursor.getString(columnIndex));
Date t = DbDatetimeUtility.getCurrentDate();
((TextView)view).setText(DbDatetimeUtility.returnDifferentTime(d,t));
return true;
case R.id.avatar:
byte[] imageByte = cursor.getBlob(columnIndex);
((ImageView)view).setImageBitmap(DbBitmapUtility.getResizedBitmap(DbBitmapUtility.getImage(imageByte),125,125));
return true;
}
return false;
}
});
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
//final ListView listView = getListView();
final ListView listView = getListView();
listView.setAdapter(adapter);
getLoaderManager().initLoader(0, null, this);
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent intent = new Intent(this, ChatActivity.class);
intent.putExtra(Common.PROFILE_ID, String.valueOf(id));
startActivity(intent);
}
//----------------------------------------------------------------------------
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
CursorLoader loader = new CursorLoader(this,
DataProvider.CONTENT_URI_PROFILE,
new String[]{DataProvider.COL_ID, DataProvider.COL_NAME, DataProvider.COL_COUNT,DataProvider.PROFILE_COL_LASTMSGAT,DataProvider.PROFILE_COL_IMAGE},
null,
null,//new String[]{DataProvider.PROFILE_COL_LASTMSGAT},
DataProvider.PROFILE_COL_LASTMSGAT + " DESC");
return loader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
}
Thanks in advance!
Briefly for now, the main points are:
onCreateLoader gets the data from the SQLite database.
This code adapter = new SimpleCursorAdapter, populates the adapter.
This code listView.setAdapter(adapter); populates the ListView.
There is a nice Stackoverflow answer at Using SimpleCursorAdapter to get Data from Database to ListView
I want to delete the items from the fragments. When long click on the items than a action bar is changed and a delete button appears. I click on the delete button The item seems to be deleted from the list view. But when I restart the app the item appears again.
public class ReadFragment extends Fragment {
ListView spinner;
TextView empty;
String selected;
List<String> list;
String[] filenames;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_read, container,
false);
spinner = (ListView) rootView.findViewById(R.id.spinner2);
this.spinner.setEmptyView(rootView.findViewById(R.id.emptyElement));
getFilenames();
getactionbar();
return rootView;
}
private void getFilenames() {
// TODO Auto-generated method stub
filenames = getActivity().fileList();
list = new ArrayList<String>();
for (int i = 0; i < filenames.length; i++) {
// Log.d("Filename", filenames[i]);
list.add(filenames[i]);
}
ArrayAdapter<String> filenameAdapter = new ArrayAdapter<String>(
getActivity(), android.R.layout.simple_list_item_1,
android.R.id.text1, list);
spinner.setAdapter(filenameAdapter);
spinner.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
selected = ((TextView) view).getText().toString();
Intent intent = new Intent(getActivity(), ReadData.class);
intent.putExtra("key", selected);
startActivity(intent);
}
});
}
private void getactionbar() {
// TODO Auto-generated method stub
spinner.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
spinner.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
// Here you can do something when items are selected/de-selected,
// such as update the title in the CAB
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// Respond to clicks on the actions in the CAB
switch (item.getItemId()) {
case R.id.ic_action_discard:
deletefiles();
Toast.makeText(getActivity(), "Deleted", Toast.LENGTH_LONG).show();
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
private void deletefiles() {
// TODO Auto-generated method stub
SparseBooleanArray checkedItemPositions = spinner.getCheckedItemPositions();
int itemCount = spinner.getCount();
for(int i=itemCount-1; i >= 0; i--){
if(checkedItemPositions.get(i)){
filenameAdapter.remove(list.get(i));
}
}
checkedItemPositions.clear();
filenameAdapter.notifyDataSetChanged();
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate the menu for the CAB
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context, menu);
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// Here you can make any necessary updates to the activity when
// the CAB is removed. By default, selected items are deselected/unchecked.
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// Here you can perform updates to the CAB due to
// an invalidate() request
return false;
}
});
}
}
Can anyone help me deleting the item forever, I mean once it is deleted it should not appear in the listview again when the app is relaunched.
Try, tries it worked here
final Button btnRemove = (Button) findViewById(R.id.button1);
btnRemove.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
lst.remove(adapter.getItem(2));
adapter.notifyDataSetChanged();
}
});;
I don't know if it is intentionally, but you copy the items from the Activity into another array before passing it to the Adapter. So when you call adapter.remove() it only removes the item from the new one leaving the original List in the Activity untuched (guess you save that one to storage in the Activitys onPause or something).