Android list view with additional extra hidden fields - android

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);

Related

Spinner not showing data

I am using a spinner in my program and it gets data from my azure SQL database, but when i clicked the drop down nothing happens. Here is my code
try {
ConnectionHelper conStr = new ConnectionHelper();
connect = conStr.connectionclass();
String query = "select * from fabric";
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery(query);
ArrayList<String> data = new ArrayList<String>();
while (rs.next()) {
String id = rs.getString("FABRIC_NAME");
data.add(id);
}
String[] array = data.toArray(new String[0]);
ArrayAdapter NoCoreAdapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, data);
Fabric.setAdapter(NoCoreAdapter);
} catch (SQLException e) {
e.printStackTrace();
}
Fabric.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String name = Fabric.getSelectedItem().toString();
Toast.makeText(Calc_140_plain.this, name, Toast.LENGTH_SHORT)
.show();
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
i cant seem to find an error in LogCat as well
Make sure your data array has some element
while (rs.next()) {
String id = rs.getString("FABRIC_NAME");
data.add(id);
}
Log.d("data","size:"+data.size());
print size after while to check data is not empty.
Try this:
ArrayAdapter NoCoreAdapter = new ArrayAdapter<String>(context,
android.R.layout.simple_list_item_1, data);
instead of:
ArrayAdapter NoCoreAdapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, data);

List view with rawquery Could not execute method

I have a little issue that I don't know how to address.
I have a Cursor that gets data from my data base it looks like this:
public Cursor getAllData(){
int id;
SQLiteDatabase DB = this.getWritableDatabase();
String dateTime = Helper.getCurrentDate();
String date = dateTime.substring(0, 10);
String date_to_look = date.substring(0, 10);
String sql = "SELECT h.product_id, h.qty, h.date_time, p.product " +
" FROM product_history h " +
" LEFT JOIN products p ON (p.rowid = h.product_id) ";
Cursor res = DB.rawQuery(sql, null);
return res;
}
Then on my activity I'm using the following method:
public void populateListView() {
Cursor cursordata = myDb.getAllData();
String productname = cursordata.getString(cursordata.getColumnIndex("product"));
String [] products = {productname};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, products);
ListView listviewman = (ListView)findViewById(R.id.listviewman);
listviewman.setAdapter(adapter);
}
Execute it with onclick:
public void shine(View v){
Button shine = (Button)findViewById(R.id.shine);
populateListView();
}
What am I doing wrong?
Edit:
Shows last row from the table only.
public void populateListView() {
Cursor cursordata = myDb.getAllData();
if (cursordata.moveToFirst()) {
do {
String productname = cursordata.getString((cursordata.getColumnIndex("product")));
String [] products = {productname};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, products);
ListView listviewman = (ListView)findViewById(R.id.listviewman);
listviewman.setAdapter(adapter);
} while (cursordata.moveToNext());
}
Sahil here is the updated version of your suggestion which i use, it's not working:
public void populateListView() {
Cursor cursordata = myDb.getAllData();
List<String> li_records=new ArrayList<String>;
if (cursordata.moveToFirst()) {
do {
String productname = cursordata.getString((cursordata.getColumnIndex("product")));
String[] products = {productname};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, products);
ListView listviewman = (ListView) findViewById(R.id.listviewman);
listviewman.setAdapter(adapter);
li_records.add(productname);
} while (cursordata.moveToNext());
}
String[] products=li_records.toArray();
}
try this it will work fine:
public void populateListView() {
Cursor cursordata = myDb.getAllData();
ArrayList<String> products = new ArrayList<>();
if (cursordata.moveToFirst()) {
do {
String productname = cursordata.getString((cursordata.getColumnIndex("product")));
products.add(productname);
} while (cursordata.moveToNext());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, products);
ListView listviewman = (ListView)findViewById(R.id.listviewman);
listviewman.setAdapter(adapter);
}
Try to put
cursordata.moveToFirst()
after
List<String> li_records=new ArrayList<String>;
Cursor cursordata = myDb.getAllData();
use do while loop like this,
// looping through all rows and adding to list
if (cursordata.moveToFirst()) {
do {
String productname = c.getString((c.getColumnIndex("product")));
li_records.add(productname);
} while (cursordata.moveToNext());
}
String[] products=li_records.toArray();
use this array in your adapter

How to upgrade gridview in android using two threads with only one gridview in xml layout

I am having items in a gridview which where displayed from sqlite ..Now using another thread i am fetching data from json webservice and storing the data in sqlite now i want to display the updated items in the same grid view along with the existing items..
private void displayUpdate(String Bid) {
Log.w("Update cALL","Executing Update");
System.out.println("aeqw cursor that in display table value"+getid(Bid).getCount());
Cursor cursorx =getid(Bid);
int p=Integer.parseInt(Bid);
System.err.println("Recieving Bid to displayUpdate method"+p);
if (getid(Bid) != null)
{
while(cursorx.moveToFirst())
{
Log.e("Entering Loop", "WHILE EXECUTING");
String temp_id1 = cursorx.getString(0);
System.err.println("Name related to Bid to displayUpdate method"+temp_id1);
final String temp_name1 = cursorx.getString(1);
System.err.println("Name related to Bid to displayUpdate method"+temp_name1);
String temp_author1=cursorx.getString(2);
String temp_desc1=cursorx.getString(3);
byte[] temp_image1 = cursorx.getBlob(4);
String temp_rating1 = cursorx.getString(5);
String temp_price1 = cursorx.getString(6);
String temp_update1=cursorx.getString(7);
System.err.println("Name related to Bid to displayUpdate method"+temp_name1);
mapIdUp.add(temp_id1);
mapNameUp.add(temp_name1);
mapAuthorUp.add(temp_author1);
mapDescUp.add(temp_desc1);
mapRatingUp.add(temp_rating1);
mapPriceUp.add(temp_price1);
mapUp.add(temp_image1);
mapUpdatedUp.add(temp_update1);
Log.e("temp_id from the sqlite", temp_id1);
Log.i(temp_name1, temp_name1);
Log.i(temp_desc1, temp_desc1);
Log.i(temp_rating1, temp_rating1);
Log.e(temp_update1,temp_update1);
String[] captionArray1 = (String[]) mapNameUp.toArray(new String[mapNameUp.size()]);
ItemsAdapter itemsAdapter1 = new ItemsAdapter(
Bookicon.this, R.layout.item,captionArray1);
gridView1=(GridView)findViewById(R.id.list);
gridView1.setAdapter(itemsAdapter1);
itemsAdapter1.notifyDataSetChanged();
gridView1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
Intent i = new Intent(getApplicationContext(), DetailsActivity.class);
i.putExtra("id", position);
startActivity(i);
}
});
break;
}
}
}
this method is called in the second thread to display the updated books ..
where are this method is used to display all the items in the sqlite table
private void getDataAndPopulate()
{
Log.w("hello","zyuk,");
Cursor cursor = getEvents("bcuk_book");
while (cursor.moveToNext())
{
String temp_id = cursor.getString(0);
final String temp_name = cursor.getString(1);
String temp_author=cursor.getString(2);
String temp_desc=cursor.getString(3);
byte[] temp_image = cursor.getBlob(4);
String temp_rating = cursor.getString(5);
String temp_price = cursor.getString(6);
String temp_update=cursor.getString(7);
mapId.add(temp_id);
mapName.add(temp_name);
mapAuthor.add(temp_author);
mapDesc.add(temp_desc);
mapRating.add(temp_rating);
mapPrice.add(temp_price);
map.add(temp_image);
mapUpdated.add(temp_update);
Log.e("temp_id from the sqlite", temp_id);
Log.i(temp_name, temp_name);
Log.i(temp_desc, temp_desc);
Log.i(temp_rating, temp_rating);
Log.e(temp_update,temp_update);
String[] captionArray = (String[]) mapName.toArray(new String[mapName.size()]);
ItemsAdapter itemsAdapter = new ItemsAdapter(
Bookicon.this, R.layout.item,captionArray);
gridView=(GridView)findViewById(R.id.list);
gridView.setAdapter(itemsAdapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
Intent i = new Intent(getApplicationContext(), DetailsActivity.class);
i.putExtra("id", position);
startActivity(i);
}
});
}
}
Issue is i am not able to display the updated one whereas it was showing already stored items ..
If let us assume there are items like 1,2,3,4,5 when i update new item with 6 i.e one record it is displaying first item i.e 1. If update 2 records then it displaying only first two records..
How to solve this issue

Listview shows old and new content after updating

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();
}
});

Passing info from one intent to the other

I have an app which reads some data from JSON, and I have 2 classes which do this.
Right now both classes display the full list of registered members.
But what I'm trying to achieve is that when a member is clicked I only get to see that member and not the other ones as well.
Here is the code from both classes:
From the listview:
public class Listviewer extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions.getJSONfromURL("http://de-saksen.nl/deelnemers.txt");
try{
JSONArray deelnemers = json.getJSONArray("deelnemers");
for(int i=0;i<deelnemers.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = deelnemers.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "Character Naam: " + e.getString("naamingw2"));
map.put("sex", "Geslacht: " + e.getString("geslacht"));
map.put("rank", "Rang: " + e.getString("rang"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main,
new String[] { "name", "sex", "rank"},
new int[] { R.id.item_title, R.id.item_subtitle, R.id.item_subtitle2 });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Listviewer.this, Profileviewer.class);
startActivity(intent);
}
});
}
}
And from the profile view:
public class Profileviewer extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions.getJSONfromURL("http://de-saksen.nl/deelnemers.txt");
try{
JSONArray deelnemers = json.getJSONArray("deelnemers");
for(int i=0;i<deelnemers.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = deelnemers.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "Naam: " + e.getString("naamingw2"));
map.put("sex", "Geslacht: " + e.getString("geslacht"));
map.put("rank", "Rang: " + e.getString("rang"));
map.put("race", "Ras: " + e.getString("ras"));
map.put("profession", "Beroep: " + e.getString("beroep"));
map.put("skills", "Hobby's: " + e.getString("hobbys"));
map.put("lvl", "Level: " + e.getString("level"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.profile,
new String[] { "name", "sex", "rank", "race", "profession", "skills", "lvl" },
new int[] { R.id.item_title, R.id.item_subtitle, R.id.item_subtitle2, R.id.item_subtitle3, R.id.item_subtitle4, R.id.item_subtitle5, R.id.item_subtitle6 });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Profileviewer.this, Listviewer.class);
startActivity(intent);
}
});
}
}
I recon I have to pass a variable to the other class containing what member has been clicked, but how do I achieve this?
using the intent:
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Profileviewer.this, Listviewer.class);
intent.putExtra("Key", value);
startActivity(intent);
}
});
Then in Listviewer.java:
getIntent().getStringExtra("Key"); //for example
To pass user data, modify like:
String [] users = new String[] { "name", "sex", "rank", "race", "profession", "skills", "lvl" };
int[] ids = new int[] { R.id.item_title, R.id.item_subtitle, R.id.item_subtitle2, R.id.item_subtitle3, R.id.item_subtitle4, R.id.item_subtitle5, R.id.item_subtitle6 };
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.profile,
users, ids);
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Profileviewer.this, Listviewer.class);
intent.putExtra("Key", users[position]);
startActivity(intent);
}
});
If you want to pass int value:
categoryView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(CategoryView.this, "id::" + id,
Toast.LENGTH_SHORT).show();
Intent menuIntent = new Intent(CategoryView.this,MenuListView.class);
Bundle b = new Bundle();
b.putInt("categoryId", (int) id); //Your id
menuIntent.putExtras(b);
menuIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(menuIntent);
//finish();
}
});
you can send basic information when create an Intent object using Extras. Take a look at http://developer.android.com/guide/components/intents-filters.html .
If you had to load a lot of information and Extras is not right enough, you just sent a "key" that you will use to take back all info you need.
For example:
ThisClass
Intent intent = new Intent(thisClass, otherClass);
intent.putExtra("id", "1");
intent.putExtra("model", "model1");
startActivity(inte);
OtherClass
String query = "SELECT * FROM " + T_NAME + " WHERE 'id' = " + getIntent().getIntExtra("id",0);
Cursor c = db.rawQuery(query, null)

Categories

Resources