I am faching data from server and passing this data to custom adapter to display it on image adapter i am using asynchtask for faching data my problem is taht i want to change image in list view after every 5 seconds please suggest me a solution here is my activity file
public class MainActivity extends Activity {
private String[] image,name,descr;
ListView list;
LazyImageLoadAdapter adapter;I am faching data from server and passing this data to custom adapter to display it on image adapter i am using asynchtask for faching data my problem is taht i want to change image in list view after every 5 seconds please suggest me a solution here is my activity file
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String serverURL = "http://10.0.2.2/JsonReturn.php";
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
list=(ListView)findViewById(R.id.list);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(listener);
// Create custom adapter for listview
}
#Override
public void onDestroy()
{
// Remove adapter refference from list
list.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener=new OnClickListener(){
#Override
public void onClick(View arg0) {
//Refresh cache directory downloaded images
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
};
public void onItemClick(int mPosition)
{
String tempValues = image[mPosition];
Toast.makeText(MainActivity.this,
"Image URL : "+tempValues,
Toast.LENGTH_LONG)
.show();
}
private class LongOperation extends AsyncTask<String, Void, Void> {
// Required initialization
ListView lst=(ListView)findViewById(R.id.list);
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
String data ="";
//TextView uiUpdate = (TextView) findViewById(R.id.output);
/// TextView jsonParsed = (TextView) findViewById(R.id.jsonParsed);
int sizeData = 0;
// EditText serverText = (EditText) findViewById(R.id.serverText);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
//Start Progress Dialog (Message)
Dialog.setMessage("Please wait..");
Dialog.show();
try{
// Set Request parameter
data +="&" + URLEncoder.encode("data", "UTF-8")+ "="+"RAja";//serverText.getText();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}
// Append Server Response To Content String
Content = sb.toString();
}
catch(Exception ex)
{
Error = ex.getMessage();
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
/*****************************************************/
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if (Error != null) {
Toast.makeText(getApplicationContext(), "Error"+Error, Toast.LENGTH_LONG).show();;
//uiUpdate.setText("Output : "+Error);
} else {
// Show Response Json On Screen (activity)
//uiUpdate.setText( Content );
Toast.makeText(getApplicationContext(), "content"+Content, Toast.LENGTH_LONG).show();;
/****************** Start Parse Response JSON Data *************/
String OutputData = "";
JSONObject jsonResponse;
try {
/****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
jsonResponse = new JSONObject(Content);
/***** Returns the value mapped by name if it exists and is a JSONArray. ***/
/******* Returns null otherwise. *******/
JSONArray jsonMainNode = jsonResponse.optJSONArray("Android");
/*********** Process each JSON Node ************/
int lengthJsonArr = jsonMainNode.length();
image=new String[lengthJsonArr];
name=new String[lengthJsonArr];
descr=new String[lengthJsonArr];
for(int i=0; i < lengthJsonArr; i++)
{
/****** Get Object for each JSON node.***********/
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
/******* Fetch node values **********/
String nm = jsonChildNode.optString("name").toString();
String img = jsonChildNode.optString("image").toString();
String desc = jsonChildNode.optString("desc").toString();
image[i]=img;
name[i]=nm;
descr[i]=desc;
OutputData += " Name : "+ nm +" \n "
+ "Number : "+ img +" \n "
+ "Time : "+ desc +" \n "
+"--------------------------------------------------\n";
//Log.i("JSON parse", song_name);
}
/****************** End Parse Response JSON Data *************/
//Show Parsed Output on screen (activity)
//jsonParsed.setText( OutputData );
Toast.makeText(getApplicationContext(), "Parsed Data"+ OutputData, Toast.LENGTH_LONG).show();;
adapter=new LazyImageLoadAdapter(MainActivity.this, image,name,descr);
//Set adapter to listview
list.setAdapter(adapter);
//lst.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
and my image adapter class file is as follow
public class LazyImageLoadAdapter extends BaseAdapter implements OnClickListener{
private Activity activity;
private String[] data,name,desc;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyImageLoadAdapter(Activity a, String[] d,String[] name,String[] desc) {
activity = a;
data=d;
this.name=name;
this.desc=desc;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Create ImageLoader object to download and show image in list
// Call ImageLoader constructor to initialize FileCache
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder{
public TextView text;
public TextView text1;
public TextView textWide;
public ImageView image;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
vi = inflater.inflate(R.layout.listview_row, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.text = (TextView) vi.findViewById(R.id.text);
holder.text1=(TextView)vi.findViewById(R.id.text1);
holder.image=(ImageView)vi.findViewById(R.id.image);
/************ Set holder with LayoutInflater ************/
vi.setTag( holder );
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText(name[position]);
holder.text1.setText(desc[position]);
ImageView image = holder.image;
//DisplayImage function from ImageLoader Class
imageLoader.DisplayImage(data[position], image);
/******** Set Item Click Listner for LayoutInflater for each row ***********/
vi.setOnClickListener(new OnItemClickListener(position));
return vi;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
/********* Called when Item click in ListView ************/
private class OnItemClickListener implements OnClickListener{
private int mPosition;
OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View arg0) {
MainActivity sct = (MainActivity)activity;
sct.onItemClick(mPosition);
}
}
}
i have tried to put set adapter() method in oncreate() of activity but it gives me error so how can i change images display on list view after some specific time and i also want to put list.setAdapter() in MainActivity Instead LongOperation Class But it Gives nullpointerException
Related
I need to delete a list item from listview on clicking a delete button in android eclipse. The list values are populated from mysql database(JSON), so on deleting, I need to delete the same from database also.
Here is my main Activity; I need to delete a listitem from a listview on clicking a delete button on each item in the listview:
public class MainActivity extends Activity implements AsyncResponse2 {
private ProgressDialog dialog;
ListView l1;
//for getting count
TextView count;
private static final String TAG_COUNT = "cnt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //to hide title bar
setContentView(R.layout.activity_main);
l1=(ListView)findViewById(R.id.listView1);
/** Reference to the delete button of the layout main.xml */
Button btnDel = (Button) findViewById(R.id.deleteid);
initView();
//str for getting count
count=(TextView)findViewById(R.id.countid);
//to display count while loading(so outside buttonclick)
String key1 = "saasvaap123";
String signupid1 = "8";
String url2 = "http://gooffers.in/omowebservices/index.php/webservice/Public_User/saved_offers_list?";
//http://gooffers.in/omowebservices/index.php/webservice/Public_User/saved_offers_list?key=saasvaap123&signup_id=8
//put the below lines outside button onclick since we load the values into edittext when opening the app
CustomHttpClient2 task2 = new CustomHttpClient2();
task2.execute(url2,key1,signupid1);
task2.delegate = MainActivity.this;
//end
}
//str getting count
//str customhttp2
private class CustomHttpClient2 extends AsyncTask<String, String, String>{
public AsyncResponse2 delegate=null;
private String msg;
#Override
protected void onPostExecute(String result2) {
// TODO Auto-generated method stub
super.onPostExecute(result2);
delegate.processFinish2(result2);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
if(params == null) return null;
// get url from params
String url2 = params[0];
String key1 = params[1];
String signupid1 = params[2];
ArrayList<NameValuePair> postParameters;
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("key",key1));
postParameters.add(new BasicNameValuePair("signup_id",signupid1));
try {
// create http connection
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url2);
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
// connect
HttpResponse response = client.execute(httppost);
// get response
HttpEntity entity = response.getEntity();
if(entity != null){
return EntityUtils.toString(entity);
}
else{
return "No string.";
}
}
catch(Exception e){
return "Network problem";
}
}
}
public void processFinish2 (String output2){
Toast.makeText(MainActivity.this,output2, Toast.LENGTH_SHORT).show();
try{
//str
JSONObject jsonResponse = new JSONObject(output2);
JSONArray aJson = jsonResponse.getJSONArray("gen_off");
// create apps list
for(int i=0; i<aJson.length(); i++) {
JSONObject json = aJson.getJSONObject(i);
//end
//str
String strCount = json.getString(TAG_COUNT);
count.setText(strCount);//setting name to original name text
//end
}
}catch (JSONException e) {
Toast.makeText(MainActivity.this,"Exception caught!", Toast.LENGTH_SHORT).show();
}
}
//end getting count
private void initView() {
// show progress dialog
// dialog = ProgressDialog.show(this, "", "Loading...");
String key="saasvaap123";
String signup_id="8";
String url = "http://gooffers.in/omowebservices/index.php/webservice/Public_User/saved_offers_list?";
FetchDataTask task = new FetchDataTask();
task.execute(url,key,signup_id);
}
public class FetchDataTask extends AsyncTask<String, Void, String>{
// private final FetchDataListener listener;
private String msg;
#Override
protected String doInBackground(String... params) {
if(params == null) return null;
// get url from params
String url = params[0];
String key1 = params[1];
String signupid1 = params[2];
ArrayList<NameValuePair> postParameters;
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("key",key1));
postParameters.add(new BasicNameValuePair("signup_id",signupid1));
//str
try {
// create http connection
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
// connect
HttpResponse response = client.execute(httppost);
// get response
HttpEntity entity = response.getEntity();
if(entity != null){
return EntityUtils.toString(entity);
}
else{
return "No string.";
}
}
catch(Exception e){
return "Network problem";
}
}
//end
//
#Override
protected void onPostExecute(String sJson) {
try {
JSONObject jsonResponse = new JSONObject(sJson);
JSONArray aJson = jsonResponse.getJSONArray("gen_off");
Toast.makeText(MainActivity.this, aJson.toString(),Toast.LENGTH_SHORT).show();
// create apps list
List<SavedOffers> apps = new ArrayList<SavedOffers>();
for(int i=0; i<aJson.length(); i++) {
JSONObject json = aJson.getJSONObject(i);
SavedOffers app = new SavedOffers();
app.setTitle(json.getString("title"));
app.setOriginalRate(json.getString("price"));
app.setOfferRate(json.getString("off_price"));
app.setPercentage(json.getString("percent"));
app.setSavings(json.getString("savings"));
app.setUrl(json.getString("image"));
// add the app to apps list
apps.add(app);
}
SavedOffersAdapter adapter = new SavedOffersAdapter(MainActivity.this, apps);
// set the adapter to list
l1.setAdapter(adapter);
//for delete
// adapter.notifyDataSetChanged();
/** Defining a click event listener for the button "Delete" */
Button btnDel = (Button) findViewById(R.id.deleteid);
OnClickListener listenerDel = new OnClickListener() {
#Override
public void onClick(View v) {
/** Getting the checked items from the listview */
SparseBooleanArray checkedItemPositions = l1.getCheckedItemPositions();
int itemCount = l1.getCount();
for(int i=itemCount-1; i >= 0; i--){
if(checkedItemPositions.get(i)){
adapter.remove(l1.get(i));
}
}
checkedItemPositions.clear();
adapter.notifyDataSetChanged();
}
};
/** Setting the event listener for the delete button */
btnDel.setOnClickListener(listenerDel);
/** Setting the adapter to the ListView */
l1.setAdapter(adapter); //end delete
//notify the activity that fetch data has been complete
// if(listener != null) listener.onFetchComplete(apps);
} catch (JSONException e) {
// msg = "Invalid response";
// if(listener != null) listener.onFetchFailure(msg);
// return;
}
}
/**
* This function will convert response stream into json string
* #param is respons string
* #return json string
* #throws IOException
*/
public String streamToString(final InputStream is) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
catch (IOException e) {
throw e;
}
finally {
try {
is.close();
}
catch (IOException e) {
throw e;
}
}
return sb.toString();
}
}
}
// this is my adapter class , I think change is only needed in main activity
// , I need to delete a specific list item from listview on clicking the delete button
public class SavedOffersAdapter extends ArrayAdapter<SavedOffers>{
private List<SavedOffers> items;
Bitmap bitmap;
ImageView image;
public SavedOffersAdapter(Context context, List<SavedOffers> items) {
super(context, R.layout.app_custom_list, items);
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
private class ViewHolder {
//TextView laptopTxt;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// ViewHolder holder;//added
View v = convertView;
if(v == null) {
LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.app_custom_list, null);
}
SavedOffers app = items.get(position);
if(app != null) {
TextView productName = (TextView)v.findViewById(R.id.nameid);
TextView originalRate = (TextView)v.findViewById(R.id.originalid);
originalRate.setPaintFlags(originalRate.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
TextView offerRate = (TextView)v.findViewById(R.id.offerid);
TextView percentage = (TextView)v.findViewById(R.id.discountid);
TextView savings = (TextView)v.findViewById(R.id.savingsid);
image =(ImageView)v.findViewById(R.id.prctimgid);
if(productName != null) productName.setText(app.getTitle());
if(originalRate != null) originalRate.setText(app.getOriginalRate());
if(offerRate != null) offerRate.setText(app. getOfferRate());
if(percentage != null) percentage.setText(app. getPercentage());
if(savings != null) savings.setText(app. getSavings());
if(image!=null){
new DownloadImageTask(image).execute(app.getUrl());
}
}
return v;
}
In your listviews adapter's getView method you link to the button on the layout your inflating and just attach a setOnClickListener... to the button and have it remove that item from your list or array that your adapter uses and then notifyDataHasChanged.
Delete that item from items in that position.
So 1. you want to delete the item from the ListView
2. you want to delete the item from the SQL DB.
The first one is very easy, but you kind of need to know the underlining adapter and how it serves data to your ListView. When you instantiate a BaseAdapter for the ListView you pass in a List or an array. This array will be the data your BaseAdapter serves to your ListView, each view in the listview will be showing an element from the array (done in getView()). If you dynamically delete one of those items, then adjust your array (or just use a List and it's .remove(), and finally notifyDataSetChanged(); your BaseAdapter will refresh your list without that View (or rather that View will be replaced with the new one). So for instance below I pass in a List<WeatherLocation> (WeatherLocation is a containing class that has weather stuff for a particular area (city, zipcode, degree"Biddeford", 04005, 72) to my BaseAdapter.
// Instantiate ListView
ListView lvLocations = (ListView) findViewById(R.id.lvLocations);
// Instantiate our BaseAdapter (pass in the List<WeatherLocation>)
WeatherLocationAdapter mWeatherLocationAdapter = new WeatherLocationAdapter(savedList, this, R.layout.view_weather_location);
lvLocations.setAdapter(mWeatherLocationAdapter);
This is an example of a regular ListView setting an Adapter to a custom BaseAdapter.
The BaseAdapter is so simple, that really the only method you care about (majorly) is the getView() method.
R.layout.view_weather_location is just a `LinearLayout` I made, it has 3 TextViews in it that I tie (show) my data with, by attaching data to those TextViews in the `getView()` method of the `BaseAdapter`. You would put a `Button there and tie it to what you want (to delete the data item)`.
public class WeatherLocationAdapter extends BaseAdapter{
private List <WeatherLocation> mLocations;
private Context mContext;
private int rowForLocationToInflate;
private LayoutInflater inflater;
public WeatherLocationAdapter(List<WeatherLocation> mLocations, Context mContext, int rowForLocationToInflate) {
this.mLocations = mLocations;
this.mContext = mContext;
this.rowForLocationToInflate = rowForLocationToInflate;
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//TODO just built up layout now must tie to it.
private void addLocation(WeatherLocation newLocation){
mLocations.add(newLocation);
//TODO maybe invalidate after adding new item.
}
#Override
public int getCount() {
return mLocations.size();
}
#Override
public WeatherLocation getItem(int position) {
return mLocations.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//TODO build a viewholder
View rowView = inflater.inflate(rowForLocationToInflate, parent, false);
TextView tvZipcode = (TextView) rowView.findViewById(R.id.tvZipCode);
TextView tvCity = (TextView) rowView.findViewById(R.id.tvCity);
TextView tvTemp = (TextView) rowView.findViewById(R.id.tvDegree);
tvZipcode.setText(mLocations.get(position).getZipcode());
tvCity.setText(mLocations.get(position).getCity());
tvTemp.setText(String.valueOf(mLocations.get(position).getTemperature()));
// If you had a Button in your LinearLayout you were attaching to you that you wanted to delete that view/item with, it would look something like this in my case.
Button bDel = (Button) row.findViewById(R.id.bDel);
bDel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mLocations.remove(position);
}
});
return rowView;
}
}
In the onClick you would also remove the item from the SQL db. I can show that too, but I feel you have some coding to do as it stands.
I am faching data from server and passing this data to custom adapter to display it on image adapter i am using asynchtask for faching data my problem is taht i want to change image in list view after every 5 seconds please suggest me a solution here is my activity file
public class MainActivity extends Activity {
private String[] image,name,descr;
ListView list;
LazyImageLoadAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String serverURL = "http://10.0.2.2/JsonReturn.php";
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
list=(ListView)findViewById(R.id.list);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(listener);
// Create custom adapter for listview
}
#Override
public void onDestroy()
{
// Remove adapter refference from list
list.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener=new OnClickListener(){
#Override
public void onClick(View arg0) {
//Refresh cache directory downloaded images
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
};
public void onItemClick(int mPosition)
{
String tempValues = image[mPosition];
Toast.makeText(MainActivity.this,
"Image URL : "+tempValues,
Toast.LENGTH_LONG)
.show();
}
private class LongOperation extends AsyncTask<String, Void, Void> {
// Required initialization
ListView lst=(ListView)findViewById(R.id.list);
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
String data ="";
//TextView uiUpdate = (TextView) findViewById(R.id.output);
/// TextView jsonParsed = (TextView) findViewById(R.id.jsonParsed);
int sizeData = 0;
// EditText serverText = (EditText) findViewById(R.id.serverText);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
//Start Progress Dialog (Message)
Dialog.setMessage("Please wait..");
Dialog.show();
try{
// Set Request parameter
data +="&" + URLEncoder.encode("data", "UTF-8")+ "="+"RAja";//serverText.getText();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}
// Append Server Response To Content String
Content = sb.toString();
}
catch(Exception ex)
{
Error = ex.getMessage();
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
/*****************************************************/
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if (Error != null) {
Toast.makeText(getApplicationContext(), "Error"+Error, Toast.LENGTH_LONG).show();;
//uiUpdate.setText("Output : "+Error);
} else {
// Show Response Json On Screen (activity)
//uiUpdate.setText( Content );
Toast.makeText(getApplicationContext(), "content"+Content, Toast.LENGTH_LONG).show();;
/****************** Start Parse Response JSON Data *************/
String OutputData = "";
JSONObject jsonResponse;
try {
/****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
jsonResponse = new JSONObject(Content);
/***** Returns the value mapped by name if it exists and is a JSONArray. ***/
/******* Returns null otherwise. *******/
JSONArray jsonMainNode = jsonResponse.optJSONArray("Android");
/*********** Process each JSON Node ************/
int lengthJsonArr = jsonMainNode.length();
image=new String[lengthJsonArr];
name=new String[lengthJsonArr];
descr=new String[lengthJsonArr];
for(int i=0; i < lengthJsonArr; i++)
{
/****** Get Object for each JSON node.***********/
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
/******* Fetch node values **********/
String nm = jsonChildNode.optString("name").toString();
String img = jsonChildNode.optString("image").toString();
String desc = jsonChildNode.optString("desc").toString();
image[i]=img;
name[i]=nm;
descr[i]=desc;
OutputData += " Name : "+ nm +" \n "
+ "Number : "+ img +" \n "
+ "Time : "+ desc +" \n "
+"--------------------------------------------------\n";
//Log.i("JSON parse", song_name);
}
/****************** End Parse Response JSON Data *************/
//Show Parsed Output on screen (activity)
//jsonParsed.setText( OutputData );
Toast.makeText(getApplicationContext(), "Parsed Data"+ OutputData, Toast.LENGTH_LONG).show();;
adapter=new LazyImageLoadAdapter(MainActivity.this, image,name,descr);
//Set adapter to listview
list.setAdapter(adapter);
//lst.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
and my image adapter class file is as follow
public class LazyImageLoadAdapter extends BaseAdapter implements OnClickListener{
private Activity activity;
private String[] data,name,desc;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyImageLoadAdapter(Activity a, String[] d,String[] name,String[] desc) {
activity = a;
data=d;
this.name=name;
this.desc=desc;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Create ImageLoader object to download and show image in list
// Call ImageLoader constructor to initialize FileCache
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder{
public TextView text;
public TextView text1;
public TextView textWide;
public ImageView image;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
vi = inflater.inflate(R.layout.listview_row, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.text = (TextView) vi.findViewById(R.id.text);
holder.text1=(TextView)vi.findViewById(R.id.text1);
holder.image=(ImageView)vi.findViewById(R.id.image);
/************ Set holder with LayoutInflater ************/
vi.setTag( holder );
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText(name[position]);
holder.text1.setText(desc[position]);
ImageView image = holder.image;
//DisplayImage function from ImageLoader Class
imageLoader.DisplayImage(data[position], image);
/******** Set Item Click Listner for LayoutInflater for each row ***********/
vi.setOnClickListener(new OnItemClickListener(position));
return vi;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
/********* Called when Item click in ListView ************/
private class OnItemClickListener implements OnClickListener{
private int mPosition;
OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View arg0) {
MainActivity sct = (MainActivity)activity;
sct.onItemClick(mPosition);
}
}
}
i have tried to put set adapter() method in oncreate() of activity but it gives me error so how can i change images display on list view after some specific time please suggest solution
you should set the adapter only one time and when update the data you should only the call the method of adapter notifydatasetchange()
in your code make a bool variable isFirsttime and keep it initially true
Toast.makeText(getApplicationContext(), "Parsed Data"+ OutputData, Toast.LENGTH_LONG).show();
if(isFirsttime)
{
adapter=new LazyImageLoadAdapter(MainActivity.this, image,name,descr);
//Set adapter to listview
list.setAdapter(adapter);
}
else{
adapter.notifyDataSetChanged();
}
Make isFirsttime bool variable globally and set it true
i hope it will help you
I am fetching data from server and passing this data to custom adapter to display it on image adapter. I am using asynchtask for fetching data. My problem is that I want to change image in list view after every 5 seconds. Please suggest me a solution. Here is my activity file
public class MainActivity extends Activity {
private String[] image,name,descr;
ListView list;
LazyImageLoadAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String serverURL = "http://10.0.2.2/JsonReturn.php";
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
list=(ListView)findViewById(R.id.list);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(listener);
// Create custom adapter for listview
}
#Override
public void onDestroy()
{
// Remove adapter refference from list
list.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener=new OnClickListener(){
#Override
public void onClick(View arg0) {
//Refresh cache directory downloaded images
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
};
public void onItemClick(int mPosition)
{
String tempValues = image[mPosition];
Toast.makeText(MainActivity.this,
"Image URL : "+tempValues,
Toast.LENGTH_LONG)
.show();
}
private class LongOperation extends AsyncTask<String, Void, Void> {
// Required initialization
ListView lst=(ListView)findViewById(R.id.list);
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
String data ="";
//TextView uiUpdate = (TextView) findViewById(R.id.output);
/// TextView jsonParsed = (TextView) findViewById(R.id.jsonParsed);
int sizeData = 0;
// EditText serverText = (EditText) findViewById(R.id.serverText);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
//Start Progress Dialog (Message)
Dialog.setMessage("Please wait..");
Dialog.show();
try{
// Set Request parameter
data +="&" + URLEncoder.encode("data", "UTF-8")+ "="+"RAja";//serverText.getText();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}
// Append Server Response To Content String
Content = sb.toString();
}
catch(Exception ex)
{
Error = ex.getMessage();
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
/*****************************************************/
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if (Error != null) {
Toast.makeText(getApplicationContext(), "Error"+Error, Toast.LENGTH_LONG).show();;
//uiUpdate.setText("Output : "+Error);
} else {
// Show Response Json On Screen (activity)
//uiUpdate.setText( Content );
Toast.makeText(getApplicationContext(), "content"+Content, Toast.LENGTH_LONG).show();;
/****************** Start Parse Response JSON Data *************/
String OutputData = "";
JSONObject jsonResponse;
try {
/****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
jsonResponse = new JSONObject(Content);
/***** Returns the value mapped by name if it exists and is a JSONArray. ***/
/******* Returns null otherwise. *******/
JSONArray jsonMainNode = jsonResponse.optJSONArray("Android");
/*********** Process each JSON Node ************/
int lengthJsonArr = jsonMainNode.length();
image=new String[lengthJsonArr];
name=new String[lengthJsonArr];
descr=new String[lengthJsonArr];
for(int i=0; i < lengthJsonArr; i++)
{
/****** Get Object for each JSON node.***********/
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
/******* Fetch node values **********/
String nm = jsonChildNode.optString("name").toString();
String img = jsonChildNode.optString("image").toString();
String desc = jsonChildNode.optString("desc").toString();
image[i]=img;
name[i]=nm;
descr[i]=desc;
OutputData += " Name : "+ nm +" \n "
+ "Number : "+ img +" \n "
+ "Time : "+ desc +" \n "
+"--------------------------------------------------\n";
//Log.i("JSON parse", song_name);
}
/****************** End Parse Response JSON Data *************/
//Show Parsed Output on screen (activity)
//jsonParsed.setText( OutputData );
Toast.makeText(getApplicationContext(), "Parsed Data"+ OutputData, Toast.LENGTH_LONG).show();;
adapter=new LazyImageLoadAdapter(MainActivity.this, image,name,descr);
//Set adapter to listview
list.setAdapter(adapter);
//lst.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
and my image adapter class file is as follow
public class LazyImageLoadAdapter extends BaseAdapter implements OnClickListener{
private Activity activity;
private String[] data,name,desc;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyImageLoadAdapter(Activity a, String[] d,String[] name,String[] desc) {
activity = a;
data=d;
this.name=name;
this.desc=desc;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Create ImageLoader object to download and show image in list
// Call ImageLoader constructor to initialize FileCache
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder{
public TextView text;
public TextView text1;
public TextView textWide;
public ImageView image;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
vi = inflater.inflate(R.layout.listview_row, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.text = (TextView) vi.findViewById(R.id.text);
holder.text1=(TextView)vi.findViewById(R.id.text1);
holder.image=(ImageView)vi.findViewById(R.id.image);
/************ Set holder with LayoutInflater ************/
vi.setTag( holder );
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText(name[position]);
holder.text1.setText(desc[position]);
ImageView image = holder.image;
//DisplayImage function from ImageLoader Class
imageLoader.DisplayImage(data[position], image);
/******** Set Item Click Listner for LayoutInflater for each row ***********/
vi.setOnClickListener(new OnItemClickListener(position));
return vi;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
/********* Called when Item click in ListView ************/
private class OnItemClickListener implements OnClickListener{
private int mPosition;
OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View arg0) {
MainActivity sct = (MainActivity)activity;
sct.onItemClick(mPosition);
}
}
}
I have tried to put set adapter() method in oncreate() of activity but it gives me error. So how can i change images display on list view after some specific time? Please suggest solution.
I am getting nullpointer exception in list.setAdapter(adapter); statement
Your declaration is wrong at here
YOUR CODE
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
list=(ListView)findViewById(R.id.list);
Here you declared the ListView after called AsyncTask so it'll never find ListView at Adapter set time.
Please Change it
list=(ListView)findViewById(R.id.list);
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
Problem comes with Initialization.
move this line list=(ListView)findViewById(R.id.list); above this line, new LongOperation().execute(serverURL);
I am using a modified version of the contacts project from AndroidHive.
It basically just pulls n list of articles and their contact from a Joomla Site.
I am using a Image Plugin that gets a image from a url. i can successfully use it on the article detail activity view but i don't know how to add it to each List Item on the MainAcitivity file. I am new to Android development so please excuse the confusion.
The script to add the image is:
ImageView thumb = (ImageView) findViewById(R.id.thumb);
UrlImageViewHelper.setUrlDrawable(thumb, "https://www.site.co.za/test.png");
and my MainActivity which generated the ListView:
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get articles JSON
private static String url = "http://192.168.12.21/sebastian/broadcast/index.php/blog?format=json";
// JSON Node names
private static final String TAG_ARTICLES = "articles";
// Get the fields
private static final String TAG_ID = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_SHORTTEXT = "shorttext";
private static final String TAG_FULLTEXT = "fulltext";
private static final String TAG_IMAGE = "image";
private static final String TAG_DATE = "date";
// articles JSONArray
JSONArray articles = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> articleList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
articleList = 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 title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String shorttext = ((TextView) view.findViewById(R.id.shorttext)).getText().toString();
String fulltext = ((TextView) view.findViewById(R.id.fulltext)).getText().toString();
String image = ((TextView) view.findViewById(R.id.image)).getText().toString();
String date = ((TextView) view.findViewById(R.id.date)).getText().toString();
// Starting single article activity
Intent in = new Intent(getApplicationContext(),
SingleArticleActivity.class);
in.putExtra(TAG_TITLE, title);
in.putExtra(TAG_SHORTTEXT, shorttext);
in.putExtra(TAG_FULLTEXT, fulltext);
in.putExtra(TAG_IMAGE, image);
in.putExtra(TAG_DATE, date);
startActivity(in);
}
});
// Calling async task to get json
new GetArticles().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetArticles extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.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
articles = jsonObj.getJSONArray(TAG_ARTICLES);
// looping through All articles
for (int i = 0; i < articles.length(); i++) {
JSONObject c = articles.getJSONObject(i);
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String shorttext = c.getString(TAG_SHORTTEXT);
String fulltext = c.getString(TAG_FULLTEXT);
String image = c.getString(TAG_IMAGE);
String date = c.getString(TAG_DATE);
// tmp hashmap for single article
HashMap<String, String> article = new HashMap<String, String>();
// adding each child node to HashMap key => value
article.put(TAG_ID, id);
article.put(TAG_TITLE, title);
article.put(TAG_SHORTTEXT, shorttext);
article.put(TAG_FULLTEXT, fulltext);
article.put(TAG_IMAGE, image);
article.put(TAG_DATE, date);
// adding article to article list
articleList.add(article);
}
} 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(
MainActivity.this, articleList,
R.layout.list_item, new String[] {
TAG_TITLE,
TAG_SHORTTEXT,
TAG_FULLTEXT,
TAG_IMAGE,
TAG_DATE
},
new int[] {
R.id.title,
R.id.shorttext,
R.id.fulltext,
R.id.image,
R.id.date
});
setListAdapter(adapter);
}
}
}
**I don't know where in the MainActivity file do i add the script to add an image to each List Item.
I already got it working on the SingleArticleActivity but cannot get it to work on the List of Items**
Thanks for the help
UPDATE
What im trying to do:
foreach(ListItem in the List) {
ImageView thumb = (ImageView) findViewById(R.id.thumb);
UrlImageViewHelper.setUrlDrawable(thumb, "https://www.site.co.za/test.png");
}
You have to just use this one..
ImageView thumb = (ImageView) findViewById(R.id.thumb);
UrlImageViewHelper.setUrlDrawable(thumb, articleList.get(position).get(TAG_IMAGE));
CustomAdapter cdp = new CustomAdapter(YourActivityName.this , articleList);
setListAdapter(adapter);
Now make class of CustomAdapter extends with BaseAdapter
public class CustomAdapter extends BaseAdapter {
ArrayList<HashMap<String, String>> list;
Context ctx;
public CustomAdapter(Context c , ArrayList<HashMap<String, String>> articleList){
this.ctx = c;
this.list = articleList;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
View view = convertView;
if (view == null) {
view = getLayoutInflater().inflate(R.layout.list_item,
parent, false);
holder = new ViewHolder();
assert view != null;
holder.imageView = (ImageView) view.findViewById(R.id.image);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
UrlImageViewHelper.setUrlDrawable(thumb, articleList.get(position).get(TAG_IMAGE));
return view;
}
class ViewHolder {
ImageView imageView;
}
}
I am using this method in the getView method of my ListView adapter which returns a drawable which I later set it to my ImageView.
public Drawable LoadImageFromWebOperations(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
return default_image;
}
}
Hope this helps.
Try this A powerful image downloading and caching library for Android Picasso
Images add much-needed context and visual flair to Android applications. Picasso allows for hassle-free image loading in your application-often in one line of code!
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
I am trying to Parse the JSON to list view
There is no error in log cat
The image is getting parsed but the data which should be displayed in
front of rank and country is not getting displayed
Why is the error occuring
How to resolve this
JSONfunctions.java
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView rank;
TextView country;
ImageView flag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
rank = (TextView) itemView.findViewById(R.id.rank);
country = (TextView) itemView.findViewById(R.id.country);
// Locate the ImageView in listview_item.xml
flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
rank.setText(resultp.get(MainActivity.NAME));
country.setText(resultp.get(MainActivity.TYPE));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), flag);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data rank
intent.putExtra("name", resultp.get(MainActivity.NAME));
// Pass all data country
intent.putExtra("type", resultp.get(MainActivity.TYPE));
// Pass all data flag
intent.putExtra("flag", resultp.get(MainActivity.FLAG));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
}
MainActivity.java
public class MainActivity extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
static String TYPE = "country";
static String FLAG = "flag";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://54.218.73.244:7002/");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("restaurants");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("name", jsonobject.getString("restaurantNAME"));
map.put("type", jsonobject.getString("restaurantTYPE"));
map.put("flag", jsonobject.getString("restaurantIMAGE"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
output
The image is getting parsed but the data which should be displayed in front of rank and country is not getting displayed
Any Ideas
hope i am clear
The image is getting parsed but the data which should be displayed in
front of rank and country is not getting displayed
because you are storing values in HashMap with different keys and trying to get values with different keys in Adapter so change it as inside doInBackground method for storing values with keys :
map.put(MainActivity.NAME, jsonobject.getString("restaurantNAME"));
map.put(MainActivity.TYPE, jsonobject.getString("restaurantTYPE"));
map.put(MainActivity.FLAG, jsonobject.getString("restaurantIMAGE"));
try below code:
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
and your map key also different: see restaurantNAME...