Ask user For Permission For Access Storage - java

I made a programme for uploading files to Mysql server and code is working fine but in Marshmallow device it not working and getting error for permission. this is my error..
05-17 21:13:13.783 32468-32468/com.example.dssandroid.myapplicationupload I/MainActivity: Selected File Path:/storage/emulated/0/Android/data/net.one97.paytm/files/Download/Invoice2867017873.pdf
05-17 21:13:13.860 32468-32468/com.example.dssandroid.myapplicationupload I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#db75da1 time:94083612
05-17 21:13:15.020 32468-1040/com.example.dssandroid.myapplicationupload W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Android/data/net.one97.paytm/files/Download/Invoice2867017873.pdf: open failed: EACCES (Permission denied)
05-17 21:13:15.020 32468-1040/com.example.dssandroid.myapplicationupload W/System.err: at libcore.io.IoBridge.open(IoBridge.java:452)
05-17 21:13:15.021 32468-1040/com.example.dssandroid.myapplicationupload W/System.err: at java.io.FileInputStream.<init>(FileInputStream.java:76)
05-17 21:13:15.021 32468-1040/com.example.dssandroid.myapplicationupload W/System.err: at com.example.dssandroid.myapplicationupload.MainActivity.uploadFile(MainActivity.java:147)
05-17 21:13:15.021 32468-1040/com.example.dssandroid.myapplicationupload W/System.
now i want to know how to ask user for access storage permission before running my. i am also giving my code so please help to resolve this issue...
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private static final int PICK_FILE_REQUEST = 1;
private static final String TAG = MainActivity.class.getSimpleName();
private String selectedFilePath;
private String SERVER_URL = "http://192.168.1.12:8080/uploadImage/uploadImage.php";
ImageView resumeSelect;
Button btnupload;
TextView tvFileName;
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resumeSelect = (ImageView)findViewById(R.id.attachment);
btnupload = (Button)findViewById(R.id.upload);
tvFileName = (TextView)findViewById(R.id.file_name);
resumeSelect.setOnClickListener(this);
btnupload.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v== resumeSelect){
//on attachment icon click
showFileChooser();
}
if(v== btnupload){
//on upload button Click
if(selectedFilePath != null){
dialog = ProgressDialog.show(MainActivity.this,"","Uploading File...",true);
new Thread(new Runnable() {
#Override
public void run() {
//creating new thread to handle Http Operations
uploadFile(selectedFilePath);
}
}).start();
}else{
Toast.makeText(MainActivity.this,"Please choose a File First",Toast.LENGTH_SHORT).show();
}
}
}
private void showFileChooser() {
Intent intent = new Intent();
//sets the select file to all types of files
intent.setType("*/*");
//allows to select data and return it
intent.setAction(Intent.ACTION_GET_CONTENT);
//starts new activity to select file and return data
startActivityForResult(Intent.createChooser(intent,"Choose File to Upload.."),PICK_FILE_REQUEST);
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK){
if(requestCode == PICK_FILE_REQUEST){
if(data == null){
//no data present
return;
}
Uri selectedFileUri = data.getData();
selectedFilePath = FilePath.getPath(this,selectedFileUri);
Log.i(TAG,"Selected File Path:" + selectedFilePath);
if(selectedFilePath != null && !selectedFilePath.equals("")){
tvFileName.setText(selectedFilePath);
}else{
Toast.makeText(this,"Cannot upload file to server",Toast.LENGTH_SHORT).show();
}
}
}
}
//android upload file to server
public int uploadFile(final String selectedFilePath){
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(selectedFilePath);
String[] parts = selectedFilePath.split("/");
final String fileName = parts[parts.length-1];
if (!selectedFile.isFile()){
dialog.dismiss();
runOnUiThread(new Runnable() {
#Override
public void run() {
tvFileName.setText("Source File Doesn't Exist: " + selectedFilePath);
}
});
return 0;
}else{
try{
FileInputStream fileInputStream = new FileInputStream(selectedFile);
URL url = new URL(SERVER_URL);
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("uploaded_file",selectedFilePath);
//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=\"uploaded_file\";filename=\""
+ selectedFilePath + "\"" + 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();
Log.i(TAG, "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);
//response code of 200 indicates the server status OK
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
#Override
public void run() {
tvFileName.setText("File Upload completed.\n\n You can see the uploaded file here: \n\n" + "http://192.168.1.101/uploadImage/upload/"+ fileName);
Toast.makeText(MainActivity.this, "File Uploaded Successfully", Toast.LENGTH_SHORT).show();
}
});
}
//closing the input and output streams
fileInputStream.close();
dataOutputStream.flush();
dataOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,"File Not Found",Toast.LENGTH_SHORT).show();
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "URL error!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Cannot Read/Write File!", Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
return serverResponseCode;
}
}
}

In marshmallow 6.0.0 and above you need to use run time permissions.
This function checks permissions is granted or not?, also prompt permission that is required
public boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG,"Permission is granted");
return true;
} else {
Log.v(TAG,"Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted");
return true;
}
}
Check Permission result callback: if permission is granted or not
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
//resume tasks needing this permission
}
}

After the Android 6.0 Marshmallow google add restrict add permissions at runtime.
see that link
add that line of code to your MainActivity in on create() Method.
private ArrayList<Integer> listPermission;// add all permission in list which you used in manifes.xml
listPermission = new ArrayList<>();
listPermission.add(AISPermission.WRITE_EXTERNAL_STORAGE);
listPermission.add(AISPermission.READ_CONTACTS);
listPermission.add(AISPermission.SEND_SMS);
listPermission.add(AISPermission.MICROPHONE);
PermissionUtils.requestPermission(context, listPermission, new PermissionUtils.OnRequestedPermissionListListener() {
#Override
public void onPermissionListResult(ArrayList<Integer> responsePermissionList, ArrayList<Boolean> isPermissionGrantedList) {
// if(isPermissionGrantedList.get())
for (int i = 0; i < responsePermissionList.size(); i++) {
if (responsePermissionList.get(i) != listPermission.get(i) || !isPermissionGrantedList.get(i)) {
return;
}
}
startActivity(new Intent(context, MainActivity.class));
}
});
}

Related

Android Studios Uploading pictures into intern database

Im trying to develope a function so i can upload pictures into my intern database in Android Studios. Has somebody an idea how i can solve this?
Well , first thing you need to add two button to select picture and to submit upload picture something like ..
Button Buttonlog;
Button Buttonbro;
ProgressBar progressBar;
private TextView messageText;
private TextView file-token-name;
private ProgressDialog dialog = null;
private String upLoadServerUri = null;
private String imagepath=null;
private ImageView imageview;
private static final int PICK_IMAGE_GALLERY = 1;
#SuppressLint("ClickableViewAccessibility")
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main15);
file-token-name=findViewById(R.id.filename);
file-token-name.setVisibility(View.GONE);
Buttonbro = findViewById(R.id.button_selectpic);
Buttonbro.setVisibility(View.VISIBLE);
Buttonbro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (ActivityCompat.checkSelfPermission(MainActivity15.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity15.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PICK_IMAGE_GALLERY);
} else {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, PICK_IMAGE_GALLERY);
}
} catch (Exception e) {
e.printStackTrace();
}
loadGallery();
}
});
progressBar = findViewById(R.id.progress);
imageview = findViewById(R.id.imageView_pic);
upLoadServerUri = "https://www.yoursite.net/upljsonfile.php";
Buttonlog.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View v) {
final String file1;
file1=file-token-name.getText().toString();
//Start ProgressBar first (Set visibility VISIBLE)
progressBar.setVisibility(View.VISIBLE);
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
//Starting Write and Read data with URL
//Creating array for parameters
String[] field = new String[1];
field[0] = "file1";
//Creating array for data
final String[] data = new String[1];
data[0] = file1;
if (!isFinishing()) {
PutData putData = new PutData("https://www.yorwebsite.net/post-to-database-file-name.php", "POST", field, data);
if (putData.startPut()) {
if (putData.onComplete()) {
progressBar.setVisibility(View.GONE);
String result = putData.getResult();
//End ProgressBar (Set visibility to GONE
if (result.equals("Post Succssefl")) {
if (!file1.equals("")) {
dialog = ProgressDialog.show(MainActivity15.this, "", "Uploading file...", true);
messageText.setText("uploading started.....");
// dialog = new ProgressDialog(MainActivity15.this);
// dialog.setMessage("Uploading File");
// dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setIndeterminate(true);
dialog.setMax(100);
dialog.show();
new Thread(new Runnable() {
public void run() {
uploadFile(imagepath);
}
}).start();
if (isFinishing()) {
if (dialog != null) {
dialog.dismiss();
dialog = null;
}
}
} else {
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), MainActivity11.class);
startActivity(i);
finish();
}
} else {
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
}
}
isFinishing();
}
}
}
}); //End Write and Read data with URL
}
});
}
And then our loadGallery() func
private void loadGallery() {
Intent choose = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(choose, PICK_IMAGE_GALLERY);
}
after that you have to allow permission take your image select path something like ..
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressLint("Recycle")
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
assert cursor != null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
if (requestCode == PICK_IMAGE_GALLERY) {// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, PICK_IMAGE_GALLERY);
} //do something like displaying a message that he didn`t allow the app to access gallery and you wont be able to let him select from gallery
}
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#SuppressLint({"SetTextI18n", "NewApi"})
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_GALLERY && data != null && resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = data.getData();
assert selectedImageUri != null;
imagepath = getPath(selectedImageUri);
Bitmap bitmap = BitmapFactory.decodeFile(imagepath);
imageview.setImageBitmap(bitmap);
messageText.setText("Uploading file path:" + imagepath);
String uriString = selectedImageUri.toString();
File myFile = new File(uriString);
String displayName;
if (uriString.startsWith("content://")) {
try (Cursor cursor = getContentResolver().query(selectedImageUri, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
file-token-name.setText(displayName);
}
}
} else if (uriString.startsWith("file://")) {
displayName = myFile.getName();
file-token-name.setText(displayName);
}
}
}
now we add our upload file func something like ..
#SuppressLint("LongLogTag")
public void uploadFile(String sourceFileUri) {
HttpURLConnection conn;
DataOutputStream dos;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"+imagepath);
runOnUiThread(new Runnable() {
#SuppressLint("SetTextI18n")
public void run() {
messageText.setText("Source File not exist :"+ imagepath);
}
});
}
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("file", sourceFileUri);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
+ sourceFileUri + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
int sentBytes=0;
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
sentBytes += bufferSize;
int progres =(bytesRead * 100 / bytesAvailable);
new Thread(
// do your stuff
new publishProgress(progres)
).start();
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)
int 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"
+" C:/xamp/wamp/fileupload/uploads";
messageText.setText(msg);
Toast.makeText(MainActivity15.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
Intent i = new Intent(getApplicationContext(), MainActivity11.class);
startActivity(i);
finish();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
#SuppressLint("SetTextI18n")
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(MainActivity15.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() {
#SuppressLint("SetTextI18n")
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(MainActivity15.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
}
dialog.dismiss();
} // End else block
}
fainaly .. our tow php file one to upload our file"upljsonfile.php",And second to post our file name to database "post-to-database-file-name.php", like code bellow ..
the first file "upljsonfile.php" :
<?php
$response = array();
if (empty($_FILES) || $_FILES['file']['error']) {
$response["code"] = 2;
$response["message"] = "failed to move uploaded file";
echo json_encode($response);
}
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
$fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : $_FILES["file"]["name"];
$filePath = "uploadfiles/$fileName";
// Open temp file
$out = #fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
if ($out) {
// Read binary input stream and append it to temp file
$in = #fopen($_FILES['file']['tmp_name'], "rb");
if ($in) {
while ($buff = fread($in, 4096))
fwrite($out, $buff);
} else
$response["code"] = 2;
$response["message"] = "Oops! Failed to open input Stream error occurred.";
echo json_encode($response);
#fclose($in);
#fclose($out);
#unlink($_FILES['file']['tmp_name']);
} else
$response["code"] = 2;
$response["message"] = "Oops! Failed to open output error occurred.";
echo json_encode($response);
// Check if file has been uploaded
if (!$chunks || $chunk == $chunks - 1) {
// Strip the temp .part suffix off
rename("{$filePath}.part", $filePath);
}
$response["code"] = 2;
$response["message"] = "successfully uploaded";
echo json_encode($response);
?>
and the second file "post-to-database-file-name.php :
<?php
require "databasemob.php";
$db = new DataBase();
if (isset($_POST['file1']) ) {
if ($db->dbConnect()) {
if ($db->filenamepost("filename", $_POST['file1'])) {
echo "Post Succssefl";
} else echo "Some error !";
} else echo "Error: Database connection";
} else echo "All fields are required";
?>
and the databasemob.php :
<?php
require "DataBaseConfig.php";
class DataBase
{
public $connect;
public $data;
private $sql;
protected $servername;
protected $username;
protected $password;
protected $databasename;
public function __construct()
{
$this->connect = null;
$this->data = null;
$this->sql = null;
$dbc = new DataBaseConfig();
$this->servername = $dbc->servername;
$this->username = $dbc->username;
$this->password = $dbc->password;
$this->databasename = $dbc->databasename;
}
function dbConnect()
{
$this->connect = mysqli_connect($this->servername, $this->username, $this->password, $this->databasename);
return $this->connect;
}
function prepareData($data)
{
return mysqli_real_escape_string($this->connect, stripslashes(htmlspecialchars($data)));
}
function filenamepost($table, $file1)
{
$file1 = $this->prepareData($file1);
$ssq="SET NAMES 'utf8mb4';";
mysqli_query($this->connect,$ssq);
$this->sql =
"INSERT INTO " . $table . " (`file1`) VALUES ('" . $file1 . "')";
if (mysqli_query($this->connect, $this->sql)) {
return true;
} else return false;
}
}
?>
last file DataBaseConfig.php :
<?php
class DataBaseConfig
{
public $servername;
public $username;
public $password;
public $databasename;
public function __construct()
{
$this->servername = 'localhost';
$this->username = 'username';
$this->password = 'pass#';
$this->databasename = 'filename';
}
}
?>
this way its work by take ur file name from file Uri from phone and prosses for tow way by uploading file and post file to your database ,, hope it help you :)

android how to make upload image and insert caption to mysql with php

I can't insert caption on my project, I want my project can upload image and insert some data to database on web server, I can insert but my data have an duplicate.. please help me....
Here source code for MainActivity.java
public class MainActivity extends Activity implements OnClickListener{
private TextView messageText;
private EditText Txnama, Txtanggal, Txcaption;
private Button uploadButton, btnselectpic;
private ImageView imageview;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;
private String upLoadServerUri = null;
private String imagepath=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uploadButton = (Button)findViewById(R.id.uploadButton);
btnselectpic = (Button)findViewById(R.id.button_selectpic);
messageText = (TextView)findViewById(R.id.messageText);
imageview = (ImageView)findViewById(R.id.imageView_pic);
Txnama = (EditText)findViewById(R.id.nama);
Txtanggal = (EditText)findViewById(R.id.tanggal);
Txcaption = (EditText)findViewById(R.id.caption);
btnselectpic.setOnClickListener(this);
uploadButton.setOnClickListener(this);
upLoadServerUri = "http://aplikasilaras.esy.es/php/Uploadcoba.php";
ImageView img= new ImageView(this);
}
#Override
public void onClick(View arg0) {
if(arg0==btnselectpic)
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
}
else if (arg0==uploadButton) {
dialog = ProgressDialog.show(MainActivity.this, "", "Uploading file...", true);
messageText.setText("uploading started.....");
new Thread(new Runnable() {
public void run() {
uploadFile(imagepath);
}
}).start();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
//Bitmap photo = (Bitmap) data.getData().getPath();
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
imageview.setImageBitmap(bitmap);
messageText.setText("Uploading file path:" +imagepath);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"+imagepath);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"+ imagepath);
}
});
return 0;
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+" F:/wamp/wamp/www/uploads";
messageText.setText(msg);
Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(MainActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
}
Try to change php code with this, it's work on me.
<?php
$conn = mysql_connect('YOUR_HOST', 'YOUR_USERNAME', 'YOUR_PASSWORD') or die(mysql_error());
$db = mysql_select_db('YOUR_DB_NAME') or die(mysql_error());
$file_path = "uploads/"; //YOUR FOLDER FOR SAVING IMAGE, MY FOLDER NAME IS uploads
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
$query = "insert into YOUR_TABLE_NAME values('', '$file_path')";
mysql_query($query);
echo "success";
} else{
echo "fail";
}
?>

Upload image to server and store path with text values into MySQL

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.

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