How to upgrade from HTTPClient to volley - java

In this class I am sending request to server asynchronously by extending AsyncTask using HttpClient, I have created two custom classes one for Uploading and Downloading of Images from the server, and other for sending JSON Object and array. Beside this I'm also able to differentiate the requests using RequestTag
Can we also do the same using volley?
How can I upgrade to Volley from the HttpClient having same approach like in below class?
package com.creative.projectmanager;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import org.apache.commons.logging.Log;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
/**
* server manager class. performs all server requests asynchronously
*/
public class ServerManager {
final private String SERVER_ADDRESS = "http://192.168.200.10/";
public void login(String email, String password, int requestTag) {
String url = SERVER_ADDRESS + "index.php?mobile/" + "login";
HashMap<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
params.put("authenticate", "false");
android.util.Log.w("My App", email + " " + password + " " + requestTag);
AsyncHttpPost requestSender = new AsyncHttpPost(url, params, requestTag);
requestSender.execute();
}
public void downloadImage(String imageUrl, int imageSize, int requestTag) {
ImageDownloadTask imageDownloadTask = new ImageDownloadTask(imageUrl, imageSize, requestTag);
imageDownloadTask.execute();
}
private class AsyncHttpPost extends AsyncTask<Void, Void, String> {
private String url = "";
private HashMap<String, String> postParams = null;
private int requestTag;
private String errorMessage = "";
public AsyncHttpPost(String url, HashMap<String, String> params, int tag) {
this.url = url;
postParams = params;
this.requestTag = tag;
}
#Override
protected String doInBackground(Void... params) {
byte[] result;
String resultString = "";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<>();
for (String key:postParams.keySet()
) {
nameValuePairs.add(new BasicNameValuePair(key, postParams.get(key)));
}
android.util.Log.w("My App",nameValuePairs.toString());
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpClient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
errorMessage = "ok";
result = EntityUtils.toByteArray(response.getEntity());
resultString = new String(result, "UTF-8");
}
}
catch (UnsupportedEncodingException e) {
errorMessage = "Encoding is not supported";
}
catch (Exception e) {
errorMessage = "An error occurred";
}
return resultString;
}
#Override
protected void onPostExecute(String s) {
if (errorMessage.equals("ok")) {
sourceActivity.requestFinished(s, requestTag);
}
else
sourceActivity.requestFailed(errorMessage, requestTag);
}
}
private class ImageDownloadTask extends AsyncTask<String, String, String> {
private String imageUrl;
private int imageSize;
private int requestTag;
Bitmap image;
public ImageDownloadTask(String imageUrl, int imageSize, int requestTag) {
this.imageUrl = imageUrl;
this.imageSize = imageSize;
this.requestTag = requestTag;
}
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL(imageUrl);
InputStream inputStream = new BufferedInputStream(url.openStream());
image = createScaledBitmapFromStream(inputStream, imageSize);
}
catch (Exception e){
//do nothing
}
return null;
}
#Override
protected void onPostExecute(String s) {
sourceActivity.imageDownloaded(image, requestTag);
}
protected Bitmap createScaledBitmapFromStream(InputStream inputStream, int minimumDesiredBitmapSize) {
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream, 32*1024);
try {
BitmapFactory.Options decodeBitmapOptions = new BitmapFactory.Options();
if (minimumDesiredBitmapSize > 0) {
BitmapFactory.Options decodeBoundsOptions = new BitmapFactory.Options();
decodeBoundsOptions.inJustDecodeBounds = true;
bufferedInputStream.mark(32 * 1024);
BitmapFactory.decodeStream(bufferedInputStream, null, decodeBoundsOptions);
bufferedInputStream.reset();
int originalWidth = decodeBoundsOptions.outWidth;
int originalHeight = decodeBoundsOptions.outHeight;
decodeBitmapOptions.inSampleSize = Math.max(1, Math.min(originalWidth/minimumDesiredBitmapSize, originalHeight/minimumDesiredBitmapSize));
}
return BitmapFactory.decodeStream(bufferedInputStream, null, decodeBitmapOptions);
}
catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
bufferedInputStream.close();
} catch (IOException ignored) {}
}
}
}
}

There are a lot of examples of how to make requests with Volley, so "upgrading" will mean rewriting your code in different way.
Volley, in my opinion is not the best library for HTTP calls, I would recommend you to try
http://square.github.io/retrofit/
for loading images use http://square.github.io/picasso/ or glide. These libraries will help you make you code cleaner whit out boilerplate stuff.

Related

Android - Post image within json object to server using volley library

I want post json object included image to my server using Volley Library it post empty fields to server , image file posted successfully
I should post Json in this formate
{ "user_id":"value" , "post_title":"value","Specialty":"value","post_detail":"value", "uploaded_file","file" }
here is my android code
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import com.imaadv.leaynik.Util.AppConstants;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Created by NT on 10/26/15.
*/
public class PhotoMultipartRequest<T> extends Request<T> {
private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
private Response.Listener<T> mListener;
private File mImageFile;
protected Map<String, String> headers;
private JSONObject params;
private String file_name;
private boolean hasFile;
public PhotoMultipartRequest(JSONObject params, String url, Response.ErrorListener errorListener, Response.Listener<T> listener, String file_name, File imageFile, boolean hasFile) {
super(Method.POST, url, errorListener);
mListener = listener;
mImageFile = imageFile;
this.params = params;
this.file_name = file_name;
this.hasFile = hasFile;
BuildMultiPartEntity();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<>();
}
headers.put("accept", "application/json");
headers.put("Content-type","application/json");
return headers;
}
private void BuildMultiPartEntity() {
// Set keys = params.keySet();
// for (Iterator i = keys.iterator(); i.hasNext(); ) {
// String key = (String) i.next();
// try {
//
// }catch (Exception e){
// e.printStackTrace();
// }
//
// }
StringBody userId = new StringBody(params.get(AppConstants.USER_ID) ,ContentType.APPLICATION_JSON);
StringBody postDetail = new StringBody(params.get(AppConstants.POST_DETAIL) ,ContentType.APPLICATION_JSON);
StringBody postTitle = new StringBody(params.get(AppConstants.POST_TITLE) ,ContentType.APPLICATION_JSON);
StringBody Speciality = new StringBody(params.get(AppConstants.SPECIALTY) ,ContentType.APPLICATION_JSON);
mBuilder.addPart(AppConstants.USER_ID ,userId );
mBuilder.addPart(AppConstants.POST_DETAIL ,postDetail );
mBuilder.addPart(AppConstants.POST_TITLE ,postTitle );
mBuilder.addPart(AppConstants.SPECIALTY ,Speciality );
mBuilder.addTextBody(AppConstants.DATA, params.toString());
if (hasFile) {
mBuilder.addBinaryBody(file_name, mImageFile, ContentType.create("image/jpeg"), mImageFile.getName());
}
mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mBuilder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));
}
#Override
public String getBodyContentType() {
String contentTypeHeader = mBuilder.build().getContentType().getValue();
return contentTypeHeader;
}
#Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
mBuilder.build().writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream bos, building the multipart request.");
}
return bos.toByteArray();
}
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
T result = null;
return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
}
#Override
protected void deliverResponse(T response) {
mListener.onResponse(response);
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
Log.i("Error1", volleyError.getMessage());
return super.parseNetworkError(volleyError);
}
#Override
public void deliverError(VolleyError error) {
Log.i("Error2", error.getMessage());
super.deliverError(error);
}
}
Could any one guide me what is wrong in my code
You can see your answer on follow this 3 link.....
Click here
http://www.survivingwithandroid.com/2013/05/android-http-downlod-upload-multipart.html
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
https://www.simplifiedcoding.net/android-volley-tutorial-to-upload-image-to-server/
Best Luck..

Getting StackOverFlowError in Android over a Recursive Call while trying to parse JSON Data

I am trying to learn how to parse JSON data in Android. I referred to a tutorial here: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
All I got was a StackOverFlowError whose resolution I am unable to figure out. Any help with this will be appreciated. You can find all the relevant Java code below. Please feel free to tell me if you need the code for XML files as well.
Code for ServiceHandler class:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
/**
* Created by on 02-07-2015.
*/
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method);
}
public String makeServiceCall(String url, int method, List<NameValuePair> params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
if (params != null) {
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
} catch (UnsupportedEncodingException ue) {
ue.printStackTrace();
} catch (ClientProtocolException ce) {
ce.printStackTrace();
} catch (IOException io) {
io.printStackTrace();
}
return response;
}
}
Code for JSONActivity Activity:
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by on 03-07-2015.
*/
public class JSONActivity extends ListActivity {
private ProgressDialog pDialog;
private static String url = "http://api.androidhive.info/contacts/";
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
JSONArray contacts=null;
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webservicestrial);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(JSONActivity.this);
pDialog.setMessage("Fetching...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (pDialog.isShowing())
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(
JSONActivity.this, contactList,
R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL,
TAG_PHONE_MOBILE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
#Override
protected Void doInBackground(Void... params) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(url,ServiceHandler.GET);
Log.d("Response:", ">"+jsonStr);
if (jsonStr!=null) {
try {
JSONObject jsonObject = new JSONObject(jsonStr);
contacts = jsonObject.getJSONArray(TAG_CONTACTS);
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
contact.put(TAG_PHONE_MOBILE, mobile);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
}else {Log.e("ServiceHandler", "Couldn't get any data from the url");}
return null;
}
}
}
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method);
}
This method is calling itself, hence resulting in a Stack overflow. You probably meant to access the other makeServiceCall method. Therefore you have to add the List<NameValuePair> param
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method);
}
This is an infinite loop. You have to add the third parameter (List<NameValuePair>) when calling the method, for example:
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, new ArrayList<NameValuePair>());
}

How to add a Parsed JSON image from URL to imageView Dynamically?

I have the following code and i like to add my parsed JSON image from URL to my ImageView I don't know how to do it and my code is the following (I get responce and the other data go the desired TextViews):
DisplaySearchResultsActivity.java
package com.cloudlionheart.museumsearchapplication;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class DisplaySearchResultsActivity extends ListActivity
{
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> museumItemsList;
// url to get all products list
private static String url_search_results = "http://10.0.3.2/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_MUSEUM_ITEMS = "museumItems";
private static final String TAG_MUSEUM_ITEM_ID = "id";
private static final String TAG_MUSEUM_ITEM_NAME = "itemName";
private static final String TAG_MUSEUM_ITEM_ARTIST = "artistName";
private static final String TAG_MUSEUM_ITEM_LOCATION = "itemLocation";
private static final String TAG_MUSEUM_ITEM_HISTORICAL_PERIOD = "itemHistoricalPeriod";
private static final String TAG_MUSEUM_ITEM_IMAGE = "itemImage";
// products JSONArray
JSONArray museumItems = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_search_resaults);
// Hashmap for ListView
museumItemsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
}
/**
* Background Async Task to Load all product by making HTTP Request
*/
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DisplaySearchResultsActivity.this);
pDialog.setMessage("Loading Museum Items. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected String doInBackground(String... args)
{
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_search_results, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Museum Items: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
museumItems = json.getJSONArray(TAG_MUSEUM_ITEMS);
// looping through All Products
for (int i = 0; i < museumItems.length(); i++)
{
JSONObject c = museumItems.getJSONObject(i);
// Storing each json item in variable
String item_id = c.getString(TAG_MUSEUM_ITEM_ID);
String item_name = c.getString(TAG_MUSEUM_ITEM_NAME);
String item_artist = c.getString(TAG_MUSEUM_ITEM_ARTIST);
String item_historic_period = c.getString(TAG_MUSEUM_ITEM_HISTORICAL_PERIOD);
String item_location = c.getString(TAG_MUSEUM_ITEM_LOCATION);
String list_image = c.getString(TAG_MUSEUM_ITEM_IMAGE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_MUSEUM_ITEM_ID, item_id);
map.put(TAG_MUSEUM_ITEM_NAME, item_name);
map.put(TAG_MUSEUM_ITEM_ARTIST, item_artist);
map.put(TAG_MUSEUM_ITEM_HISTORICAL_PERIOD, item_historic_period);
map.put(TAG_MUSEUM_ITEM_LOCATION, item_location);
map.put(TAG_MUSEUM_ITEM_IMAGE, list_image);
// adding HashList to ArrayList
museumItemsList.add(map);
}
}
} 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(
DisplaySearchResultsActivity.this, museumItemsList,
R.layout.list_item, new String[]{TAG_MUSEUM_ITEM_ID,
TAG_MUSEUM_ITEM_NAME, TAG_MUSEUM_ITEM_ARTIST,
TAG_MUSEUM_ITEM_HISTORICAL_PERIOD, TAG_MUSEUM_ITEM_LOCATION,
TAG_MUSEUM_ITEM_IMAGE},
new int[]{R.id.museum_item_id, R.id.museum_item_name,
R.id.museum_item_artist, R.id.museum_item_historic_period,
R.id.museum_item_location, R.id.museum_list_image});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
and my other class
JSONParser.java
package com.cloudlionheart.museumsearchapplication;
/**
* Created by CloudLionHeart on 5/7/2015.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
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;
}
}
Using Picasso:
Picasso.with(context)
.load(imageUrl)
.into(imageView);
You can use image loader library to load image dynamically into imageview.
As it given easy documentation, just follow it. You have to pass url of image.
I Hope it will help you..!
public class LoadImageFromURL extends AsyncTask{
#Override
protected Bitmap doInBackground(String... params) {
try {
URL url = new URL("image-url");
InputStream is = url.openConnection().getInputStream();
Bitmap bitMap = BitmapFactory.decodeStream(is);
return bitMap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
yourImageview.setImageBitmap(result);
}
}
<uses-permission android:name="android.permission.INTERNET"/>
add Permission into you manifest.

Calling async task class not working

I'm sure I am doing something wrong, new to Android, I already have the URL stored in a string in a for loop, need to grab the image from that URL using AsyncTask. Quite new to Android so I am running into some issues. Any help is appreciated.
SecondClass.java
package edu.colum.iam.JSON;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class SecondClass extends Activity {
private TextView first, second, third;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
first = (TextView)findViewById(R.id.firsttv);
second = (TextView)findViewById(R.id.secondtv);
third = (TextView)findViewById(R.id.thirdtv);
String id = getIntent().getStringExtra("id");
System.out.println(id);
String response = readBuilding(id.trim());
System.out.println(response);
try {
JSONObject jsonObj = new JSONObject(response);
if(jsonObj.length()>0)
{
String CourseName = jsonObj.getString("CourseName");
String CourseNumber = jsonObj.getString("CourseNumber");
String CourseDescription = jsonObj.getString("CourseDescription");
JSONArray arrayOfImages = jsonObj.getJSONArray("Images");
String theImage = arrayOfImages.get(0).toString(); //getting first image in the array and returning the link as a string
int arrSize = arrayOfImages.length();
List<String> urlOfImage = new ArrayList<String>(arrSize);
first.setText("CourseName:- "+CourseName);
second.setText("CourseNumber:- "+CourseNumber);
third.setText("CourseDescription:- "+CourseDescription);
for(int i = 0; i < arrayOfImages.length(); ++i)
{
theImage = arrayOfImages.get(i).toString();
urlOfImage.add(theImage);
ImageDownloadTask(theImage);
}
}
} catch (Exception e){
e.printStackTrace();
}
}
public String readBuilding(String id)
{
return postJSON("http://iam.colum.edu/portfolio/api/course/"+id+"?json=True");
}
private String postJSON(String stringURL) {
StringBuilder builder = new StringBuilder();
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(stringURL);
try {
httpget.addHeader("Content-Type","application/json; charset=utf-8");
HttpResponse response = httpclient.execute(httpget);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
}
ImageDownloadTask.java
package edu.colum.iam.JSON;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;
public class ImageDownloadTask extends AsyncTask<String, Void, Bitmap> {
/** The url from where to download the image. */
private String url;
/** Reference to the view which should receive the image */
private final WeakReference<ImageView> imageRef;
/**
* Constructor.
*
* #param imageView
* The ImageView which will receive the image.
*/
public ImageDownloadTask(ImageView imageView) {
imageRef = new WeakReference<ImageView>(imageView);
}
/**
* This function will be executed to download the image in a background
* process.
*
*/
#Override
protected Bitmap doInBackground(String... params) {
try {
InputStream in = new java.net.URL(url).openStream();
Bitmap bitmap = BitmapFactory.decodeStream(in);
return bitmap;
} catch (Exception e) {
Log.e("ImageDownload", e.getMessage());
}
return null;
}
/**
* This function will be called after the image download and attaches
* the bitmap to the ImageView.
*
*/
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageRef != null) {
ImageView imageView = imageRef.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}
There might be more issues here (such as possibly accessing network on main thread?), but this ImageDownloadTask(theImage); won't actually execute your AsyncTask. It shouldn't even compile. You'd want something like new ImageDownloadTask(theImage).execute();
For downloading images by URL I recommend to use third part libraries. For example Picasso (http://square.github.io/picasso).
To download image you just need to write this:
Picasso.with(SecondClass.this).load(url).into(imageView);

Sending Parameters to .net Restful WebService from Android

I am trying to send an invoke a webservice method that took a jagged array as a parameters. I build the array, but it always passed null to the web service.
Here is my java class:
package com.mitch.wcfwebserviceexample;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity implements OnClickListener {
private String values ="";
Button btn;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button)this.findViewById(R.id.btnAccess);
tv = (TextView)this.findViewById(R.id.tvAccess);
btn.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
try
{
AsyncTaskExample task = new AsyncTaskExample(this);
task.execute("");
String test = values;
tv.setText(values);
} catch(Exception e)
{
Log.e("Click Exception ", e.getMessage());
}
}
public class AsyncTaskExample extends AsyncTask<String, Void,String>
{
private String Result="";
//private final static String SERVICE_URI = "http://10.0.2.2:1736";
private final static String SERVICE_URI = "http://10.0.2.2:65031/SampleService.svc";
private MainActivity host;
public AsyncTaskExample(MainActivity host)
{
this.host = host;
}
public String GetSEssion(String URL)
{
boolean isValid = true;
if(isValid)
{
String[][] val = {
new String[] {"Student.ID","123456"},
new String[] {"Student.username","user1"},
new String[] {"Student.password","123456"},
new String[] {"Student.location.id","12"}
};
HttpPost requestAuth = new HttpPost(URL +"/Login");
try
{
JSONObject json = new JSONObject();
// json.put("sessionId", sessionId);
JSONArray params = new JSONArray();
params.put(val);
json.put("authenParams", params);
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
requestAuth.setHeader("Accept","application/json");
requestAuth.setEntity(se);
DefaultHttpClient httpClientAuth = new DefaultHttpClient();
HttpResponse responseAuth = httpClientAuth.execute(requestAuth);
HttpEntity responseEntityAuth = responseAuth.getEntity();
char[] bufferAuth = new char[(int)responseEntityAuth.getContentLength()];
InputStream streamAuth = responseEntityAuth.getContent();
InputStreamReader readerAuth = new InputStreamReader(streamAuth);
readerAuth.read(bufferAuth);
streamAuth.close();
String rawAuthResult = new String(bufferAuth);
Result = rawAuthResult;
String d = null;
// }
} catch (ClientProtocolException e) {
Log.e("Client Protocol", e.getMessage());
} catch (IOException e) {
Log.e("Client Protocol", e.getMessage() );
} catch(Exception e)
{
Log.e("Client Protocol", e.getMessage() );
}
}
return Result;
}
#Override
protected String doInBackground(String... arg0) {
android.os.Debug.waitForDebugger();
String t = GetSEssion(SERVICE_URI);
return t;
}
#Override
protected void onPostExecute(String result) {
// host.values = Result;
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected void onCancelled() {
// TODO Auto-generated method stub
super.onCancelled();
}
}
}
Below is my method that is supposed to recieve the parameter:
I put a break point in the code below and check it. The parameter is always null.
public string Login(string[][] value)
{
string[] tester = null;
string testerExample="";
foreach (string[] st in value)
{
tester = st;
}
foreach (string dt in tester)
{
testerExample = dt;
}
return testerExample;
}
Here is the method declaration in IStudentService:
[OperationContract]
[WebInvoke(
Method="POST", UriTemplate="Login", BodyStyle= WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
string Login(string[][] value);
I tried to as you suggested, and it did not work. It return "Request Error"
Here is the sample code that I paste.
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://10.0.2.2:65031/SampleService.svc/login");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("tester","abcd"));
pairs.add(new BasicNameValuePair("sampletest","1234"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,HTTP.UTF_8);
post.setEntity(entity);
HttpResponse response = client.execute(post);
HttpEntity responseEntity = response.getEntity();
char[] buffer = new char[(int)responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer); stream.close();
String value = new String(buffer);
I finally got it to work they way that I want it to. The issue was that I was building the Array this way (see below section 1) and pass it to the JSONObject or JSONArray. I switched and build the Array using JSONArray and pass it to the JSONObject (see section 2). It works like a charm.
Section1:
Wrong way to do it - (It may work this way if you were to look through the array and put them in a JSONArray. It's will be too much work when it can be done directly.)
String[][] Array = {
new String[]{"Example", "Test"},
new String[]{"Example", "Test"},
};
JSONArray jar1 = new JSONArray();
jar1.put(0, Array); **// Did not work**
Section 2:
The way I did it after long hours of trying and some very helpful tips and hints from #vorrtex.
JSONArray jar1 = new JSONArray();
jar1.put(0, "ABC");
jar1.put(1, "Son");
jar1.put(2, "Niece");
JSONArray jarr = new JSONArray();
jarr.put(0, jar1);
JSONArray j = new JSONArray();
j.put(0,"session");
JSONObject obj = new JSONObject();
obj.put("value", jarr);
obj.put("test", j);
obj.put("name","myName");
Log.d("Obj.ToString message: ",obj.toString());
StringEntity entity = new StringEntity(obj.toString());
Looking at the web service, and it has exactly what I was looking for.
Thanks for you help!!!!

Categories