Listview prints Object not string java - java

I'm trying to display a listview with data out of openERP / odoo.
OpenERP returns an list of objects that I'm trying to use into a listview, but it prints out "Ljava.lang.object#number".
listOfValues return the list of objects, in my onPostExecute I want to connect it with the listview. But it doesn't work, anyone suggestion?
private class ListViewLoaderTask extends AsyncTask{
#Override
protected SimpleAdapter doInBackground(String... strJson) {
connector=new OpenerpRpc(getBaseContext());
connector.Config();
current_page += 1;
listOffValues = getListOffFieldValues(current_page, false, listOffValues);
String[] from = { "project_id"};
int[] to = { R.id.tv_address};
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), listOffValues, R.layout.lv_gps_layout, from, to);
return adapter;
}
/** Invoked by the Android on "doInBackground" is executed */
#Override
protected void onPostExecute(final SimpleAdapter adapter) {
// Setting adapter for the listview
mListView.setAdapter(adapter);
for(int i=0;i<adapter.getCount();i++){
HashMap<String, Object[]> hm = (HashMap<String, Object[]>) adapter.getItem(i);
final HashMap<String, String> companyDetails = new HashMap<String, String>();
Object po_ids = (Object[]) hm.get("project_id");
Object[] ret=(Object[]) hm.get("project_id");
Integer number = ((Integer) hm.get("project_id")[0]);
String projectId = ((String) hm.get("project_id")[1]);
companyDetails.put("project_id",projectId);
adapter.notifyDataSetChanged();
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String listName;
HashMap<String, String> hmDownload = new HashMap<String, String>();
String l = companyDetails.get("project_id");
Intent myIntent = new Intent(MainActivity.this, YardActivity.class);
myIntent.putExtra("id", Long.toString(id));
myIntent.putExtra("position", Integer.toString(position)); //Optional parameters
MainActivity.this.startActivity(myIntent);
}
});
}
progress.dismiss();
Log.d("/****","Data from odoo is finished");
}
}
Here is the output when i debug:
http://i62.tinypic.com/24esx87.png
I updated my example where you can see that I can get the name of the project out of the list. But when I try to visulize that It print that java.lang string. Is your solution the only solution? When I hit on an item in my listview I get the projectId that I hit, so why it dont what to visiulize the string value?

HashMap<String, Object[]> hm = (HashMap<String, Object[]>)adapter.getItem(i);
change to
HashMap<String, MyModel[]> hm = (HashMap<String, MyModel[]>) adapter.getItem(i);
where my model is a class you create that describe your data,
take a look at ObjectItem.java
http://www.javacodegeeks.com/2013/09/android-listview-with-adapter-example.html

Related

Android Adapter notifyDataSetChanged works only on loading (second adapter)

I have little trouble with my adapter. After I add new content to my list and refreshing with notifyDataSetChanged the onClickListener doesn't work for that new item. After I do click back and go back to the add menu, the item works fine.
So the loading part works perfectly.
The first Adapter with list it do works perfectly. Its pretty much the same code.
In onCreate function...
Button addContent = (Button)findViewById(R.id.addContent_button);
final ListView myList = (ListView)findViewById(R.id.mainMenuList);
final boolean deleteMode = false;
String[] liegenSchaften = new String[] {};
final List<String> content = new ArrayList<String>(Arrays.asList(liegenSchaften));
final ArrayAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, content);
myList.setAdapter(adapter);
//load the Save Data
Map<String, ?> map = getSaveMap();
//add exists data to list
for (Map.Entry<String, ?> entry : map.entrySet()) {
content.add(entry.getValue().toString());
}
// Update adapter, this works fine!
adapter.notifyDataSetChanged();
addContent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
content.add(editedText.getText().toString());
/* This adapter dont Update the new Content, the item display and is not clickeble */
adapter.notifyDataSetChanged();
editor.putString(editedText.getText().toString(), editedText.getText().toString());
editor.commit();
}
});
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//load the Save Data
Map<String, ?> map = getSaveMap();
Object obj = myList.getAdapter().getItem(position);
String value = obj.toString();
//add exists data to list
for (Map.Entry<String, ?> entry : map.entrySet()) {
if(entry.getValue().toString() == value) {
if(deleteMode) {
editor.remove(value);
editor.commit();
content.remove(position);
adapter.notifyDataSetChanged();
} else {
selectedContent = entry.getValue().toString();
addMessage.setText(entry.getValue().toString() + " Wurde gewählt.");
addMessage.show();
}
}
}
}
});
I have found the problem:
The query was wrong. Now I have used equals and the ArrayAdapter works beautifully!
if(entry.getValue().toString().equals(value))

Binding data through PHP to Android using JSON

I am developing an android application using PHP and mysql as external database. Now in my activity page whole JSON data are there but not bind in listview. I tried a lot and search on google as well.
My activity.java is below:
private void getdatalatlog(double latitude, double longitude) {
String link = "http://192.168.0.104/PHP/webservice/comments.php?latitude='"+latitude+"'&longitude='"+longitude+"'";
aq.progress(R.id.progressBar1).ajax(link, JSONObject.class, this,"jsonCallback");
}
public void jsonCallback(String link, JSONObject json, AjaxStatus status) throws JSONException {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
json = jParser.getJSONFromUrl(link);
mComments = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_MESSAGE);
String username = c.getString(TAG_USERNAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_MESSAGE, content);
map.put(TAG_USERNAME, username);
mCommentList.add(map);
}
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.single_post, new String[] { TAG_TITLE,TAG_USERNAME ,TAG_MESSAGE
}, new int[] { R.id.shop_name,R.id.address,R.id.distance
});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
My getdatalatlong() method is called in onCreate() method. And in jsonCallback() method's json object, I got all data of my database.
Check whether you are getting the JSON Object from the server.
if you got means do this. Store that JSON Result in an string(usually i call it JSONString).
For example :
{
"username":"Vignesh";
"title" : "Check My Site";
"content" : "vickytechy.hol.es"
}
Then use this to get the values by the index
JSONObject jsonObject = new JSONObject(JSONString);//JSONString is the JSON result;
Name = jsonObject.optString("username");//Name = Vignesh
Title = jsonObject.optString("title");//Title = Check My Site
Content = jsonObject.optString("content");//Content = vickytechy.hol.es

New activity when click on ListView

I treat XML and deduce which category parent_id = 0. Each line in the list has a unique id. How to display the list of strings that Activity belong to this line? (eg string has id = 1. When you click on this line you want to display a string in which the parent_id = 1). Need to use the new Activity or can use CatalogActivity.java?
CatalogActivity.java
public class CatalogActivity extends ListActivity {
private ProgressDialog pDialog;
static final String URL = "https://api.api2cart.com/v1.0/category.list.xml?api_key=6aed775211e8c3d556db063d12125d2d&store_key=ed58a22dfecb405a50ea3ea56979360d&start=0&count=38&params=id,name,parent_id,images";
static final String KEY_ITEM = "category";
static final String KEY_ID = "id";
static final String KEY_PARENT_ID = "parent_id";
static final String KEY_TITLE = "name";<br>
static final String KEY_THUMB_URL = "http_path";
String Parend_id;
int id_parent;
ListView list;
LazyAdapter adapter;
ArrayList<HashMap<String, String>> catalogList;
//#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
catalogList= new ArrayList<HashMap<String, String>>();
new LoadCatalog().execute();
}
class LoadCatalog extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CatalogActivity.this);
pDialog.setMessage("Загрузка каталога ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all song nodes <song>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
//HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
Parend_id=parser.getValue(e, KEY_PARENT_ID);
if(Parend_id.equals("0")) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
catalogList.add(map);
}
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
list=getListView();
adapter=new LazyAdapter(CatalogActivity.this, catalogList);
list.setAdapter(adapter);
}
});
// list=(ListView)findViewById(R.id,list);
// Getting adapter by passing xml data ArrayList
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent showInfo = new Intent(getApplicationContext(), CatalogActivity.class);
startActivity(showInfo);
}
});
}
}
}
example XML file (XML rendered as a PNG)
When I click on Components in ListView put Mac as id Components = parent_id Mac

Using Textwatcher with a simpleexpandablelistview in Android

In my previous app, I had a listview and and edittext at the bottom of it. I have been using the textwatcher in the edittext to filter a listview. The contents of the listview come from a simplecursoradapter.
edittext.addTextChangedListener(filterTextWatcher);
cursor.setFilterQueryProvider(new FilterQueryProvider() {
#Override
public Cursor runQuery(CharSequence constraint) {
Cursor cursor=mDbHelper.fetchFilteredNotes(edittext.getText().toString());
return cur;
}
});
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(android.text.Editable s) {
};
public void beforeTextChanged(CharSequence s, int start, int count, int after) {};
public void onTextChanged(CharSequence s, int start, int before, int count) {
simplecursoradapter.getFilter().filter(s.toString());
};
};
In my current app, I have an expandablelistview. I would like to use a similar feature like filtering the content of the expandablelistview.
Am not sure if I can make use of textwatcher for this. Is there any other way to get this done or can I use textwatcher in this as well. ?
This is the relevant portion of code:
private DbAdapter mDbHelper;
List<Map<String, String>> groupData,groupDataCat;
List<List<Map<String, String>>> childData,childDataCat;
Map<String, String> curGroupMap;
List<Map<String, String>> meaning=null;
Map<String, String> curChildMap;
private static final String WORD = "WORD";
private static final String MEANING = "MEANING";
SimpleExpandableListAdapter mAdapter;
ExpandableListView elvCat;
temp=mDbHelper.fetchAllNotes();
temp.moveToFirst();
getActivity().startManagingCursor(temp);
if(temp.moveToFirst()){
groupDataCat = new ArrayList<Map<String, String>>();
childDataCat = new ArrayList<List<Map<String, String>>>();
for (int i = 0; i < temp.getCount(); i++) {
Map<String, String> catGroupMap = new HashMap<String, String>();
groupDataCat.add(catGroupMap);
catGroupMap.put(WORD, temp.getString(temp.getColumnIndexOrThrow(DbAdapter.KEY_WORD)));
List<Map<String, String>> meaning = new ArrayList<Map<String, String>>();
Map<String, String> catChildMap = new HashMap<String, String>();
meaning.add(catChildMap);
catChildMap.put(MEANING, temp.getString(temp.getColumnIndexOrThrow(DbAdapter.KEY_MEANING)));
childDataCat.add(meaning);
temp.moveToNext();
}
}
mAdapter = new SimpleExpandableListAdapter(
WordListFragment.this.getActivity(),
groupDataCat,
R.layout.word_list_item,
new String[] {WORD},
new int[] { R.id.tvWord },
childDataCat,
R.layout.meaning_list_item,
new String[] {MEANING},
new int[] { R.id.tvMeaning}
);
view=inflater.inflate(R.layout.word_list_temp, container, false);
elvCat = (ExpandableListView) view.findViewById(R.id.elvWord);
elvCat.setAdapter(mAdapter);
return view;
}
The way I got this to work was that in the onTextChanged() method, I called up a function which would query the database and get the filtered data. I repopulate the expandable listview again based on the query results.
private void populateList(String filter) {
temp = mDbHelper.fetchSugNotes(filter);
temp.moveToFirst();
this.startManagingCursor(temp);
groupDataCat = new ArrayList<Map<String, String>>();
childDataCat = new ArrayList<List<Map<String, String>>>();
for (int i = 0; i < temp.getCount(); i++) {
Map<String, String> catGroupMap = new HashMap<String, String>();
groupDataCat.add(catGroupMap);
catGroupMap.put(WORD, temp.getString(temp
.getColumnIndexOrThrow(DbAdapter.KEY_WORD)));
List<Map<String, String>> meaning = new ArrayList<Map<String, String>>();
Map<String, String> catChildMap = new HashMap<String, String>();
meaning.add(catChildMap);
catChildMap.put(MEANING, temp.getString(temp
.getColumnIndexOrThrow(DbAdapter.KEY_MEANING)));
childDataCat.add(meaning);
temp.moveToNext();
}
mAdapter = new SimpleExpandableListAdapter(this, groupDataCat,
R.layout.word_list_item, new String[] { WORD },
new int[] { R.id.tvWord }, childDataCat,
R.layout.meaning_list_item, new String[] { MEANING },
new int[] { R.id.tvMeaning });
elvCat.setAdapter(mAdapter);

Android listview sorting using xml parsing

I am having a bit of trouble with android. I have a sorted listview of items retrieved from a database using xml parsing.
i have to display the product on list view with sorted by price
This is my xml feed:
<Feed>
<category>
<Product>
<Name>New Masters of Flash</Name>
<Price>79.99</Price>
</Product>
<Product>
<Name>Professional Java Server Programming</Name>
<Price>63.99</Price>
</Product>
<Product>
<Name>Designing Web Usability</Name>
<Price>80.00</Price>
</Product>
</category>
</Feed>
This is my android code:
public class Catalogue extends Activity {
// static String URL = "https://dl.dropbox.com/u/48258247/catalogue.json";
static final String URL = "http://192.168.1.168/xcart432pro/internet.xml";
static String KEY_CATEGORY = "Product";
static final String KEY_TITLE = "Name";
static final String KEY_DESCRIPTION = "Description";
static final String KEY_COST = "Price";
static final String KEY_THUMB_URL = "Image";
ListView list;
ListAdapter adapter;
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_CATEGORY);
// looping through all song nodes <song>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_DESCRIPTION, parser.getValue(e, KEY_DESCRIPTION));
map.put(KEY_COST, parser.getValue(e, KEY_COST));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
songsList.add(map);
}
list=(ListView)findViewById(R.id.listView1);
// Getting adapter by passing xml data ArrayList
adapter=new ListAdapter(this, songsList);
list.setAdapter(adapter);
// Bundle bundle = getIntent().getExtras();
// KEY_CATEGORY=bundle.getString(KEY_SUBCATE);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map = songsList.get(position);
Intent in = new Intent(
Catalogue.this,
com.ssmobileproductions.catalogue.SingleMenuItem.class);
in.putExtra(KEY_TITLE, map.get(KEY_TITLE));
in.putExtra(KEY_DESCRIPTION, map.get(KEY_DESCRIPTION));
in.putExtra(KEY_THUMB_URL, map.get(KEY_THUMB_URL));
in.putExtra(KEY_COST, map.get(KEY_COST));
startActivity(in);
}
});
Here i have to display the product on list view with sorted by price.How can i do.please help me programmatically in android.
Edit:
I have added some code like below:
Button btninsert = (Button) findViewById(R.id.sort);
btninsert.setOnClickListener(new View.OnClickListener() {
final ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
public void onClick(View v) {
Collections.sort(songsList, new PriceComparator());
}
});
final ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_CATEGORY);
create one class and wrote the code below:
public class PriceComparator implements Comparator<HashMap<String, String>> {
static final String KEY_COST = "Price";
public PriceComparator() {
// TODO Auto-generated constructor stub
}
public int compare(HashMap<String, String> map1, HashMap<String, String> map2) {
return map1.get(KEY_COST).compareTo(map2.get(KEY_COST));
}
Now i have to run the app and click the button means nothing is happened????
But i have to display product list is sorted by price.
I believe you need to use a custom Comparator:
Comparator<HashMap<String, String>> comparator = new Comparator<HashMap<String, String>>() {
#Override
public int compare(HashMap<String, String> map1, HashMap<String, String> map2) {
return map1.get(KEY_COST).compareTo(map2.get(KEY_COST));
}
};
And then sort your list before creating your adapter with:
Collections.sort(songsList, comparator);
Addition
You need to do make a few small changes.
Make songsList a field variable, like list and adapter:
ListView list;
ListAdapter adapter;
ArrayList<HashMap<String, String>> songsList; // Add me!
Update how you initialize songsList:
songsList = new ArrayList<HashMap<String, String>>(); // Shorten me!
Change your onClick method:
public void onClick(View v) {
Collections.sort(songsList, comparator);
adapter.notifyDataSetChanged(); // Add me!
}
display the product on list view with sorted by price
=> As you are having ArrayList>, you need to create custom Comparator to make comparison.
For example:
public class PriceComparator implements Comparator<HashMap<String, String>> {
public PriceComparator() {
// TODO Auto-generated constructor stub
}
public int compare(HashMap<String, String> map1, HashMap<String, String> map2) {
return map1.get(KEY_COST).compareTo(map2.get(KEY_COST));
}
}
And to apply this custom comparator to your ArrayList>, do like:
Collections.sort(mylist, new PriceComparator());
Use Hashtable and sort the keys like following:
Here hashTable will contain name and price, and keys will contain the price, so sorting keys and then addind the sorted elements in sortedItems Vector will return you the sorted elements.
Hashtable hash = new Hashtable();
Vector<String> sortedItems = new Vector<String>();
Enumeration enumeration = hash .keys();
Vector keySet = new Vector();
while (enumeration.hasMoreElements()) {
keySet.add(enumeration.nextElement());
}
Collections.sort(keySet);
Iterator i = keySet.iterator();
String str;
while (i.hasNext()) {
str = (String) i.next();
sortedItems.addElement(hash .get(str));
Log.e("", (str + ":" + hash .get(str)));
}

Categories

Resources