Android SimpleAdapter refreshing - android

I have a problem with refreshing data on the screen, app get the data through JSON everything works fine, but now I need to do the refresh button in the menu. I built my application according to an example. As I understand it does good idea to use SimpleAdapter and need to write a custom adapter. Can you help me please?
ServiceHandler
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
MainActivity
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "******";
// JSON Node names
private static final String TAG_ZLECENIA = "zlecenia";
private static final String TAG_ID = "id";
private static final String TAG_CO = "co";
private static final String TAG_KYDA = "kyda";
private static final String TAG_ILE = "ile";
private static final String TAG_LIM = "lim_czas";
// zlecenia JSONArray
JSONArray zlecenia = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> ZleceniaList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ZleceniaList = 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 co = ((TextView) view.findViewById(R.id.co))
.getText().toString();
String kyda = ((TextView) view.findViewById(R.id.kyda))
.getText().toString();
}
});
// Calling async task to get json
new GetContacts().execute();
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
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
zlecenia = jsonObj.getJSONArray(TAG_ZLECENIA);
// looping through All Contacts
for (int i = 0; i < zlecenia.length(); i++) {
JSONObject c = zlecenia.getJSONObject(i);
String id = c.getString(TAG_ID);
String co = c.getString(TAG_CO);
String kyda = c.getString(TAG_KYDA);
String ile = c.getString(TAG_ILE);
String lim = c.getString(TAG_LIM);
// tmp hashmap for single contact
HashMap<String, String> zlecenia = new HashMap<String, String>();
// adding each child node to HashMap key => value
zlecenia.put(TAG_ID, id);
zlecenia.put(TAG_CO, co);
zlecenia.put(TAG_KYDA, kyda);
zlecenia.put(TAG_ILE, ile);
zlecenia.put(TAG_LIM, lim);
// adding contact to contact list
ZleceniaList.add(zlecenia);
}
} 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, ZleceniaList, R.layout.list_item,
new String[] { TAG_KYDA, TAG_CO, TAG_ILE, TAG_LIM,},
new int[] { R.id.kyda, R.id.co, R.id.ile, R.id.lim });
setListAdapter(adapter);
}
}
}
rest/menu/main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity" >
<item
android:id="#+id/action_refresh"
android:showAsAction="ifRoom"
android:title="Refresh"
android:icon="#drawable/ic_refresh_white_36dp"
/>
</menu>

You have to override the onOptionsItemSelected() method and handle the refresh menu item click action.

Related

When we click on item in listview then how we get id of that item

I have a json in which i have product_id and product_name through the Json products are showing in listview now i want that when clicked on item then id of that product should be show in toast. I am new to android i am unable to do this
can anyone tell me how can i do this please
public class CityNameActivity extends ListActivity{
ListView list;
private ProgressDialog pDialog;
// URL to get Cities JSON
private static String url = "http://14.140.200.186/Hospital/get_city.php";
// JSON Node names
private static final String TAG_CITIES = "Cities";
//private static final String TAG_ID = "id";
private static final String TAG_NAME = "city_name";
// Cities JSONArray
JSONArray Cities = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> citylist;
//ArrayList<String> citylist;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cityname_activity_main);
ListView listView=getListView();
citylist = new ArrayList<HashMap<String, String>>();
// list.setOnClickListener(this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent in = new Intent(getApplicationContext(),
Specialities_Activity.class);
startActivity(in);}
});
new GetCities().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetCities extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CityNameActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
Cities = jsonObj.getJSONArray(TAG_CITIES);
// looping through All Cities
for (int i = 0; i < Cities.length(); i++) {
JSONObject c = Cities.getJSONObject(i);
//String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
HashMap<String, String> Cities = new HashMap<String, String>();
Cities.put(TAG_NAME, name);
// adding contact to Cities list
citylist.add(Cities);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**`enter code here`
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(CityNameActivity.this, citylist, R.layout.city_list_item, new String[] { TAG_NAME}, new int[] { R.id.name});
setListAdapter(adapter);
}
}
Code of Service Handlerclass:
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
code of Hospital Activity in which hospital is showing in listview i want that not all hospitals show only show hospital of specific city
public class HospitalList_Activity extends ListActivity {
private ProgressDialog pDialog;
// URL to get Hospitals JSON
private static String url = "http://14.140.200.186/hospital/get_hospital.php";
// JSON Node names
private static final String TAG_HOSPITAL = "Hospitals";
//private static final String TAG_ID = "id";
private static final String TAG_NAME = "hospital_name";
// Hospitals JSONArray
JSONArray Hospitals = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> hospitallist;
//ArrayList<String> citylist;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hospital_list_);
ListView listView=getListView();
hospitallist = new ArrayList<HashMap<String, String>>();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent in = new Intent(getApplicationContext(), Specialities_Activity.class);
startActivity(in);
}
});
new GetHospitals().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetHospitals extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(HospitalList_Activity.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
Hospitals = jsonObj.getJSONArray(TAG_HOSPITAL);
// looping through All Cities
for (int i = 0; i < Hospitals.length(); i++) {
JSONObject c = Hospitals.getJSONObject(i);
//String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
HashMap<String, String> Hospitals = new HashMap<String, String>();
Hospitals.put(TAG_NAME, name);
// adding contact to Cities list
hospitallist.add(Hospitals);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**`enter code here`
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(HospitalList_Activity.this, hospitallist, R.layout.hospital_list_item, new String[] { TAG_NAME}, new int[] { R.id.name});
setListAdapter(adapter);
}
}
public class CityNameActivity extends ListActivity {
ListView list;
Map <String, String> cityListWithId = new HashMap<String, String>();
private ProgressDialog pDialog;
// URL to get Cities JSON
private static String url = "http://14.140.200.186/Hospital/get_city.php";
// JSON Node names
private static final String TAG_CITIES = "Cities";
private static final String TAG_ID = "city_id";
private static final String TAG_NAME = "city_name";
// Cities JSONArray
JSONArray Cities = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> citylist;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cityname_activity_main);
ListView listView=getListView();
citylist = new ArrayList<HashMap<String, String>>();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//String tagname = ((TextView) findViewById(R.id.name)).getText().toString();
Map<String, String> tempHashmap = (Map<String, String>) parent.getItemAtPosition(position);
String tagName = tempHashmap.get(TAG_NAME);
System.out.println("tagname" + tagName);
String tagId = (String)cityListWithId.get(tagName);
System.out.println("tagId" + tagId);
Toast.makeText(CityNameActivity.this, tagId,Toast.LENGTH_SHORT).show();
}
});
new GetCities().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetCities extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CityNameActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
Cities = jsonObj.getJSONArray(TAG_CITIES);
// looping through All Cities
for (int i = 0; i < Cities.length(); i++) {
JSONObject c = Cities.getJSONObject(i);
//String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
cityListWithId.put(c.getString(TAG_NAME), c.getString(TAG_ID));
HashMap<String, String> Cities = new HashMap<String, String>();
Cities.put(TAG_NAME, name);
// adding contact to Cities list
citylist.add(Cities);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**`enter code here`
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(CityNameActivity.this, citylist, R.layout.city_list_item, new String[] { TAG_NAME}, new int[] { R.id.name});
setListAdapter(adapter);
}
}
}
On ItemClick() method you can add this to get the id of the product.
HashMap<String,String> data = cityList.get(position);
//position is the paramater from ItemClick
String id = data.get("your key for Id");
why you every time hit the service . as per my opinion don't call service in onItemClick . when you start activity or app start Async task and pass data to list view .
please find below code . i am just refactor few thing so please let me if there some thing wrong
public class CityNameActivity extends ListActivity
{
private ProgressDialog pDialog;
// URL to get Cities JSON
private static String url = "http://14.140.200.186/Hospital/get_city.php";
// JSON Node names
private static final String TAG_CITIES = "Cities";
//private static final String TAG_ID = "id";
private static final String TAG_NAME = "city_name";
// Cities JSONArray
JSONArray Cities = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> citylist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new GetCities().execute();
ListView listView=getListView();
citylist = new ArrayList<HashMap<String, String>>();
// list.setOnClickListener(this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(citylist!=null && !citylist.isEmpty())
{
Toast.makeText(CityNameActivity.this,""+citylist.get(position).get(TAG_NAME).toString(),Toast.LENGTH_SHORT).show();
}
}
});
new GetCities().execute();
}
private class GetCities extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CityNameActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
Cities = jsonObj.getJSONArray(TAG_CITIES);
// looping through All Cities
for (int i = 0; i < Cities.length(); i++) {
JSONObject c = Cities.getJSONObject(i);
//String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
HashMap<String, String> Cities = new HashMap<String, String>();
Cities.put(TAG_NAME, name);
// adding contact to Cities list
citylist.add(Cities);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**`enter code here`
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(CityNameActivity.this, citylist, R.layout.city_list_item, new String[] { TAG_NAME}, new int[] { R.id.name});
setListAdapter(adapter);
}
}
}

Json Data is not showing in listview

I am learning about Json Parsing I want to show the data in the listview from url
for this i did some code but data in the listview is not showing which is coming from url please tell me what mistakes i am making in the code.
MainActivity Code is
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get Cities JSON
private static String url = "http://14.140.200.186/Hospital/get_city.php";
// JSON Node names
private static final String TAG_CITIES = "Cities";
//private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
// Cities JSONArray
JSONArray Cities = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> citylist;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
citylist = new ArrayList<HashMap<String, String>>();
// Calling async task to get json
new GetCities().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetCities extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(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
Cities = jsonObj.getJSONArray(TAG_CITIES);
// looping through All Cities
for (int i = 0; i < Cities.length(); i++) {
JSONObject c = Cities.getJSONObject(i);
//String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
HashMap<String, String> Cities = new HashMap<String, String>();
// adding each child node to HashMap key => value
//Cities.put(TAG_ID, id);
Cities.put(TAG_NAME, name);
// adding contact to Cities list
citylist.add(Cities);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(MainActivity.this, citylist, R.layout.list_item, new String[] { TAG_NAME}, new int[] { R.id.name,});
setListAdapter(adapter);
}
}
Second Class code is
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;}
And in the activity_main simply i have a listview in LinearLayout
And i have also another layout file list_item with single texview for show showing result..
now please slove my problem
Thanku
Change From:
private static final String TAG_NAME = "name";
To
private static final String TAG_NAME = "city_name";
It will help now Please check your Service which You are using.
Change From:
private static final String TAG_NAME = "name";
To
private static final String TAG_NAME = "city_name";
There are couple of places where things could have gone wrong.
First:
} else if (method == GET) {
Check if above condition is satisfied. You may want to replace GET with ServiceHandler.GET.
Second:
setListAdapter(adapter);
You need to write code to actually make list adapter visible.
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**`enter code here`
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(MainActivity.this, citylist, R.layout.list_item, new String[] { TAG_NAME}, new int[] { R.id.name,});
list.setAdapter(adapter);
}
Hope it will be help you.
You can do this way:
From
ArrayList<HashMap<String, String>> citylist;
to
ArrayList<String> citylist;
Your loop should looks like below:
for (int i = 0; i < Cities.length(); i++) {
JSONObject c = Cities.getJSONObject(i);
//String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
// adding contact to Cities list
citylist.add(name);
}
Pass only ArrayList to adapter.
Edit 2 :
From
ListAdapter adapter = new SimpleAdapter(MainActivity.this, citylist, R.layout.list_item, new String[] { TAG_NAME}, new int[] { R.id.name,});
To
ArrayAdapter adapter = new ArrayAdapter<String>(MainActivity.this, R.layout.list_item, citylist);
Hope this will help you.

Show data from world weather online api

I am developing weather application by using world weather online API
for android.How i show data in application? data is showing in logcat.Following is my code.
MainActivity.java
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_NAME = "name";
// contacts JSONArray
JSONArray data = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
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();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
data = jsonObj.getJSONArray(TAG_DATA);
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
// adding contact to contact list
dataList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(MainActivity.this,
dataList, R.layout.list_item, new String[] { TAG_NAME }, new int[] {
R.id.name });
setListAdapter(adapter);
}
}
}
ServiceHandler.java
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
First of all, this format will refer to the V1 free version. World Weather Online has released v2, which is superior. I was in the process of updating and saw this question sitting out there so I'll answer based off of what I had that did work.
You are on the right track to use the AsyncTask, here is my call to AsyncTask. You should know I use my "DataPoint" class to simply contain the data from WWO that I need to use. Based on your question, you can show the data that I will put in the DataPoint object in anyway you see fit on the screen, since at the end of the queryWeatherService(), you will end up with a parsed set of data.
//Some call to query the weather, which executes the AsyncTask
private DataPoint queryWeatherService()
{
// This method will retrieve the data from the weather service
DataPoint newDataPoint = new DataPoint();
if (!waiting)
{
try{
newDataPoint = new WeatherServiceClass().execute(
String.valueOf(getlatitude()), //Not shown here: pass in some String of a float value of of your lat coordinate.
String.valueOf(getlongitude())) //Not shown here: pass in some String of a float value of of your long coordinate.
.get();
} catch (InterruptedException | ExecutionException e)
{
e.printStackTrace();
}
}
return newDataPoint;
// Documentation:
// https://developer.worldweatheronline.com/page/documentation
}
The WeatherServiceClass that extends the AsyncTask
public class WeatherServiceClass extends AsyncTask<String, String, DataPoint> {
private String latitude;
private String longitude;
public WeatherServiceClass() {
}
#Override
protected DataPoint doInBackground(String... params) {
DataPoint dp = new DataPoint();
JSONWeatherParser jparser = new JSONWeatherParser();
latitude = params[0];
longitude = params[1];
String data = ((new WeatherHttpClient().getWeatherData(latitude, longitude)));
try {
dp = jparser.getWeather(data);
} catch (JSONException e) {
e.printStackTrace();
}
return dp;
//Reference:
// http://www.javacodegeeks.com/2013/06/android-build-real-weather-app-json-http-and-openweathermap.html
}
}
Here is the WeatherHttpClient class:
public class WeatherHttpClient {
private static String BASE_URL = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=";
private static String BASE_URL_PT2 = "&format=json&num_of_days=5&date=today&key=[ENTER YOUR KEY HERE, I'M NOT GIVING YOU MINE]";
public String getWeatherData(String latitude, String longitude){
HttpURLConnection con = null;
InputStream is=null;
try{
con = (HttpURLConnection)(new URL(BASE_URL + latitude+","+longitude+BASE_URL_PT2)).openConnection();
con.setRequestMethod("GET");
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
//Reading the response
StringBuffer buffer = new StringBuffer();
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line=br.readLine()) != null)
buffer.append(line + "\r\n");
is.close();
con.disconnect();
return buffer.toString();
}
catch(Throwable t) {
t.printStackTrace();
}
finally {
try { is.close();} catch(Throwable t){}
try { con.disconnect();} catch(Throwable t){}
}
return null;
}
Finally, here is my JSONWeatherParser:
public class JSONWeatherParser {
public JSONWeatherParser() {
}
public DataPoint getWeather(String data) throws JSONException {
DataPoint dp = new DataPoint();
Weather weather = new Weather(); //This is just a class that has a bunch of strings in it for the weather info.
JSONObject jObj = new JSONObject(data);
//Parsing JSON data
JSONObject dObj = jObj.getJSONObject("data");
JSONArray cArr = dObj.getJSONArray("current_condition");
JSONObject JSONCurrent = cArr.getJSONObject(0);
weather.setCurrent_temp(getString("temp_F",JSONCurrent));
weather.setHour(getString("observation_time",JSONCurrent));
JSONArray jArr = dObj.getJSONArray("weather");
JSONObject JSONWeather = jArr.getJSONObject(0);
JSONArray jArrIcon = JSONWeather.getJSONArray("weatherIconUrl");
JSONObject JSONIcon = jArrIcon.getJSONObject(0);
weather.setDate(getString("date",JSONWeather));
weather.setPrecipmm(getString("precipMM",JSONWeather));
weather.setTempMaxc(getString("tempMaxC",JSONWeather));
weather.setTempMaxf(getString("tempMaxF",JSONWeather));
weather.setTempMinf(getString("tempMinF",JSONWeather));
weather.setTempMinc(getString("tempMinC",JSONWeather));
weather.setWeatherCode(getString("weatherCode",JSONWeather));
weather.setWeatherIconURL(getString("value",JSONIcon));
weather.setWinddir16point(getString("winddir16Point",JSONWeather));
weather.setWinddirDegree(getString("winddirDegree",JSONWeather));
weather.setWindspeedKmph(getString("windspeedKmph",JSONWeather));
weather.setWindspeedMiles(getString("windspeedMiles",JSONWeather));
dp.setWeather(weather); //assigns and converts the relevant weather strings to DataPoint
// For details of these operations and how each works go here:
// http://www.javacodegeeks.com/2013/06/android-build-real-weather-app-json-http-and-openweathermap.html
return dp;
}
private static String getString(String tagName, JSONObject jObj)
throws JSONException {
return jObj.getString(tagName);
}
}

json url not displying in android

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 :)

Issue in passing a string from one activity to another

Background : I am trying to develop my first android application which is a student discussion panel. I am good with PHP and MySQL but don't have much experience in android Java.
Issue:
In SelectedQuestionActivity class, if I simply give the URL as http://thewbs.getfreehosting.co.uk/talky/fetchans.php?qid=3, it works just fine and it fetches the corresponding answer to the question.
But if I do it the way I have shown in the code below, the application crashes. I am not sure where I am wrong.
CODE:
AllQuestionActivity.java
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.qid)).getText()
.toString();
//pid is the value of the selected question for example www.example.com/fetchans?qid=3 so here pid value is supposed to be 3.
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SelectedQuestionActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
startActivity(in);
}
});
Now in SelectedQuestionActivity.java
code:
public class SelectedQuestionActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
Intent intent = getIntent();
String qid = intent.getExtras().getString(TAG_PID);
// url to get all products list
private String url_all_products = "http://thewbs.getfreehosting.co.uk/talky/fetchans.php?qid="+qid;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "ques";
private static final String TAG_PID = "aid";
private static final String TAG_NAME = "aname";
private static final String TAG_INFO = "answer";
private static final String TAG_DATE = "date";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_ans);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
}
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SelectedQuestionActivity.this);
pDialog.setMessage("Loading Answers. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
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_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Answers: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String info = c.getString(TAG_INFO);
String date = c.getString(TAG_DATE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
map.put(TAG_INFO, info);
map.put(TAG_DATE, date);
// adding HashList to ArrayList
productsList.add(map);
}
}
else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
SelectedQuestionActivity.this, productsList,
R.layout.list_selected_ques, new String[] { TAG_PID,
TAG_NAME, TAG_INFO, TAG_DATE },
new int[] { R.id.aid, R.id.aname, R.id.answer, R.id.date});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
JSONparser.java
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 method
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;
}
}
Currently you are trying to getIntent outside onCreate of ListActivity so move it inside onCreate method as :
Intent intent;
String qid;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_ans);
// get Intent here
intent = getIntent();
qid = intent.getExtras().getString(TAG_PID);
// your code here
and also no need to use runOnUiThread method for updating UI from onPostExecute because onPostExecute method called on Ui thread we can access UI elements in it
EDIT:-
you are not adding any paramter to NameValuePair inside doInBackground . add quid before sending it to makeHttpRequest as :
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
add quid param here
params.add(new BasicNameValuePair("qid",qid)); //<<<< add here
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(
url_all_products,
"GET",
params);
// your code here
You are passing a string from one activity object to another , while you didn't write code to receive it on the new activity in the right place.
To solve this you should add some code to your onCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_ans);
String url = getIntent().getStringExtra(TAG_PID);
if (url != null)
url_all_products = url;
You should need to get your intent values in onCreate() as below :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_ans);
Intent intent = getIntent();
String qid = intent.getExtras().getString(TAG_PID);
}

Categories

Resources