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
Related
Hello friends i am new to android and i am learning about android programming. I am working with my friends. I have web service from which i am showing list of cities in listview now my friend give me task that is when i will click on city then id of that city return me so i don't how to do so please anybody can help me to do so.
public class CityNameActivity extends ListActivity{
private TextView displayText;
ListView list;
private ProgressDialog pDialog;
// URL to get Cities JSON
private static String url = "http://14.140.200.186/Hospital/get_city.php";
// JSON Node names
private static final String TAG_CITIES = "Cities";
private static final String TAG_ID = "city_id";
private static final String TAG_NAME = "city_name";
// Cities JSONArray
JSONArray Cities = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> citylist;
//ArrayList<String> citylist;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cityname_activity_main);
ListView listView=getListView();
citylist = new ArrayList<HashMap<String, String>>();
new GetCities().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetCities extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CityNameActivity.this);
pDialog.setMessage("Please wait...");
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 jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
Cities = jsonObj.getJSONArray(TAG_CITIES);
// looping through All Cities
for (int i = 0; i < Cities.length(); i++) {
JSONObject c = Cities.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
HashMap<String, String> Cities = new HashMap<String, String>();
Cities.put(TAG_ID, id);
Cities.put(TAG_NAME, name);
// adding contact to Cities list
citylist.add(Cities);
}
} 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();
/**`enter code here`
* Updating parsed JSON data into ListView
* */
final ListAdapter adapter = new SimpleAdapter(CityNameActivity.this, citylist, R.layout.city_list_item, new String[] { TAG_NAME}, new int[] { R.id.name});
setListAdapter(adapter);
}
}}
cityname_mai_activity.xml
<ListView
android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView4" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select City"
android:id="#+id/textView4"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="25dp"/>
city_list_item:
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textSize="16sp"
android:textStyle="bold" />
You have to use the Spinner like these below:
Spinner spin = (Spinner) findViewById(R.id.spinner);
spin.setOnItemSelectedListener(this);
ArrayAdapter aa = new ArrayAdapter(this,R.layout.spinner_item,ARRAYLIST_DATA_HERE);
aa.setDropDownViewResource(R.layout.spinner_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
String items=spinner.getSelectedItem().toString();
Log.i("Selected item : ",items);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
return true;
Use the spinner_item xml
xmlns:android="http://schemas.android.com/apk/res/android"
style="?android:attr/spinnerDropDownItemStyle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#BAB7BA"
android:ellipsize="start"
android:gravity="left"
android:padding="10dip"
android:textColor="#color/white" />
Did you check On Click Listener for your ListView ?? I think that will solve your problem.. Use onClikcListener's on ItemClick event which will give you position and based on that position you can get item from your Arraylist which will give you id from that..
I have a class which extends listactivity. I am parsing data from a json file and putting data in list. i have also created a checkbox to check student is present if it checked. For that i have created an array to get the position from list. I am getting the student names but checkbox is giving me null values. Please Help!!! Here is my code,
public class Student_data extends ListActivity {
private ProgressDialog pDialog;
private Button button;
ListView lv;
// URL to get contacts JSON
private static String url = "http://10.0.2.2/studentdata.json";
private static int[] present, absent;
private static int i = 0, j = 0, x;
// JSON Node names
private static final String TAG_DEP_ID = "dep_id";
private static final String TAG_HEAD = "stdata";
private static final String TAG_NAME = "name";
private static final String TAG_ENROLL = "enrollment";
// contacts JSONArray
JSONArray data = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> studentList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.student_list);
studentList = new ArrayList<HashMap<String, String>>();
button = (Button) findViewById(R.id.saveData);
button.setOnClickListener(new ButtonClick());
lv = getListView();
new GetContacts().execute();
lv.setOnItemClickListener(new CheckBoxClick());
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Student_data.this);
pDialog.setMessage("Please wait...");
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 jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
data = jsonObj.getJSONArray(TAG_HEAD);
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
String id = c.getString(TAG_DEP_ID);
String name = c.getString(TAG_NAME);
String enrll = c.getString(TAG_ENROLL);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_DEP_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_ENROLL, enrll);
// adding contact to contact list
studentList.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);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
*/
ListAdapter adapter = new SimpleAdapter(Student_data.this, studentList, R.layout.data_item,
new String[] { TAG_NAME }, new int[] { R.id.name });
setListAdapter(adapter);
}
}
public class CheckBoxClick implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
CheckBox chkbox = (CheckBox) arg1;
if (chkbox.isChecked()) {
present[i] = arg2;
i++;
}
if (chkbox.isChecked()) {
absent[j] = arg2;
j++;
}
}
}
public class ButtonClick implements OnClickListener {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
}
}
data_item.xml--->
<?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"
android:padding="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:weightSum="2" >
<!-- Name Label -->
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="#000"
android:textSize="16sp"
android:textStyle="bold" />
<CheckBox
android:id="#+id/chkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
Try this
if (((CheckBox) arg1).isChecked()) {
//your code
}
I have a android code which that get some data in json format from php file,
I successfully created a listview using those json now I want to create a second activity to show product details when I click on those items.
Here is the code :
public class MainActivity extends Activity {
private String jsonResult;
private String url = "xxxx/get_all_products.php";
private ListView listView;
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_FOUND = "found";
private static final String TAG_DESCRIPTION = "description";
ArrayList<HashMap<String, String>> productList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
productList = new ArrayList<HashMap<String, String>>();
accessWebService();
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[]{url});
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> productList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("products");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("name");
String price = jsonChildNode.optString("price");
String found = jsonChildNode.optString("found");
// String outPut = name + "-" + number;
// String outPut = name + "-" + price + "-" + found;
// productList.add(createProduct("products", outPut));
HashMap<String, String> product = new HashMap<String, String>();
product.put(TAG_NAME, name);
product.put(TAG_FOUND, found);
product.put(TAG_PRICE, price);
productList.add(product);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, productList,
R.layout.list_item, new String[] { TAG_NAME, TAG_PRICE,
TAG_FOUND }, new int[] { R.id.name,
R.id.price, R.id.found });
listView.setAdapter(simpleAdapter);
}
}
and also there are there are two xml layout files.
I read many examples for doing this about setOnItemClickListener whit no success.....
for example tried this with no success :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String selval = ((TextView) view).getText().toString();
Intent intnt = new Intent(getApplicationContext(), SingleListItem.class);
intnt.putExtra("selval ", selval);
}
Here are the errors :
FATAL EXCEPTION: main
java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.TextView
at sig.example.com.sig00.MainActivity$1.onItemClick(MainActivity.java:59)
Here are xml files :
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<!-- Name Label -->
<!-- android:id="#+id/listView1" -->
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp">
</ListView>
and the list_item.xml is
<?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="vertical"
android:padding="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<!-- Name Label -->
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="#43bd00"
android:textSize="16sp"
android:textStyle="bold"
android:gravity="center"/>
<!-- Email label -->
<TextView
android:id="#+id/price"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#acacac" />
<!-- Mobile number label -->
<TextView
android:id="#+id/found"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:textColor="#5d5d5d"
android:textStyle="bold" />
</LinearLayout>
Replace your code from your setOnItemClickListener() to this one :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String selval = listview.getItemAtPosition(position).getText().toString();
// Also I've found a solution on SO that a guy solved this problem doing soemthing like this :
// TextView txt = (TextView) parent.getChildAt(position - listview.firstVisiblePosition()).findViewById(R.id.sometextview);
// String keyword = txt.getText().toString();
Intent intnt = new Intent(getApplicationContext(), SingleListItem.class);
intnt.putExtra("selval ", selval);
EDIT
Your error is that in your intent you are putting as extra "selval ", with an BLANK SPACE so if in your next activity you are doing this :
Class SingleListItem extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.productdetails);
TextView txtProduct = (TextView) findViewById(R.id.product_label);
Intent i = getIntent(); // getting attached intent data
String selval = i.getStringExtra("selval"); // displaying selected product name txtProduct.setText(selval);
}
It never will return your selval string cause you are asking for "sevlal" not from "selval ".
Just remove your unnecessary space and it will work :)
The View in onItemClick is not a TextView, it's the entire row. You should do the following
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//String selval = ((TextView) view.findViewById(R.id.yourId)).getText().toString();
HashMap<String, String> item = parent.getItemAtPosition(position);
String selval = item.get(TAG_PRICE);
Intent intnt = new Intent(getApplicationContext(), SingleListItem.class);
intnt.putExtra("selval ", selval);
}
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);
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.