I am writing an app to upload images to my server from gallery and from camera
the problem I am having is when i take a picture from the camera and I click my upload button it crashes out of the app
according to the debug logs it has something to do with the bitmap pointing to a null object refrence as well as bitmap failing to decode the stream
there are a few answers on SO pretaining to this but non have worked so far
Error log
E/BitmapFactory: Unable to decode stream: java.lang.NullPointerException
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.smartpractice.myapplication, PID: 18010
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
at com.smartpractice.myapplication.MainActivity.upload(MainActivity.java:79)
at com.smartpractice.myapplication.MainActivity.access$100(MainActivity.java:41)
at com.smartpractice.myapplication.MainActivity$2.onClick(MainActivity.java:67)
at android.view.View.performClick(View.java:6663)
at android.view.View.performClickInternal(View.java:6635)
at android.view.View.access$3100(View.java:794)
at android.view.View$PerformClick.run(View.java:26199)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7593)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
Activity java
public class MainActivity extends Activity {
Button btpic, btnup;
private Uri fileUri;
String picturePath;
Uri selectedImage;
Bitmap photo;
String ba1;
public static String URL = "Paste your URL here";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btpic = (Button) findViewById(R.id.cpic);
btpic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickpic();
}
});
btnup = (Button) findViewById(R.id.up);
btnup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
upload();
}
});
}
private void upload() {
// Image location URL
Log.e("path", "----------------" + picturePath);
// Image
Bitmap bm = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 0, bao);
byte[] ba = bao.toByteArray();
ba1 = Base64.encodeToString(ba, Base64.NO_WRAP);
Log.e("base64", "-----" + ba1);
// Upload image to server
new uploadToServer().execute();
}
private void clickpic() {
// Check Camera
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// Open default camera
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, 100);
} else {
Toast.makeText(getApplication(), "Camera not supported", Toast.LENGTH_LONG).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100 && resultCode == RESULT_OK) {
selectedImage = data.getData();
photo = (Bitmap) data.getExtras().get("data");
Bitmap photo = (Bitmap) data.getExtras().get("data");
ImageView imageView = (ImageView) findViewById(R.id.Imageprev);
imageView.setImageBitmap(photo);
}
}
public class uploadToServer extends AsyncTask<Void, Void, String> {
private ProgressDialog pd = new ProgressDialog(MainActivity.this);
protected void onPreExecute() {
super.onPreExecute();
pd.setMessage("Wait image uploading!");
pd.show();
}
#Override
protected String doInBackground(Void... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("base64", ba1));
nameValuePairs.add(new BasicNameValuePair("ImageName", System.currentTimeMillis() + ".jpg"));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String st = EntityUtils.toString(response.getEntity());
Log.v("log_tag", "In the try Loop" + st);
} catch (Exception e) {
Log.v("log_tag", "Error in http connection " + e.toString());
}
return "Success";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
pd.hide();
pd.dismiss();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==REQUEST_CAMERA)
{
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),"temp.jpg");
FileOutputStream fo;
try {
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
new uploadFileToServerTask().execute(destination.getAbsolutePath());
}
}
Uploading File to server
private class uploadFileToServerTask extends AsyncTask<String, String, Object> {
#Override
protected String doInBackground(String... args) {
try {
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
#SuppressWarnings("PointlessArithmeticExpression")
int maxBufferSize = 1 * 1024 * 1024;
java.net.URL url = new URL((ApplicationConstant.UPLOAD_IMAGE_URL) + IMAGE + customer_id);
Log.d(ApplicationConstant.TAG, "url " + url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs.
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Set HTTP method to POST.
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
FileInputStream fileInputStream;
DataOutputStream outputStream;
{
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
String filename = args[0];
outputStream.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + filename + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
Log.d(ApplicationConstant.TAG, "filename " + filename);
fileInputStream = new FileInputStream(filename);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
}
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.d("serverResponseCode", "" + serverResponseCode);
Log.d("serverResponseMessage", "" + serverResponseMessage);
fileInputStream.close();
outputStream.flush();
outputStream.close();
if (serverResponseCode == 200) {
return "true";
}
} catch (Exception e) {
e.printStackTrace();
}
return "false";
}
#Override
protected void onPostExecute(Object result) {
}
}
Related
I try to capture a image by intenting camera and set that as a profile picture in my app.
Camera captures images but picture nothing is set in profile, still blank and want to upload that picture to my server.
While reading the picture by DataInputStream it says, "The method readLine() from the type DataInputStream is deprecated".
Help me to resolve this problem.
Here is my code is:
public void settings(){
AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(SignUp.this);
alertDialog2.setTitle("");
alertDialog2.setMessage("Please select an image..");
alertDialog2.setIcon(R.drawable.act_camera);
alertDialog2.setPositiveButton("CAMERA.",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
condition="from_camera";
pd = ProgressDialog.show(SignUp.this, "", "Please wait...", true);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAM_REQUREST);
}
});
alertDialog2.setNegativeButton("GALLERY.",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
condition="from_gallery";
pd = ProgressDialog.show(SignUp.this, "", "Please wait...", true);
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
alertDialog2.show();
}
#JavascriptInterface
public void showCustomAlert() {
// TODO Auto-generated method stub
Context context = getApplicationContext();
// Create layout inflator object to inflate toast.xml file
LayoutInflater inflater = getLayoutInflater();
// Call toast.xml file for toast layout
View toastRoot = inflater.inflate(R.layout.toast, null);
Toast toast = new Toast(context);
// Set layout to toast
toast.setView(toastRoot);
toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL,
0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAM_REQUREST)
{
bitmap_profile_image = (Bitmap) data.getExtras().get("data");
imagepath = ImageWrite(bitmap_profile_image);
pd.dismiss();
}
else if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data)
{
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
cursor.close();
john.setImageBitmap(thumbnail);
System.out.println("Step--------->1");
pd1 = ProgressDialog.show(SignUp.this, "", "Please wait...", true);
System.out.println("Step--------->1");
imagepath = ImageWrite(thumbnail);
pd1.dismiss();
pd.dismiss();
Log.w("path of image from gallery......*******.....", picturePath+"");
}
else{
}
Imageuploading();
}
public String ImageWrite(Bitmap bitmap1)
{
//pd = ProgressDialog.show(context,null, "Please wait...",true);
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
File file = new File(extStorageDirectory, "slectimage.PNG");
try
{
outStream = new FileOutputStream(file);
bitmap1.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
pd.dismiss();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
pd.dismiss();
} catch (IOException e)
{
e.printStackTrace();
pd.dismiss();
}
String imageInSD = "/sdcard/slectimage.PNG";
pd.dismiss();
return imageInSD;
}
protected void Imageuploading() {
// TODO Auto-generated method stub
pd1 = ProgressDialog.show(this,null, "Please wait...",true);
try{
Log.e("SANGUUU", "dfdf");
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
String pathToOurFile = (String) imagepath;
System.out.println("patho our file"+pathToOurFile);
//String urlServer = "http://demo.cogzideltemplates.com/client/snapchat-clone/index.php/user/image_upload";
String urlServer = "http://demo.cogzidel.com/sedio/mobile/image_upload";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
System.out.println("test");
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
URL serverResponseMessage1 = connection.getURL();
System.out.println("url value"+serverResponseMessage1);
connection.getResponseMessage();
// Toast.makeText(getApplicationContext(), serverResponseMessage, Toast.LENGTH_LONG).show();
System.out.println("image"+serverResponseMessage);
int len=connection.getContentLength();
System.out.println("Length of url--->1"+len);
fileInputStream.close();
outputStream.flush();
outputStream.close();
DataInputStream inputStream1 = null;
inputStream1 = new DataInputStream (connection.getInputStream());
String str="";
String Str1_imageurl="";
while (( str = inputStream1.readLine()) != null) // here getting deprecated error
{
Log.e("Debug","Server Response "+str);
Str1_imageurl = str;
Log.e("Debug","Server Response String imageurl"+str);
}
inputStream1.close();
System.out.println("image url"+Str1_imageurl);
// Toast.makeText(getApplicationContext(), Str1_imageurl, Toast.LENGTH_LONG).show();
pd1.dismiss();
stry=Str1_imageurl.trim();
}
catch(Exception e){
e.printStackTrace();
}
}
//create helping method cropCapturedImage(Uri picUri)
public void cropCapturedImage(Uri picUri){
//call the standard crop action intent
Intent cropIntent = new Intent("com.android.camera.action.CROP");
//indicate image type and Uri of image
cropIntent.setDataAndType(picUri, "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
//indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
//indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
//retrieve data on return
cropIntent.putExtra("return-data", true);
//start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, 2);
}
Onclick of Button Open a Camera
// Util.TEMP_PHOTO_FILE_NAME is String file name ;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mFileTemp = new File(Environment
.getExternalStorageDirectory(),
Util.TEMP_PHOTO_FILE_NAME);
} else {
mFileTemp = new File(getApplicationContext().getFilesDir(),
Util.TEMP_PHOTO_FILE_NAME);
}
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
Uri mImageCaptureUri = null;
// String state = Environment.getExternalStorageState();
if (mFileTemp == null) {
System.out.println("no file found");
} else {
System.out.println("file found");
}
if (Environment.MEDIA_MOUNTED.equals(state)) {
mImageCaptureUri = Uri.fromFile(mFileTemp);
} else {
mImageCaptureUri = InternalStorageContentProvider.CONTENT_URI;
}
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
intent.putExtra("return-data", true);
startActivityForResult(intent, SELECT_CAMERA_IMAGE_REQUEST);
/*
* Intent cameraIntent = new
* Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
* startActivityForResult(cameraIntent,
* SELECT_CAMERA_IMAGE_REQUEST);
*/
} catch (ActivityNotFoundException e) {
Log.d("Tag", "cannot take picture", e);
}
onActivityResult:
private File picfile;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_CAMERA_IMAGE_REQUEST
&& resultCode == Activity.RESULT_OK) {
picfile = mFileTemp;
postFlagFileCheck = 1;
bitmap_postImage = BitmapFactory.decodeFile(picfile
.getAbsolutePath());
setImagePreview(bitmap_postImage);
}
}
sending that Image file to server
HttpClient httpclient;
httpclient = HttpClientSingalTon.getHttpClienttest();
HttpPost httpPostRequest = new HttpPost(URL);
// Try This
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(yourimagefile, "image/jpeg");
mpEntity.addPart("file", cbFile);
httpPostRequest.setEntity(mpEntity);
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
u have to use these libs
http://www.java2s.com/Code/Jar/h/Downloadhttpmime401jar.htm
http://www.java2s.com/Code/Jar/a/Downloadapachemime4j06jar.htm
If you are able to get path of the image then try to fetch the image form that path.
There is an alternative to upload the image on server. You can convert the image into Sting using Base64 encoding and send that string via JSON to your server.
I can't insert caption on my project, I want my project can upload image and insert some data to database on web server, I can insert but my data have an duplicate.. please help me....
Here source code for MainActivity.java
public class MainActivity extends Activity implements OnClickListener{
private TextView messageText;
private EditText Txnama, Txtanggal, Txcaption;
private Button uploadButton, btnselectpic;
private ImageView imageview;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;
private String upLoadServerUri = null;
private String imagepath=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uploadButton = (Button)findViewById(R.id.uploadButton);
btnselectpic = (Button)findViewById(R.id.button_selectpic);
messageText = (TextView)findViewById(R.id.messageText);
imageview = (ImageView)findViewById(R.id.imageView_pic);
Txnama = (EditText)findViewById(R.id.nama);
Txtanggal = (EditText)findViewById(R.id.tanggal);
Txcaption = (EditText)findViewById(R.id.caption);
btnselectpic.setOnClickListener(this);
uploadButton.setOnClickListener(this);
upLoadServerUri = "http://aplikasilaras.esy.es/php/Uploadcoba.php";
ImageView img= new ImageView(this);
}
#Override
public void onClick(View arg0) {
if(arg0==btnselectpic)
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
}
else if (arg0==uploadButton) {
dialog = ProgressDialog.show(MainActivity.this, "", "Uploading file...", true);
messageText.setText("uploading started.....");
new Thread(new Runnable() {
public void run() {
uploadFile(imagepath);
}
}).start();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
//Bitmap photo = (Bitmap) data.getData().getPath();
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
imageview.setImageBitmap(bitmap);
messageText.setText("Uploading file path:" +imagepath);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"+imagepath);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"+ imagepath);
}
});
return 0;
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+" F:/wamp/wamp/www/uploads";
messageText.setText(msg);
Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(MainActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
}
Try to change php code with this, it's work on me.
<?php
$conn = mysql_connect('YOUR_HOST', 'YOUR_USERNAME', 'YOUR_PASSWORD') or die(mysql_error());
$db = mysql_select_db('YOUR_DB_NAME') or die(mysql_error());
$file_path = "uploads/"; //YOUR FOLDER FOR SAVING IMAGE, MY FOLDER NAME IS uploads
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
$query = "insert into YOUR_TABLE_NAME values('', '$file_path')";
mysql_query($query);
echo "success";
} else{
echo "fail";
}
?>
I am still a beginner of Andorid programming and would need some help to the following:
What I currently have are 2 codes, which the first uploads an image to the server and stores the path into a MySQL table. The second code stores 2 EditText field values into a MySQL database table.
What I actually want is to combine both codes, so it should be possible to upload an image to the server and then store the associated string path with 2 EditText field values into a MySQL database table at once.
1.) For uploading image and to store the string path into MySQL table I have following codes:
-Upload Image to server (JAVA side):
public class MainActivity extends Activity implements OnClickListener {
private TextView messageText;
private Button uploadButton, btnselectpic;
private ImageView imageview;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;
private String upLoadServerUri = null;
private String imagepath = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uploadButton = (Button) findViewById(R.id.uploadButton);
btnselectpic = (Button) findViewById(R.id.button_selectpic);
messageText = (TextView) findViewById(R.id.messageText);
imageview = (ImageView) findViewById(R.id.imageView_pic);
btnselectpic.setOnClickListener(this);
uploadButton.setOnClickListener(this);
upLoadServerUri = "http://10.0.2.2/uploads/UploadToServer.php";
ImageView img = new ImageView(this);
}
#Override
public void onClick(View arg0) {
if (arg0 == btnselectpic) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Complete action using"), 1);
} else if (arg0 == uploadButton) {
dialog = ProgressDialog.show(MainActivity.this, "",
"Uploading file...", true);
messageText.setText("uploading started.....");
new Thread(new Runnable() {
public void run() {
uploadFile(imagepath);
}
}).start();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
// Bitmap photo = (Bitmap) data.getData().getPath();
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
Bitmap bitmap = BitmapFactory.decodeFile(imagepath);
imageview.setImageBitmap(bitmap);
messageText.setText("Uploading file path:" + imagepath);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :" + imagepath);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :" + imagepath);
}
});
return 0;
} else {
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if (serverResponseCode == 200) {
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+ " F:/wamp/wamp/www/uploads";
messageText.setText(msg);
Toast.makeText(MainActivity.this,
"File Upload Complete.", Toast.LENGTH_SHORT)
.show();
}
});
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText
.setText("MalformedURLException Exception : check script url.");
Toast.makeText(MainActivity.this,
"MalformedURLException", Toast.LENGTH_SHORT)
.show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(MainActivity.this,
"Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
}
-Upload Image to server and store string path (PHP side):
$file_path = "uploads/";
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
// replace $host,$username,$password,$dbname with real info
$link=mysqli_connect($host,$username,$password,$dbname);
mysqli_query($link,"INSERT INTO `files` (filename,path) VALUES ('".$_FILES['uploaded_file']['tmp_name']."','".$file_path."')") or trigger_error($link->error."[ $sql]");
mysqli_close($link);
} else{
echo "fail";
2.) For inserting EditText values from Android to MySQL Database I have following codes:
-Insert values to MySQL database table (JAVA side):
public class MainActivity extends Activity {
String name;
String id;
InputStream is=null;
String result=null;
String line=null;
int code;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText e_id=(EditText) findViewById(R.id.editText1);
final EditText e_name=(EditText) findViewById(R.id.editText2);
Button insert=(Button) findViewById(R.id.button1);
insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
id = e_id.getText().toString();
name = e_name.getText().toString();
insert();
}
});
}
public void insert()
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id",id));
nameValuePairs.add(new BasicNameValuePair("name",name));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/insert.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
JSONObject json_data = new JSONObject(result);
code=(json_data.getInt("code"));
if(code==1)
{
Toast.makeText(getBaseContext(), "Inserted Successfully",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Sorry, Try Again",
Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
-Insert values to MySQL database table (PHP side):
<?php
$host='127.0.0.1';
$uname='root';
$pwd='password';
$db="android";
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
$id=$_REQUEST['id'];
$name=$_REQUEST['name'];
$flag['code']=0;
if($r=mysql_query("insert into sample values('$id','$name') ",$con))
{
$flag['code']=1;
echo"hi";
}
print(json_encode($flag));
mysql_close($con);
?>
HOW CAN I COMBINE 1.) and 2.)? I tried it almost 3 days but it simply does not work and I despair :S. Hope somebody can help.
Thanks in advance.
Combine these two code file in same activity first by calling them in two different functions
and on uploading image file take image name from imagepath string using substring function
and send that image name along with JSON data and in server side while inserting store that image path in the format ip_address/image_upload_folder/imagename.
I am having trouble figuring out how to pass the image's uri as I need it to grab the file unless there is another way and I just don't see it (I am pretty new to this). I have the image selected working and setting the imageview's bitmap to the bitmap but now trying to have it be send to the server once the submit button is clicked.
I know I can do execute(uri); but how do I actually pull out the uri from the imageview?
Here is the code : )
public class wardrobe extends Activity implements OnClickListener {
// set variable for the fields
private EditText nameField, sizeField, colorField, quantityField;
private Spinner typeField, seasonField;
private ImageView imageview;
private ProgressBar progressBarField;
private TextView imageTextSelect, resImage;
private ProgressDialog progressDialog = null;
private int serverResponseCode = 0;
private Button uploadImageButton, postWardrobe;
private String upLoadServerUri = null;
private String imagepath = null;
private Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wardrobe);
// image upload stuff
imageview = (ImageView) findViewById(R.id.user_photo);
imageTextSelect = (TextView) findViewById(R.id.imageTextSelect);
// button for upload image
uploadImageButton = (Button) findViewById(R.id.uploadImageButton);
// button for posting details
postWardrobe = (Button) findViewById(R.id.postButton);
uploadImageButton.setOnClickListener(this);
postWardrobe.setOnClickListener(this);
#Override
public void onClick(View v) {
/**
* Opens dialog picker, so the user can select image from the gallery.
* The result is returned in the method <code>onActivityResult()</code>
*/
if (v == uploadImageButton) {
// below allows you to open the phones gallery
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Complete action using"), 1);
}
if (v == postWardrobe) {
// execute the post request
new ImageUploadTask().execute();
}
}
}
/**
* Retrives the result returned from selecting image, by invoking the method
* <code>selectImageFromGallery()</code>
*/
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == 1 && null != data) {
decodeUri(data.getData());
}
}
public void decodeUri(Uri uri) {
ParcelFileDescriptor parcelFD = null;
try {
parcelFD = getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor imageSource = parcelFD.getFileDescriptor();
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(imageSource, null, o);
// the new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) {
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFileDescriptor(imageSource, null, o2);
imageview.setImageBitmap(bitmap);
// can take off below just shows path
imageTextSelect.setText("select : " + uri);
} catch (FileNotFoundException e) {
// handle errors
} catch (IOException e) {
// handle errors
} finally {
if (parcelFD != null)
try {
parcelFD.close();
} catch (IOException e) {
// ignored
}
}
}
PART I AM TRYING TO GET WORKING : )
private class ImageUploadTask extends AsyncTask<Void, Void, String> {
What I need is the uri or the file...
String fileName = imagepath;
File sourceFile = new File(imagepath);
private String webAddressToPost = "http://10.0.2.2/wardrobe";
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
// private ProgressDialog dialog
private ProgressDialog progressDialog = new ProgressDialog(
wardrobe.this);
#Override
protected void onPreExecute() {
progressDialog.setMessage("Uploading...");
progressDialog.show();
}
#Override
protected String doInBackground(Void... arg0) {
if (!sourceFile.isFile()) {
progressDialog.dismiss();
Log.e("uploadFile", "Source File not exist :" + imagepath);
runOnUiThread(new Runnable() {
public void run() {
imageTextSelect.setText("Source File not exist :"
+ imagepath);
}
});
return 0;
} else {
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if (serverResponseCode == 200) {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+ " F:/wamp/wamp/www/uploads";
imageTextSelect.setText(msg);
Toast.makeText(wardrobe.this,
"File Upload Complete.", Toast.LENGTH_SHORT)
.show();
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
progressDialog.dismiss();
ex.printStackTrace();
imageTextSelect
.setText("MalformedURLException Exception : check script url.");
Toast.makeText(wardrobe.this, "MalformedURLException",
Toast.LENGTH_SHORT).show();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
progressDialog.dismiss();
e.printStackTrace();
imageTextSelect.setText("Got Exception : see logcat ");
Toast.makeText(wardrobe.this,
"Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
}
You have to use http post with multipart data to upload images.
try this link
I am trying to use Async to be more efficient and to allow for image uploads to my webserver I have tried various methods but there is always something not working...
Here is my latest code but having problems with the return being an Int and if I change the
AsyncTask Int then it errors because the imagePath being passed to it is a String...
This is the error
Type mismatch: cannot convert from int to String
For return 0 and return serverResponseCode;
public class wardrobe extends Activity implements OnClickListener {
// set variable for the fields
private EditText nameField, sizeField, colorField, quantityField;
private Spinner typeField, seasonField;
private ImageView imageview;
private ProgressBar progressBarField;
private TextView imageTextSelect, resImage;
private ProgressDialog progressDialog = null;
private int serverResponseCode = 0;
private Button uploadImageButton, postWardrobe;
private String upLoadServerUri = null;
private String imagepath = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wardrobe);
// image upload stuff
imageview = (ImageView) findViewById(R.id.user_photo);
imageTextSelect = (TextView) findViewById(R.id.imageTextSelect);
// button for upload image
uploadImageButton = (Button) findViewById(R.id.uploadImageButton);
// button for posting details
postWardrobe = (Button) findViewById(R.id.postButton);
uploadImageButton.setOnClickListener(this);
postWardrobe.setOnClickListener(this);
#Override
public void onClick(View v) {
if (v == uploadImageButton) {
// below allows you to open the phones gallery
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Complete action using"), 1);
}
if (v == postWardrobe) {
// validate input and that something was entered
if (nameField.getText().toString().length() < 1
|| colorField.getText().toString().length() < 1
|| sizeField.getText().toString().length() < 1
|| quantityField.getText().toString().length() < 1) {
// missing required info (null was this but lets see)
Toast.makeText(getApplicationContext(),
"Please complete all sections!", Toast.LENGTH_LONG)
.show();
} else {
JSONObject dataWardrobe = new JSONObject();
try {
dataWardrobe.put("type", typeField.getSelectedItem()
.toString());
dataWardrobe.put("color", colorField.getText().toString());
dataWardrobe.put("season", seasonField.getSelectedItem()
.toString());
dataWardrobe.put("size", sizeField.getText().toString());
dataWardrobe.put("quantity", quantityField.getText()
.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// make progress bar visible
progressBarField.setVisibility(View.VISIBLE);
// execute the post request
new dataSend().execute(dataWardrobe);
// image below
progressDialog = ProgressDialog.show(wardrobe.this, "",
"Uploading file...", true);
imageTextSelect.setText("uploading started.....");
new Thread(new Runnable() {
public void run() {
doFileUpload(imagepath);
}
}).start();
}
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == 1) {
// Bitmap photo = (Bitmap) data.getData().getPath();
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
Bitmap bitmap = BitmapFactory.decodeFile(imagepath);
imageview.setImageBitmap(bitmap);
// add to text view what was added
imageTextSelect.setText("Uploading file path: " + imagepath);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null,
null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Here is the part I am struggling with:
public int doFileUpload(String sourceFileUri) {
String upLoadServerUri = "http://10.0.2.2/wardrobe";
String fileName = imagepath;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(imagepath);
if (!sourceFile.isFile()) {
progressDialog.dismiss();
Log.e("uploadFile", "Source File not exist :" + imagepath);
runOnUiThread(new Runnable() {
public void run() {
imageTextSelect.setText("Source File not exist :"
+ imagepath);
}
});
return 0;
} else {
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if (serverResponseCode == 200) {
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+ " F:/wamp/wamp/www/uploads";
imageTextSelect.setText(msg);
Toast.makeText(wardrobe.this,
"File Upload Complete.", Toast.LENGTH_SHORT)
.show();
}
});
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
progressDialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
imageTextSelect
.setText("MalformedURLException Exception : check script url.");
Toast.makeText(wardrobe.this, "MalformedURLException",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
progressDialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
imageTextSelect.setText("Got Exception : see logcat ");
Toast.makeText(wardrobe.this,
"Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
progressDialog.dismiss();
return serverResponseCode;
} // End else block
}
I see many several problems here. First, you almost never (if ever) want to call runOnUiThread() from AsyncTask. Every method of AsyncTask runs on the UI except for doInBackground() so this usually isn't needed and often causes problems. Update the UI with the correct methods depending on what you are doing.
Second, I think you misunderstand what doInBackground() is returning. Its result is returned to onPostExecute() which is the 3rd param in your class declaration
private class doFileUpload extends AsyncTask <String, Void, String> {
So this means that onPostExecute() (which I don't see you overriding) should expect a String and that is what doInBackground() should return. So you should convert your return variables to String if you want to pass a String to onPostExecute()
AsyncTask Docs
Typically
progressDialog.dismiss();
is called in onPostExecute() and
progressDialog.show();
would be called in onPreExecute() when using an AsyncTask. Then you don't have to create a new Thread in your onClick().