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);
}
Related
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:
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 have a problem when I want to get the value from a global variable inside AsyncTask class. I want to call it from another class..
Here's my AsyncTask class code:
public class PlacesDisplayTask extends AsyncTask<Object, Integer, List<HashMap<String, String>>> {
List<NearbyPlaceModel> data_place = new ArrayList<>();
JSONObject googlePlacesJson;
GoogleMap googleMap;
#Override
protected List<HashMap<String, String>> doInBackground(Object... inputObj) {
List<HashMap<String, String>> googlePlacesList = null;
Places placeJsonParser = new Places();
try {
googleMap = (GoogleMap) inputObj[0];
googlePlacesJson = new JSONObject((String) inputObj[1]);
googlePlacesList = placeJsonParser.parse(googlePlacesJson);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return googlePlacesList;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> list) {
googleMap.clear();
data_place.clear();
for (int i = 0; i < list.size(); i++) {
if(i < 10 ) {
HashMap<String, String> googlePlace = list.get(i);
double lat = Double.parseDouble(googlePlace.get("lat"));
double lng = Double.parseDouble(googlePlace.get("lng"));
String placeName = googlePlace.get("place_name");
String vicinity = googlePlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(Configure.getBitmapFromURL(googlePlace.get("icon"))));
markerOptions.title(placeName + " : " + vicinity);
googleMap.addMarker(markerOptions);
NearbyPlaceModel items = new NearbyPlaceModel();
items.setVicinity(vicinity);
items.setPlace_name(placeName);
items.setLat(String.valueOf(lat));
items.setLang(String.valueOf(lng));
data_place.add(items);
}
}
}
}
I want to set the global variable data_place = new ArrayList<>(); from another class which is my activity, like this..
ListView nearby_place = (ListView) findViewById(R.id.itemListView);
ListAdapter customAdapter = new ListAdapter(this, R.layout.nearby_place_listview, data_place);
nearby_place.setAdapter(customAdapter);
Or did I something wrong with my code..?
You can get the result by using an interface.
Create an interface with required callback method.
Implement it on your activity,
You will get the result on your callback method
Here I am giving you an example based on your code.
Your MainActivity class should be like this-
public class MainActivity extends AppCompatActivity implements PlaceInterface{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// your code...
// calling the AsyncTask and send reference of the interface on it
new PlacesDisplayTask(this).execute(); // something like this
}
#Override
public void myPlaceList(ArrayList<NearbyPlaceModel> nearbyPlaceModelArrayList) {
ListView nearby_place = (ListView) findViewById(R.id.itemListView);
ListAdapter customAdapter = new ListAdapter(this, R.layout.nearby_place_listview, nearbyPlaceModelArrayList);
nearby_place.setAdapter(customAdapter);
}
}
Your PlacesDisplayTask class should be like this-
public class PlacesDisplayTask extends AsyncTask<Object, Integer, List<HashMap<String, String>>> {
ArrayList<NearbyPlaceModel> data_place = new ArrayList<>(); // change
JSONObject googlePlacesJson;
GoogleMap googleMap;
PlaceInterface placeInterface; // change
public PlacesDisplayTask(PlaceInterface placeInterface){ // change
this.placeInterface = placeInterface;
}
#Override
protected List<HashMap<String, String>> doInBackground(Object... inputObj) {
List<HashMap<String, String>> googlePlacesList = null;
Places placeJsonParser = new Places();
try {
googleMap = (GoogleMap) inputObj[0];
googlePlacesJson = new JSONObject((String) inputObj[1]);
googlePlacesList = placeJsonParser.parse(googlePlacesJson);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return googlePlacesList;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> list) {
googleMap.clear();
data_place.clear();
for (int i = 0; i < list.size(); i++) {
if(i < 10 ) {
HashMap<String, String> googlePlace = list.get(i);
double lat = Double.parseDouble(googlePlace.get("lat"));
double lng = Double.parseDouble(googlePlace.get("lng"));
String placeName = googlePlace.get("place_name");
String vicinity = googlePlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(Configure.getBitmapFromURL(googlePlace.get("icon"))));
markerOptions.title(placeName + " : " + vicinity);
googleMap.addMarker(markerOptions);
NearbyPlaceModel items = new NearbyPlaceModel();
items.setVicinity(vicinity);
items.setPlace_name(placeName);
items.setLat(String.valueOf(lat));
items.setLang(String.valueOf(lng));
data_place.add(items);
placeInterface.myPlaceList(data_place); // change
}
}
}
}
And this is the Interface-
public interface PlaceInterface {
void myPlaceList(ArrayList<NearbyPlaceModel> nearbyPlaceModelArrayList);
}
Hope this will help you. :)
If I understand it correctly! In your AsyncTask class create getter and setter method. This way you can get data_place and set data_place from your activity.
public List<NearbyPlaceModel> getData_place() {
return data_place;
}
public void setData_place(List<NearbyPlaceModel> data_place) {
this.data_place = data_place;
}
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);