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();
}
});
}
}
Related
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);
Hi in my project i have to fetch a contacts phone number and the name from the phone.I can get call the phone number and name but when i add it to the ArrayList<HashMap<String, String>>i'm getting the only the last value i don't know why. but when i log it i'm getting all the value can u guys help me where did i go wrong
public class Contacts extends Activity {
Button btnGetContacts;
int z = 1;
String namereview = null;
public String phoneNumber1 = "", phoneNumber, name1, url,urljoingroup;
ListView listSliding;
Button slideHandleButton;
HashMap<String, String> map1;
ListContactAdaptor allContactAdapter;
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> resultp = new HashMap<String, String>();
String name;
String message = null;
String sGetContactUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.getcontactlist_main);
listSliding = (ListView) findViewById(R.id.GetContacts_Listview);
customer_contact();
}
#SuppressLint("NewApi")
public void customer_contact() {
int timescount = 1, y = 1;
map1 = new HashMap<String, String>();
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, null);
while (phones.moveToNext()) {
name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
Log.v("Name", name);
phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// phoneNumber = phoneNumber.replaceAll("[^\\d.]", "");
map1.put("NAME", phoneNumber);
map1.put("COMMAND", name);
Log.i("name", "name : " + name);
Log.i("count", "count :" + z);
Log.i("pnone", "phone no: " + phoneNumber);
arraylist.add(map1);
Log.i("arraylist", arraylist+"");
}
phones.close();
allContactAdapter = new ListContactAdaptor(XmlActivity.this,
arraylist);
Log.v("ADAPTER", allContactAdapter + "");
// Binds the Adapter to the ListView
listSliding.setAdapter(allContactAdapter);
}
class ListContactAdaptor extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
// public static String CategoryHeading;
public ListContactAdaptor(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
Log.i("data", data + "");
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
// Declare Variables
TextView name, command;
Button joinme;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.getcontactlist_view,
parent, false);
// Get the position from the results
resultp = new HashMap<String, String>();
resultp = data.get(position);
name = (TextView) itemView.findViewById(R.id.name);
command = (TextView) itemView.findViewById(R.id.commamd);
joinme= (Button) itemView.findViewById(R.id.getImage);
name.setText(resultp.get("NAME"));
Log.v("GET NAME", resultp.get("NAME"));
if (resultp.get("COMMAND").equals("")) {
command.setText("No Group");
} else {
command.setText(resultp.get("COMMAND"));
}
Log.v("GET COMMAND", resultp.get("COMMAND"));
return itemView;
}
}
}
Put this in while loop
map1 = new HashMap<String, String>();
like
while (phones.moveToNext())
{
map1 = new HashMap<String, String>();
.
.
}
I have database with 2 table, custom layout for my listView, and I'm using ListAdapter to display all data on ListView - this works fine. But, I have problem when I wish display something other on listView from my Database. The data is just append on my ListView - I won't this! How I refresh/update ListAdapter?
This is my MainActivity:
ListAdapter adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search = (EditText) findViewById(R.id.search);
lista = (ListView) findViewById(android.R.id.list);
sqlite = new Sqlite(MainActivity.this);
//When apps start, listView is populated with data
adapter = new SimpleAdapter(this, sqlite.getAllData(),
R.layout.lv_layout,
new String[]{"ime","naziv","kolicina","adresa"},
new int[]R.id.kupac,R.id.proizvod,R.id.kolicina,R.id.adresa});
setListAdapter(adapter);
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,int count) {
// TODO Auto-generated method stub
String tekst = s.toString();
ArrayList<HashMap<String, String>> rez =
Sqlite.getFilterData(tekst);
adapter = new SimpleAdapter(MainActivity.this,
rez,R.layout.lv_layout,
new String[]{"ime","naziv","kolicina","adresa"},
new int[]{R.id.kupac,R.id.proizvod,R.id.kolicina,R.id.adresa});
lista.setAdapter(adapter);
}
}
The problem is when the method onTextChanged is called. I get all the data but the data just append to my ListView. How to fix it?
And this is my Sqlite class where is needed method:
ArrayList<HashMap<String,String>> results_criteria = new ArrayList<HashMap<String,String>>();
public ArrayList<HashMap<String, String>> getFilterData(String criteria)
{
String ime_kupca = "";
String product = "";
String adress = "";
String kolicina = "";
SQLiteDatabase myDb = this.getReadableDatabase();
Cursor cursor = myDb.rawQuery("SELECT " + DB_COLUMN_IME + "," + DB_COLUMN_NAZIV + "," + DB_COLUMN_KOLICINA + "," + DB_COLUMN_ADRESA + " FROM " + DB_TABLE1_NAME + "," + DB_TABLE2_NAME + " WHERE kupac.ID = proizvod.ID AND " + DB_COLUMN_IME + " LIKE '%" + criteria + "%'", null);
if(cursor != null){
if(cursor.moveToFirst()){
do{
HashMap<String,String>map = new HashMap<String,String>();
ime_kupca = cursor.getString(cursor.getColumnIndex(DB_COLUMN_IME));
product = cursor.getString(cursor.getColumnIndex(DB_COLUMN_NAZIV));
kolicina = cursor.getString(cursor.getColumnIndex(DB_COLUMN_KOLICINA));
adress = cursor.getString(cursor.getColumnIndex(DB_COLUMN_ADRESA));
map.put("ime", ime_kupca);
map.put("naziv", product);
map.put("kolicina", kolicina);
map.put("adresa", adress);
results_criteria.add(map);
}while(cursor.moveToNext());
//cursor.close();
}
cursor.close();
}
Log.i("Rez", "" + results_criteria);
return results_criteria;
In my app I am fetching all the bookmarks available in the default browser and populating it in the list view . What i want is that when i click on a particular listItem(bookmark) , It should directly open that bookmark in the default browser .
String[] requestedColumns = { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.VISITS,
Browser.BookmarkColumns.BOOKMARK };
#SuppressWarnings("deprecation")
Cursor faves = managedQuery(Browser.BOOKMARKS_URI, requestedColumns,
Browser.BookmarkColumns.BOOKMARK + "=1", null,
Browser.BookmarkColumns.VISITS);
Log.d("Bookmarks", "Bookmarks count: " + faves.getCount());
int titleIdx = faves.getColumnIndex(Browser.BookmarkColumns.TITLE);
String url[] = new String[] {android.provider.Browser.BookmarkColumns.URL};
Log.d("SimpleBookmarks url", url[0]);
//int url_column_index = faves.getColumnIndexOrThrow(Browser.BookmarkColumns.URL);
faves.moveToFirst();
if (bookmark_check) {
while (!faves.isAfterLast()) {
Log.d("SimpleBookmarks", faves.getString(titleIdx));
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("bookmark", faves.getString(titleIdx));
map.put("url", "");
listitem.add(map);
faves.moveToNext();
}
}
Log.v("data", "" + listitem);
SimpleAdapter listitemAdapter = new SimpleAdapter(this, listitem,
R.layout.list_style, new String[] { "bookmark", "url" },
new int[] { R.id.topTextView, R.id.bottomTextView });
lv.setAdapter(listitemAdapter);
Finally got the solution .
String[] requestedColumns = { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL };
#SuppressWarnings("deprecation")
final Cursor faves = managedQuery(Browser.BOOKMARKS_URI,
requestedColumns, Browser.BookmarkColumns.BOOKMARK + "=1",
null, null);
faves.moveToFirst();
int titleIdx = faves.getColumnIndex(Browser.BookmarkColumns.TITLE);
final int urlIdx = faves.getColumnIndex(Browser.BookmarkColumns.URL);
if (bookmark_check) {
while (!faves.isAfterLast()) {
faves.getString(urlIdx));
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("name", faves.getString(titleIdx));
map.put("phone no", faves.getString(urlIdx));
listitem.add(map);
faves.moveToNext();
}
}
SimpleAdapter listitemAdapter = new SimpleAdapter(this, listitem,
R.layout.list_style, new String[] { "name", "phone no" },
new int[] { R.id.topTextView, R.id.bottomTextView });
lv.setAdapter(listitemAdapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
RelativeLayout lr = (RelativeLayout) arg1;
TextView mText = (TextView) lr.getChildAt(1);
String st = mText.getText().toString();
if (!st.startsWith("https://") && !st.startsWith("http://")) {
st = "http://" + mText.getText().toString();
}
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(st));
startActivity(i);
}
});
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));