Change image dynamically into a ListView from JSON - android

I have the following code retrivieng data from URL in JSON format and updating a ListView. The code is working perfectly. In the xml layout, i have two TextView and one ImageView.
How can I update the ImageView dinamically?
I'm not getting the images from a URL, my images are stored inside my project (res/drawable folder). The var TAG_ICON has the name of my image which is exact the same name of the image inside my project.
Example:
response from JSON: TAG_ICON = lamp01
name of the image: lamp01.png
This is my main Class:
public class DeviceList extends ListActivity {
private static String url = "http://192.168.10.2/myhome/get_all_devices.php";
// Hashmap ListView
ArrayList<HashMap<String, String>> deviceList = new ArrayList<HashMap<String, String>>();
// class JSON
JSONParser jParser = new JSONParser();
// Criar JSON Nodes
private static final String TAG_DEVICES = "devices";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_ICON = "icon";
// array JSONArray
JSONArray devices = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.device_list);
// Loat ListView
new LoadDevices().execute();
ListView lv = getListView();
}
// class LoadDevices
class LoadDevices extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute(){
super.onPreExecute();
}
protected String doInBackground(String... args) {
// JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// add to array
devices = json.getJSONArray(TAG_DEVICES);
// Looping trough all results
for(int i = 0; i < devices.length(); i++){
JSONObject c = devices.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String description = c.getString(TAG_DESCRIPTION);
String icon = c.getString(TAG_ICON);
// creating a HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_DESCRIPTION, description);
map.put(TAG_ICON, icon);
deviceList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url){
runOnUiThread(new Runnable() {
public void run() {
// update JSON ListView
ListAdapter adapter = new SimpleAdapter(DeviceList.this, deviceList,R.layout.device_row,
new String[]{
TAG_NAME,
TAG_DESCRIPTION,
},
new int[] {
R.id.device_row_TextViewName,
R.id.device_row_TextViewDescription,
});
// update listView
setListAdapter(adapter);
}
});
}
}
}
Here's my XML layout for a single row
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/device_row_RelativeLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/list_selector"
android:orientation="horizontal"
android:padding="5dip" >
<LinearLayout
android:id="#+id/device_row_LinearLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip"
android:padding="3dip" >
<ImageView
android:id="#+id/device_row_ImageViewIcon"
android:contentDescription="#string/app_name"
android:layout_width="60dip"
android:layout_height="60dip"
android:src="#drawable/lamp03" />
</LinearLayout>
<TextView
android:id="#+id/device_row_TextViewName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/device_row_RelativeLayout"
android:layout_marginTop="5dip"
android:layout_marginLeft="75dip"
android:layout_toRightOf="#+id/device_row_ImageViewIcon"
android:text="Lâmpada do Quarto"
android:textColor="#4169E1"
android:textSize="20dip"
android:textStyle="bold"
android:typeface="sans" />
<TextView
android:id="#+id/device_row_TextViewDescription"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/device_row_TextViewName"
android:layout_marginBottom="5dip"
android:layout_alignLeft="#+id/device_row_TextViewName"
android:paddingTop="1dip"
android:layout_marginRight="15dip"
android:layout_centerHorizontal="true"
android:text="Usado para controlar a lâmpada do quarto."
android:textColor="#343434"
android:textSize="13dip" />
</RelativeLayout>

If the images are in your drawable folder you need to first use the title to find the image in your drawable folder. Make sure that the title of the file is the same as the title tag you are returning from the server.
int imageId = getResources().getIdentifier("yourpackagename:drawable/" + TAG_TITLE, null, null);
Then just find the ImageView and set the image
ImageView picture = (ImageView)findViewById(R.id.device_row_ImageViewIcon);
picture.setImageResource(imageId);

Related

How to pass parsed data from JSON through Intent?

I have created an android app with json parser (tutorial which I followed) and successfully displayed my data. However I cannot display more data in SingleActivity then I have in ListView. (Acctualy I can. But it's just the desired string names.) How can I do that?
SingleFilmActivity.java
public class SingleFilmActivity extends AppCompatActivity {
// JSON Node names
private static final String TAG_NAME = "jmeno";
private static final String TAG_START = "zacatek";
private static final String TAG_END = "konec";
private static final String TAG_CATEGORY = "kategorie";
private static final String TAG_POPIS = "popis";
private static final String TAG_BAN = "omezeni";
private static final String TAG_DAY = "den";
private static final String TAG_CLASS = "trida";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_film);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String zacatek = in.getStringExtra(TAG_START);
String konec = in.getStringExtra(TAG_END);
String kategorie = in.getStringExtra(TAG_CATEGORY);
String popis = in.getStringExtra(TAG_POPIS);
String omezeni = in.getStringExtra(TAG_BAN);
String den = in.getStringExtra(TAG_DAY);
String trida = in.getStringExtra(TAG_CLASS);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblZacatek = (TextView) findViewById(R.id.zacatek_label);
TextView lblKonec = (TextView) findViewById(R.id.konec_label);
TextView lblKategorie = (TextView) findViewById(R.id.kategorie_label);
TextView lblPopis = (TextView) findViewById(R.id.popis_label);
TextView lblOmezeni = (TextView) findViewById(R.id.omezeni_label);
TextView lblDen = (TextView) findViewById(R.id.den_label);
TextView lblTrida = (TextView) findViewById(R.id.trida_label);
lblName.setText(name);
lblZacatek.setText(zacatek);
lblKonec.setText(konec);
lblKategorie.setText(kategorie);
lblPopis.setText(popis);
lblOmezeni.setText(omezeni);
lblDen.setText(den);
lblTrida.setText(trida);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
Den2Fragment.java
public class Den2Fragment extends ListFragment {
private ProgressDialog pDialog;
// JSON Node names
private static final String TAG_FILMY = "filmy";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "jmeno";
private static final String TAG_START = "zacatek";
private static final String TAG_END = "konec";
private static final String TAG_CATEGORY = "kategorie";
private static final String TAG_POPIS = "popis";
private static final String TAG_BAN = "omezeni";
private static final String TAG_DAY = "den";
private static final String TAG_CLASS = "trida";
// Hashmap for ListView
private ArrayList<HashMap<String, String>> filmList = new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_den2, container, false);
}
#Override
public void onViewCreated (View view, Bundle savedInstanceState) {
ListView lv = getListView();
// ListView on item click listener
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String zacatek = ((TextView) view.findViewById(R.id.zacatek)).getText().toString();
String kategorie = ((TextView) view.findViewById(R.id.kategorie)).getText().toString();
Intent in = new Intent(getActivity().getApplicationContext(), SingleFilmActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_START, zacatek);
in.putExtra(TAG_END,TAG_END);
in.putExtra(TAG_CATEGORY, kategorie);
in.putExtra(TAG_POPIS, TAG_POPIS);
in.putExtra(TAG_BAN, TAG_BAN);
in.putExtra(TAG_DAY, TAG_DAY);
in.putExtra(TAG_CLASS, TAG_CLASS);
startActivity(in);
}
});
// Calling async task to get json
new GetFilmy().execute();
}
/** Async task class to get json by making HTTP call */
private class GetFilmy extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Prosím čekejte");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String url =" foo.com";
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray filmy = jsonObj.getJSONArray(TAG_FILMY);
// looping through All Films
for (int i = 0; i < filmy.length(); i++) {
JSONObject f = filmy.getJSONObject(i);
String id = f.getString(TAG_ID);
String name = f.getString(TAG_NAME);
String zacatek = f.getString(TAG_START);
String kategorie = f.getString(TAG_CATEGORY);
// tmp hashmap for single film
HashMap<String, String> film = new HashMap<>();
// adding each child node to HashMap key => value
film.put(TAG_ID, id);
film.put(TAG_NAME, name);
film.put(TAG_START, zacatek);
film.put(TAG_CATEGORY, kategorie);
// adding film to film list
filmList.add(film);
}
} catch (JSONException e) {e.printStackTrace();}
} else {Log.e("ServiceHandler", "Couldn't get any data from the url");}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing()) pDialog.dismiss();
/** Updating parsed JSON data into ListView */
ListAdapter adapter = new SimpleAdapter(
getActivity(), filmList, R.layout.list_item_true,
new String[] { TAG_NAME, TAG_START, TAG_CATEGORY },
new int[] { R.id.name, R.id.zacatek, R.id.kategorie });
setListAdapter(adapter);
}
}
}
list_item_true.xml
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2sp"
android:paddingTop="6sp"
android:textColor="#000000"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/zacatek"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2sp"
android:textColor="#5d5d5d"
android:textStyle="bold" />
<TextView
android:id="#+id/kategorie"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="start"
android:textColor="#5d5d5d" />
content_single_film.xml
<TextView android:id="#+id/name_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25sp"
android:textStyle="bold"
android:paddingTop="10sp"
android:paddingBottom="10sp"
android:textColor="#000000" />
<TextView android:id="#+id/zacatek_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#727272"
android:textStyle="bold" />
<TextView android:id="#+id/konec_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#727272" />
<TextView android:id="#+id/kategorie_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#727272"
android:textStyle="bold" />
<TextView android:id="#+id/omezeni_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#727272"
android:textStyle="bold" />
<TextView android:id="#+id/den_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#727272" />
<TextView android:id="#+id/trida_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#727272" />
<TextView android:id="#+id/popis_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#212121" />
Sorry for posting a lot of code, but I'm not sure what I am doing wrong.
Better you convert whole json to the string.
Intent intent= new Intent(Current.this, Next.class);
intent.putExtra("jsonValue",YourJson.toString);
startActivity(intent);
And in next activity you can get the value of the string with
Intent get=getIntent();
String json= get.getStringExtra("jsonValue");
you got your json String now you can parse it and get values
Better to use Gson. It is so simple and easy
Film film = new Film(...);
String gsonStr = new Gson().toJson(film);
Intent intent= new Intent(Current.this, Next.class);
intent.putExtra("gson",gsonStr);
startActivity(intent);
//From Next Activity
Intent intent=getIntent();
String gStr = intent.getStringExtra("gson");
Film getFilm = new Gson().fromJson(gStr,Film.class);

ListView not showing JSON data

My listview is suposed to import json data into the listview, but it doesnt.
Here is my rooster.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.nijdeken.ccapp.rooster">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Les"
android:id="#+id/lesson"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Lokaal"
android:id="#+id/room"
android:layout_above="#android:id/list"
android:layout_toLeftOf="#+id/teacher"
android:layout_toStartOf="#+id/teacher"
android:layout_marginRight="57dp"
android:layout_marginEnd="57dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Docent"
android:id="#+id/teacher"
android:layout_above="#android:id/list"
android:layout_toLeftOf="#+id/start"
android:layout_toStartOf="#+id/start"
android:layout_marginRight="92dp"
android:layout_marginEnd="92dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Tijd"
android:id="#+id/start"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-thin"
android:id="#android:id/list"
android:layout_below="#+id/lesson"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
And my Rooster.java file:
public class rooster extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://api.ccapp.it/v2/zportal/schedule/37?token=df679ovlka5urmajmd7tg28lc0";
String apiUrl = "http://api.ccapp.it";
// JSON Node names
private static final String TAG_TIME = "start";
private static final String TAG_ROOM = "locations";
private static final String TAG_TEACHER = "teachers";
private static final String TAG_LESSON = "subjects";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rooste);
// ListView listView = (ListView) findViewById(android.R.id.list);
// FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
// fab.attachToListView(listView);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.lesson))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.room))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.teacher))
.getText().toString();
// Starting single contact activity
// Intent in = new Intent(getApplicationContext(),
// SingleContactActivity.class);
// in.putExtra(TAG_NAME, name);
// in.putExtra(TAG_EMAIL, cost);
// in.putExtra(TAG_PHONE_MOBILE, description);
// startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
Servicehandler sh = new Servicehandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, Servicehandler.GET);
Log.d("Schedule: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray("");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String subject = c.getString(TAG_LESSON);
String teachers = c.getString(TAG_TEACHER);
String location = c.getString(TAG_ROOM);
String start = c.getString(TAG_TIME);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_LESSON, subject);
contact.put(TAG_TEACHER, teachers);
contact.put(TAG_ROOM, location);
contact.put(TAG_TIME, start);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
rooster.this, contactList,
R.layout.list_item, new String[] { TAG_LESSON, TAG_ROOM,
TAG_TEACHER, TAG_TIME }, new int[] { R.id.lesson,
R.id.room, R.id.teacher, R.id.time });
setListAdapter(adapter);
}
}
public static void getRooster(String appcode, int week){
// url="http://api.ccapp.it/v2/zportal/schedule/"+week+"?token="+appcode;
url="http://nijdeken.com/json/schedule.json";
}
}
Your JSON url is giving null output. I tried in browser then i got the value as empty []....
Please give the input to your JSON.
http://api.ccapp.it/v2/zportal/schedule/37?token=df679ovlka5urmajmd7tg28lc0

How to set image like background in listview if image is must be loaded from url which parsed from JSON?

I've got a program which parses JSON file from server and makes a listview of it's objects. I need to create background image (or even a thumbnail near title) for each element of list and this image must be downloaded from url.
private static String url = "my url here";
private static final String TAG_NAME = "name";
private static final String TAG_AUTHOR = "author";
private static final String TAG_POSTS = "posts";
private static final String TAG_ID = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_DATE = "date";
private static final String TAG_CONTENT = "content";
private static final String TAG_THUMBNAIL_URL = "thumbnail";
JSONArray posts = null;
ArrayList<HashMap<String, String>> postList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
postList = new ArrayList<HashMap<String,String>>();
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String c_id = ((TextView)view.findViewById(R.id.id)).getText().toString();
String c_title = ((TextView)view.findViewById(R.id.title)).getText().toString();
String c_date = ((TextView)view.findViewById(R.id.date)).getText().toString();
String c_content = ((TextView)view.findViewById(R.id.content)).getText().toString();
String a_name = ((TextView)view.findViewById(R.id.name)).getText().toString();
ImageView image = (ImageView) findViewById(R.id.thumb);
Intent in = new Intent(getApplicationContext(), SimplePostActivity.class);
in.putExtra(TAG_AUTHOR, a_name);
in.putExtra(TAG_ID, c_id);
in.putExtra(TAG_TITLE, c_title);
in.putExtra(TAG_DATE, c_date);
in.putExtra(TAG_CONTENT, c_content);
startActivity(in);
Bitmap bMap = BitmapFactory.decodeFile("/sdcard/" + c_id + ".jpeg");
image.setImageBitmap(bMap);
}
});
new GetData().execute();
}
public class GetData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
Parser parser = new Parser();
String jsonStr = parser.makeServiceCall(url, Parser.GET);
Log.d("Response: ", "> " +jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
posts = jsonObj.getJSONArray(TAG_POSTS);
for (int i = 0; i < posts.length(); i++) {
JSONObject num = posts.getJSONObject(i);
String id = num.getString(TAG_ID);
String title = num.getString(TAG_TITLE);
String date = num.getString(TAG_DATE);
String content = num.getString(TAG_CONTENT);
JSONObject author_object = num.getJSONObject(TAG_AUTHOR);
String name = author_object.getString(TAG_NAME);
HashMap<String, String> post = new HashMap<String, String>();
post.put(TAG_NAME, name);
post.put(TAG_ID, id);
post.put(TAG_TITLE, title);
post.put(TAG_DATE, date);
post.put(TAG_CONTENT, content);
postList.add(post);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("Parser", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(pDialog.isShowing())
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(MainActivity.this, postList, R.layout.list_item,
new String[] {TAG_NAME, TAG_ID, TAG_DATE, TAG_TITLE, TAG_CONTENT},
new int[] {R.id.name, R.id.id, R.id.title, R.id.date, R.id.content});
setListAdapter(adapter);
}
}
Can somebody tell me how to do that ? I don't even know how to start...
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<TextView
android:id="#+id/title"
android:textColor="#0fffff"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone"/>
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/></RelativeLayout>
You must:
Add an ImageView to your layout.
In order to display images you'll have to implement your own listview adapter and invoke images loading in getView method.
Use Picasso library to background download. It's use is as simple as:
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

Why does my ListView not update with SimpleAdapter?

I am retrieving JSON data from my server with which I want to update my ListView with. Everything works fine with retrieving the data but after it's finished and it tries to update the list I just get an empty page with no errors. Log.d("ListLocations", "after") is able to run as well so I don't see any problems with PostExecute and intiliasation of SimpleAdapter
I have adapted my code from this tutorial: http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/#ff0000
This is my ListActivity class:
public class ListLocations extends ListActivity
{
//Root url and controller
private static String root = "someURL/";
private static String locationsController = "locations";
// Progress Dialog
private ProgressDialog pDialog;
//JSON node names for locations
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_TERRAIN = "terrain";
private static final String TAG_DIFFICULTY = "difficulty";
private static final String TAG_RATINGS = "ratings";
private static final String TAG_UID = "uid";
private static final String TAG_LONG= "long";
private static final String TAG_LAT= "lat";
private static final String TAG_DISTANCE= "distance";
private static final String TAG_COMID= "comid";
//Will be used to contain the list of locations extracted from JSON
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_locations);
new GetLocations().execute(root + locationsController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_list_locations, menu);
return true;
}
class GetLocations extends AsyncTask<String, Void, Void>
{
// private ProgressDialog pDialog;
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(ListLocations.this);
pDialog.setMessage("Loading locations. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
public Void doInBackground(String... urls)
{
try
{
JSONHandler jsonHandler = new JSONHandler();
JSONObject json= jsonHandler.getJSONFromUrl(urls[0]);
Log.d("ListLocations",json.toString());
JSONArray locations = json.getJSONArray("locations");
int length = locations.length();
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
for(int i = 0; i < length; i++)
{
JSONObject loc = locations.getJSONObject(i);
//Create HashMap
HashMap<String, String> map = new HashMap<String, String>();
//Get and store values into map
map.put("id", loc.getString(TAG_ID));
map.put("name", loc.getString(TAG_NAME));
map.put("distance", loc.getString(TAG_DISTANCE));
map.put("difficulty", loc.getString(TAG_DIFFICULTY));
map.put("terrain", loc.getString(TAG_TERRAIN));
map.put("ratings", loc.getString(TAG_RATINGS));
map.put("long", loc.getString(TAG_LONG));
map.put("lat", loc.getString(TAG_LAT));
map.put("uid", loc.getString(TAG_UID));
map.put("comid", loc.getString(TAG_COMID));
//Add map to list
list.add(map);
}
System.out.println(list);
}
catch (Exception e)
{
e.printStackTrace();
}
Log.d("ListLocations", "Successfully finished HTTP Request");
return(null);
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
Log.d("ListLocations", "inside run");
ListAdapter adapter = new SimpleAdapter(
ListLocations.this, list,
R.layout.list_item, new String[] { TAG_ID,
TAG_NAME},
new int[] { R.id.id, R.id.name });
Log.d("ListLocations", "after");
// updating listview
setListAdapter(adapter);
}
});
}
}
}
This is list_item.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<!-- location id (pid) - will be HIDDEN - used to pass to other activity -->
<TextView
android:id="#+id/id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<!-- Name Label -->
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="17dip"
android:textStyle="bold" />
</LinearLayout>
This is activity_list_locations.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
You never put the data in the list field from the Activity that you use with the SimpleAdapter because the list variable in the doInBackground method is a local variable and not the field. Instead of:
//...
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
for(int i = 0; i < length; i++) {
//...
write:
//...
list = new ArrayList<HashMap<String, String>>();
for(int i = 0; i < length; i++) {
//...
so you don't make a local variable and put the elements in the right list.

ArrayList of Hashmaps not showing in Android listview

I am trying to populate a listview with an arraylist of Hashmaps (String, Integer). I'm not getting have any errors however the list does not show anything. I have looked at other questions similar to this but in those cases they did not have any data in their arraylists. From the logcat i can see the list is present but the view isn't showing. Any idea how to resolve this?
CODE :
public class JsonActivity extends ListActivity{
private ProgressDialog progressDialog;
// JSON Node names
private static final String TAG_ID = "id";
private static final String TAG_ARTISTNAME = "artistname";
// chartItemList is the array list that holds the chart items
ArrayList<HashMap<String, Integer>> chartItemList = new ArrayList<HashMap<String,
Integer>>();
JsonParser Parser = new JsonParser();
// JSONArray
JSONArray chartItems = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progressdialog);
//url from where the JSON has to be retrieved
String url = "http://web.com/test.php";
//Check if the user has a connection
ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
if (!info.isConnected()) {
Toast.makeText(this, "Please check your connection and try again.",
Toast.LENGTH_SHORT).show();
}
//if positive, fetch the articles in background
else new getChartItems().execute(url);
}
//else show toast
else {
Toast.makeText(this, "Please check your connection and try again.",
Toast.LENGTH_SHORT).show();
}
}
class getChartItems extends AsyncTask<String, String, String> {
// Shows a progress dialog while executing background task
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(JsonActivity.this);
progressDialog.setMessage("Loading chart...");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.show();
}
//Gets the json data for chart items data and presents it in a list view
#Override
protected String doInBackground(String... args) {
String url = "http://web.com/test.php";
String json = Parser.getJSONFromUrl(url);
int id;
String artistname;
try{
chartItems = new JSONArray(json);
JSONObject json_data=null;
for(int i=0;i<chartItems.length();i++){
json_data = chartItems.getJSONObject(i);
artistname=json_data.getString("artistname");
id=json_data.getInt("id");
HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
// adding each child node to HashMap key => value
hashMap.put(artistname,id);
// adding HashMap to ArrayList
chartItemList.add(hashMap);
}
;
}
catch (JSONException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
System.out.println(chartItemList);
//updating list view with the parsed items
ListAdapter adapter = new SimpleAdapter(JsonActivity.this, chartItemList,
R.layout.listview,
new String[] {TAG_ARTISTNAME,TAG_ID }, new int[]
{R.id.artistname,R.id.id });
setListAdapter(adapter);
}
});
return null;
}
//Removes the progress dialog when the data has been fetched
protected void onPostExecute(String args) {
progressDialog.dismiss();
}
}
}
VIEW :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#eee">
<!-- Name Label -->
<TextView
android:id="#+id/id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#ff0a0a"
android:textSize="16sp"
android:textStyle="bold"
android:paddingTop="6dip"
android:paddingBottom="2dip" />
<TextView
android:id="#+id/artistname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:textSize="10sp"
android:paddingTop="6dip"
android:paddingBottom="2dip" />
</LinearLayout>
</LinearLayout>
Change this line :
// adding each child node to HashMap key => value
hashMap.put(artistname,id);
with this,
// adding each child node to HashMap key => value
hashMap.put(TAG_ARTISTNAME, artistname);
hashMap.put(TAG_ID, id);
HashMap will store values in key=>value pairs only.

Categories

Resources