I'm trying to upload image to xampp server, with android-studio and php
But I will not succeed
Please help me
here is my code(java and php):
java code:
in this codes im trying to select picture from gallery and show a dialog and then uploading image...
public final int REQUEST_OPEN_GALLERY = 5;
ProgressDialog dialog;
Thread uploadThread;
String lineEnd = "\r\n";
String twoHyphens = "--";
String id = "";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
public static Handler uploadHandler;
public static String imageProfile = "";
profile_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chooseFile();
}
});
}
private void chooseFile() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_OPEN_GALLERY);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_OPEN_GALLERY && resultCode == RESULT_OK && data != null) {
Uri uri = data.getData();
String[] info = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(uri, info, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(info[0]);
final String filePath = cursor.getString(columnIndex);
//Toast.makeText(MainActivity.this,filePath,Toast.LENGTH_SHORT).show();
dialog = ProgressDialog.show(getContext(), "upload", "Uploading file...");
uploadThread = new Thread(new Runnable() {
#Override
public void run() {
uploadFile(filePath);
}
});
uploadThread.start();
}
}
private void uploadFile(String filePath) {
File file = new File(filePath);
try {
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL("http://192.168.1.6/zanborak/sabtenam/upload.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("uploaded_file", filePath);
DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd + "Content-Disposition: form-data;" +
" name=\"uploaded_file\";filename=\"" + filePath + "\"\r\n\r\n");
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dataOutputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
if (connection.getResponseCode() == 200) {
uploadHandler.post(new Runnable() {
#Override
public void run() {
dialog.dismiss();
Toast.makeText(getContext(), "Upload Completed", Toast.LENGTH_SHORT).show();
imageProfile = "";
}
});
}
fileInputStream.close();
dataOutputStream.flush();
dataOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
and php:
in this code im trying move the image to "upload" folder...
<?php
include "connect.php";
$rand=microtime();
$path="upload/".$rand.($_FILES["uploaded_file"]["name"]);
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"],$path);
?>
It would be better if you use Retrofit library. it a light library to exchange data & media through Http protocol and await the response.
you can see how to add it as a dependency in official website.
you also need to add Gson serializer dependency in your gradle.
Once done create responsable to get Retrofit object:
public class RetrofitApiClient {
private static final String BASE_URL = "http://192.168.1.6/"; //htt
private static Retrofit retrofit = null;
private static Gson gson = new GsonBuilder()
.serializeNulls()
.setLenient()
.create();
private RetrofitApiClient() {} // So that nobody can create an object with constructor
public static synchronized Retrofit getClient() {
if (retrofit==null) {
int timeOut = 5 * 60;
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(timeOut, TimeUnit.SECONDS)
.writeTimeout(timeOut, TimeUnit.SECONDS)
.readTimeout(timeOut, TimeUnit.SECONDS)
.build();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
}
return retrofit;
}
}
Retrofit turns your HTTP API into a Java interface, so create an interface to handle url for the upload
public interface FileService {
#Multipart
#POST("/zanborak/sabtenam/upload.php")
Call<String> UploadImage(
#Part MultipartBody.Part file);
}
Now you can create a class responsable to push your file to the server and wait for the response.
public class ImageUploaderClass {
//listerner for the task
public interface OnSuccessfullTask {
void onSuccess();
void onFailed(String error);
}
public static void uploadImage(String filePath, OnSuccessfullTask task) {
try {
FileService apiInterface = RetrofitApiClient.getClient().create( FileService .class);
File file = new File(filePath);
//create RequestBody instance from file
RequestBody requestFile = RequestBody.create(MediaType.parse("image"), file);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body = MultipartBody.Part.createFormData("uploaded_file", file.getName(), requestFile);
// finally, execute the request
Call<String> call = apiInterface.UploadImage(body);
call.enqueue(new Callback<String>() {
#Override
public void onResponse(#NonNull Call<String> call, #NonNull Response<String> response) {
String responseBody = response.body();
if (responseBody != null) {
if ("ok".equals(responseBody)) {
task.onSuccess();
} else {
task.onFailed(responseBody);
}
} else {
task.onFailed(responseBody);
}
}
#Override
public void onFailure(#NotNull Call<String> call, #NotNull Throwable t) {
task.onFailed(t.getMessage());
}
});
}
catch (Exception ignored){}
}
}
in your Php returns something to the app in case of success or failure
<?php
include "connect.php";
$rand=microtime();
$path="upload/".$rand.($_FILES["uploaded_file"]["name"]);
$r = move_uploaded_file($_FILES["uploaded_file"]["tmp_name"],$path);
if($r){
echo 'ok';
}
else{
echo 'error';
}
?>
Lastly you can call uploadImage in ActivityResult and pass it the file name and the Actions you need in case of success ot failure
Related
I am developing an android application that uploads an image to a specified directory using PHP and okhttp . Well , the frontend and backend work fine on my personal device , but it crashes on non-Samsung devices.
When I dug into the problem I found out that the server returns :
com.android.okhttp.internal.http.Http1xStream$FixedLengthSource#17768aa).inputStream()
on the non-Samsung devices.
The Java Code of the file Upload is as Follows :
public class UploadGalleryStoryPost {
private Context context;
private String fileName = "", User_Id = "",Type="";
private ProgressDialog progressDialog;
private int serverResponseCode = 0;
private String count = "";
private String fileCount = "";
public UploadGalleryStoryPost(String fileName, Context context, String User_Id, String Type, String count, String fileCount) {
this.fileName = fileName;
this.context = context;
this.User_Id = User_Id;
this.Type = Type;
this.count = count;
this.fileCount = fileCount;
new UploadingGalleryPost().execute();
}
private class UploadingGalleryPost extends AsyncTask<Void, Void, Void> {
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize =1024 * 1024;
File sourceFile_profile = new File(fileName);
private String upLoadServerUri = APP_SERVER_URL+"AddAStory.php";
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog=new ProgressDialog(context);
progressDialog.setMessage("Uploading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPostExecute(Void result) {
try{
if(serverResponseCode == 200){
int count1 = Integer.parseInt(count);
int fileCount1 = Integer.parseInt(fileCount);
Log.e("value", " "+ String.valueOf(count1-1)+" "+fileCount1);
if((fileCount1-1) == count1) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context, R.style.myDialog);
builder1.setCancelable(false);
builder1.setTitle("Alert!");
builder1.setMessage("Uploaded successfully.");
builder1.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Intent i = new Intent(context, DashBoard.class);
context.startActivity(i);
}
});
AlertDialog dialog1 = builder1.create();
dialog1.show();
}
else {
progressDialog.dismiss();
Toast.makeText(context, fileName+" has been uploaded successfully", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
Log.e("UploadtoserverException", "Exception : "
+ e.getMessage(), e);
}
super.onPostExecute(result);
}
#Override
protected Void doInBackground(Void... voids) {
try{
// open a URL connection to the Servlet
FileInputStream fileInputStream_profile = new FileInputStream(sourceFile_profile);
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.setChunkedStreamingMode(1024);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("Attachment", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"Attachment\";filename=\""+fileName+"\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream_profile.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream_profile.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream_profile.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream_profile.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"User_Id\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(User_Id);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"Type\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Type);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
conn.getErrorStream();
Log.e("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode+" "+ conn.getErrorStream());
//close the streams //
fileInputStream_profile.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
Log.e("UploadtoserverException", "Exception : "
+ e.getMessage(), e);
}
return null;
}
}
}
The php code is :
<?php
date_default_timezone_set('Asia/Kolkata');
$date = date('Y-m-d H:i:s');
$new_time = date("Y-m-d H:i:s", strtotime('+24 hours'));
$day = date("l");
$response = array();
include 'db_connect.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$User_Id = $_POST['User_Id'];
$Story_Content = $_POST['Story_Content'];
$B_Id = $_POST['B_Id'];
$Type = $_POST['Type'];
if($Type == 'BGTXT'){
$sql = "INSERT INTO Story_Common(User_Id,Timestamp_Start,Status, Timestamp_End)
VALUES('$User_Id','$date','Open','$new_time')";
$result = sqlsrv_query($conn, $sql);
if($result){
$sql1 = "SELECT TOP 1 * FROM Story_Common ORDER BY Story_Id DESC";
$res1 = sqlsrv_query($conn, $sql1);
if (sqlsrv_has_rows($res1) == true)
{
while ($row_sql1 = sqlsrv_fetch_array($res1, SQLSRV_FETCH_BOTH))
{
$Story_Id = $row_sql1["Story_Id"];
}
}
$sql2 = "INSERT INTO Story(Story_Id,Story_Content,B_Id)
VALUES('$Story_Id',N'$Story_Content','$B_Id')";
$result2 = sqlsrv_query($conn, $sql2);
if($result2){
$response['success'] = 200;
$response['message'] = "Insert in db success.";
}
else{
$response['success'] = 0;
$response['message'] = "Failed to insert db.";
}
}
else{
$response['success'] = 0;
$response['message'] = "Failed to insert db.";
}
}
else if($Type == 'Photo/Video'){
$sql = "INSERT INTO Story_Common(User_Id,Timestamp_Start,Status,Timestamp_End)
VALUES('$User_Id','$date','Open','$new_time')";
$result = sqlsrv_query($conn, $sql);
if($result){
if (empty($_FILES["Attachment"]["name"])) {
$path = "NA";
}
else {
$Attachment=$_FILES["Attachment"]["name"];
$temp=$_FILES["Attachment"]["tmp_name"];
$tst= time();
$url = "Post_Media/" . $tst . $Attachment;
$path="http://kidsfb.kidsfb.com/ver1PHP/".$url;
move_uploaded_file($temp,$url);
}
$sql1 = "SELECT TOP 1 * FROM Story_Common ORDER BY Story_Id DESC";
$res1 = sqlsrv_query($conn, $sql1);
if (sqlsrv_has_rows($res1) == true)
{
while ($row_sql1 = sqlsrv_fetch_array($res1, SQLSRV_FETCH_BOTH))
{
$Story_Id = $row_sql1["Story_Id"];
}
}
$sql2 = "INSERT INTO Story_Media(Story_Id,Media_Att)
VALUES('$Story_Id','$path')";
$result2 = sqlsrv_query($conn, $sql2);
if($result2){
$response['success'] = 200;
$response['message'] = "Insert in db success.";
}
else{
$response['success'] = 0;
$response['message'] = "Failed to insert db.";
}
}
else{
$response['success'] = 0;
$response['message'] = "Failed to insert db.";
}
}
echo json_encode($response);
}
?>
Tried increasing the buffer size to 2048 from 1024 still doesn't work on other devices.
It is work to me very well so please try this one
//php file imageUpload.php
$encodedImage = $_POST['image'];
$encodedImage_Name = $_POST['img_name'];
$imageLocation = "Images/IMG_$encodedImage_Name.jpg";
$imagpath="Images/IMG_$encodedImage_Name.jpg";
$uploade_url= 'http://192.168.1.18/'.$imagpath;
echo "[\n";
if(file_put_contents($imageLocation, base64_decode($encodedImage))){
$myObj=new \stdClass();
$myObj->success = 'true';
$myJSON = json_encode($myObj);
echo $myJSON;
}
else{
$myObj=new \stdClass();
$myObj->success = 'false';
$myJSON = json_encode($myObj);
echo $myJSON;
}
echo "]\n";
//java file
static final int PICK_FROM_GALLERY=123;
Bitmap imageBitmap;
boolean isSelected;
//to open the image from gallery
profile.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PICK_FROM_GALLERY);
} else {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, PICK_FROM_GALLERY);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} );
//open image set to Bitmap
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==PICK_FROM_GALLERY){
if (resultCode == RESULT_OK){
Uri path = data.getData();
try {
imageBitmap= MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(),path);
profile.setImageBitmap(imageBitmap);
Log.e("Image path",imageBitmap+"");
isSelected=true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void UploadImage(){
if (isSelected == true) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG,75, byteArrayOutputStream);
byte[] imageInByte = byteArrayOutputStream.toByteArray();
//picked image covert to base64
String encodedImage = Base64.encodeToString(imageInByte,Base64.DEFAULT);
OkHttpClient client = new OkHttpClient();
RequestBody reqestBody = new MultipartBody.Builder()
.setType( MultipartBody.FORM )
.addFormDataPart( "image",encodedImage )
.addFormDataPart( "img_name","abc" )
.build();
Request request = new Request.Builder()
.url("Upload Url in Server (exsample : http://192.168.1.18/imageUpload.php) " )
.post( reqestBody )
.build();
client.newCall( request ).enqueue( new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
final String myResponse = response.body().string();
getActivity().runOnUiThread( new Runnable() {
#Override
public void run() {
try {
String JSON_STRING = myResponse;
JSONArray mJsonArray = new JSONArray( JSON_STRING );
JSONObject mJsonObject = mJsonArray.getJSONObject( 0 );
String success = mJsonObject.getString( "success" );
Log.d( "Image Uploade", success );
if (success.equals( "true" )) {
Toast.makeText( getActivity(), " Success! ", Toast.LENGTH_LONG ).show();
} else {
pd.dismiss();
Toast.makeText( getActivity(), " failed! Please try again later", Toast.LENGTH_LONG ).show();
}
} catch (JSONException e) {
Log.e( "Image Uploade", e.toString() );
Toast.makeText( getActivity(), e.toString(), Toast.LENGTH_LONG ).show();
}
}
} );
} else {
Log.d( "Image Uploade", "Error" );
}
}
} );
}else{
Toast.makeText( getActivity(), " Please select a PostImage before submitting", Toast.LENGTH_LONG ).show();
}
}
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) {
}
}
I am trying to upload a video on the server, I didn't anything on this, please suggest
I can upload the text, that's working,
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://54.146.132.94/webservices/target_response",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(mContext, "" + response, Toast.LENGTH_SHORT).show();
Log.i("error", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mContext, "" + error.toString(), Toast.LENGTH_SHORT).show();
Log.i("error", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("I_trails", String.valueOf(itr));
params.put("E_trails", String.valueOf(et));
params.put("D_trails", String.valueOf(dt));
params.put("N_trails", String.valueOf(nt));
params.put("user_id", String.valueOf(get_id));
params.put("target_id", String.valueOf(get_target_id));
params.put("session_date", date);
params.put("data_mode", data_mode);
params.put("mode", mode);
params.put("link", link);
// params.put("video", selectedPath);
params.put("time", time_upload_real);
params.put("location_id", LocID);
params.put("No_of_trails", String.valueOf(notr));
/*params.put("comment", my_comment);*/
return params;
}
};
// Adding the StringRequest object into requestQueue.
requestQueue.add(stringRequest);
here the code to upload video, please let me know how to upload this video with the data, that I am uploading.
if (null != selectedPath && !selectedPath.isEmpty()){
Toast.makeText(mContext, "selected path: "+selectedPath, Toast.LENGTH_SHORT).show();
new Thread(new Runnable() {
#Override
public void run() {
//creating new thread to handle Http Operations
uploadFile(selectedPath);
}
}).start();
then,
public int uploadFile(final String selectedPath){
int serverResponseCode = 0;
HttpURLConnection connection;
DataOutputStream dataOutputStream;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead,bytesAvailable,bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File selectedFile = new File(selectedPath);
try {
FileInputStream fileInputStream = new FileInputStream(selectedFile);
URL url = new URL("http://54.146.132.94/webservices/target_response");
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);//Allow Inputs
connection.setDoOutput(true);//Allow Outputs
connection.setUseCaches(false);//Don't use a cached Copy
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("video",selectedPath);
//creating new dataoutputstream
dataOutputStream = new DataOutputStream(connection.getOutputStream());
//writing bytes to data outputstream
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"video\";filename=\""
+ selectedPath + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
//returns no. of bytes present in fileInputStream
bytesAvailable = fileInputStream.available();
//selecting the buffer size as minimum of available bytes or 1 MB
bufferSize = Math.min(bytesAvailable,maxBufferSize);
//setting the buffer as byte array of size of bufferSize
buffer = new byte[bufferSize];
//reads bytes from FileInputStream(from 0th index of buffer to buffersize)
bytesRead = fileInputStream.read(buffer,0,bufferSize);
//loop repeats till bytesRead = -1, i.e., no bytes are left to read
while (bytesRead > 0){
//write the bytes read from inputstream
dataOutputStream.write(buffer,0,bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fileInputStream.read(buffer,0,bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
//closing the input and output streams
fileInputStream.close();
dataOutputStream.flush();
dataOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// dialog.dismiss();
return serverResponseCode;
}
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_GALLERY);
and after selecting video
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
if (requestCode == PICK_FROM_GALLERY) {
Uri aa = data.getData();
mVideoURI = Uri.parse(String.valueOf(aa));
}
}
dont forget to use private Uri mVideoURI;
at top
inside your post volley method use :
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
/// photo field in link
if (mVideoURI != null) {
params.put("video", new DataPart("file_avatar.mp4", UploadHelper.getFileDataFromDrawable(getActivity(), mVideoURI)));
}
return params;
}
UPDATE
1- CREATE BroadcastHelper CLASS :
public class BroadcastHelper {
public static final String BROADCAST_EXTRA_METHOD_NAME = "INPUT_METHOD_CHANGED";
public static final String ACTION_NAME = "hassan.scott";
private static final String UPDATE_LOCATION_METHOD = "update";
public static void sendInform(Context context, String method) {
Intent intent = new Intent();
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void sendInform(Context context, String method, Intent intent) {
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2- Send intent from your adapter
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent url = new Intent("url");
url ("url_adapter",item.get(position).getURL());
BroadcastHelper.sendInform(context,"url",url);
}
});
3- in your fragment this use :
Receiver receiver;
boolean isReciverRegistered = false;
#Override
public void onResume() {
super.onResume();
if (receiver == null) {
receiver = new Receiver();
IntentFilter filter = new IntentFilter(BroadcastHelper.ACTION_NAME);
getActivity().registerReceiver(receiver, filter);
isReciverRegistered = true;
}
}
#Override
public void onDestroy() {
if (isReciverRegistered) {
if (receiver != null)
getActivity().unregisterReceiver(receiver);
}
super.onDestroy();
}
private class Receiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
Log.v("r", "receive " + arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME));
String methodName = arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME);
if (methodName != null && methodName.length() > 0) {
Log.v("receive", methodName);
switch (methodName) {
case "url":
/* call post method here */
default:
break;
}
}
}
}
UploadHelper Class :
public class UploadHelper {
/**
* Turn drawable resource into byte array.
*
* #param context parent context
* #param id drawable resource id
* #return byte array
*/
public static byte[] getFileDataFromDrawable(Context context, int id) {
Drawable drawable = ContextCompat.getDrawable(context, id);
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
/**
* Turn drawable into byte array.
*
* #return byte array
*/
public static byte[] getFileDataFromDrawable(Context context, Uri uri) {
// Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
InputStream iStream = context.getContentResolver().openInputStream(uri);
int bufferSize = 2048;
byte[] buffer = new byte[bufferSize];
// we need to know how may bytes were read to write them to the byteBuffer
int len = 0;
if (iStream != null) {
while ((len = iStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
}
Volley wasn't really meant for video uploading. It is better suited to large in number - small in size uploads/downloads. I would recommend using a different method to upload your video.
Volley is not suitable for large download or streaming operations,
since Volley holds all responses in memory during parsing. For large
download operations, consider using an alternative like
DownloadManager.*
Taken from https://developer.android.com/training/volley/
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 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().