How to declare method globally in Class - java

I want to call startUpload(position); method in loginbutton.setOnClickListener(new View.OnClickListener() {} like this:
loginbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SaveData();
alertDialog.dismiss();
startUpload(position);
}
but always getting : position cannot be resolved to a variable
so where i am doing mistake, how can i resolve this issue..?
//Upload
public void startUpload(final int position) {
Runnable runnable = new Runnable() {
public void run() {
handler.post(new Runnable() {
public void run() {
View v = lstView.getChildAt(position - lstView.getFirstVisiblePosition());
// Show ProgressBar
ProgressBar progress = (ProgressBar)v.findViewById(R.id.progressBar);
progress.setVisibility(View.VISIBLE);
// Status
TextView status = (TextView)v.findViewById(R.id.ColStatus);
status.setText("Uploading..");
new UploadFileAsync().execute(String.valueOf(position));
}
});
}
};
new Thread(runnable).start();
}
// Async Upload
public class UploadFileAsync extends AsyncTask<String, Void, Void> {
String resServer;
int position;
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
position = Integer.parseInt(params[0]);
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
int resCode = 0;
String resMessage = "";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
// File Path
strSDPath = ImageList.get(position).toString();
// Upload to PHP Script
String strUrlServer = "http://10.0.2.2/res/uploadFile.php";
try {
/** Check file on SD Card ***/
File file = new File(strSDPath);
if(!file.exists())
{
resServer = "{\"StatusID\":\"0\",\"Error\":\"Please check path on SD Card\"}";
return null;
}
FileInputStream fileInputStream = new FileInputStream(new File(strSDPath));
URL url = new URL(strUrlServer);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
DataOutputStream outputStream = new DataOutputStream(conn
.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream
.writeBytes("Content-Disposition: form-data; name=\"filUpload\";filename=\""
+ strSDPath + "\"" + 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) {
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);
// Response Code and Message
resCode = conn.getResponseCode();
if(resCode == HttpURLConnection.HTTP_OK)
{
InputStream is = conn.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int read = 0;
while ((read = is.read()) != -1) {
bos.write(read);
}
byte[] result = bos.toByteArray();
bos.close();
resMessage = new String(result);
}
Log.d("resCode=",Integer.toString(resCode));
Log.d("resMessage=",resMessage.toString());
fileInputStream.close();
outputStream.flush();
outputStream.close();
resServer = resMessage.toString();
} catch (Exception ex) {
// Exception handling
return null;
}
return null;
}
protected void onPostExecute(Void unused) {
statusWhenFinish(position,resServer);
}
}
// when upload finish
protected void statusWhenFinish(int position, String resServer) {
View v = lstView.getChildAt(position - lstView.getFirstVisiblePosition());
// Show ProgressBar
ProgressBar progress = (ProgressBar)v.findViewById(R.id.progressBar);
progress.setVisibility(View.GONE);
// Status
TextView status = (TextView)v.findViewById(R.id.ColStatus);
/*** Default Value ***/
String strStatusID = "0";
String strMessage = "Unknow Status!";
try {
JSONObject c = new JSONObject(resServer);
strStatusID = c.getString("StatusID");
strMessage = c.getString("Message");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Prepare Status
if(strStatusID.equals("0"))
{
// When update Failed
status.setText( strMessage );
status.setTextColor(Color.RED);
// Enabled Button again
Button btnUpload = (Button) v.findViewById(R.id.btnUpload);
btnUpload.setText("Already Uploaded");
btnUpload.setTextColor(Color.RED);
btnUpload.setEnabled(true);
}
else
{
status.setText("Upload Completed.");
status.setTextColor(Color.GREEN);
}
}
}

The declaration of position is key here.
Make sure it is in the method that contains this loginButton.onClickListener code and make sure it is declared as final

If it can be resolved as a variable it's not because of your method,
it's because position is not an attribute.
So, delcare it as :
int position = -1;
And then set it to use your method.

TRY IT
Create a Global variable POSITION then assign POSITION=position in your startUpload() method , it'll work.

When referencing variables, they must be definitive within the scope of the method.
So for methods, make sure it is either passed as a parameter, or it is defined as a global variable within the class.

Related

How to upload video in android using volley

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/

uploading a file with DataOutputStream doesn't display real progress

I am uploading a file from android to my webserver using the DataOutputStream with the following code:
public class SnapshotUploadTask extends AsyncTask<Object, Integer, Void> {
private final File file;
private final ProgressDialog progressDialog;
private final Activity activity;
public SnapshotUploadTask(File file, ProgressDialog progressDialog, Activity activity) {
this.progressDialog = progressDialog;
this.file = file;
this.activity = activity;
}
#Override
protected void onPreExecute() {
progressDialog.setProgress(0);
}
#Override
protected Void doInBackground(Object... arg0) {
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead;
int bytesAvailable;
int bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 512;
try {
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL("http://bla.bla.bla/upload");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
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("uploaded_file", file.getName());
DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + file.getName() + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
final int hundredPercent = bytesAvailable;
progressDialog.setMax(hundredPercent);
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);
final int restBytes = bytesAvailable;
final int uploadedBytes = hundredPercent - restBytes;
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.setProgress((int) uploadedBytes);
if (restBytes <= 0) {
progressDialog.setMessage(activity.getString(R.string.camera_uploading_done));
}
}
});
}
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
if (serverResponseCode == 200) {
progressDialog.dismiss();
}
fileInputStream.close();
dataOutputStream.flush();
dataOutputStream.close();
} catch (Exception e) {
progressDialog.dismiss();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
}
Now what happens is that i update my progressDialog as soon as i have written a certain amount of bytes into the OutputStream which leads to the progressDialog reaching 100% before the data is actually received by the server.
I only know when the transmission is complete when i get to connection.getResponseCode();
What i want instead is to update the progress when the data chunks are actually received by the server. Is there a way to do that?
You need to be aware that HttpURLConnection buffers all the output unless you set fixed-length or chunked transfer mode, which you should certainly do instead of implementing it yourself. It does that so it can set the Content-Length header accurately. If you use one of these transfer modes there is no buffering.
NB You're misusing available(): see the Javadoc; and you're writing junk in most cases:
dataOutputStream.write(buffer, 0, bufferSize);
should be
dataOutputStream.write(buffer, 0, bytesRead);
You don't need all that fiddling around with available() inside the read loop either. Something like this is sufficient:
long total = 0;
int maxBufferSize = 8192; // at least. 512 is far too small.
while ((bytesRead = fileInputStream.read(buffer, 0, bufferSize)) > 0) {
dataOutputStream.write(buffer, 0, bytesRead);
total += bytesRead;
final long uploadedBytes = total;
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.setProgress(uploadedBytes);
}
});
}
}
// at this point we are at end of stream
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.setMessage(activity.getString(R.string.camera_uploading_done));
}
}
E&OE

Upload code gets executed only once

I'm trying to design an application that starts a camera intent, uploads a photo, (and hopefully, work in progress: parse an XML response from the server, then move to another activity and fill in some form fields).
The problem is that so far the upload code is executed the 1st time I run the application, the 2nd time it gets skipped, the 3rd time works fine, 4th skips and so on.
MainActivity:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// buttons
Button lunchCamBtn = (Button) findViewById(R.id.lunchVerBtn);
lunchCamBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
}
});
Button lunchCaptBtn = (Button) findViewById(R.id.lunchCaptBtn);
lunchCaptBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
dispatchTakePictureIntent();
}
});
}
String path;
String picfname;
static final int REQUEST_IMAGE_CAPTURE = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
Random rnd = new Random(System.currentTimeMillis());
DateFormat dateFormat = new SimpleDateFormat("ddMMyyyy");
Date date = new Date();
String picfname = "bul "+dateFormat.format(date)+" "+rnd.nextInt(90)+".png";
File output = new File(dir,picfname);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(output));
path = output.getAbsolutePath();
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Toast.makeText(getApplicationContext(), path.toString(),
Toast.LENGTH_LONG).show();
UploadFiles upld =new UploadFiles(MainActivity.this);
upld.execute(path.toString());
}
UploadFiles:
public class UploadFiles extends AsyncTask<String, Integer, Boolean> {
WeakReference<Activity> mActivityReference;
public UploadFiles(Activity activity){
this.mActivityReference = new WeakReference<Activity>(activity);
}
#Override
protected Boolean doInBackground(String... params) {
Boolean succesz = true;
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String selectedPath = params[0];
String pathToOurFile = selectedPath;
String urlServer = "http://192.168.0.104/upload2.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
Bitmap bmp = BitmapFactory.decodeFile(pathToOurFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 90, bos);
InputStream fileInputStream = new ByteArrayInputStream(bos.toByteArray());
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setChunkedStreamingMode(1024);
connection.setReadTimeout(25000 /* milliseconds */);
connection.setConnectTimeout(30000 /* milliseconds */);
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];
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);
InputStream stream = connection.getInputStream();
InputStreamReader isReader = new InputStreamReader(stream);
String line = "";
line = convertStreamToString(stream);
System.out.print(line);
fileInputStream.close();
outputStream.flush();
outputStream.close();
} catch (Exception ex) {
}
return succesz;
}
private String convertStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (Exception e) {
//Toast.makeText(this, "Stream Exception", Toast.LENGTH_SHORT).show();
}
return total.toString();
}
#Override
protected void onPostExecute(Boolean result) {
if (result && mActivityReference.get() != null) {
Activity activity = mActivityReference.get();
Intent iinent= new Intent(activity,TestActivity.class);
activity.startActivity(iinent);
//activity.finish();
}
}}
I know now that this issue is caused by the convertStreamToString method in class UploadFiles but I can't understand what exactly causes it. When I remove it completely everything works fine. Thank you in advance!
The first minor problem:
Using available is basically wrong, though it might work.
The second minor problem:
Do not use DataOutputStream here. I guess it is done to be able to write Strings to an OutputStream.
response.setContentType("...; charset=Windows-1252");
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(os, "Windows-1252"));
Somehow also specifying the encoding/charset may help.
Problem with the convertStreamToString:
In no extra encoding parameter is added to the InputStreamReader, the default platform encoding is used. UTF-8 on Android. That would fail relatively fast.
You might give a less strict single-byte encoding a try to see what happens:
BufferedReader rd = new BufferedReader(new InputStreamReader(is, "Windows-1252"));
In general encoding is not handled: URLConnection.getContentEncoding() maybe is informative.
You are doing couple of things wrong here.
Don't leave exception blocks empty. It hides all the error. Use Log.e to print that.
Don't use System.out.println. Use Log.* only for logging.
Don't use AsyncTask to upload your file. Use IntentService Instead. And using localbroadcastmanager broadcast upload events for your activity to listen. It will be more configuration change friendly.
Instead of doing all this file upload sorcery yourself. Use httpmime library instead. It works simply awesome on android. I have my apps on production using this. Something like this you have to do.
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlToUpload);
MultipartEntity entity = new MultipartEntity();
Bitmap bmp = BitmapFactory.decodeFile(sourceFileUri);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 50, bos);
InputStream in = new ByteArrayInputStream(bos.toByteArray());
ContentBody imageContent = new InputStreamBody(in, "image/jpeg", sourceFile.getName());
entity.addPart("file", imageContent);
post.setEntity(entity);
HttpResponse response = client.execute(post);
You will have your everything in 'response' for you to read.
String responseBody = EntityUtils.toString(response.getEntity());
From here you can download this library http://repo1.maven.org/maven2/org/apache/httpcomponents/httpmime/4.2.5/
I have used this https://github.com/alexbbb/android-upload-service for file uploads.
I handle all the response-related logic inside the Broadcast receiver, where I'm waiting for the upload responses.

How to pass android image uri to the execute call for the async task?

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

Trying to use Async with image upload to webserver android?

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().

Categories