i need very much our help.
I need create a expandableListView and put inside more images loaded to url.
Now i have this:
i take the text to file xml but i dunno how show in image my image dinamic.
This is code:
Main.java
public class Main extends ExpandableListActivity {
static final String KEY_DISCOUNTED_PRICE = "discounted_price";
static final String KEY_PRICE = "price";
static final String KEY_DISCOUNT = "discount";
static final String KEY_THUMB_URL_SELLER = "seller_image_url";
static final String KEY_THUMB_URL = "image_url";
static final String KEY_DESCRIPTION = "description";
static final String KEY_TITLE_OFFERTA = "title_offerta";
String contenuto_nodo;
ArrayList <String> array_contenuto_nodo =new ArrayList<String>();
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
static final String shades[][] = {
// Shades of grey
{
"lightgrey","#D3D3D3",
"dimgray","#696969",
"sgi gray 92","#EAEAEA"
},
// Shades of blue
{
"dodgerblue 2","#1C86EE",
"steelblue 2","#5CACEE",
"powderblue","#B0E0E6"
},
// Shades of yellow
{
"yellow 1","#FFFF00",
"gold 1","#FFD700",
"darkgoldenrod 1"," #FFB90F"
},
// Shades of red
{
"indianred 1","#FF6A6A",
"firebrick 1","#FF3030",
"maroon","#800000"
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
TaskHomePageLista task = new TaskHomePageLista();
task.execute();
try {Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// ImageLoader class instance
SimpleExpandableListAdapter expListAdapter =
new SimpleExpandableListAdapter(
this,
createGroupList(), // groupData describes the first-level entries
R.layout.list_row, // Layout for the first-level entries
new String[] { KEY_PRICE, KEY_DISCOUNT, KEY_DESCRIPTION, KEY_DISCOUNTED_PRICE, KEY_TITLE_OFFERTA}, // Key in the groupData maps to display
new int[] { R.id.price, R.id.discount, R.id.description, R.id.discounted_price, R.id.title_offerta}, // Data under "colorName" key goes into this TextView
createChildList(), // childData describes second-level entries
R.layout.child_row, // Layout for second-level entries
new String[] { "shadeName", "rgb" }, // Keys in childData maps to display
new int[] { R.id.childname, R.id.rgb }
);
setListAdapter( expListAdapter );
// Imageview to show
}
/**
* Creates the group list out of the colors[] array according to
* the structure required by SimpleExpandableListAdapter. The resulting
* List contains Maps. Each Map contains one entry with key "colorName" and
* value of an entry in the colors[] array.
*/
private List createGroupList() {
return (List)songsList;
}
/**
* Creates the child list out of the shades[] array according to the
* structure required by SimpleExpandableListAdapter. The resulting List
* contains one list for each group. Each such second-level group contains
* Maps. Each such Map contains two keys: "shadeName" is the name of the
* shade and "rgb" is the RGB value for the shade.
*/
private List createChildList() {
ArrayList result = new ArrayList();
for( int i = 0 ; i < shades.length ; ++i ) {
// Second-level lists
ArrayList secList = new ArrayList();
for( int n = 0 ; n < shades[i].length ; n += 2 ) {
HashMap child = new HashMap();
child.put( "shadeName", shades[i][n] );
child.put( "rgb", shades[i][n+1] );
secList.add( child );
}
result.add( secList );
}
return result;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class TaskHomePageLista extends AsyncTask<String, Void, Void> {
protected void onPreExecute(Void... params) {
}
protected Void doInBackground(String... args) {
try {
// passo i parametri di mail e password alle variabili
//setto la pagina
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost("http://www.miosito.HomePageXml.aspx");
// aggiungo alla lista le variabili
// chiamo la pagina che mi da una risposta.
HttpResponse response = httpClient.execute(httpPost, localContext);
InputStream in = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(in);
String[] nomi = new String[6];
nomi[0] = "price";
nomi[1] = "image_url";
nomi[2] = "seller_image_url";
nomi[3] = "discount";
nomi[4] = "discounted_price";
nomi[5] = "description";
if (doc != null) {
// dichiaro n3 per la lunghezza dell'item principale di quello che devo selezionare.
NodeList n3 = doc.getElementsByTagName("promo");
NodeList n2 = doc.getElementsByTagName("home");
for (int i = 0; i < n3.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
for( int num=0; num < nomi.length; num++){
n2 = doc.getElementsByTagName(nomi[num]);
if (n2.getLength() > 0) {
Node node = n2.item(i);
contenuto_nodo = node.getTextContent();
array_contenuto_nodo.add(contenuto_nodo+"///");
if(nomi[num].equals("price")){
map.put(KEY_PRICE, "Valore" + Html.fromHtml("<BR>" + node.getTextContent() + " €"));
}
if(nomi[num].equals("image_url")){
map.put(KEY_THUMB_URL, node.getTextContent());
}
// if(nomi[num].equals("seller_image_url")){
// map.put(KEY_THUMB_URL_SELLER, node.getTextContent());
// }
if(nomi[num].equals("discount")){
map.put(KEY_DISCOUNT, "Sconto" + Html.fromHtml("<BR>" + node.getTextContent() + " %"));
}
if(nomi[num].equals("discounted_price")){
map.put(KEY_DISCOUNTED_PRICE, node.getTextContent()+ " €");
}
if(nomi[num].equals("description")){
map.put(KEY_DESCRIPTION, node.getTextContent());
}
System.out.println("sto elaborando");
}
n2 = doc.getElementsByTagName("home");
}
n2 = doc.getElementsByTagName("promo");
if (n2.getLength() > 0) {
Node node = n2.item(i);
node = node.getFirstChild();
map.put(KEY_TITLE_OFFERTA, node.getTextContent());
}
songsList.add(map);
}
System.out.println("array_titolo_categoria_home is: " + array_contenuto_nodo );
// controllo_login_tempo = "finito";
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void... params) {
}
}
}
In KEY_THUMB_URL after AsynkTask i have the url of image. I need show at harth with image loader. But i dunno how implement image loader in the SimpleExpandableListAdapter. Please help me is very important!
I think i can use this:
int loader = R.drawable.loader;
// Imageview to show
ImageView image = (ImageView) findViewById(R.id.image);
// Image url
String image_url = "http://api.androidhive.info/images/sample.jpg";
// ImageLoader class instance
ImageLoader imgLoader = new ImageLoader(getApplicationContext());
// whenever you want to load an image from url
// call DisplayImage function
// url - image url to load
// loader - loader image, will be displayed before getting image
// image - ImageView
imgLoader.DisplayImage(image_url, loader, image);
but i dunno where i must put this code... Please help!
Look this image for screen
http://www.magicfly.it/app/screen.jpg
Finally I found a solution.
"This class can be used by external clients of SimpleAdapter to bind values to views. You should use this class to bind values to views that are not directly supported by SimpleAdapter or to change the way binding occurs for views supported by SimpleAdapter."
So ImageView. The expected bind value is a resource id or a string and setViewImage(ImageView, int) or setViewImage(ImageView, String) is invoked.
public class MyViewBinder implements ViewBinder {
#Override
public boolean setViewValue(View view, Object data,
String textRepresentation) {
if ((view instanceof ImageView) & (data instanceof Bitmap)) {
ImageView iv = (ImageView) view;
Bitmap bm = (Bitmap) data;
iv.setImageBitmap(bm);
return true;
}
return false;
}
}
and
HashMap<String, Object> man = new HashMap<String,Object>();
Bitmap bitmap = BitmapFactory.decodeStream(aURL.openStream());
modles.put(samURL,bitmap);
then
adapter.setViewBinder(new MyViewBinder()); //its below declaration of adapter
source : click here
Related
Looks like find the image but i don't know how to insert into the simple adapter (or anything that let me set the image in my layout)
https://gyazo.com/61ab064c19ae50090f08e6436776a52e
I want to set an image for each object in the array, like:
monsterimglist.setImageResource(R.mipmap.icon_name);
For the moment im testing to show R.mipmap.a1 in all the array items in the listview.
Error: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
Someone can help me? Thanks a lot
ListView monsterslistview;
ImageView monsterimg;
TextView monstername;
TextView monstertype;
private static String monsterid;
ArrayList<HashMap<String, String>> MonstersList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_monsters);
//Fiquem els elements creats la seva id corresponent
monstername = (TextView) findViewById(R.id.namelayout);
monstertype = (TextView) findViewById(R.id.typelayout);
monsterslistview = (ListView) findViewById(R.id.monsterslistview);
monsterimg = (ImageView) findViewById(R.id.imglayout);
HashMap<String, String> hashMap;
//Creem un nou objecte ArrayList per inserir les dades
MonstersList = new ArrayList<HashMap<String, String>>();
//..........Process JSON DATA................
try {
JSONObject reader = new JSONObject(loadJSONFromAsset());
//Guardem a un Array de tipus JSON les dades
JSONArray jr = reader.getJSONArray("monsters");
for (int i = 0; i < jr.length(); i++) {
JSONObject jsonObjectLine = jr.getJSONObject(i);
// Desem els items JSON en una variable
String id = jsonObjectLine.getString("id");
String name = jsonObjectLine.getString("name");
String type = jsonObjectLine.getString("type");
String icon = jsonObjectLine.getString("icon");
//Toast.makeText(ListMonsters.this, id, Toast.LENGTH_LONG).show();
// Afegim la clau-valor a un objecte HashMap
hashMap = new HashMap<String, String>();
hashMap.put("id", id);
hashMap.put("name", name);
hashMap.put("type", type);
hashMap.put("icon", icon);
MonstersList.add(hashMap);
//mostrem per pantalla els elements que volem mostar
ListAdapter adapter = new SimpleAdapter(
ListMonsters.this,
MonstersList,
R.layout.onemonster,
new String[]{"name", "type","icon"},
new int[]{R.id.namelayout, R.id.typelayout, R.id.imglayout}
);
//Picasso.with(getApplicationContext()).load(R.mipmap.a1).into(monsterimglist);
monsterslistview.setAdapter(adapter);
//String idagafat = MonstersList.get(i).get("icon").replace(" ", "");
monsterimg.setImageResource(R.mipmap.a1);
monsterslistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/**
String idagafat = MonstersList.get(position).get("id").replace(" ", "");
String positionagafada = String.valueOf(position);
openmonster(idagafat, positionagafada);
**/
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// Funció llegir json
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = ListMonsters.this.getAssets().open("monsters.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
public void openmonster(String id, String pos){
int posarray = Integer.parseInt(pos);
Toast.makeText(ListMonsters.this, MonstersList.get(posarray).get("icon").replace(" ", ""), Toast.LENGTH_SHORT).show();
//Toast.makeText(ListMonsters.this, MonstersList.get(posarray).get("name").replace(" ", ""), Toast.LENGTH_SHORT).show();
//Toast.makeText(ListMonsters.this, MonstersList.get(posarray).get("type").replace(" ", ""), Toast.LENGTH_SHORT).show();
}
}
Close the Bracket before creating the adapter.May be it will change your result.
Updated :
ListView monsterslistview; ImageView monsterimg; TextView monstername; TextView monstertype;
private static String monsterid; ArrayList<HashMap<String, String>> MonstersList;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_monsters);
//Fiquem els elements creats la seva id corresponent
monstername = (TextView) findViewById(R.id.namelayout);
monstertype = (TextView) findViewById(R.id.typelayout);
monsterslistview = (ListView) findViewById(R.id.monsterslistview);
monsterimg = (ImageView) findViewById(R.id.imglayout);
HashMap<String, String> hashMap;
//Creem un nou objecte ArrayList per inserir les dades
MonstersList = new ArrayList<HashMap<String, String>>();
//..........Process JSON DATA................
try {
JSONObject reader = new JSONObject(loadJSONFromAsset());
//Guardem a un Array de tipus JSON les dades
JSONArray jr = reader.getJSONArray("monsters");
for (int i = 0; i < jr.length(); i++) {
JSONObject jsonObjectLine = jr.getJSONObject(i);
// Desem els items JSON en una variable
String id = jsonObjectLine.getString("id");
String name = jsonObjectLine.getString("name");
String type = jsonObjectLine.getString("type");
String icon = jsonObjectLine.getString("icon");
//Toast.makeText(ListMonsters.this, id, Toast.LENGTH_LONG).show();
// Afegim la clau-valor a un objecte HashMap
hashMap = new HashMap<String, String>();
hashMap.put("id", id);
hashMap.put("name", name);
hashMap.put("type", type);
hashMap.put("icon", icon);
MonstersList.add(hashMap);
} //-----This Bracket was missed in your code
//mostrem per pantalla els elements que volem mostar
ListAdapter adapter = new SimpleAdapter(
ListMonsters.this,
MonstersList,
R.layout.onemonster,
new String[]{"name", "type","icon"},
new int[]{R.id.namelayout, R.id.typelayout, R.id.imglayout}
);
//Picasso.with(getApplicationContext()).load(R.mipmap.a1).into(monsterimglist);
monsterslistview.setAdapter(adapter);
//String idagafat = MonstersList.get(i).get("icon").replace(" ", "");
monsterimg.setImageResource(R.mipmap.a1);
monsterslistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/**
String idagafat = MonstersList.get(position).get("id").replace(" ", "");
String positionagafada = String.valueOf(position);
openmonster(idagafat, positionagafada);
**/
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// Funció llegir json public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = ListMonsters.this.getAssets().open("monsters.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json; }
public void openmonster(String id, String pos){
int posarray = Integer.parseInt(pos);
Toast.makeText(ListMonsters.this, MonstersList.get(posarray).get("icon").replace(" ", ""), Toast.LENGTH_SHORT).show();
//Toast.makeText(ListMonsters.this, MonstersList.get(posarray).get("name").replace(" ", ""), Toast.LENGTH_SHORT).show();
//Toast.makeText(ListMonsters.this, MonstersList.get(posarray).get("type").replace(" ", ""), Toast.LENGTH_SHORT).show(); }
I am using this Tutorial for Creating a custom listview with radio button. In this tutorial when we click the item in the list then color of item change.
This is happening when i am testing this code above 4.0 but below 4.0 it is not workin properly I am not understand why????
Class Blog.java
public class Blog extends Activity {
ListView listView;
ArrayList< String>arrayList; // list of the strings that should appear in ListView
ArrayAdapter arrayAdapter; // a middle man to bind ListView and array list
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom);
listView = (ListView) findViewById(R.id.lstDemo);
// LIST OF STRINGS / DATA THAT SHOULD APPEAR IN LISTVIEW HERE WE HAVE HARD CODED IT WE CAN TAKE THIS INPUT FROM USER AS WELL
arrayList = new ArrayList();
arrayList.add("India");
arrayList.add("USA");
arrayList.add("England");
arrayList.add("Singapur");
arrayList.add("China");
arrayList.add("Canada");
arrayList.add("Srilanka");
arrayList.add("SouthAfrica");
arrayAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_single_choice,arrayList);
listView.setAdapter(arrayAdapter);
// LETS HIGHLIGHT SELECTED ITEMS
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView arg0, View view, int position,
long itemId) {
/*
* when we click on item on list view we can get it catch item here.
* so view is the item clicked in list view and position is the position
* of that item in list view which was clicked.
*
* Now that we know which item is click we can easily change the color
* of text but when we click on next item we we have to deselect the old
* selected item means recolor it back to default , and then hight the
* new selected item by coloring it .
*
* So here's the code of doing it.
*
*
* */
CheckedTextView textView = (CheckedTextView) view;
for (int i = 0; i < listView.getCount(); i++) {
textView= (CheckedTextView) listView.getChildAt(i);
if (textView != null) {
textView.setTextColor(Color.WHITE);
}
}
listView.invalidate();
textView = (CheckedTextView) view;
if (textView != null) {
textView.setTextColor(Color.BLUE);
}
}
});
}
}
My xml View
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/lstDemo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:choiceMode="singleChoice">
</ListView>
Define your variables like this
private ProgressDialog pDialog;
private ListView lv;
private ArrayList<GoModelAll> m_ArrayList = null;
GoArrayAdapter gaa;
Define your AsyncTask like this
new GoAsyncTask().execute();
Your AsyncTask class Code like this
class GoAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
/*pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();*/
pd.show();
}
#Override
protected String doInBackground(String... params) {
sal = new StaticApiList();
myUrl = StaticApiList.go_api;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(myUrl);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("httpResponse");
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
jsonString = stringBuilder.toString();
Log.i("talk_all_json", jsonString);
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("Exception generates caz of httpResponse :"
+ cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out
.println("Second exception generates caz of httpResponse :"
+ ioe);
ioe.printStackTrace();
}
return null;
}
#SuppressWarnings("static-access")
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
vivek = true;
try{
m_ArrayList = new ArrayList<GoModelAll>();
if (jsonString.length() > 0) {
JSONArray jArray = new JSONArray(jsonString);
dh.open();
for(int i=0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
description = jObject.getString("description");
excert = jObject.getString("excert");
thumsrc = jObject.getString("thumsrc");
title = jObject.getString("title");
postid = jObject.getInt("postid");
Log.d("talklog", "Title -> " + title + " , thumsrc -> " + thumsrc
+ " , excert -> " + excert + " , description -> " + description);
Log.d("talklog", "============================= end of " + i + " ===============================");
gma = new GoModelAll();
gma.description = description;
gma.excert = excert;
gma.thumsrc = thumsrc;
gma.title = title;
gma.postid = postid;
Cursor cursor = dh.getSeenStatus(gma.postid);
if(cursor.getCount()>0)
{
cursor.moveToFirst();
if(cursor.getInt(0) == 0)
{
gma.isSeen = false;
}
else
{
gma.isSeen = true;
}
}
else
{
ContentValues cv = new ContentValues();
cv.put(DbHandler.KEY_ID, postid);
cv.put(DbHandler.KEY_VALUE, 0);
dh.addData(DbHandler.TABLE_SEEN, cv);
}
m_ArrayList.add(gma);
}
dh.close();
}
gaa = new GoArrayAdapter(getActivity(), m_ArrayList);
lv = (ListView) getActivity().findViewById(R.id.go_list);
lv.setVisibility(View.VISIBLE);
lv.setAdapter(gaa);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
dh.open();
dh.updateSeenStatus(m_ArrayList.get(arg2).postid, 1);
m_ArrayList.get(arg2).isSeen = true;
dh.close();
GoDetail fragment = new GoDetail();
Bundle bundle = new Bundle();
bundle.putString("title", m_ArrayList.get(arg2).title);
bundle.putString("excert", m_ArrayList.get(arg2).excert);
bundle.putString("description", m_ArrayList.get(arg2).description);
bundle.putString("thumsrc", m_ArrayList.get(arg2).thumsrc);
bundle.putString("header_title", "Go");
//bundle.putInt("postid", m_ArrayList.get(arg2).postid);
fragment.setArguments(bundle);
((BaseContainerFragment)getParentFragment()).replaceFragment(fragment, true);
}
});
}catch(Exception e){
e.printStackTrace();
}
//pDialog.dismiss();
pd.dismiss();
}
}
Your Adapter class
public class GoArrayAdapter extends ArrayAdapter<GoModelAll> {
private final Context context;
ImageLoader imgLoader;
private final ArrayList<GoModelAll> values;
DataHelper dh;
public GoArrayAdapter(Context context,
ArrayList<GoModelAll> values) {
super(context, R.layout.go_row, values);
this.context = context;
this.values = values;
imgLoader = new ImageLoader(context);
dh = new DataHelper(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.go_row, parent, false);
/** Get view over here.. */
GoModelAll asm = values.get(position);
TextView title = (TextView) rowView.findViewById(R.id.go_tv);
ImageView business_logo = (ImageView) rowView.findViewById(R.id.go_image);
ImageView go_red = (ImageView)rowView.findViewById(R.id.go_red);
if(asm.isSeen)
{
go_red.setVisibility(View.INVISIBLE);
}
/**Set view over here..*/
title.setText(asm.title);
// Loader image - will be shown before loading image
int loader = R.drawable.image_not_available;
String image_url = asm.thumsrc;
imgLoader.DisplayImage(image_url, loader, business_logo);
return rowView;
}
}
At last your Model class
public class GoModelAll {
public String description = "";
public String excert = "";
public String thumsrc = "";
public String title = "";
public int postid = 0;
public boolean isSeen = false;
}
Show us your adapter code as well and try not to change an item of list view from setOnItemClickListener instead change your data and notify adapter to refresh the view.
Set this as background to your list item :
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="#color/white" />
<item android:color="#color/black" />
</selector>
I have gone through Android: How to correctly use NotifyDataSetChanged with SimpleExpandableListAdapter?, and have a similar program structure but the list (of access points) appears on creation (first scan) and disappears on the next wifi scan.
public class APScanActivity extends ExpandableListActivity {
public static WifiManager mywifiManager;
private TextView PlotTitle;
boolean mDualPane;
int mCurCheckPosition = 0;
List<ScanResult> scanResults;
SimpleExpandableListAdapter expListAdapter;
ExpandableListView APList;
List GroupList = new ArrayList();
List ChildList = new ArrayList();
int scanResultsSize;
ArrayList<String> NetworkList;
Multimap<String,String> Networks;
private long[] expandedIds;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mywifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
setContentView(R.layout.activity_autoscan);
APList = getExpandableListView();
PlotTitle = (TextView) findViewById(R.id.displayMsg);
View detailsFrame = findViewById(R.id.detailFragment);
mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
if (savedInstanceState != null) {
// Restore last state for checked position.
mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
}
if (mDualPane) {
// In dual-pane mode, list view highlights selected item.
getExpandableListView().setChoiceMode(ExpandableListView.CHOICE_MODE_SINGLE);
showDetails(mCurCheckPosition,null);
}
if (mywifiManager.isWifiEnabled())
PlotTitle.setText("Choose Accesspoint from Network list");
registerReceiver(wifiScanReceiver, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
new WifiScanner().execute();
}
/** Implement a background task for Wi-Fi scans **/
public static class WifiScanner extends AsyncTask<Void, Void, Boolean> {
protected Boolean doInBackground(Void... params) {
return mywifiManager.startScan();
}
}
private BroadcastReceiver wifiScanReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
/** Get the Wi-Fi scan results **/
scanResults = mywifiManager.getScanResults();
new WifiScanner().execute();
scanResultsSize = (scanResults == null) ? 0 : scanResults
.size();
Networks = ArrayListMultimap.create(); // This is our multimap with ssid,bssid pairs
for (int index = 0; index < scanResultsSize; index++) {
ScanResult scanResult = scanResults.get(index);
String ssid = scanResult.SSID;
String AccessPoint = scanResult.BSSID+" ("+scanResult.level+"dBm )";
Networks.put(ssid, AccessPoint);
}
NetworkList = new ArrayList<String>(Networks.keySet());
GroupList.clear();
ChildList.clear();
GroupList = createGroupList();
ChildList = createChildList();
if (expListAdapter == null){
expListAdapter = new SimpleExpandableListAdapter(
context,
GroupList, // Creating group List.
R.layout.group_row, // Group item layout XML.
new String[] { "Network" }, // the key of group item.
new int[] { R.id.row_name }, // ID of each group item.-Data under the key goes into this TextView.
ChildList, // childData describes .
R.layout.child_row, // Layout for sub-level entries(second level).
new String[] {"AccPt"}, // Keys in childData maps to.
new int[] { R.id.grp_child} // Data under the keys above go into these TextViews.
);
//setListAdapter(expListAdapter);
APList.setAdapter(expListAdapter);
}
expListAdapter.notifyDataSetChanged();
}
};
#SuppressWarnings({ "unchecked", "rawtypes" })
public List createGroupList() {
ArrayList result = new ArrayList();
for( int i = 0 ; i < NetworkList.size() ; ++i ) {
HashMap m = new HashMap();
m.put( "Network",NetworkList.get(i) ); // the key and it's value.
result.add( m );
}
return (List)result;
}
#SuppressWarnings({ "unchecked", "rawtypes" })
public List createChildList() {
ArrayList result = new ArrayList();
for( int i = 0 ; i < NetworkList.size() ; ++i ) {
/* each group need one HashMap-Here for each group we have subgroups */
String nn = NetworkList.get(i);
ArrayList<String> APlist = new ArrayList<String>(Networks.get(nn));
ArrayList secList = new ArrayList();
for( int n = 0 ; n < APlist.size() ; n++ ) {
HashMap child = new HashMap();
String AP = APlist.get(n);
child.put( "AccPt", AP);
secList.add( child );
}
result.add( secList );
}
return result;
}
I cant figure out how the data update gets notified to the adapter. Unlike the arraylist adapter there are no direct add/remove etc. methods on the SimpleExpandableListAdapter.
From the previous post on the same topic Android: How to correctly use NotifyDataSetChanged with SimpleExpandableListAdapter?
Removed createGroupList() and createChildList().
Directly add elements of child nad group data using GroupList.add and ChildList.add instead of assigning from the functions return variable.
I have a little problem with putting an image to a list view using simple adapter. I'm getting the image from my online server(AMAZON). After downloading the image based on the user id, i try to set them in my listview but nothing was display and no error is occured.
Below is my code:
// looping through All applicants
for (int i = 0; i < applicant.length(); i++) {
JSONObject c = applicant.getJSONObject(i);
// Storing each JSON item in variable
String uid = c.getString(TAG_UID);
String name = c.getString(TAG_NAME);
String overall = c.getString(TAG_OVERALL);
String apply_datetime = c.getString(TAG_APPLY_DATETIME);
String photo = c.getString(TAG_PHOTO);
// creating new HashMap
//HashMap<String, String> map = new HashMap<String, String>();
//IMAGE
HashMap<String, Object> map = new HashMap<String, Object>();
// adding each child node to HashMap key (value)
map.put(TAG_UID, uid);
map.put(TAG_NAME, name);
map.put(TAG_OVERALL, overall);
map.put(TAG_APPLY_DATETIME, apply_datetime);
// adding HashList to ArrayList
// applicantsList.add(map);
// LISTING IMAGE TO LISTVIEW
try {
imageURL = c.getString(TAG_PHOTO);
InputStream is = (InputStream) new URL(
"my url link/images/"
+ imageURL).getContent();
d = Drawable.createFromStream(is, "src name");
} catch (Exception e) {
e.printStackTrace();
}
map.put(TAG_PHOTO, d);
// adding HashList to ArrayList
applicantsList.add(map);
}
As you can see, after i download the image. i set to listview using simpleAdapter below:
SimpleAdapter adapter = new SimpleAdapter(
SignUpApplicantActivity.this, applicantsList,
R.layout.list_applicant, new String[] {
TAG_UID, TAG_NAME, TAG_OVERALL,
TAG_APPLY_DATETIME, TAG_PHOTO }, new int[] {
R.id.applicantUid, R.id.applicantName,
R.id.applicantOverall,
R.id.apply_datetime, R.id.list_image });
// updating listView
setListAdapter(adapter);
Did you called notifyDatasetChange() ? your adapter may not be invalidated if you don't call it.
From the SimpleAdapter documentation the image data is expected to be a resource ID or a string (an image URI) - see setViewImage(ImageView,String)
I see 2 solutions:
Provide a URI in the data map, not a drawable.
Implement your own view binder to bind the drawable to the ImageView:
adapter.setViewBinder(new SimpleAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Object data, String textRepresentation) {
if(view.getId() == R.id.list_image) {
ImageView imageView = (ImageView) view;
Drawable drawable = (Drawable) data;
imageView.setImageDrawable(drawable);
return true;
}
return false;
}
});
Try
try{
for (int i = 0; i < applicant.length(); i++) {
JSONObject c = applicant.getJSONObject(i);
// Storing each JSON item in variable
String uid = c.getString(TAG_UID);
String name = c.getString(TAG_NAME);
String overall = c.getString(TAG_OVERALL);
String apply_datetime = c.getString(TAG_APPLY_DATETIME);
String photo = c.getString(TAG_PHOTO);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key (value)
map.put(TAG_UID, uid);
map.put(TAG_NAME, name);
map.put(TAG_OVERALL, overall);
map.put(TAG_APPLY_DATETIME, apply_datetime);
map.put(TAG_PHOTO, photo);
// adding HashList to ArrayList
applicantsList.add(map);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
SimpleAdapter adapter = new SimpleAdapter(
SignUpApplicantActivity.this, applicantsList,
R.layout.list_applicant, new String[] {
TAG_UID, TAG_NAME, TAG_OVERALL,
TAG_APPLY_DATETIME, TAG_PHOTO }, new int[] {
R.id.applicantUid, R.id.applicantName,
R.id.applicantOverall,
R.id.apply_datetime, R.id.list_image });
// updating listView
setListAdapter(adapter);
Maybe my code can help you!?!
I have made
convertDrawable(int Integer)
and String.valueOf(convertDrawable(iconId))
HashF.put(TAG_ID, String.valueOf(convertDrawable(iconId)));
private void getList(JSONObject json) {
try {
details = json.getJSONArray(TAG_LIST);
for (int i = 0; i < details.length(); i++) {
JSONObject main = details.getJSONObject(i);
Integer date = main.getInt(TAG_DATE);
JSONArray nArray = main.getJSONArray(TAG_NOW);
JSONObject detail = nArray.getJSONObject(0);
Integer iconId = detail.getInt(TAG_ID);
HashMap<String, String> HashF = new HashMap<String, String>();
HashF.put(TAG_DATE, convertDate(date));
HashF.put(TAG_ID, String.valueOf(convertDrawable(iconId)));
fList.add(HashF);
}
} catch (Exception e) {
}
ListAdapter adapter =
new SimpleAdapter(getActivity(),
fList, R.layout.list_item,
new String[]{
TAG_DATE,
TAG_ID
},
new int[]{
R.id.datum,
R.id.icon_fore
});
setListAdapter(adapter);
}
public static String convertDate(Integer Time) {
SimpleDateFormat sdf =
new SimpleDateFormat(
"dd, MMMM", Locale.getDefault());
Calendar kal =
Calendar.getInstance();
kal.setTimeInMillis(Time * 1000L);
sdf.setTimeZone(kal.getTimeZone());
return sdf.format(kal.getTime());
}
public static int convertDrawable(int aId){
int icon = 0;
if(aId == 8300){
icon = R.drawable.draw1;
}
if (aId >= 7010 && actualId < 7919){
icon = R.drawable.draw2;
}
if (aId >= 2010 && actualId <3010) {
icon = R.drawable.draw3;
}
if (aId >= 3010 && actualId < 4010) {
icon = R.drawable.draw4;
}
if (aId >= 6010 && actualId < 7010) {
icon = R.drawable.draw5;
}
if (aId >= 5010 && actualId < 6010) {
icon = R.drawable.draw6;
}
if (aId == 3801){
icon = R.drawable.draw7;
}
if (aId == 8032){
icon = R.drawable.draw8;
}
if (aId == 8083){
icon = R.drawable.draw9;
}
if (aId == 8704) {
icon = R.drawable.draw10;
}
return icon;
}
Anyway make a look at Bitmap is not a Drawable
Below is Simple declaration in this a child and parent is being build with dynamic list value.With relevant code as createGroupList() and createChildList(). I am able to manipulate with TextView but one of field is my dynamic image from getting to JSON not is being load in WebView.
expListAdapter = new SimpleExpandableListAdapter(
this, createGroupList(), // Creating group List.
R.layout.group_row,
new String[] { "Group Item" },
new int[] { R.id.`enter code here`row_name },
createChildList(), // Creating Child List.
R.layout.child_row,
new String[] { "Sub Item0", "Sub Item1", "Sub Item2", "Sub Item3" },
new int[] { R.id.grpChildName, R.id.grpChildAddress, R.id.grpChildPhoneNo, R.id.childImage }
);
setListAdapter(expListAdapter);
private List createGroupList() {
String header = "";
int headerSize = 0;
ArrayList result = new ArrayList();
for (int i = 0; i < dynamicList.size(); i++) {
HashMap m = new HashMap();
String taxiCompanyData[] = dynamicList.get(i);
if (header != taxiCompanyData[3]) {
m.put("Group Item", taxiCompanyData[3]);
header = taxiCompanyData[3];
headerList[headerSize] = header;
headerSize++;
result.add(m);
counter++;
}
}
return (List) result;
}
Above is Group creating and
private List createChildList() {
ArrayList result = new ArrayList();
Log.i("Info ", "headerList.length" + headerList.length);
for (int i = 0; i < headerList.length; i++) {
final ArrayList secList = new ArrayList();
System.out.println("dynamic list size is in main"
+ dynamicList.size());
webView = (WebView) findViewById(R.id.childImage);
for (int j = 0; j < dynamicList.size(); j++) {
String taxiCompanyData[] = dynamicList.get(j);
if (taxiCompanyData[3].equalsIgnoreCase(headerList[i])) {
final HashMap child = new HashMap();
child.put("Sub Item0", taxiCompanyData[0]);
child.put("Sub Item1", taxiCompanyData[1]);
child.put("Sub Item2", taxiCompanyData[2]);
// child.put("Sub Item3", taxiCompanyData[4]);
Thread th = new Thread(){
#Override
public void run() {
webView.loadUrl("https://lh5.googleusercontent.com/-u8heQyD_4y4/T5VMu-Zc6wI/AAAAAAAi71s/EP32a3D-fc0/s90/Corsino");
secList.add(child);
};
};
th.start();
}
}
result.add(secList);
}
return (List)result;
}
I am unable to load WebUI. Please help anyone.