I have made a lot of project and for every web-serves i make a a AsyncTask class. If i want to get data from 20 web-serves then i have to make 20 A AsyncTask classes . so this is not the use-ability code.Any one help me to make a Generic AsyncTask class so in whole project i have just 1 AsyncTask class and i use that class.
public class HTTPAsyncTask extends AsyncTask<String, Void, String> {
private CallBack mCb;
HashMap<String, String> mData = null;
List<NameValuePair> mParams= new ArrayList<NameValuePair>();
String mTypeOfRequest;
String mStrToBeAppended = "";
boolean isPostDataInJSONFormat = false;
JSONObject mJSONPostData = null;
public HTTPAsyncTask(CallBack c, HashMap<String, String> data, JSONObject jsonObj, String request) {
mCb = c;
mTypeOfRequest = request;
mJSONPostData = jsonObj;
if((data != null) && (jsonObj == null)){
mData = data;
if(mTypeOfRequest.equalsIgnoreCase("GET")){
Iterator<String> it = mData.keySet().iterator();
while(it.hasNext()){
String key = it.next();
mParams.add(new BasicNameValuePair(key, mData.get(key)));
}
for (int i = 0; i<mParams.size()-1; i++){
mStrToBeAppended+= "?" + mParams.get(i).getName() + "=" + mParams.get(i).getValue() + "&";
}
//add the last parameter without the "&"
mStrToBeAppended+= "?" + mParams.get(mParams.size()-1).getName() + "=" + mParams.get(mParams.size()-1).getValue();
}
if(mTypeOfRequest.equalsIgnoreCase("POST")){
Iterator<String> it = mData.keySet().iterator();
while(it.hasNext()){
String key = it.next();
mParams.add(new BasicNameValuePair(key, mData.get(key)));
}
}
}
if ((mData == null) && (jsonObj != null)){
isPostDataInJSONFormat = true;
}
}
#Override
protected String doInBackground(String... baseUrls) {
publishProgress(null);
if(mTypeOfRequest.equalsIgnoreCase("GET")){
String finalURL = baseUrls[0]+ mStrToBeAppended;
return HttpUtility.GET(finalURL);
}
if (mTypeOfRequest.equalsIgnoreCase("POST")){
if(isPostDataInJSONFormat == false){
return HttpUtility.POST(baseUrls[0],mParams );
}
else {
return HttpUtility.POST(baseUrls[0], mJSONPostData);
}
}
return null;
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
mCb.onResult(result);
}
#Override
protected void onProgressUpdate(Void...voids ) {
mCb.onProgress();
}
Related
I have created an Android application in that I am calling webservice that have attribute name and attribute value and I wants to display attribute value in Spinner and attribute name display in TextView. If attribute value is two then two arrylist is store. If attribute name is same in both list then store only one list. If attributename change then add new arraylist. Below is my code
//call webservice for product attribute
private class getCategoryProductAttribute extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(ProductDescriptionActivity.this);
StringBuilder result = null;
String response;
#Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("Loding..");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... strings) {
if (pref.isLoggedIn() == true) {
constant_pref.getPrefData();
} else {
constant_pref.UserName = "remplastic#admin";
constant_pref.Password = "remplastic#admin";
constant_pref.AppVersion = getVersionInfo();
constant_pref.DataVersion = "1.0";
}
Webservice addressService = new Webservice();
String query = "<value><user_name>" + constant_pref.UserName + "</user_name>" +
"<user_password>" + constant_pref.Password + "</user_password>" +
"<product_id>" + Product_Id + "</product_id>" +
"<appversion_text>" + constant_pref.AppVersion + "</appversion_text>" +
"<dataversion_text>" + constant_pref.DataVersion + "</dataversion_text></value>";
try {
addressService.XmlPostData(ConstantUrl.Product_Attribute_Url, query);
result = addressService.getResponse();
response = result.toString();
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
if (response.length() > 0) {
int code = Integer.parseInt(XMLManualParser.getTagValue(ConstantUrl.TAG_CODE, response));
String msg = XMLManualParser.getTagValue("message", response);
if (code == 1) {
spinnerlist.clear();
ArrayList<String> productlist = XMLManualParser.getMultipleTagList(ConstantUrl.TAG_LIST, response);
for (int i = 0; i < productlist.size(); ++i) {
String responseContent = productlist.get(i);
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("attr_name", XMLManualParser.getTagValue(ConstantUrl.attribute_name, responseContent));
hashMap.put("attr_value", XMLManualParser.getTagValue(ConstantUrl.attribute_value, responseContent));
hashMap.put("attr_dealerprize", XMLManualParser.getTagValue(ConstantUrl.product_dealerprice, responseContent));
hashMap.put("attr_retailer_prize", XMLManualParser.getTagValue(ConstantUrl.product_retaillerprice, responseContent));
spinnerlist.add(hashMap);
if (XMLManualParser.getTagValue(ConstantUrl.attribute_name, responseContent).toLowerCase().equalsIgnoreCase("print")) {
}
}
attribute_adapter.notifyDataSetChanged();
} else {
Toast.makeText(ProductDescriptionActivity.this, msg, Toast.LENGTH_SHORT).show();
}
attribute_adapter.notifyDataSetChanged();
}
} catch (Exception e) {
}
pdLoading.dismiss();
}
}
I'm populating a ListView from DB. The recordset from the DB contains the Zipcode which is then transformed into City and State using google map api and then set to Listview Item.
I need to be able to set the value that is being returned from the background class in Listview. Any guidance would be very much appreciated. Thanks in advance.
for (int i = 0; i < zipcodes.getLength(); i++) {
GetCityStateInfoFromPostalCode getCityStateInfoFromPostalCode = new GetCityStateInfoFromPostalCode(getActivity(), "110001", "ta");
String mCityState = getCityStateInfoFromPostalCode.getCityState();
}
Here's Background Class that fetches the info from Google maps api
public class GetCityStateInfoFromPostalCode extends AsyncTaskLoader<String> {
private String URL;
private String mState = "";
private String mCity = "";
private Context mContext;
public String getCityState() {
return mCityState;
}
private String mCityState = "";
public GetCityStateInfoFromPostalCode(Context context, String postalCode, String language) {
super(context);
this.mContext = context;
URL = "http://maps.googleapis.com/maps/api/geocode/json?components=postal_code:" + postalCode + "&language=" + language;
// Kick start the load process
forceLoad();
}
public String loadInBackground() {
JSONObject jsonObject;
JSONArray jsonRootArray;
JSONArray jsonAdressArray;
JSONObject addressComponentCityObject;
JSONObject addressComponentStateObject;
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
httpGet.addHeader("content-type", "application/json");
try {
HttpResponse resp = client.execute(httpGet);
String json = EntityUtils.toString(resp.getEntity(), "UTF-8");
jsonObject = new JSONObject(json);
addressComponentCityObject = new JSONObject();
addressComponentStateObject = new JSONObject();
jsonRootArray = jsonObject.getJSONArray("results");
//This points to "0"
JSONObject rootJson = jsonRootArray.getJSONObject(0);
//This points to address components
jsonAdressArray = rootJson.getJSONArray("address_components");
//This points to Object 1 (Second object of the jsonAddressArray)
addressComponentCityObject = jsonAdressArray.getJSONObject(1);
mCity = addressComponentCityObject.getString("long_name");
addressComponentStateObject = jsonAdressArray.getJSONObject(3);
mState = addressComponentStateObject.getString("long_name");
} catch (Throwable t) {
// Handle error here
t.printStackTrace();
}
this.mCityState = mCity + ", " + mState;
return mCityState;
}
}
with AsyncTask you can generate and override the methods below :
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
I hope this will help you :)
I have an app that connects to server sends sql request and get JSON answer as JsonArray.
Its Asynktask in seperate class (HTTPRequest.java is my AsyncTask class, Responce.java its my callback interface class) and it works correct.
when I use it in OrderActivity.java like below
#Override //my interface class function
public void onPostExecute(JSONArray Result) {
load(Result);
}
private void load(JSONArray json) {
for(int i=0;i<json.length();i++){
try {
JSONObject jo = json.getJSONObject(i);
Product p = new Product(
jo.getInt("ID"),
jo.getInt("parent"),
jo.getInt("category"),
jo.getString("Item"),
jo.getDouble("Price")
);
products.add(p);
} catch (JSONException e) {
e.printStackTrace();
}
}
it does work and fills product with data, but when I assign to my class variable JSONArray json
JSONArray json = new JSONArray;
.
.
.
#Override
public void onPostExecute(JSONArray Result) {
json = Result;
}
json is null
//HTTPRequest.java
public class HTTPRequest extends AsyncTask<String, Void, Integer> {
private Context context;
private Responce responce;
JSONArray json;
public HTTPRequest(Context context){
this.context = context;
responce = (Responce)context;
}
#Override
protected Integer doInBackground(String... params) {
OutputStream output;
InputStream inputStream = null;
HttpURLConnection connection = null;
String charset = "UTF-8";
Integer result = 0;
try {
URL uri = new URL(params[0]);
connection = (HttpURLConnection) uri.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "text/plain; charset=" + charset);
output = connection.getOutputStream();
output.write(params[1].getBytes(charset));
output.close();
int statusCode = connection.getResponseCode();
if (statusCode == 200) {
inputStream = new BufferedInputStream(connection.getInputStream());
json = new JSONArray(getJSON(inputStream));
result = 1;
}
} catch (Exception e) {
e.getLocalizedMessage();
}
return result;
}
#Override
protected void onPostExecute(Integer i) {
super.onPostExecute(i);
if(i == 1) {
responce.onPostExecute(json);
} else {
responce.onPostExecute(null);
}
}
private String getJSON(InputStream inputStream) throws IOException, JSONException {
StringBuffer stringBuffer = new StringBuffer();
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = null;
while((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line.toString());
}
result = stringBuffer.toString();
if(null!=inputStream){
inputStream.close();
}
return result;
}
}
//Responce.java
public interface Responce {
public void onPostExecute(JSONArray Result);
}
//OrderActivity.java
public class OrderActivity extends Activity implements Responce{
ArrayList<Product> products = new ArrayList<Product>();
ProductAdapter productAdapter;
OrderItemAdapter orderItemAdapter;
ListView orderlist;
JSONArray ja;
Button btnBack;
Button btnTakeOrder;
ListView picklist;
HTTPRequest httpRequest;
String url = "http://192.168.3.125:8888/data/";
String query = "select * from vwitems order by category desc";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
orderlist =(ListView)findViewById(R.id.orderlist);
orderItemAdapter = new OrderItemAdapter(OrderActivity.this);
btnBack = (Button)findViewById(R.id.btnBack);
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
productAdapter.filter(0);
}
});
btnTakeOrder = (Button)findViewById(R.id.btnTakeOrder);
btnTakeOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer oid = 0;
Order order = new Order(OrderActivity.this);
oid = order.NewOrder(1, 2, 3);
Toast.makeText(OrderActivity.this," " + order.getCount(), LENGTH_SHORT).show();
}
});
orderlist.setAdapter(orderItemAdapter);
picklist = (ListView) findViewById(R.id.picklist);
picklist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int pid = 0;
if (productAdapter.getItem(position).isCategory()) {
pid = productAdapter.getItem(position).getId();
productAdapter.filter(pid);
} else {
OrderItem oi = new OrderItem();
oi.setItemId(productAdapter.getItem(position).getId());
oi.setItem(productAdapter.getItem(position).getItem());
oi.setPrice(productAdapter.getItem(position).getPrice());
search(oi);
}
}
});
httpRequest = new HTTPRequest(this);
httpRequest.execute(url, query);
}
private boolean search(OrderItem oi){
int size = orderItemAdapter.getCount();
int i = 0;
if(size != 0)
for(OrderItem o : orderItemAdapter.getAll()){
if(o.getItemId() == oi.getItemId()){
orderItemAdapter.getItem(i).setQuantity(orderItemAdapter.getItem(i).getQuantity() + 1);
orderItemAdapter.notifyDataSetChanged();
return true;
}
i++;
}
orderItemAdapter.addItem(oi);
orderItemAdapter.notifyDataSetChanged();
return false;
}
private void load(JSONArray json) {
for(int i=0;i<json.length();i++){
try {
JSONObject jo = json.getJSONObject(i);
Product p = new Product(
jo.getInt("ID"),
jo.getInt("parent"),
jo.getInt("category"),
jo.getString("Item"),
jo.getDouble("Price")
);
products.add(p);
} catch (JSONException e) {
e.printStackTrace();
}
}
productAdapter = new ProductAdapter(OrderActivity.this, products);
picklist.setAdapter(productAdapter);
productAdapter.filter(0);
}
#Override
public void onPostExecute(JSONArray Result) {
load(Result);
}
/*
#Override
public void onPostExecute(JSONArray Result) {
json = Result;
}
**/
}
sorry i forgot include this one
//Order.java
public class Order implements Responce{
private Context context;
private JSONArray json = new JSONArray();
private HTTPRequest httpRequest;
private int OrderID;
private Date OrderDate;
private int OrderTable;
private int Waiter;
private byte OrderStatus;
private List<OrderItem> orderItems;
public Order(Context context){
this.context = context;
}
//some code here...
public Integer NewOrder(Integer guests, Integer waiter, Integer ordertable){
String query = "insert into orders(orderdate, guests, waiter, ordertable) VALUES(NOW()," + guests + ", " + waiter + ", " + ordertable + "); SELECT LAST_INSERT_ID() as ID;";
Integer result = 0;
Connect(query);
try {
JSONObject jo = json.getJSONObject(0);
result = jo.getInt("ID");
} catch (JSONException e) {
e.printStackTrace();
}
return result; //here i got 0 if i init result to 0, null or what ever i init my
}
#Override
public void onPostExecute(JSONArray Result) {
json = Result;
}
private void Connect (String query){
httpRequest = new HTTPRequest(context);
httpRequest.execute("http://192.168.3.125:8888/data/", query);
}
}
On the auto load, I need to be able to load more items from the URL. Where I am getting my Data via Json.
in my API call class I need to add to this nuber 10 as:
pairs.add(new BasicNameValuePair("limit", "10"));
Whenever the list view finish loading the currently data, then changes the value above and check again.
I though I needed to create a method in PaginationDemoActivity where it check for if more pages, then use intent to pass a new variable to overwrite ("limit", "10")) in the JSONfunctions class
Any advice ? Thanks guys
JSONfunctions
public class JSONfunctions extends Activity{
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
//Add URL Encoding by sending post data
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("c","getlist"));
pairs.add(new BasicNameValuePair("page","1"));
pairs.add(new BasicNameValuePair("limit", "10"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,HTTP.UTF_8);
httppost.setEntity(entity);
// end Add URL Encoding by sending post data
HttpResponse httpResponse = httpclient.execute(httppost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
//end test
/*
HttpResponse response = httpclient.execute(httppost);
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;
}
}
Data
public class Data {
static String URL = " my api url";
static String itemsPerPage = "20";
public static final String TAG = Data.class.getSimpleName();
public static List<Pair<String, List<Composer>>> getAllData() {
List<Pair<String, List<Composer>>> res = new ArrayList<Pair<String, List<Composer>>>();
for (int i = 0; i < 4; i++) {
res.add(getOneSection(i));
}
return res;
}
public static List<Composer> getFlattenedData() {
List<HashMap<String, String>> arraylist;
JSONObject jsonobject;
JSONArray jsonarray;
List<Composer> res = new ArrayList<Composer>();
//Pair<String, List<Composer>> mydata;
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL(URL);
Log.e("check", jsonobject.toString());
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("data");
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("id", jsonobject.getString("id"));
map.put("title", jsonobject.getString("title"));
map.put("s_desc", jsonobject.getString("s_desc"));
map.put("img", jsonobject.getString("img"));
// Set the JSON Objects into the array
arraylist.add(map);
Composer s = new Composer(
jsonobject.getString("title"),
jsonobject.getString("s_desc"),
jsonobject.getString("id"),
jsonobject.getString("img"));
res.add(s);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return res;
}
protected void updateUrlItems()
{
}
public static Pair<Boolean, List<Composer>> getRows(int page) {
List<Composer> flattenedData = getFlattenedData();
if (page == 1) {
return new Pair<Boolean, List<Composer>>(true, flattenedData.subList(0, 5));
} else {
SystemClock.sleep(2000); // simulate loading
return new Pair<Boolean, List<Composer>>(page * 5 < flattenedData.size(),
flattenedData.subList((page - 1) * 5, Math.min(page * 5, flattenedData.size())));
}
}
public static Pair<String, List<Composer>> getOneSection(int index) {
String[] titles = {"", "", "", ""};
Composer[][] composerss = {
{
new Composer("", "", "", ""),
},
};
return new Pair<String, List<Composer>>(titles[index], Arrays.asList(composerss[index]));
}
}
PaginationDemoActivity
public class PaginationDemoActivity extends Activity {
AmazingListView lsComposer;
PaginationComposerAdapter adapter;
ImageLoader imageLoader;
// Flag for current page
static Integer current_page = 10;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pagination_demo);
imageLoader = new ImageLoader(this);
lsComposer = (AmazingListView) findViewById(R.id.lsComposer);
lsComposer.setLoadingView(getLayoutInflater().inflate(R.layout.loading_view, null));
lsComposer.setAdapter(adapter = new PaginationComposerAdapter());
adapter.notifyMayHaveMorePages();
}
public void bRefresh_click(View v) {
adapter.reset();
adapter.resetPage();
adapter.notifyMayHaveMorePages();
}
class PaginationComposerAdapter extends AmazingAdapter {
List<Composer> list = Data.getRows(1).second;
private AsyncTask<Integer, Void, Pair<Boolean, List<Composer>>> backgroundTask;
public void reset() {
if (backgroundTask != null) backgroundTask.cancel(false);
list = Data.getRows(1).second;
notifyDataSetChanged();
}
#Override
public int getCount() {
return list.size();
}
#Override
public Composer getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
protected void onNextPageRequested(int page) {
Log.d(TAG, "Got onNextPageRequested page=" + page);
if (backgroundTask != null) {
backgroundTask.cancel(false);
}
backgroundTask = new AsyncTask<Integer, Void, Pair<Boolean, List<Composer>>>() {
#Override
protected Pair<Boolean, List<Composer>> doInBackground(Integer... params) {
int page = params[0];
Log.e("more page", "page: " + page);
return Data.getRows(page);
}
#Override
protected void onPostExecute(Pair<Boolean, List<Composer>> result) {
if (isCancelled()) return;
Log.e("onPostExecute", "result: " + result.first);
list.addAll(result.second);
nextPage();
notifyDataSetChanged();
if (result.first) {
// still have more pages
notifyMayHaveMorePages();
} else {
notifyNoMorePages();
}
};
}.execute(page);
}
#Override
protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
}
#Override
public View getAmazingView(int position, View convertView, ViewGroup parent) {
View res = convertView;
if (res == null) res = getLayoutInflater().inflate(R.layout.item_composer, null);
// we don't have headers, so hide it
res.findViewById(R.id.header).setVisibility(View.GONE);
TextView lName = (TextView) res.findViewById(R.id.lName);
TextView lYear = (TextView) res.findViewById(R.id.lYear);
TextView lId = (TextView) res.findViewById(R.id.lId);
// Locate the ImageView in listview_item.xml
ImageView lImg = (ImageView) res.findViewById(R.id.lImg);
Composer composer = getItem(position);
lName.setText(composer.name);
lYear.setText(composer.year);
lId.setText(composer.id);
Log.e("getAmazingView PRINT THE URL 1111111111", "URL: " + composer.img);
// Capture position and set results to the ImageView
// Passes img images URL into ImageLoader.class
imageLoader.DisplayImage(composer.img, lImg);
Log.e("222","333");
//khen
lsComposer.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// TODO Auto-generated method stub
if(id > -1){
Composer composer = adapter.getItem(position);
Intent intent = new Intent();
intent.setClass(getApplicationContext(), SingleItemView.class);
Bundle bundle = new Bundle();
bundle.putString("id", composer.id);
bundle.putString("name", composer.name);
bundle.putString("year", composer.year);
bundle.putString("img", composer.img);
intent.putExtras(bundle);
startActivity(intent);
}
}
});
//end khen
return res;
}
#Override
public void configurePinnedHeader(View header, int position, int alpha) {
}
#Override
public int getPositionForSection(int section) {
return 0;
}
#Override
public int getSectionForPosition(int position) {
return 0;
}
#Override
public Object[] getSections() {
return null;
}
}
}
i have create an android application on where the user can select the start and end point of the location.
This application will use the Google-Direction web service and make the HTTPRequest.
I will make this as short, I want to call the asynctask method in the JSONParser class from the main_activity.
The issue is, I don't know how to display the result in the main_activtiy method
here is the asynctask method
public class JSONParser {
InputStream is = null;
JSONObject jObj = null;
String json = "";
public JSONParser() {
}
public void getJSONFromUrl(final String url, final responseListener target) {
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... params) {
HttpURLConnection httpURLConnection = null;
StringBuilder stringBuilder = new StringBuilder();
try {
httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = inputStreamReader.read(buff)) != -1) {
stringBuilder.append(buff, 0, read);
}
return stringBuilder.toString();
} catch (MalformedURLException localMalformedURLException) {
return "";
} catch (IOException localIOException) {
return "";
} finally {
if (httpURLConnection != null)
httpURLConnection.disconnect();
}
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
target.onResponseComplete(result);
}
}.execute();
}
here is how the main method is calling the method
new JSONParser().getJSONFromUrl(url, new responseListener() {
#Override
public void onResponseComplete(String response) {
try {
ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
JSONArray step = new JSONObject(response).getJSONArray("routes").getJSONObject(0).getJSONArray("legs")
.getJSONObject(0).getJSONArray("steps");
for (int i = 0; i < step.length(); i++) {
HashMap<String,Object> row = new HashMap<String,Object>();
row.put("Distance", step.getJSONObject(i).getJSONObject("distance").getString("text"));
list.add(row);
}
}catch (Exception e){
e.printStackTrace();
}
}
});
}
the issue right know is how i want to display the Arraylist List value and put it into the TextView call jarak
You can change your List to be
ArrayList<HashMap<String, String>>
as you are getting a string from
step.getJSONObject(i).getJSONObject("distance").getString("text")
To get it out you can use (assuming your textview is called jarak)
for(HashMap<String,String> map : list) {
for(Entry<String, String> entry : map.entrySet()) {
jarak.setText(entry.getKey() + ", " + entry.getValue());
}
}
Hope that helps