Best way to send and receive image files in JSON in webservice? - java

Please suggest the best way to send and receive image files using JSON?

Android: Upload image or file using http POST multi-part
By using multi-part , you will be able to upload a file from your SD Card and also Bitmap image as a file.
Prerequisite: httpmime-4.1-beta1.jar
Android SDK uses apache http Client of version 3.0. That does not support for the mime type.
package com.isummation.fileupload;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
public class FileUpload extends Activity {
Bitmap bm;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
// bm = BitmapFactory.decodeResource(getResources(),
// R.drawable.forest);
bm = BitmapFactory.decodeFile("/sdcard/DCIM/forest.png");
executeMultipartPost();
} catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage());
}
}
public void executeMultipartPost() throws Exception {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
"http://10.0.2.2/cfc/iphoneWebservice.cfc?returnformat=json&method=testUpload");
ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg");
// File file= new File("/mnt/sdcard/forest.png");
// FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("uploaded", bab);
reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf"));
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
System.out.println("Response: " + s);
} catch (Exception e) {
// handle exception here
Log.e(e.getClass().getName(), e.getMessage());
}
}
}
See below link:
Multipart Image Upload

Related

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

Unable to get the response from JSON

I am new to android. Well what I am trying to do in the following code is making an http request sending to a php file from where json gets the response. In the php file I am trying to show the city names starting from A. Whenever I am running the code I am getting this error: "org.json.jsonexception value doctype of type java.lang.string cannot be converted to jsonarray". All The related Threads are of no help or i am not able to understand the solution given there.
Here is my Java Code
MainActivity.java
package com.list;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.net.ParseException;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb=null;
int ct_id;
String ct_name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textview1 = (TextView)findViewById(R.id.textView1);
textview1.setText("Erqem");
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/city.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
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,"UTF-8"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
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());
}
//paring data
try{
jArray = new JSONArray(result);
JSONObject json_data = new JSONObject();
json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ct_id=json_data.getInt("CITY_ID");
ct_name=json_data.getString("CITY_NAME");
textview1.setText(ct_name);
}
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "No City Found"+e1.toString() ,Toast.LENGTH_LONG).show();
Log.e("log_tag", "Error converting result "+e1.getMessage() );
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
php file
<?php
header('Content-type=application/json; charset=utf-8');
mysql_connect("","root","");
mysql_select_db("Deal");
$sql=mysql_query("select * from CITY where CITY_NAME like 'A%'");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
Any Help would be appreciated.Thanks.
maybe you are using incorrect address, please try 10.0.2.2:8080/city.php

How to upload an Android image to storage server [duplicate]

i tried to upload the image to the server for two days but i could not post the image .the coding is compiled and run sucessfully but the imag is not write into the server.
this is my coding:
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.Toast;
public class sde extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loadtoUrl("http://
");
}
private void loadtoUrl(String string) {
// TODO Auto-generated method stub
try {
String pathToOurFile = "/sdcard/tamil.PNG";
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );
BufferedInputStream bis = new BufferedInputStream(fileInputStream,3000);
byte[] bt=new byte[bis.available()];
HttpURLConnection connection = (HttpURLConnection)new URL(string).openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.connect();
FileOutputStream input = (FileOutputStream) connection.getOutputStream();
input.write(bt);
} catch (MalformedURLException e) {
Context context = null;
int duration = 0;
Toast.makeText(context, "erro in writing", duration);
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
here is a nice article, http://blog.sptechnolab.com/2011/03/09/android/android-upload-image-to-server/. It contains an example that will upload an image and write it at server side. It works.
public boolean fileUpload(Map<String , String> params, ByteArrayOutputStream file, String link) throws Throwable{
Account user = Util.getAccount(getApplicationContext());
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(link);
MultipartEntity multipartContent = new MultipartEntity();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String , String> entry : params.entrySet()) {
multipartContent.addPart(entry.getKey(),new StringBody(entry.getValue(),Charset.forName(HTTP.UTF_8)));
}
}
byte[] data = file.toByteArray();
ByteArrayBody img = new ByteArrayBody(data, "capture.jpg");
multipartContent.addPart("image",img);
postRequest.setEntity(multipartContent);
HttpResponse res = httpClient.execute(postRequest);
res.getEntity().getContent().close();
return true;
}catch(Throwable e){
throw e;
}
}

Android php+mysql+json error implementing AsyncTask

Im new to Android and I need a little help. I have a class witch values from one table located on remote mysql and its working fine on 2.3 but on 4.x Im getting errors when I start it. I have read somewhere its because I`m not using AsyncTask. I tried to implement it on existing working code but there is one error, so please help because I tried everything to get this to work but no success.
Here is the existing code that works on 2.3
package com.stole.fetchtest;
import java.io.BufferedReader;
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.NameValuePair;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.net.ParseException;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class FetchData extends ListActivity {
#SuppressWarnings("unchecked")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<?> nameValuePairs = new ArrayList<Object>();
List<String> r = new ArrayList<String>();
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.url.com/fetch.php");
httppost.setEntity(new UrlEncodedFormEntity(
(List<? extends NameValuePair>) nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
.show();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"));
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
.show();
}
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
r.add(json_data.getString("names"));
}
setListAdapter(new ArrayAdapter<String>(this, R.layout.names_row, r));
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), e1.toString(), Toast.LENGTH_LONG)
.show();
} catch (ParseException e1) {
Toast.makeText(getBaseContext(), e1.toString(), Toast.LENGTH_LONG)
.show();
}
}}
And then I tried to add AsyncTask, according to some tutorials found online, and it`s looking like this:
package com.stole.fetchtest;
import java.io.BufferedReader;
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.NameValuePair;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class FetchData extends ListActivity {
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<?> nameValuePairs = new ArrayList<Object>();
List<String> r = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new task().execute();
}
public class task extends AsyncTask<String, String, Void> {
#SuppressWarnings("unchecked")
#Override
protected Void doInBackground(String... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.url.com/fetch.php");
httppost.setEntity(new UrlEncodedFormEntity(
(List<? extends NameValuePair>) nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"));
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
return null;
}
protected void onPostExecute(Void v) {
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
r.add(json_data.getString("naziv"));
}
setListAdapter(new ArrayAdapter(this, R.layout.names_row, r));
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), e1.toString(),
Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
Toast.makeText(getBaseContext(), e1.toString(),
Toast.LENGTH_LONG).show();
}
}
}
}
The error I`m getting is at
setListAdapter(new ArrayAdapter(this, R.layout.names_row, r));
and it says "The constructor ArrayAdapter(FetchData.task, int, List) is undefined"
Thanks!
it should use the activity context not the task context..
setListAdapter(new ArrayAdapter(FetchData.this, R.layout.names_row, r));

Android connecting to MySql (PHP Script)

My java code:
package com.Cmode.ThesisSystem;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.net.ParseException;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class EventLogs extends ListActivity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb=null;
int e_id;
String e_name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();{
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.my.com/eventlogs.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
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);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
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());
}
//paring data
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
e_id=json_data.getInt("id");
e_name=json_data.getString("event");
}
}catch(JSONException e1){
Toast.makeText(getBaseContext(), "No events found" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
}
I have a problem with this code
Error:
The application CDroidMonitoring(process.com.Cmode.ThesisSystem) has stopped unexpectedly. Please try again
Im just new to android development. I think I have put something unusable braces or there is something wrong in the code.
Does your application have the INTERNET permission set in the manifest?
And for more information about the error check the logcat tab in Eclipse, it usually has a more descriptive error message.

Categories