Listview shows old and new content after updating - android

In my application, listview is loaded from SQLite database and it is using SimpleAdapter to set ListView. When user perform longclick on listitem, that item will be deleted from database and it should update listviw. But when i remove item from database, listview shows both old and new data.
Please suggest some solution.
Thanx.
Following is my code:
public class FavouriteListActivity extends ListActivity {
public final ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
ListAdapter adapter;
public ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();
ArrayList<String> titles = new ArrayList<String>();
String title,artist;
SQLiteAdapter adp;
SimpleCursorAdapter cursoradp;
Cursor cursor,cursorDB;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favouritelist);
// Adding menuItems to ListView
final String[] from = {"songTitle", "artist","duration"};
final int[] to={R.id.fav_songTitle,R.id.fav_songArtist,R.id.fav_duration};
ListView lv = getListView();
songsListData = getFavourites();
final ListAdapter adapter = new SimpleAdapter(this,songsListData,
R.layout.favouritelist_item, from, to);
lv.setFastScrollEnabled(true);
setListAdapter(adapter);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
{
public boolean onItemLongClick(AdapterView<?> av, View v,
final int pos,final long id) {
final AlertDialog.Builder b = new AlertDialog.Builder(FavouriteListActivity.this);
b.setTitle("Are you sure you want to delete?");
b.setIcon(android.R.drawable.ic_delete);
b.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String title = songsListData.get(pos).get("songTitle");
ListAdapter adapter = null;
adp.delete_byTitle(title);
songsListData.clear();
setListAdapter(null);
songsListData = getFavourites();
adapter = new SimpleAdapter(getApplicationContext(), songsListData,R.layout.favouritelist_item, from, to);
setListAdapter(adapter);
Toast.makeText(FavouriteListActivity.this,"Song is removed from Favourites", Toast.LENGTH_SHORT).show();
}
});
b.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
b.show();
return true;
}
});
}
public ArrayList<HashMap<String,String>> getFavourites()
{
ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();
ArrayList<String> titles = new ArrayList<String>();
adp = new SQLiteAdapter(this);
adp.openToRead();
cursorDB = adp.queueAll();
if(cursorDB.moveToFirst())
{
for(int i=0;i<cursorDB.getCount();i++)
{
titles.add(cursorDB.getString(cursorDB.getColumnIndex("Title")));
cursorDB.moveToNext();
}
String[] songTitles = new String[titles.size()];
songTitles = titles.toArray(songTitles);
if(songTitles == null)
{
songTitles =null;
}
String whereClause = MediaStore.Audio.Media.TITLE + " IN ( ?";
if (songTitles.length>1)
{
for (int j = 1 ; j < songTitles.length; ++j)
{
whereClause+=", ?";
}
}
whereClause+=")";
Cursor cursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,null ,whereClause,songTitles,MediaStore.Audio.Media.TITLE);
if (cursor == null)
{
//Query Failed , Handle error.
}
else if (!cursor.moveToFirst())
{
//No media on the device.
}
else
{
int titleColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = cursor.getColumnIndexOrThrow(android.provider.MediaStore.Audio.Media.DATA);
int artistcolumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.ARTIST);
int durationcolumn =cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.DURATION);
for(int i=0;i<cursor.getCount();i++)
{
String thisTitle = cursor.getString(titleColumn);
String path = cursor.getString(idColumn);
String artist = cursor.getString(artistcolumn);
Long duration = cursor.getLong(durationcolumn);
Utilities objUtilities = new Utilities();
String timeDuration = objUtilities.milliSecondsToTimer(duration);
HashMap<String, String> song = new HashMap<String, String>();
song.put("songTitle",thisTitle);
song.put("songPath", path);
song.put("artist", artist);
song.put("duration",timeDuration);
// Adding each song to SongList
songsList.add(song);
cursor.moveToNext();
}
}
// 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);
}
}
return songsListData;
}
}

You never clear songList, to which therefore is added all your items at each deletion.
Which in turn are all copied to songsListData.

After removing data from the database , call
Listview.invalidateViews();
and reset the adapter to the list .
Actually it gets removed from the database but it shows the older list in the ListView , so invalidate your older views and reset the adapter .

Call adapter.notifyDataSetChanged() every time your data changes.
b.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String title = songsListData.get(pos).get("songTitle");
adp.delete_byTitle(title);
songsListData.clear();
setListAdapter(null);
songsListData = getFavourites();
adapter = new SimpleAdapter(getApplicationContext(), songsListData,R.layout.favouritelist_item, from, to);
setListAdapter(adapter);
adapter.notifyDataSetChanged();
Toast.makeText(FavouriteListActivity.this,"Song is removed from Favourites", Toast.LENGTH_SHORT).show();
}
});

Related

How to set selection in spinner with SimpleAdapter?

I am populating spinner from below code and its working perfect. When user select any value from spinner then I am saving stateCodeId in sqlite. Now what I want that when user come again then I want to show the seleted value from ID which already saved in sqlite. How can I show value selected in spinner ?
public void fillStateData() {
try {
State_data = new ArrayList<Map<String, String>>();
State_data.clear();
Cursor cursor_State = db.rawQuery("SELECT nSerialNo as _id,cCodeName FROM CodeMaster where nCtgId = 6", null);
int i = 0;
if (cursor_State.moveToFirst()) {
do {
Map<String, String> datanum = new HashMap<String, String>();
if (i == 0) {
datanum.put("nStateID", "0");
datanum.put("cStateName", "Select State");
State_data.add(datanum);
datanum = new HashMap<String, String>();
datanum.put("nStateID", cursor_State.getString(0));
datanum.put("cStateName", cursor_State.getString(1));
State_data.add(datanum);
} else {
datanum.put("nStateID", cursor_State.getString(0));
datanum.put("cStateName", cursor_State.getString(1));
State_data.add(datanum);
}
i += 1;
} while (cursor_State.moveToNext());
}
String[] fromwhere = {"nStateID", "cStateName"};
int[] viewswhere = {R.id.txtnStateID, R.id.txtcStateName};
StateAdapter = new SimpleAdapter(getActivity(), State_data, R.layout.state_list_template, fromwhere, viewswhere);
spnState.setAdapter(StateAdapter);
cursor_State.close();
spnState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TextView stateId = (TextView) view.findViewById(R.id.txtnStateID);
stateCodeId = stateId.getText().toString();
fillDistrictData(stateCodeId);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
Like this I am getting ID from sqlite.
Cursor c = db.rawQuery("SELECT nStateId from MemberMaster where nCustID ="+SesPMbrID+"", null);
c.moveToFirst();
String state = c.getString(0);
Use
spinner.setSelection(position);

Android list view with additional extra hidden fields

I am using listview in android. Previously i used to pull data from database so I used CursorAdapter but now I am fetching response from website and on the website I have different links and each link has its name associated with it. I have names and links in two arrays of string. I have to show only the names and when clicked each name will open a same new intent with link as parameter.
Here is what I am doing
listView = (ListView) findViewById(R.id.list);
String[] names= new String[] { "name1",
"name2"
};
String[] links= new String[] { "link1",
"link2"
};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, send names and links);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String itemValue = (String) listView.getItemAtPosition(position);
Intent myIntent = new Intent(arg0.getContext(), NewPage.class);
myIntent.putExtra("Url",how to get this);
startActivity(myIntent);
}
});
}
Wrap the two pieces of information in a custom object:
class Data {
String name;
String link;
#Override
public String toString() {
return name;
}
}
Building the list of data items:
String[] names= new String[] { "name1",
"name2"
};
String[] links= new String[] { "link1",
"link2"
};
List<Data> output = new ArrayList<Data>();
for (int i = 0; i < names.length; i++) {
Data d = new Data();
d.name = names[i];
d.link = links[i]
output.add(d);
}
ArrayAdapter<Data> adapter = new ArrayAdapter<Data>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, output);
You can then use the Data in the OnItemClickListener:
Data item = (Data) listView.getItemAtPosition(position);
Intent myIntent = new Intent(arg0.getContext(), NewPage.class);
myIntent.putExtra("Url", d.link);
startActivity(myIntent);

show songs of an selected album in Listview

I want to show the songs of an selected album by overriding the currently used ListView.
But I don't get it. In this code I show all albums and get their songs.
Maybe you can help me.Thanks a lot, Vinzenz :)
public class Albumsshow extends ListActivity {
public ArrayList<HashMap<String, String>> albumsList = new ArrayList<HashMap<String, String>>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.browse);
ArrayList<HashMap<String, String>> albumsListData = new ArrayList<HashMap<String, String>>();
AlbumsManager plm = new AlbumsManager();
// get all songs from sdcard
this.albumsList = plm.getAlbumList(this);
// looping through playlist
for (int i = 0; i < albumsList.size(); i++) {
// creating new HashMap
HashMap<String, String> album = albumsList.get(i);
// adding HashList to ArrayList
albumsListData.add(album);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, albumsListData,
R.layout.playlist_item, new String[] { "album" }, new int[] {
R.id.songTitle });
setListAdapter(adapter);
// selecting single ListView item
final ListView lv = getListView();
final TextView tv =(TextView)findViewById(R.id.umandern);
// 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 albumIndex = position;
String[] column = { MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.MIME_TYPE, };
String where = android.provider.MediaStore.Audio.Media.ALBUM + "=?";
String whereVal[] = {albumsList.get(albumIndex).get("album") };
String orderBy = android.provider.MediaStore.Audio.Media.TITLE;
Cursor cursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
column, where, whereVal, orderBy);
if (cursor.moveToFirst()) {
do {
Log.v("music title",
cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)));
} while (cursor.moveToNext());
}
}
});
}
}
The code your using is the code i had and it's not overly hard, the only problem you may end up having is actually playing the songs but other than that you can list all albums and the songs like this....
public class AlbumsList extends ListActivity{
public ArrayList<HashMap<String,String>> songsList = new ArrayList<HashMap<String, String>>();
int count;
Cursor cursor;
ListView musiclist;
int songAlbum;
int position;
ListView list;
String songTitle = "";
String songPath = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.albums);
list = (ListView) findViewById(android.R.id.list);
String[] columns = { BaseColumns._ID,
AlbumColumns.ALBUM };
cursor = getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
columns, null, null, null);
String[] displayFields = new String[] { AlbumColumns.ALBUM };
int[] displayViews = new int[] { android.R.id.text1 };
#SuppressWarnings("deprecation")
ListAdapter adapter = (new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, cursor, displayFields,
displayViews));
setListAdapter(adapter);
}
public AlbumsList(){
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
if(cursor.moveToPosition(position)){
ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();
// get all songs from sdcard
this.songsList = this.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);
}
ListAdapter adapter = new SimpleAdapter(this, songsListData,
android.R.layout.simple_list_item_1, new String[] { "songTitle", "songPath" }, new int[] {
android.R.id.text1});
setListAdapter(adapter);
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(AlbumsList.this,
MainActivity.class);
Log.d("TAG","onItemClick");
// Sending songIndex to PlayerActivity
in.putExtra("songPath", songIndex);
startActivityForResult(in, 99);
// Closing PlayListView
finish();
}
});
}
}
public ArrayList<HashMap<String, String>> getPlayList(){
String[] columns = { MediaColumns.DATA,
BaseColumns._ID,
MediaColumns.TITLE,
MediaColumns.MIME_TYPE, };
String where = AudioColumns.ALBUM
+ "=?";
String whereVal[] = { cursor.getString(cursor
.getColumnIndex(AlbumColumns.ALBUM))};
String orderBy = MediaColumns.TITLE;
cursor = this.getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,columns,
where, whereVal, orderBy);
if (cursor.moveToFirst()) {
do {
songTitle = cursor.getString(cursor.getColumnIndexOrThrow(MediaColumns.TITLE));
songPath = cursor.getString(cursor.getColumnIndexOrThrow(MediaColumns.DATA));
HashMap<String, String> song = new HashMap<String, String>();
song.put("songTitle", songTitle);
song.put("songPath", songPath);
songsList.add(song);
} while (cursor.moveToNext());
}
cursor.close();
return songsList;
}

Set Text of TextView in ListView

In my ListView, I save my data like this:
public void listview_fuellen(){
DBHelper db = new DBHelper(this);
ListView lv = (ListView) findViewById(R.id.lvKinder);
Cursor c = db.select();
int count = c.getCount();
TextView tv = (TextView) findViewById(R.id.secondLine);
List<String> auswahl = new ArrayList<String>();
List<String> auswahl1 = new ArrayList<String>();
int i = 0;
System.out.println("$$$$$$$$$$$$$$$$$$$$$$$1" + c.getCount());
while(c.moveToNext())
{
auswahl.add(c.getString(c.getColumnIndex("name")));
auswahl1.add(" " + i);
System.out.println("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS" + auswahl.get(i).toString());
i++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_black_text,R.id.firstLine, auswahl);
//ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, R.layout.list_black_text,R.id.secondLine, auswahl1);
lv.setAdapter(adapter);
}
Now, I tried the layout for my listview from here:
http://android-developers.blogspot.co.at/2009/02/android-layout-tricks-1.html
Now, how can I set values for the second line in each ListView-Item or the icon?
EDIT:
I tried it like this now, but there are no entries in my listview then.
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();;
int i = 0;
System.out.println("$$$$$$$$$$$$$$$$$$$$$$$1" + c.getCount());
while(c.moveToNext())
{
//map = new HashMap<String, String>();
map.put("name",c.getString(c.getColumnIndex("name")));
map.put("datum", c.getString(c.getColumnIndex("zeit")));
i++;
}
mylist.add(map);
SimpleAdapter mSchedule = new SimpleAdapter(this, mylist, R.layout.list_black_text, new String[] { "datum",
"name" }, new int[] { R.id.firstLine, R.id.secondLine });
lv.setAdapter(mSchedule);
setListAdapter(mSchedule);
What have I done wrong?
for that you can make a custom adapter and then you can set values for the second line in each ListView-Item.
You can check this link
http://devtut.wordpress.com/2011/06/09/custom-arrayadapter-for-a-listview-android/

Android Muticolum listview onListItemClick

I have done Muticolum listview onListItemClick .Its working fine.Problem is
This line String selection = l.getItemAtPosition(position).toString(); return this
{routeName=TestRoute2, outlets=5, routeCode=VRT002} .I want to get it selected row's 3rd column value.How to get it.
Please help me..
Thanks in advance..
What kind of Adapter? E.g. for a SimpleCursorAdapter you would do the following:
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
long aLongValue = cursor.getLong(cursor.getColumnIndexOrThrow("anintegercolumn"));
ArrayList<HashMap<String, String>> historyArrayList;
SimpleAdapter histroyListAdapter;
HashMap<String, String> historyObjectMap;
for (CheckInCheckOutHistory checkOutHistoryObj : checkInCheckOutHistoryList) {
historyObjectMap = new HashMap<String, String>();
historyObjectMap.put("assetTag", checkOutHistoryObj.getAssetTag());
historyObjectMap.put("action", checkOutHistoryObj.getAction());
historyObjectMap.put("actionTime", checkOutHistoryObj.getActionDate());
if (checkOutHistoryObj.getAction().equals("Checked out")) {
historyObjectMap.put("gif", R.drawable.radio_button_yellow+ "");
} else {
historyObjectMap.put("gif", R.drawable.radio_button_green+ "");
}
historyArrayList.add(historyObjectMap);
}
histroyListAdapter = new SimpleAdapter(
ViewCheckInCheckOutHistory.this, historyArrayList,
R.layout.multi_colummn_list_text_style_small, new String[] {
"assetTag", "gif" , "action", "actionTime"},
new int[] { R.id.list_content_column1,
R.id.list_content_imagecolumn,
R.id.list_content_column3,
R.id.list_content_column4});
historyListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> historyObjectMapLocal = historyArrayList
.get(position);
final String assetTag = historyObjectMapLocal
.get("assetTag");
System.out.println("assetTag : " + assetTag);
}
});
In the above code the listView contents are populated using an ArrayList historyArrayList
and so the items at any column could be accessed using key ("assetTag", "gif" , "action", "actionTime").

Categories

Resources