I have a: Hashmap<String,List<String>> i want to sort it by Keys when i tried sorting it and cliked activity button my the emulator closes application. How i can fix it?
My activity inside my application look like now:
I want to sort it like: 01,02,03,04,05 etc.
Here my code blocks:
InsidesActivity.class:
public class InsidesActivity extends AppCompatActivity {
HashMap<String, List<String>> Insides_Categories;
List<String> List_Items;
ExpandableListView expandableListView;
Expandible_List ExpListClass;
Toolbar tb;
int lastPosition = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insides);
expandableListView = (ExpandableListView) findViewById(R.id.explist);
Insides_Categories = DataProvider.getInfo();
List_Items = new ArrayList<String>(Insides_Categories.keySet());
I tried this block:
// List<Map.Entry<String,List<String>>> entries = new ArrayList<Map.Entry<String,List<String>>>(Insides_Categories.entrySet());
// Collections.sort(entries, new Comparator<Map.Entry<String,List<String>>>() {
// public int compare(Map.Entry<String,List<String>> l1, Map.Entry<String,List<String>> l2) {
// return l1.getValue().get(0).compareTo(l2.getValue().get(0));
// }
// });
ExpListClass = new Expandible_List(this, Insides_Categories, List_Items);
expandableListView.setAdapter(ExpListClass);
}
}
Use LinkedHashMap to maintain your sorting order. HashMap doesn't keep order as data inserted.
public static void main(String[] args) {
Map<String, List<String>> map = new LinkedHashMap<>();
map.put("b", Arrays.asList("1", "2"));
map.put("a", Arrays.asList("2", "1"));
map.put("c", Arrays.asList("2", "1", "6"));
map.put("d", Arrays.asList("2", "1", "5"));
Stream<Entry<String, List<String>>> sorted = map.entrySet().stream().sorted(Map.Entry.comparingByKey());
System.out.println("map:" + map);
map = sorted.collect(new Supplier<Map<String, List<String>>>() {
#Override
public Map<String, List<String>> get() {
return new LinkedHashMap<>();
}
}, new BiConsumer<Map<String, List<String>>, Entry<String, List<String>>>() {
#Override
public void accept(Map<String, List<String>> t, Entry<String, List<String>> u) {
t.put(u.getKey(), u.getValue());
}
}, new BiConsumer<Map<String, List<String>>, Map<String, List<String>>>() {
#Override
public void accept(Map<String, List<String>> t, Map<String, List<String>> u) {
// TODO
}
});
System.out.println("map:" + map);
}
I solved my problem when i sorted my List like this;
List_Items = new ArrayList<String>(Insides_Categories.keySet());
Collections.sort(List_Items);
Now its looks like:
Related
I want to add image from drawalbe in hashmap please help me.
Below is code what I am trying:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_description);
setupSlider();
}
private void setupSlider()
{
mSlider = findViewById(R.id.description_slider);
HashMap<String, String> url_maps = new HashMap<>();
url_maps.put("Ramos", R.drawable.images+"");
url_maps.put("Abbas", R.drawable.ramos +"");
}
}
Because type of (R.id.images) is int, you should better put them in HashMap<String, Integer>
more infomation: https://developer.android.com/reference/android/R.id
private void setupSlider()
{
mSlider = findViewById(R.id.description_slider);
HashMap<String, Integer> url_maps = new HashMap<>();
url_maps.put("Ramos", R.drawable.images);
url_maps.put("Abbas", R.drawable.ramos);
}
I have two tasks I'd like to do in the background, but I figured it could be good to do them both in the background and return a map when done.
But my problem is I think one of them is not being processed, or at least I'm not sure if they should be both put in there.
My code is as follows.
final TextView v = (TextView) P.findViewById(R.id.abbr);
final SimpleDraweeView i = (SimpleDraweeView) P.findViewById(R.id.icon);
new AsyncTask<Object, Object, HashMap<String, Object>>() {
#Override
protected HashMap<String, Object> doInBackground(Object... params) {
String k = SyncProfiles.getIcon(A, C.getNumber());
Drawable dr;
if (k == null) {
dr = H.setDrawableColor(A, R.drawable.contact_user_bg, H.aoRandColor());
} else {
dr = null;
}
HashMap<String, Object> r = new HashMap<>();
r.put("bg", dr);
r.put("url", Images.ImageServerResize(k, 180));
return r;
}
#Override
protected void onPostExecute(HashMap<String, Object> o) {
v.setText(C.getName().trim().substring(0, 1));
if (o.get("url") == null) {
contact_bg.setBackground((Drawable) o.get("bg"));
i.setVisibility(View.GONE);
} else {
i.setImageURI(Uri.parse((String) o.get("url")));
i.setVisibility(View.VISIBLE);
}
}
}.execute();
Do not call AsyncTask.execute() more than once on a same instance.
// For example
SampleTask sampleTask = new SampleTask();
sampleTask.execute();
sampleTask.execute(); //Error, IllegalStateException
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
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);
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)));
}