Stuck trying to refresh ListView after deleting file - android

In my List2 activity (extending ListActivity), I am deleting a file and after that I call the method init(); to refresh my ListView but it's not refreshing, it's only duplicating (appearing old and new ones) items.
And if I click on one of those new generated items it will force close. I know notifyDatasetChanged doesn't work in my case.
Any help would be appreciated.
This is my List2 Class :
public class List2 extends ListActivity {
ListView lv;
private ListAdapter adapter;
public ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
public ArrayList<HashMap<String, String>> myHash = new ArrayList<HashMap<String, String>>();
// private ArrayList<DataSetObserver> observers = new
// ArrayList<DataSetObserver>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list2);
init();
lv = getListView();
registerForContextMenu(getListView());
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
// // Starting new intent
Intent in = new Intent(getApplicationContext(),
secondActivity.class);
// Sending songIndex to PlayerActivity
in.putExtra("Index", fileIndex);
// setResult(100, in);
// Closing PlayListView
startActivity(in);
finish();
}
});
}
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
}
public boolean onContextItemSelected(MenuItem item) {
final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
switch (item.getItemId()) {
case R.id.delete:
File file = new File(Path);
if (file.exists()) {
file.delete();
init();
}
return true;
default:
return super.onContextItemSelected(item);
}
}
public ArrayList<HashMap<String, String>> getPlayList() {
File home = new File(MEDIA_PATH);
if (home.listFiles(new FileExtensionFilter()).length > 0) {
for (File file : home.listFiles(new FileExtensionFilter())) {
HashMap<String, String> song = new HashMap<String, String>();
song.put(
"songTitle",
file.getName().substring(0,
(file.getName().length() - 4)));
song.put("songPath", file.getPath());
songsList.add(song);
}
}
// return songs list array
return songsList;
}
void init() {
this.getPlayList();
// looping through playlist
for (int i = 0; i < songsList.size(); i++) {
// creating new HashMap
HashMap<String, String> song = songsList.get(i);
myHash.add(song);
}
adapter = new SimpleAdapter(this, myHash, R.layout.playlist_item,
new String[] { "songTitle", "singerName" }, new int[] {
R.id.songTitle, R.id.singerName });
setListAdapter(adapter);
}
}

Its because you are adding myHash without clearing it, so it contains all of the old entries as well as the new ones. Simply call clear before you add more items to it.
void init() {
this.getPlayList();
myHash.clear();
// looping through playlist
for (int i = 0; i < songsList.size(); i++) {
// creating new HashMap
HashMap<String, String> song = songsList.get(i);
myHash.add(song);
}
adapter = new SimpleAdapter(this, myHash,
R.layout.playlist_item, new String[] { "songTitle","singerName" }, new int[] {
R.id.songTitle,R.id.singerName });
setListAdapter(adapter);
}

Related

How to create a long click event on a list view which shows options similar to context menu

How do I create a context menu after a long click event on a list view in this script?
I need to add an OnLongClickListener and show a context type menu as a result of a long click on one of the items in the listView.
public class MainActivity extends ListActivity {
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String nomer = ((TextView) view.findViewById(R.id.nomer))
.getText().toString();
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + nomer));
if (ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
return;
}
startActivity(callIntent);
}
});
}
class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url.get(), ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String nomer = c.getString(TAG_NOMER);
String date = c.getString(TAG_DATE);
String url = c.getString(TAG_URL);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put(TAG_NAME, name);
contact.put(TAG_NOMER, nomer);
contact.put(TAG_URL, url);
contact.put(TAG_DATE, date);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{TAG_NAME, TAG_NOMER, TAG_DATE,
TAG_URL}, new int[]{R.id.name, R.id.nomer,
R.id.date });
setListAdapter(adapter);
}
}
Register forcontext menu in your ListView:
registerForContextMenu(lv);
Add the overriding methods:
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId()==R.id.list_view) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_list, menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch(item.getItemId()) {
case R.id.add:
// add stuff here
return true;
case R.id.edit:
// edit stuff here
return true;
case R.id.delete:
// remove stuff here
return true;
default:
return super.onContextItemSelected(item);
}
}
And finally, add the menu file like below(Customize according to your requirement)
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/add"
android:icon="#android:drawable/ic_menu_add"
android:title="#string/menu_add" />
<item android:id="#+id/edit"
android:icon="#android:drawable/ic_menu_edit"
android:title="#string/menu_edit" />
<item android:id="#+id/delete"
android:icon="#android:drawable/my_icon_delete"
android:title="#string/menu_delete" />
</menu>
in res/menu folder

Android - update ListView from a fragment to another

I am trying to update listView from another fragment class after i delete an item from listView from current class. For example, i delete a consumer that has an expense, then the expense of that consumer will also be deleted. But consumer and expense is different page that using tab control, which is fragment, when i delete consumer, the expense list is not updated, until i go to previous page, then enter the page again. What can i do to update the expense list when consumer from consumer list is deleted? i heard of using broadcast receiver is able to do that, but how can i implement it in my code? I am new in android, please guide me.Thanks
Here is the code for consumer/participant list :
public class Participant extends ListFragment implements OnClickListener{
Intent intent;
TextView friendId;
Button addparticipant;
String eventId;
ListView lv;
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
EventController controller = new EventController(getActivity());
HashMap<String, String> queryValues = new HashMap<String, String>();
Intent objIntent = getActivity().getIntent();
eventId = objIntent.getStringExtra("eventId");
queryValues.put("eventId", eventId);
ArrayList<HashMap<String, String>> friendList = controller
.getAllFriends(queryValues);
if (friendList.size() != 0) {
lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
friendId = (TextView) view.findViewById(R.id.friendId);
String valFriendId = friendId.getText().toString();
Intent objIndent = new Intent(getActivity(),
EventPage.class);
objIndent.putExtra("friendId", valFriendId);
startActivity(objIndent);
}
});
lv.setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> arg0,
View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
friendId = (TextView) arg1.findViewById(R.id.friendId);
registerForContextMenu(getListView());
return false;
}
});
SimpleAdapter adapter = new SimpleAdapter(getActivity(),
friendList, R.layout.view_friend_entry, new String[] {
"friendId", "friendName", "friendSpending" },
new int[] { R.id.friendId, R.id.friendName,
R.id.friendSpending });
adapter.notifyDataSetChanged();
setListAdapter(adapter);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.participant, container, false);
addparticipant = (Button) rootView.findViewById(R.id.addpart);
addparticipant.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent objIntent = new Intent(getActivity(),
AddParticipant.class);
objIntent.putExtra("eventId", eventId);
startActivity(objIntent);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
String[] menuItems = getResources().getStringArray(R.array.menu);
for (int i = 0; i < menuItems.length; i++) {
menu.add(Menu.NONE, i, i, menuItems[i]);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
int menuItemIndex = item.getItemId();
EventController controller = new EventController(getActivity());
switch (menuItemIndex) {
case 0:
String valFriendId = friendId.getText().toString();
Intent objIndent = new Intent(getActivity(),
EditParticipant.class);
objIndent.putExtra("friendId", valFriendId);
startActivity(objIndent);
break;
case 1:
String valFriendId2 = friendId.getText().toString();
controller.deleteFriend(valFriendId2);
onResume();
}
return true;
}
#Override
public void onResume() {
super.onResume();
if (getListView() != null) {
updateData();
}
}
private void updateData() {
EventController controller = new EventController(getActivity());
HashMap<String, String> queryValues = new HashMap<String, String>();
Intent objIntent = getActivity().getIntent();
eventId = objIntent.getStringExtra("eventId");
queryValues.put("eventId", eventId);
SimpleAdapter adapter = new SimpleAdapter(getActivity(),
controller.getAllFriends(queryValues),
R.layout.view_friend_entry, new String[] { "friendId",
"friendName", "friendSpending" }, new int[] {
R.id.friendId, R.id.friendName, R.id.friendSpending });
setListAdapter(adapter);
}
}
Here is the code for expense list:
public class Expense extends ListFragment implements OnClickListener {
Button addexp;
TextView expenseId;
ListView lv;
String eventId, friendId;
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
EventController controller = new EventController(getActivity());
HashMap<String, String> queryValues = new HashMap<String, String>();
Intent objIntent = getActivity().getIntent();
eventId = objIntent.getStringExtra("eventId");
queryValues.put("eventId", eventId);
ArrayList<HashMap<String, String>> expenseList = controller
.getAllExpenses(queryValues);
if (expenseList.size() != 0) {
lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
expenseId = (TextView) view.findViewById(R.id.expenseId);
String valExpenseId = expenseId.getText().toString();
Intent objIndent = new Intent(getActivity(),
EditExpense.class);
objIndent.putExtra("expenseId", valExpenseId);
startActivity(objIndent);
}
});
SimpleAdapter adapter = new SimpleAdapter(getActivity(),
expenseList, R.layout.view_expense_entry, new String[] {
"expenseId", "expenseName","expenseQuantity" }, new int[] {
R.id.expenseId, R.id.expenseName, R.id.expenseQuantity });
adapter.notifyDataSetChanged();
setListAdapter(adapter);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.expense, container, false);
addexp = (Button) rootView.findViewById(R.id.addexp);
addexp.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent objIntent = new Intent(getActivity(), AddExpense.class);
objIntent.putExtra("eventId", eventId);
startActivity(objIntent);
}
#Override
public void onResume() {
super.onResume();
if (getListView() != null) {
updateData();
}
}
private void updateData() {
EventController controller = new EventController(getActivity());
HashMap<String, String> queryValues = new HashMap<String, String>();
Intent objIntent = getActivity().getIntent();
eventId = objIntent.getStringExtra("eventId");
queryValues.put("eventId", eventId);
SimpleAdapter adapter = new SimpleAdapter(getActivity(),
controller.getAllExpenses(queryValues),
R.layout.view_expense_entry, new String[] { "expenseId",
"expenseName", "expenseQuantity" }, new int[] { R.id.expenseId,
R.id.expenseName, R.id.expenseQuantity });
setListAdapter(adapter);
}
}
Same scenario with me, if you used FragmentPagerAdapter, Try like this in FirstFragment
private void updateSecondFragment(){
//Way to get TagName which generated by FragmentPagerAdapter
String tagName = "android:switcher:" + R.id.pager + ":" + 1; // Your pager name & tab no of Second Fragment
//Get SecondFragment object from FirstFragment
SecondFragment f2 = (SecondFragment)getActivity().getSupportFragmentManager().findFragmentByTag(tagName);
//Then call your wish method from SecondFragment to update appropriate list
f2.updateList();
}
I got that idea by reading this. Then edit a little !
One way could be creating the methods in the activity that contains the two fragments, and access to the fragments methods from the activity. You can update the database and reload the list in the same method.
For example, In the activity
public void updateFragment2(){ ... }
In fragment 1 you should call:
((ActivityClass)getActivity()).updateFragment2();
In the section "Communicating with the Activity" you can see the explanation of this example:
http://developer.android.com/guide/components/fragments.html

how to have a listActivity as a tab fragment of actionbar sherlock

I have an Listactivity and i want it as a fragment when someone selects it's tab,
below is the activity...
public class PlayListActivity extends ListActivity {
// Songs list
public ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);
ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();
SongsManager plm = new SongsManager();
// get all songs from sdcard
this.songsList = plm.getPlayList();
// looping through playlist
for (int i = 0; i < songsList.size(); i++) {
// creating new HashMap
HashMap<String, String> song = songsList.get(i);
// adding HashList to ArrayList
songsListData.add(song);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, songsListData,
R.layout.playlist_item, new String[] { "songTitle" }, new int[] {
R.id.songTitle });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting listitem index
int songIndex = position;
// Starting new intent
Intent in = new Intent(getApplicationContext(),
AndroidBuildingMusicPlayerActivity.class);
// Sending songIndex to PlayerActivity
in.putExtra("songIndex", songIndex);
setResult(100, in);
// Closing PlayListView
finish();
}
});
}
}
when i extend sherlockListActivity i get an error on "new SimpleAdapter" saying
The constructor SimpleAdapter(PlayListActivity, ArrayList<HashMap<String,String>>, int, String[], int[]) is undefined
how should i make it a fragment and have it output a list.

android delete file using context menu

I've got a Listview showing files currently on the SDcard. When you long press the file, a context menu pops up.
My question is: how do I pass in the selected item to the Context Menu in order to delete the file from the list, and is it possible to also delete it from the SDcard using this? My Code is as follows:
public class PlayListActivity extends ListActivity {
// Songs list
public ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);
ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();
SongsManager plm = new SongsManager();
// get all songs from sdcard
this.songsList = plm.getPlayList();
// looping through playlist
for (int i = 0; i < songsList.size(); i++) {
// creating new HashMap
HashMap<String, String> song = songsList.get(i);
// adding HashList to ArrayList
songsListData.add(song);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, songsListData,
R.layout.playlist_item, new String[] { "songTitle", "songDate" }, new int[] {
R.id.songTitle, R.id.songDate });
setListAdapter(adapter);
// setup ListView item
ListView lv = getListView();
registerForContextMenu(lv);
notifyDataSetChanged();
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting listitem index
int songIndex = position;
// Starting new intent
Intent in = new Intent(getApplicationContext(),
Bandboxstage.class);
// Sending songIndex to PlayerActivity
in.putExtra("songIndex", songIndex);
setResult(100, in);
// Closing PlayListView
finish();
}
});
}
private void notifyDataSetChanged() {
// TODO Auto-generated method stub
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.delete:
Toast.makeText(this, "Delete Called.", Toast.LENGTH_SHORT).show();
deleteFile(info.id);
return true;
case R.id.share:
Toast.makeText(this, "Share Called.", Toast.LENGTH_SHORT).show();
default:
return super.onContextItemSelected(item);
}
}
private void deleteFile(long id) {
// TODO Auto-generated method stub
}
}
Well your answer is in your implementation itself. If you notice, in your onContextItemSelected()
, the following statement brings in the info of the item you have selected in your main listview.
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
You can use info.position to find out the position of your item in the list and then get the object from your ArrayList using songsList.get(info.position).
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.delete:
Toast.makeText(this, "Delete Called.", Toast.LENGTH_SHORT).show();
//Make sure songsList is a global variable so that it can be accessed here.
HashMap<String, String> song = songsList.get(info.position);
//Call your delete function to delete the song.
return true;
case R.id.share:
Toast.makeText(this, "Share Called.", Toast.LENGTH_SHORT).show();
default:
return super.onContextItemSelected(item);
}
}
Refer this LINK it passes varialble on long click.
below is the deletefile function
file.delete() will delete the file.

How to add volume bar ,radio button and Checkbox for children in ExpandableListView?

I have to design settings for my application. My settings Group items are 1.Volume settings, 2.Share Settings, 3.Reminder settings. I Have design trough ExpandableListView. In Volume setting i want to provide a volume bar so that i can increase or reduce my volume. For share setting i want to provide checkbox for children . For Reminder setting i want to do that by radio buttons for children. Can you provide code.for that. here is My smple code.............
public class ExpandableListViewDemo4Activity extends Activity {
private static final String KEY1 = "GROUP";
private static final String KEY2 = "CHILD";
//String to be displayed
private String[] GROUPS = { "Video Volume Settings", "Reminder Settings", "Share Settings", "Other Settings" };
private String[][] CHILDREN = {
{ "low", "mediam", "high"},
{ "after 5 sec", "after 10 sec", "after 15 sec", "after 30 sec" },
{ "Facebook", "Twitter", "E-Mail", "Messaging" },
{ "channel", "news" }
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Setting a list of strings
List<Map<String, String>> groupData =
new ArrayList<Map<String, String>>();
List<List<Map<String, String>>> childData =
new ArrayList<List<Map<String, String>>>();
// Continue to set the string to the list
for (int i = 0; i < GROUPS.length; i++) {
//Adding a parent element
Map<String, String> curGroupMap =
new HashMap<String, String>();
groupData.add(curGroupMap);
curGroupMap.put(KEY1, GROUPS[i]);
curGroupMap.put(KEY2, "");
List<Map<String, String>> children =
new ArrayList<Map<String, String>>();
if (CHILDREN.length > i) {
for (int j = 0; j < CHILDREN[i].length; j++) {
//Add a child
Map<String, String> curChildMap =
new HashMap<String, String>();
children.add(curChildMap);
curChildMap.put(KEY1, CHILDREN[i][j]);
j]); }
}
childData.add(children);
}
// ExpandbleListAdapter create
ExpandableListAdapter adapter =
new SimpleExpandableListAdapter(
this,
groupData,
android.R.layout.simple_expandable_list_item_1,
new String[] { KEY1, KEY2 },
new int[] { android.R.id.text1, android.R.id.text2 },
childData,
android.R.layout.simple_expandable_list_item_2,
new String[] { KEY1, KEY2 },
new int[] { android.R.id.text1, android.R.id.text2 }
);
ExpandableListView listView =
(ExpandableListView) findViewById(R.id.ExpandableListView);
// set the Adapter
listView.setAdapter(adapter);
//Register a callback to be called when the user clicks the group
listView.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent,
View v, int groupPosition, long id) {
//What Happens When the user clicks
return false;
}
});
//Register a callback to be called when the item is clicked in the group
listView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
//What Happens When the user clicks
return true;
}
});
}
}
You should check out PreferenceActivity and PreferenceManager. Lars Vogel has an excellent tutorial on it:
http://www.vogella.de/articles/Android/article.html#preferences

Categories

Resources