How to display image in listview from json dynamically - android

I want to list text and image from json which is placed in particular url
I have successively displayed textview but how to display image my code is
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "***MY URL***";
// JSON Node names
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_URL = "hosting_thumbnail_url";
// contacts JSONArray
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_jsonparsing);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
// looping through All Contacts
for(int i = 0; i < json.length(); i++){
JSONObject c = json.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_PRICE);
//String image1 = c.getString( TAG_URL);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_PRICE, email);
//map.put(TAG_URL, image1);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME, TAG_PRICE }, new int[] {
R.id.name, R.id.email });
setListAdapter(adapter);
}
}
i want listview like this "http://pic002.cnblogs.com/images/2012/372551/2012021011374176.jpg"

You will need to write a custom list adapter. Google for "android custom listadapter image". The first hit is this one, which looks like a decent example.

As SimonSays said, you have to implement your own ListView adapter class and its getView() method.
If you plan to obtain these JSON objects dynamically in ListView I strongly recommend to use some Thread mechanism, that would set data from that JSON object to ListView immediately when it's obtained - i.e. AsyncTask

Related

How do I refresh the data in the ListView?(json&http)

First of all , there is a listview in the activity named "user" . In the activity class, I have a thread that runs every 10 seconds. The thread calls a function which executes an AsyncTask . The AsyncTask does an http request and the response is parsed by a class named JSONparse . The data is then used in a listview inside a for loopwith a simple adapter.
The actual problem here is that the older data stay in the listview , and the same elements are added every 10 seconds.
The onPostExecute is inside the JSONparse class:
private static final String TAG_OS = "istekler";
private static final String TAG_VER = "isim";
private static final String TAG_NAME = "istek";
private static final String TAG_API = "mesaj";
protected void onPostExecute(JSONObject json) {
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String isim = c.getString(TAG_VER);
String mesaj = c.getString(TAG_NAME);
String istek = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, isim);
map.put(TAG_NAME, mesaj);
map.put(TAG_API, istek);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(user.this, oslist,
R.layout.list_v,
new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.isim,R.id.mesaj, R.id.istek});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(user.this, "Parça: "+oslist.get(+position).get("istek"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
on your code you just add new elements to your list. You should call oslist.clear() to remove the old data.

Refresh listview after click Android

I have an Android app (created from tutorials) that creates a list from JSON and depending on the data it creates a yellow or black background.
What i want is when a person clicks on a item from the list, data is transmitted to a server (works)
But then i want to refresh my list because the data has changed (cannot get this to work) Can anyone help me?
This is my code:
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://www.somesite.com/kaku/kaku_list.php/";
// JSON Node names
private static final String TAG_ONTVANGERS = "ontvangers";
private static final String TAG_ID = "id";
private static final String TAG_BESCHRIJVING = "beschrijving";
private static final String TAG_KANAAL = "kanaal";
private static final String TAG_NUMMER = "nummer";
private static final String TAG_STATUS = "status";
// contacts JSONArray
JSONArray ontvangers = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> ontvanger = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
ontvangers = json.getJSONArray(TAG_ONTVANGERS);
// looping through All Contacts
for(int i = 0; i < ontvangers.length(); i++){
JSONObject c = ontvangers.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String beschrijving = c.getString(TAG_BESCHRIJVING);
String kanaal = c.getString(TAG_KANAAL);
String nummer = c.getString(TAG_NUMMER);
String status = c.getString(TAG_STATUS);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_BESCHRIJVING, beschrijving);
map.put(TAG_KANAAL, kanaal);
map.put(TAG_NUMMER, nummer);
map.put(TAG_STATUS, status);
// adding HashList to ArrayList
ontvanger.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new OntvangerAdapter(this, ontvanger,
R.layout.list_item,
new String[] { TAG_BESCHRIJVING, TAG_ID, TAG_STATUS }, new int[] {
R.id.beschrijving, R.id.Ontvanger_id, R.id.status});
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String Ontvanger_id = ((TextView) view.findViewById(R.id.Ontvanger_id)).getText().toString();
JSONParser jParser = new JSONParser();
String url1 = "http://www.somesite.com/kaku/action.php?id="+Ontvanger_id+"/" ;
// getting JSON string from URL
jParser.getJSONFromUrl(url1);
}
});
}
}
From your comments
ListAdapter does not have notifyDataSetChanged()
http://developer.android.com/reference/android/widget/ListAdapter.html
You will to use ArrayAdapter or BaseAdapter. Its better to use a Custom Listview with a Custom Adapter extending either ArrayAdapter of BaseAdapter.(you can customize listview items easily).
http://developer.android.com/reference/android/widget/ArrayAdapter.html
http://developer.android.com/reference/android/widget/BaseAdapter.html#notifyDataSetChanged()
public void notifyDataSetChanged ()
Added in API level 1
Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.
Use the method notifyDataSetCHanged(); and it'll be good.
To update the data/list in list view, you have to make a call to the method notifyDataSetChanged();
How and when to call that?
After you modify your ontvanger , call the function above.
Another side note, I think for newer API, you are not allowed to make HTTP request on UI thread anymore, you have to do it on AsyncTask or some background thread.
Hope that helps

Need to create a ProgressDialog before json parsing data

im going to create a Main Screen Activity before Android JSON Parsing Activity, his content is
main_screen.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="fill_parent"
android:orientation="vertical"
android:gravity="center_horizontal">
<!-- Sample Dashboard screen with Two buttons -->
<Button android:id="#+id/btnViewProducts"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="View Products"
android:layout_marginTop="25dip"/>
</LinearLayout>
AndroidJSONParsingActivity.java
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_ADDRESS, address);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME, TAG_EMAIL, TAG_ADDRESS }, new int[] {
R.id.name, R.id.email, R.id.address });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
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.name)).getText().toString();
String email = ((TextView) view.findViewById(R.id.email)).getText().toString();
String address = ((TextView) view.findViewById(R.id.address)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, email);
in.putExtra(TAG_ADDRESS, address);
startActivity(in);
}
});
}
}
i need to create a ProgressDialog before json parser data and close it when the parsing data has complete
I'm new in Android
Thanks you advanced
Try this...Use AsyncTask and use below code.
private ProgressDialog progressDialog; // class variable
private void showProgressDialog(String title, String message)
{
progressDialog = new ProgressDialog(this);
progressDialog.setTitle(title); // set title
progressDialog.setMessage(message); // set message
progressDialog.setCancelable(false);
progressDialog.show();
}
onPreExecute()
showProgressDialog("Please wait...", "Connecting to server for data");
onPostExecute()
if(progressDialog != null && progressDialog.isShowing())
{
progressDialog.dismiss();
}
Use Async Task to download json data,
so you can start progress dilog on preexecute method and stop it on the Post execute method

Android compilation errors e.g. "adapter cannot be resolved to a type"

It is my mainactivity code. Following is my main activity code and it shows four errors:
adapter cannot be resolved to a type
Syntax error on token ")", { expected after this token
Syntax error on token "adapter", VariableDeclaratorId expected after this token.
Source code:
public class HospitalParseActivity extends ListActivity {
//url where request is made
private static String url="url";
//JSON node names
private static final String TAG_NETFOX="transfer";
private static final String TAG_DATE="date";
private static final String TAG_CWEB="c_web";
private static final String TAG_CBANK="c_bank";
private static final String TAG_CCASH="c_cash";
private static final String TAG_SWEB="s_web";
private static final String TAG_SBANK="s_bank";
private static final String TAG_SCASH="s_cash";
//creation of JSONArray
JSONArray netfoxlimited=null;
private List<? extends Map<String, ?>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
netfoxlimited = json.getJSONArray(TAG_NETFOX);
// looping through All Contacts
for(int i = 0; i < netfoxlimited.length(); i++){
JSONObject c = netfoxlimited.getJSONObject(i);
// Storing each json item in variable
String date = c.getString(TAG_DATE);
String c_web = c.getString(TAG_CWEB);
String c_bank = c.getString(TAG_CBANK);
String c_cash = c.getString(TAG_CCASH);
String s_web = c.getString(TAG_SWEB);
String s_bank = c.getString(TAG_SBANK);
String s_cash = c.getString(TAG_SCASH);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_DATE, date);
map.put(TAG_CWEB, c_web);
map.put(TAG_CBANK, c_bank);
map.put(TAG_CCASH, c_cash);
map.put(TAG_SWEB, s_web);
map.put(TAG_SBANK, s_bank);
map.put(TAG_SCASH, s_cash);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_DATE, TAG_CWEB, TAG_CBANK,TAG_CCASH, TAG_CWEB,TAG_CBANK, TAG_CCASH }, new int[] {
R.id.date, R.id.cweb, R.id.cbank,R.id.sweb,R.id.sbank,R.id.scash });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String dt = ((TextView) view.findViewById(R.id.date)).getText().toString();
String web = ((TextView) view.findViewById(R.id.cweb)).getText().toString();
String bank = ((TextView) view.findViewById(R.id.cbank)).getText().toString();
String cash = ((TextView) view.findViewById(R.id.ccash)).getText().toString();
String web1 = ((TextView) view.findViewById(R.id.sweb)).getText().toString();
String bank1 = ((TextView) view.findViewById(R.id.sbank)).getText().toString();
String cash1 = ((TextView) view.findViewById(R.id.scash)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_DATE, dt);
in.putExtra(TAG_CWEB, web);
in.putExtra(TAG_CBANK, bank);
in.putExtra(TAG_CCASH, cash);
in.putExtra(TAG_SWEB, web1);
in.putExtra(TAG_SBANK, bank1);
in.putExtra(TAG_SCASH, cash1);
startActivity(in);
}
});
}
}
Are you writing code outside the onCreate function? Seems like onCreate function ended at the '}' after the catch block. You may just want to remove that

ArrayAdapter : Json data to be sent to spinner

Hi I have created an activity which pulls data from json format text and displays in a spinner view. But im a little confused with the last part. The contactList is a ArrayList type, ArrayAdapter is not accepting contactList as its arugument.
Is
Here's my code
public class RegisterForEventActivity extends Activity {
private static String url = "http://10.0.2.2/Contacts.txt";
private static final String TAG_NAME = "name";
private static final String TAG_CONTACTS = "contacts";
JSONArray jsonArray = null;
Spinner areaspinner;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_layout);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
jsonArray = json.getJSONArray(TAG_CONTACTS);
final String[] array_spinner = new String[jsonArray.length()];
// looping through All Contacts
for(int i = 0; i < jsonArray.length(); i++){
JSONObject c = jsonArray.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME, name);
// adding HashList to ArrayList
contactList.add(map);
ArrayAdapter<String> adapter =
new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, contactList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
areaspinner.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is because you are passing a list of HashMap, and not an array of String. Make an array of String, add your contact data in it and pass it to the array.
instead of using this
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
use this
ArrayList<String> contactList = new ArrayList<String>();
Yes, I figured it out!
sp=(Spinner)findViewById(R.id.spinner1);
// Hashmap for ListView
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
System.out.println("Hello");
try {
// Getting Array of Contacts
jsonArray = json.getJSONArray(TAG_CONTACTS);
final String[] items = new String[jsonArray.length()];
// looping through All Contacts
for(int i = 0; i < jsonArray.length(); i++){
JSONObject c = jsonArray.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_NAME);
items[i]=c.getString(TAG_NAME);
System.out.println("Hello events "+items);
}
ArrayAdapter<String> adapter =
new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}

Categories

Resources