i am getting JSON data from http://abinet.org/?json=1 and displaying the titles in a ListView. the code is working fine but the problem is, it is skipping few titles in my ListView and one title is being repeated.
You can see the json data from url given above by copy paste it in JSON editor online http://www.jsoneditoronline.org/
i want titles in the "posts" array to be displayed in ListView, however it is being displayed like this:
if you see the JSON data from the link above, its missing like 3 titles (they should come between the first and second title) and 5th title is being repeated. Dont know why this is happening. What minor adjustments i need to do? Please help me.
this is my code :
public class MainActivity extends Activity {
// URL to get contacts JSON
private static String url = "http://abinet.org/?json=1";
// JSON Node names
private static final String TAG_POSTS = "posts";
static final String TAG_TITLE = "title";
private ProgressDialog pDialog;
JSONArray contacts = null;
TextView img_url;
ArrayList<HashMap<String, Object>> contactList;
ListView lv;
LazyAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.newslist);
contactList = new ArrayList<HashMap<String, Object>>();
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
protected Void doInBackground(Void... arg0) {
// Making a request to url and getting response
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject jsonObj = jParser.getJSONFromUrl(url);
// if (jsonStr != null) {
try {
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_POSTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
// JSONObject c = contacts.getJSONObject(i);
JSONObject posts = contacts.getJSONObject(i);
String title = posts.getString(TAG_TITLE).replace("’", "'");
JSONArray attachment = posts.getJSONArray("attachments");
for (int j = 0; j< attachment.length(); j++){
JSONObject obj = attachment.getJSONObject(j);
JSONObject image = obj.getJSONObject("images");
JSONObject image_small = image.getJSONObject("thumbnail");
String imgurl = image_small.getString("url");
HashMap<String, Object> contact = new HashMap<String, Object>();
contact.put("image_url", imgurl);
contact.put(TAG_TITLE, title);
contactList.add(contact);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
adapter=new LazyAdapter(MainActivity.this, contactList);
lv.setAdapter(adapter);
}
}
}
this is my JsonParser class (although its not required):
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
and this is adapter class:
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, Object>> data;
private static LayoutInflater inflater=null;
public LazyAdapter(Activity a,ArrayList<HashMap<String, Object>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.third_row, null);
TextView title = (TextView)vi.findViewById(R.id.headline3); // title
SmartImageView iv = (SmartImageView) vi.findViewById(R.id.imageicon);
HashMap<String, Object> song = new HashMap<String, Object>();
song = data.get(position);
// Setting all values in listview
title.setText((CharSequence) song.get(MainActivity.TAG_TITLE));
iv.setImageUrl((String) song.get("image_url"));
thumb_image);
return vi;
}
}
Please help me. I am stuck at this for more than a week now. I think there is just something to be changed in my MainActivity class.
Some of the 10 (well today there are 10 ) 'titles' have no 'attachments'. Some have one and some have two. There are only 5 titles wich have one or two images. You only create a new
HashMap<String, Object> contact
if there are attachments. (The attachment are the images). You should create the 'contact' before you enter the attachments loop. Further you only need one image for each title. You can set the image null if there are no attachments. In getView if the image is null you set some image from your drawable res.
Related
Im trying to parse json array data into listview!I searched the whole internet and always was on one point! Json aray must have header something like this
"emp_info":[{"employee name":"Adam","employee no":"101700"},{"employee name":"John","employee no":"101701"},{"employee name":"Paul","employee no":"101702"},{"employee name":"Mark","employee no":"101703"},{"employee name":"Donald","employee no":"101704"},{"employee name":"Brain","employee no":"101705"},{"employee name":"Kevin","employee no":"101706"}]}
Where by my understanding the "emp_info" is the header file by which i must search for rest data inside it in android!My College pretending that i can accept and parse the same data into listview without that header name,but every bit of code where i searched to parse json in android was a single line like this!
JSONObject obj = new JSONObject(jsonString);
JSONArray stations = obj.getJSONArray("emp_inf");
where i just have to put the jsonarray header file as you can see in this piece of code!So please help me is that possible to accept json array without this code?because if i try to remove this code i get nullpointer in my code!Will be very happy if you could at least say yes or no!
Posting Full Codes!
Here is the android class which gets the Json and loads it into List View
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://54.148.41.171/server/index/dompy");
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>> employeeList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("emp_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("empployee no");
String number = jsonChildNode.optString("etc.");
String outPut = name + "-" + number;
employeeList.add(createEmployee("data", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
android.R.layout.simple_list_item_1,
new String[] { "employee no" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
}
private HashMap<String, String> createEmployee(String name, String number) {
HashMap<String, String> employeeNameNo = new HashMap<String, String>();
employeeNameNo.put(name, number);
return employeeNameNo;
}
}
And by this json array im successfully able to fetch the json which type is the next!
{"emp_info":[{"employee name":"Adam","employee no":"101700"},{"employee name":"John","employee no":"101701"},{"employee name":"Paul","employee no":"101702"},{"employee name":"Mark","employee no":"101703"},{"employee name":"Donald","employee no":"101704"},{"employee name":"Brain","employee no":"101705"},{"employee name":"Kevin","employee no":"101706"}]}
And here is the json array which my college pretends that i must accept!
{"data":"123"}
And im Saying that its not possible to load this json into list view just because it dont have header file like mine the emp_info,but hes saying its not matter i just MUST accept!We just on same project and i just cant understand is it even possible to do what he says?
String name = jsonChildNode.optString("empployee no");
String number = jsonChildNode.optString("etc.");
How can you get the data by "etc." tag I could not understand it firstly. It should return "" instead of employee number.
Hi in my application I am using jsonurl to displaying text with image.I want to parse the image and text ,But it showing unfortunately error and my application got crashed.can any one please help me.
CustomizedListView.java:
public class CustomizedListView extends Activity {
// All static variables
static final String URL = "http://indianpoliticalleadersmap.com/android/DemoSchool/json/json_item.php";
// XML node keys
static final String TAG_SCHEDULES = "veg_food"; // parent node
static final String TAG_ID = "id";
static final String TAG_TITLE = "itemname";
static final String TAG_THUMB_URL = "image";
ListView list;
LazyAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(TAG_SCHEDULES);
// looping through all song nodes <song>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(TAG_ID, parser.getValue(e, TAG_ID));
map.put(TAG_TITLE, parser.getValue(e, TAG_TITLE));
map.put(TAG_THUMB_URL, parser.getValue(e, TAG_THUMB_URL));
// adding HashList to ArrayList
songsList.add(map);
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, songsList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
}
There is a difference between JSON and XML parsing. Take a look at the code below. Here I am parsing the date coming from a database into a listview.
Activity class:
public static class EventFragment extends ListFragment {
ArrayList<HashMap<String, String>> eventsList;
private String url_all_events = //url goes here;
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
// JSON Node names
private static final String CONNECTION_STATUS = "success";
private static final String TABLE_EVENT = "Event";
private static final String pid = "pid";
private static final String COL_GROUP = "Group";
private static final String COL_NAME = "Event_Name";
private static final String COL_DESC = "Event_Desc";
private static final String COL_DATE = "Event_Date";
private static final String COL_TIME = "Event_Time";
JSONArray Events = null;
public static final String ARG_SECTION_NUMBER = "section_number";
public EventFragment() {
}
public void onStart() {
super.onStart();
eventsList = new ArrayList<HashMap<String, String>>();
new LoadAllEvents().execute();
// selecting single ListView item
ListView lv = getListView();
// Lauching the Event details screen on selecting a single event
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String ID = ((TextView) view.findViewById(R.id.pid))
.getText().toString();
Intent intent = new Intent(view.getContext(),
EventDetails.class);
intent.putExtra(pid, ID);
view.getContext().startActivity(intent);
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_events,
container, false);
return rootView;
}
class LoadAllEvents extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Just a moment...");
pDialog.setIndeterminate(true);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_events,
"GET", params);
try {
// Checking for SUCCESS TAG
int success = json.getInt(CONNECTION_STATUS);
if (success == 1) {
// products found
// Getting Array of Products
Events = json.getJSONArray(TABLE_EVENT);
// looping through All Contacts
for (int i = 0; i < Events.length(); i++) {
JSONObject evt = Events.getJSONObject(i);
// Storing each json item in variable
id = evt.getString(pid);
group = evt.getString(COL_GROUP);
name = evt.getString(COL_NAME);
desc = evt.getString(COL_DESC);
date = evt.getString(COL_DATE);
time = evt.getString(COL_TIME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(pid, id);
map.put(COL_GROUP, group);
map.put(COL_NAME, name);
map.put(COL_DESC, desc);
map.put(COL_DATE, date);
map.put(COL_TIME, time);
// adding HashList to ArrayList
eventsList.add(map);
}
} else {
// Options are not available or server is down.
// Dismiss the loading dialog and display an alert
// onPostExecute
pDialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(getActivity(),
eventsList, R.layout.list_item, new String[] {
pid, COL_GROUP, COL_NAME, COL_DATE, COL_TIME },
new int[] { R.id.pid, R.id.group, R.id.name, R.id.header,
R.id.title2 });
setListAdapter(adapter);
}
});
}
}
}
JSON Parser class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Hope this helps :)
what is the correct way of fixing this problem?
This is my activity code
public class MainActivity extends Activity {
JSONParser jsonParser = new JSONParser();
ItemsAdapter adapter;
ListView list;
ListView list2;
HashMap<String, String> map;
ProgressDialog myPd_bar;
static String img_url;
private String strJson1 = "";
private String url = "http://www.*************************************************";
String img_test_url = "http://*************************************************";
ImageView imageView;
String bName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView1);
list2 = (ListView) findViewById(R.id.listView2);
accessWebService();
}
// Async Task to access the web
private class LoadData extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
myPd_bar = new ProgressDialog(MainActivity.this);
myPd_bar.setMessage("Loading....");
myPd_bar.setTitle(null);
myPd_bar.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
strJson1 = 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) {
getImageData();
myPd_bar.dismiss();
}
}// end async task
public void accessWebService() {
LoadData task = new LoadData();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void getImageData() {
map = new HashMap<String, String>();
ArrayList<Pair<String,String>> listData = new ArrayList<Pair<String,String>>();
try {
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("bank");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
img_url = jsonChildNode.optString("logo");
String test1 = img_test_url + img_url;
bName = jsonChildNode.optString("id");
//map.put(bName, test1);
listData.add(new Pair<String,String>(bName,test1 ));
}
ItemsAdapter adapter = new ItemsAdapter(getApplicationContext(),listData);
list.setAdapter(adapter);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Connection Error...",
Toast.LENGTH_LONG).show();
}
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
#SuppressWarnings("unchecked")
Pair<String, String> item = (Pair<String, String>)arg0.getItemAtPosition(arg2);
String id = item.first;
Log.d("Bank Name", id);
List<String> cards_name = new ArrayList<String>();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Bank_Name", id));
Log.d("request!", "starting");
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
Log.d("Credite Cards", jsonResponse.toString());
JSONArray jsonMainNode = jsonResponse.optJSONArray("creditcards");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String card = jsonChildNode.optString("name");
Log.d("Card_name", card);
cards_name.add(card);
}
ArrayAdapter adapter2 = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, cards_name);
list2.setAdapter(adapter2);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
}
});
}
}
I guess this where you go wrong
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
In onPostExecute you have
getImageData();
In getImageData() you have listview item click listener
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
..// rest of the code
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
// network operation on main thread
This getting json object must be doen in a background thread
Also you cannot update ui from background thread
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
Must be removed
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
//this should be in a separate non ui thread
For the http request in android the better way to use the following library which is manage all the auto setting for the request there are simple few line code
Check the following link.
http://loopj.com/android-async-http/
download the jar file and paste in the lib folder and then just write few lines like for simple get methods
});
import com.loopj.android.http.*;
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
System.out.println(response);
}
});
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...
In my application, I have created a separate class for AsynchronousTask. From the main class I execute the Asynchronous task class, is it possible to use the list view in Asynchronous task class?
MAIN CLASS
search_items_task = new Search_class();
search_items_task.execute(search_str);
ASYNCHRONOUS TASK CLASS
public class Search_class extends AsyncTask<String, Void, String> {
JSONObject json = new JSONObject();
JSONArray jsonarray;
String viewsubmenuSuccess;
//Activity activity;
ListView search_lv;
protected String doInBackground(String... params) {
try {
HttpClient client = new DefaultHttpClient();
HttpResponse response;
HttpPost post = new HttpPost("http://www.name.in/cakefoodnew/customer/submenus");
post.setHeader("json", json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
post.setEntity(se);
response = client.execute(post);
// get a data
InputStream in = response.getEntity().getContent();
String a = convertStreamToString(in);
// Log.v("Search", ""+a);
try {
jsonarray = new JSONArray("[" + a + "]");
json = jsonarray.getJSONObject(0);
String menus = json.getString("submenus");
viewsubmenuSuccess = json.getString("viewsubmenuSuccess");
// Log.v("Search", ""+a);
try {
jsonarray = new JSONArray(menus);
for (int ij = 0; ij < jsonarray.length(); ij++) {
json = jsonarray.getJSONObject(ij);
String name = json.getString("submenu");
if (name.toLowerCase().contains(params[0].toLowerCase())) {
String id = json.getString("submenu_id");
String price = json.getString("submenu_price");
String avaliable_quantity = json.getString("submenu_stock");
HashMap<String, String> map = new HashMap<String, String>();
map.put(MENU_ID, id);
map.put(MENU_NAME, name);
map.put(MENU_PRICE, price);
map.put(MENU_STOCK, avaliable_quantity);
search_details.add(map);
//Log.v("search_details", ""+search_details);
}
}
} catch (Exception e) {
// TODO: handle exception
}
} catch (Exception e) {
}
} catch (Exception e) {
e.printStackTrace();
}
return viewsubmenuSuccess;
}
protected void onPostExecute(String result) {
if (viewsubmenuSuccess.equalsIgnoreCase("1")) {
//search_lv = (ListView)activity.findViewById(R.id.search_list_view);
//Order_page_custom for customized list view
/*Order_page_custom adapter = new Order_page_custom(activity,search_details);
search_lv.setAdapter(adapter);*/
}
}
Yes, Make a Constructor of Search_Class AsyncTask with ListView and Context parameter. Define ListView in onCreate() of Your activity after setContentView() and then Call AsyncTask..
Something Like;
Context mContext
ListView search_lv;
public Search_class(Context context, ListView list)
{
mContext = context;
search_lv = list;
}
Now in
protected void onPostExecute(String result) {
if (viewsubmenuSuccess.equalsIgnoreCase("1")) {
Order_page_custom adapter = new Order_page_custom(mContext,search_details);
search_lv.setAdapter(adapter);
}
}
And in Main Class (Activity Class)
setContentView(R.layout.<activity_layout>);
search_lv = (ListView)findViewById(R.id.search_list_view);
search_items_task = new Search_class(this, search_lv);
search_items_task.execute(search_str);