I have a list view, each item is composed of three elements: picture view and 3 text view, the latter contains the name of a product, product price and quantity, i want when I click on the item it correspanding quantity increases by one.
Here's the code:
public class BoissonActivity extends Activity {
ListView maListViewPerso;
BaseDeDonne db = new BaseDeDonne(this);
private static String choix="boisson";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.boisson_layout);
maListViewPerso = (ListView) findViewById(R.id.listviewperso);
Log.d("Lire: ", "Lire tous les produits..");
ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map;
listItem.clear();
List<Produit> produit = db.getSelectProduit(choix);
for (Produit cn : produit) {
map = new HashMap<String, Object>();
map.put("titre",String.valueOf(cn.getNom()));
map.put("description","Prix:"+cn.getPrix_produit());
map.put("quantite", 0);
String url="/sdcard/Image_Produits/"+cn.getImage_produit()+".jpg";
URL pictureURL = null;
try {
pictureURL = new URL(url);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeFile(url);
map.put("img", bitmap);
listItem.add(map);
String log = "Id: "+cn.getId()+" ,Nom: " + cn.getNom()+ " ,Image: " + cn.getImage_produit() +
" ,Prix: " + cn.getPrix_produit()+" ,Catégorie: " + cn.getCategorie();
Log.d("produits: ", log);
}
SimpleAdapter mSchedule = new SimpleAdapter (this.getBaseContext(), listItem, R.layout.affichageitem,
new String[] {"img", "titre", "description","quantite"}, new int[] {R.id.img, R.id.titre, R.id.description,R.id.quantite});
mSchedule.setViewBinder(new MyViewBinder());
maListViewPerso.setAdapter(mSchedule);
i tried this but only the first textview is changed :
maListViewPerso.setOnItemClickListener(new OnItemClickListener()
{ int compteur=0;
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
TextView t = (TextView)findViewById(R.id.quantite);
t.setText(String.valueOf(compteur));
compteur++;
}
});
Add an onListItemClick..
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Your code here to increment the qty
}
EDIT
Use the View parameter passed in to access the proper view (i'm taking values from the code you added above, so it doesn't exactly match what I show above).
TextView t = (TextView) arg1.findViewById(R.id.quantite);
t.setText(String.valueOf(compteur));
Related
When i run the following program:
ArrayList<HashMap<String, String>> AL = new ArrayList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_outaccountinfo);
ListView lv = (ListView) findViewById(R.id.lvoutinfo);
ArrayList<HashMap<String, String>> AL = new ArrayList<HashMap<String, String>>();
DBOpen open = new DBOpen(Outaccountinfo.this);
SQLiteDatabase db = open.getWritableDatabase();
Cursor cursor = db.query("outaccount", null, null, null, null, null, null, null);
while (cursor.moveToNext()) {
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
String str_id = cursor.getString(cursor.getColumnIndex("id"));
String str_money = cursor.getString(cursor.getColumnIndex("outmoney"));
String str_time = cursor.getString(cursor.getColumnIndex("time"));
String str_type = cursor.getString(cursor.getColumnIndex("type"));
String str_mark = cursor.getString(cursor.getColumnIndex("mark"));
map.put("id", str_id);
map.put("outmoney", str_money);
map.put("time", str_time);
map.put("type", str_type);
map.put("mark", str_mark);
AL.add(map);
} while (cursor.moveToNext());
}
}
String[] str = new String[cursor.getCount()];
for (int i = 0; i < cursor.getCount(); i++) {
str[i] = AL.get(i).get("id").toString() + "|" + " " + "money:" + String.valueOf(AL.get(i).get("outmoney"))
+ " " + "time:" + AL.get(i).get("time").toString() + " " + "type:" + AL.get(i).get("type").toString()
+ " " + "mark:" + AL.get(i).get("mark").toString();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
str);
lv.setAdapter(arrayAdapter);
}
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
HashMap<String, String> map = (HashMap<String, String>) parent.getItemAtPosition(position);
Toast.makeText(Outaccountinfo.this, map.get("type"), Toast.LENGTH_SHORT).show();
}
});
}
I receive the following error:
java.lang.String cannot be cast to java.util.HashMap
Who can help me to achieve the purpose without changing the purpose of the program?
Thanks!
You are using ArrayAdapter<String> Means that you pass your adapter object of Strings.
Now, when you clicked on your item and asked for parent.getItemAtPosition(position); you get an Object.
If you will go inside this function you can see that the Object that you get is by position and by the type you sent to the Adapter (String).
So, when you try to cast that String to (HashMap<String, String>) you get the exception.
Try to do something like that after you clicked:
HashMap<String, String> map = new HashMap<String, String>(); // Parameter in outside the click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
map.put("someKey", parent.getItemAtPosition(position));
Toast.makeText(Outaccountinfo.this, map.get("type"), Toast.LENGTH_SHORT).show();
}
});
*****Can you try this code It might be helpful.*****
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv = (ListView) findViewById(R.id.lvoutinfo);
ArrayList<HashMap<String, String>> AL = new ArrayList<HashMap<String, String>>();
SQLiteDatabase db = openOrCreateDatabase("Account",MODE_PRIVATE,null);
db.execSQL("CREATE TABLE IF NOT EXISTS outaccount(id text,outmoney text,time text,type text,mark text);");
db.execSQL("INSERT INTO outaccount VALUES('1','100','10','saving','80');");
Cursor cursor = db.query("outaccount", null, null, null, null, null, null, null);
while (cursor.moveToNext()) {
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
String str_id = cursor.getString(cursor.getColumnIndex("id"));
String str_money = cursor.getString(cursor.getColumnIndex("outmoney"));
String str_time = cursor.getString(cursor.getColumnIndex("time"));
String str_type = cursor.getString(cursor.getColumnIndex("type"));
String str_mark = cursor.getString(cursor.getColumnIndex("mark"));
map.put("id", str_id);
map.put("outmoney", str_money);
map.put("time", str_time);
map.put("type", str_type);
map.put("mark", str_mark);
AL.add(map);
} while (cursor.moveToNext());
}
}
String[] str = new String[cursor.getCount()];
for (int i = 0; i < cursor.getCount(); i++) {
str[i] = AL.get(i).get("id").toString() + "|" + " " + "money:" + String.valueOf(AL.get(i).get("outmoney"))
+ " " + "time:" + AL.get(i).get("time").toString() + " " + "type:" + AL.get(i).get("type").toString()
+ " " + "mark:" + AL.get(i).get("mark").toString();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
str);
lv.setAdapter(arrayAdapter);
}
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
HashMap<String, String> map = (HashMap<String, String>) parent.getItemAtPosition(position);
Toast.makeText(MainActivity.this, map.get("type"), Toast.LENGTH_SHORT).show();
}
});
}
}
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);
I have a list view.when any one clicking the list it showing list content as
{first_name=abc, last_name=xyz, id=1, address=kolkata}
but I want those get those value individually from that string who to get that.
My onListItemClick Listner
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
Object o = this.getListAdapter().getItem(position);
String return_data = o.toString();
Toast.makeText(this, ""+return_data, Toast.LENGTH_LONG).show();
}
Added total class including List adapter
public class showUserInfoListActivity extends ListActivity {
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
static final String KEY_ID = "id";
static final String KEY_FIRST_NAME = "first_name";
static final String KEY_LAST_NAME = "last_name";
static final String KEY_ADDRESS = "address";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_user_info_list);
//---get all Records---
DataBaseAdapter db = new DataBaseAdapter(this);
db.open();
Cursor c = db.getAllRecords();
if (c.moveToFirst())
{
do
{
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, c.getString(0));
map.put(KEY_FIRST_NAME, c.getString(1));
map.put(KEY_LAST_NAME, " "+c.getString(2));
map.put(KEY_ADDRESS, c.getString(3));
// adding HashList to ArrayList
menuItems.add(map);
} while (c.moveToNext());
}
db.close();
// Adding menuItems to ListView
// All filed data are not shown in the list KEY_ID is hidden
ListAdapter adapter = new SimpleAdapter(this, menuItems,R.layout.user_info_list_item,
new String[] { KEY_FIRST_NAME, KEY_LAST_NAME, KEY_ADDRESS, KEY_ID },
new int[] {R.id.first_name , R.id.last_name, R.id.address});
setListAdapter(adapter);
}
//On select from the list show data
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
Object o = this.getListAdapter().getItem(position);
//String return_data = o.toString();
MyClass return_data = (MyClass)o;
Toast.makeText(this, ""+return_data, Toast.LENGTH_LONG).show();
}
class MyClass{
}
}
Instead of
String return_data = o.toString();
you need to cast o to whatever class of object it is.
MyClass return_data = (MyClass)o;
Then you can access its fields and call its methods as usual.
In your case:
HashMap<String, String> returndata = (HashMap<String, String>) o;
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)
i hav to display the thumbnail of the image along with the title of it in a list view by parsing the JSON feed.. My code
public class Main extends ListActivity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
String url;
Bitmap bitmap;
ImageView img;
int im ;
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = Json_mysamActivity.getJSONfromURL("http://gdata.youtube.com/feeds/mobile/videos?max-results=3&alt=json");
try {
JSONObject jb = json.getJSONObject("feed");
JSONArray jarr = jb.getJSONArray("entry");
for(int i=0;i<jarr.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jarr.getJSONObject(i);
JSONObject det = e.getJSONObject("title");
map.put("id", String.valueOf(i));
map.put("$t", "t:" + det.getString("$t"));
map.put("type", "type: " + det.getString("type"));
JSONObject det1 = e.getJSONObject("media$group");
JSONArray det12 = det1.getJSONArray("media$thumbnail");
for(int j=0;j<1;j++)
{
JSONObject det12obj = det12.getJSONObject(i);
url = det12obj.getString("url");
map.put("url", "url:"+ det12obj.getString("url"));
mylist.add(map);
}
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String[] from = new String[] { "$t", "type","url" };
int[] to = new int[] { R.id.item_title, R.id.item_subtitle, R.id.test_image };
MySimpleCursorAdapter adapter = new MySimpleCursorAdapter(this, R.layout.main, mylist ,
from, to);
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(Main.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
public class MySimpleCursorAdapter extends SimpleCursorAdapter {
// SimpleCursorAdapter requires cursor in the place of ArrayList but I need to pass //arraylist, how should I implement it
public MySimpleCursorAdapter(Context context, int layout, ArrayList<HashMap<String, String>> mylist,
String[] from, int[] to) {
super(context, layout, mylist, from, to);
}
#Override
public void setViewImage(ImageView v, String url) {
String path =url ;
Bitmap b = BitmapFactory.decodeFile(path);
v.setImageBitmap(b);
}
}
}
What you need is a SimpleAdapter. A cursor adapter is used for displaying daat in a list that comes from a database. SimpleAdapter is used for data in RAM (your list after parsing the json).
Check this first google entry, it should do.
In case you are using arraylist as datasource you should use ArrayAdapter, so Extend your adapter from ArrayAdapter. see link for Custom Array Adapter:
http://android-er.blogspot.in/2010/06/custom-arrayadapter-with-with-different.html
When you are loading image views in list, its good practice to use LazyLoading, see below link for Lazy Loading in android:
http://ballardhack.wordpress.com/2010/04/05/loading-remote-images-in-a-listview-on-android/
for this you have to use LayoutInflater, write your own adapter class extends ArrayAdapter,
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
adapter = new CustomAdapter(this, R.layout.list_row, R.id.title, data,
mInflater, imgid);