I Want to make a url in one of my activities(UploadActivity.java) by taking information from 3 edit text boxes in another activity (LoginActivity.java) and passing that data into the other activity,
All the questions i found here on SO only prtains to a static URL i.e. www.blahblah.com/blah-blah.asp?My=Yes etc.
basicly the user must input his email, password and client ID(made by my company) and then it must be consolidated into a string
like this one
public static final String UPLOAD_URL =
"https://www.smartpractice.co.za/files-upload-ruben.asp?clientID=6868";
I'm using above url to upload user's location to the server.
Must I declare the edittext boxes in the activity? because at the moment it is only i the XML layout of the activity
I found this in another question and I don't understand how to implement it into my code.
Your edit text
EditText your_edit_text = (EditText) findViewById(R.id.your_id);
Get user data from edit text as fallows ..
String edit_text_data = your_edit_text.getText().toString();
Now when you need to put that data on url .. use this like ..
String your_url = "http://www.google.com=" + edit_text_data;
I want the Url here in this String in the "" quotations
public static final String UPLOAD_URL =
"https://www.smartpractice.co.za/files-upload-ruben.asp?MyForm=Yes";
UploadActivity JAVA
public class UploadActivity extends AppCompatActivity implements View.OnClickListener {
public static final String UPLOAD_URL = "https://www.smartpractice.co.za/files-upload-ruben.asp?MyForm=Yes";
public static final String UPLOAD_KEY = "image";
private int PICK_IMAGE_REQUEST = 1;
private Button buttonChoose;
private Button buttonUpload;
private ImageView imageView;
private Bitmap bitmap;
private Uri filePath;
#Override
public void onCreate(Bundle savedInstanceState ) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
init();
}
private void init(){
buttonChoose = findViewById(R.id.btnChoose);
buttonUpload = findViewById(R.id.btnUpload);
imageView = findViewById(R.id.imageView);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#SuppressWarnings("deprecation")
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
return Base64.encodeToString(imageBytes, Base64.DEFAULT);
}
private void uploadImage(){
#SuppressLint("StaticFieldLeak")
class UploadImage extends AsyncTask<Bitmap,Void,String> {
private ProgressDialog loading;
private RequestHandler rh = new RequestHandler();
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(UploadActivity.this, "Uploading Image", "Please wait...",true,true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(UploadActivity.this,s,Toast.LENGTH_LONG).show();
}
#RequiresApi(api=Build.VERSION_CODES.KITKAT)
#Override
protected String doInBackground(Bitmap... params) {
Bitmap bitmap = params[0];
String uploadImage = getStringImage(bitmap);
HashMap<String,String> data = new HashMap<>();
data.put(UPLOAD_KEY, uploadImage);
data.put("name",getFileName(filePath));
return rh.postRequest(UPLOAD_URL,data);
}
}
UploadImage ui = new UploadImage();
ui.execute(bitmap);
}
#Override
public void onClick(View v) {
if (v == buttonChoose) {
showFileChooser();
}
if(v == buttonUpload){
if(filePath!=null) {
uploadImage();
} else {
Toast.makeText(UploadActivity.this,"Select Image",Toast.LENGTH_LONG).show();
}
}
}
#RequiresApi(api=Build.VERSION_CODES.KITKAT)
String getFileName(Uri uri){
String result = null;
if (Objects.equals(uri.getScheme(), "content")) {
try (Cursor cursor=getContentResolver().query(uri, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
result=cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
}
}
if (result == null) {
result = uri.getPath();
assert result != null;
int cut = result.lastIndexOf('/');
if (cut != -1) {
result = result.substring(cut + 1);
}
}
return result;
}
}
**LoginActivity
the edit text boxes are in the XML layout so far **
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
}
In short Take editText values from LoginActivity and pass it to UploadActivity and use that information to build a URL in UploadActivity.
Take edittext values from LoginActivity & Pass the values to UploadActivity
Bind your views in onCreate method in LoginActivity (change the ids with yours) & pass the input to UploadActivity through Intent.
public class LoginActivity extends AppCompatActivity {
private EditText email,password,email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
email = findViewById(R.id.clientID);
Button loginBtn = findViewById(R.id.loginBtn);
loginBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
String emailAddress = email.getText().toString().trim();
String userPassword = password.getText().toString().trim();
//Pass the data to next activity
String clientId = clientID.getText().toString().trim();
Intent intent = new Intent(LoginActivity.this, UploadActivity.class);
intent.putExtra("clientId", clientId);
intent.putExtra("email", emailAddress);
intent.putExtra("password", userPassword);
startActivity(intent);
}
});
}
}
Use above information to build a URL in UploadActivity
#RequiresApi(api=Build.VERSION_CODES.KITKAT)
#Override
protected String doInBackground(Bitmap... params) {
Bitmap bitmap = params[0];
String uploadImage = getStringImage(bitmap);
HashMap<String,String> data = new HashMap<>();
data.put(UPLOAD_KEY, uploadImage);
data.put("name",getFileName(filePath));
Intent intent = getIntent();
String clientId = intent.getStringExtra("clientId");
Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
.authority("ww.smartpractice.co.za")
.appendPath("files-upload-ruben.asp")
.appendQueryParameter("clientID", clientId);
String myUrl = builder.build().toString();
return rh.postRequest(myUrl,data);
}
Cheers :)
Related
Almost its going a second week that I'm trying to upload multiple images on server as I can send single image on server but I don't know how to do it with multiple images.
By following this link I can upload only single image to the server but how can I upload multiple images to the server?
I've created a new project where I'm using a image picker library named as TedBottomPicker from which I can select multiple images.
I want to ask you can I use this same API for multiple image to upload on server?
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$image = $_POST['image'];
require_once('dbConnect.php');
$sql ="SELECT id FROM faltu ORDER BY id ASC";
$res = mysqli_query($con,$sql);
$id = 0;
while($row = mysqli_fetch_array($res)){
$id = $row['id'];
}
$path = "uploads/$id.png";
$server_ip = gethostbyname(gethostname());
$actualpath = 'http://'.$server_ip.'/imagess/'.$path;
$sql = "INSERT INTO faltu (image) VALUES ('$actualpath')";
if(mysqli_query($con,$sql)){
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded";
}
mysqli_close($con);
}else{
echo "Error";
}
And here is my Java code where I'm using TedBottomPicker library for selecting multiple images. Problem I'm getting here that how can I upload them on server? Here is what I've tried.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final String UPLOAD_URL = "http://192.168.1.105/imagess/upload.php";
public static final String UPLOAD_KEY = "image";
RelativeLayout rl_pickImage;
private List<Uri> selectedUriList;
private ViewGroup mSelectedImagesContainer;
private RequestManager requestManager;
TextView txt_img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rl_pickImage = findViewById(R.id.rel_pickImage);
mSelectedImagesContainer = findViewById(R.id.selected_photos_container);
txt_img = findViewById(R.id.txt_img);
Button buttonUpload = findViewById(R.id.buttonUpload);
requestManager = Glide.with(this);
rl_pickImage.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
#Override
public void onClick(View v) {
setMultiShowButton();
uploadImage();
}
private void setMultiShowButton() {
PermissionListener permissionlistener = new PermissionListener() {
#Override
public void onPermissionGranted() {
TedBottomPicker.with(MainActivity.this)
//.setPeekHeight(getResources().getDisplayMetrics().heightPixels/2)
.setPeekHeight(1600)
.showTitle(false)
.setCompleteButtonText("Done")
.setEmptySelectionText("No Select")
.setSelectMaxCount(5)
.setDeSelectIcon(R.drawable.error)
.setSelectedUriList(selectedUriList)
.showMultiImage(new TedBottomSheetDialogFragment.OnMultiImageSelectedListener() {
#Override
public void onImagesSelected(List<Uri> uriList) {
selectedUriList = uriList;
showUriList(uriList);
}
});
}
#Override
public void onPermissionDenied(ArrayList<String> deniedPermissions) {
Toast.makeText(MainActivity.this, "Permission Denied\n" + deniedPermissions.toString(), Toast.LENGTH_SHORT).show();
}
};
checkPermission(permissionlistener);
}
private void checkPermission(PermissionListener permissionlistener) {
TedPermission.with(MainActivity.this)
.setPermissionListener(permissionlistener)
.setDeniedMessage("If you reject permission,you can not use this service\n\nPlease turn on permissions at [Setting] > [Permission]")
.setPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
.check();
}
private void showUriList(List<Uri> uriList) {
// Remove all views before
// adding the new ones.
mSelectedImagesContainer.removeAllViews();
// iv_image.setVisibility(View.GONE);
mSelectedImagesContainer.setVisibility(View.VISIBLE);
txt_img.setText("Select image");
int widthPixel = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());
int heightPixel = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());
for (Uri uri : uriList) {
View imageHolder = LayoutInflater.from(this).inflate(R.layout.image_item, null);
CircleImageView thumbnail = imageHolder.findViewById(R.id.media_image);
requestManager
.load(uri.toString())
.apply(new RequestOptions().fitCenter())
.into(thumbnail);
mSelectedImagesContainer.addView(imageHolder);
thumbnail.setLayoutParams(new FrameLayout.LayoutParams(widthPixel, heightPixel));
txt_img.setText("Remove or Select Another");
}
}
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
return Base64.encodeToString(imageBytes, Base64.DEFAULT);
}
private void uploadImage() {
class UploadImage extends AsyncTask<Bitmap, Void, String> {
private ProgressDialog loading;
private RequestHandler rh = new RequestHandler();
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Uploading...", null, true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Bitmap... params) {
Bitmap bitmap = params[0];
String uploadImage = getStringImage(bitmap);
HashMap<String, String> data = new HashMap<>();
data.put(UPLOAD_KEY, uploadImage);
return rh.sendPostRequest(data);
}
}
UploadImage ui = new UploadImage();
ui.execute(bitmap);
}
}
I have a page in my app with similar codes with different values and they send info to my PHP MySQL just fine. On the other hand, this page in my app cannot send the files and giving me an error message:
E/Volley: [258] BasicNetwork.performRequest: Unexpected response code 406
for http://applybpojobs.com/widevalueappfiles/server/api/addvehicle.php
I have already tried numerous solutions on web and this site to no avail. Can anyone help me figure this out?
Here is my java:
public class Addvehicle extends AppCompatActivity {
private static final String TAG = Addvehicle.class.getSimpleName();
private EditText plate_number, vin, car_make, car_model, car_year, displacement,
fuel_type, transmission, mileage, owner_name, address, phone_number,
email_adress, facebook;
private TextView btnCreate;
private TextView btnClose;
private ImageView upload_car, preview;
private int GALLERY = 1, CAMERA = 2;
private static String URL_ADD_VEHICLE = "http://abcde/server/api/addvehicle.php";
//private static String URL_VEHICLE_IMAGE = "http://abcde/server/api/addvehicle.php";
private Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addvehicle);
requestMultiplePermissions();
/*EditText Area*/
plate_number = findViewById(R.id.plate_number);
vin = findViewById(R.id.vin);
car_make = findViewById(R.id.car_make);
car_model = findViewById(R.id.car_model);
car_year = findViewById(R.id.car_year);
displacement = findViewById(R.id.displacement);
fuel_type = findViewById(R.id.fuel_type);
transmission = findViewById(R.id.transmission);
mileage = findViewById(R.id.mileage);
owner_name = findViewById(R.id.owner_name);
address = findViewById(R.id.address);
phone_number = findViewById(R.id.phone_number);
email_adress = findViewById(R.id.email_adress);
facebook = findViewById(R.id.facebook);
/*TextView Area*/
btnClose = findViewById(R.id.btnClose);
btnCreate = findViewById(R.id.btnCreate);
/*Button Area*/
upload_car = findViewById(R.id.iv);
preview = findViewById(R.id.iv);
upload_car.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showPictureDialog();
}
});
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Addvehicle.this, Home.class));
}
});
btnCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showLoader();
addVehicle(getStringImage(bitmap));
}
});
}
private void showPictureDialog(){
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera" };
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
case 1:
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
private void takePhotoFromCamera() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY) {
if (data != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);
String path = getStringImage(bitmap);
Toast.makeText(Addvehicle.this, "Image Saved!", Toast.LENGTH_SHORT).show();
preview.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(Addvehicle.this, "Failed!", Toast.LENGTH_SHORT).show();
}
addVehicle(getStringImage(bitmap));
}
} else if (requestCode == CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
preview.setImageBitmap(thumbnail);
getStringImage(thumbnail);
Toast.makeText(Addvehicle.this, "Image Saved!", Toast.LENGTH_SHORT).show();
}
addVehicle(getStringImage(bitmap));
}
private void addVehicle(final String stringImage) {
final String plate_number = this.plate_number.getText().toString().trim();
final String vin = this.vin.getText().toString().trim();
final String car_make = this.car_make.getText().toString().trim();
final String car_model = this.car_model.getText().toString().trim();
final String car_year = this.car_year.getText().toString().trim();
final String displacement = this.displacement.getText().toString().trim();
final String fuel_type = this.fuel_type.getText().toString().trim();
final String transmission = this.transmission.getText().toString().trim();
final String mileage = this.mileage.getText().toString().trim();
final String owner_name = this.owner_name.getText().toString().trim();
final String address = this.address.getText().toString().trim();
final String phone_number = this.phone_number.getText().toString().trim();
final String email_adress = this.email_adress.getText().toString().trim();
final String facebook = this.facebook.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_ADD_VEHICLE,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i(TAG, response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
String Success = jsonObject.getString("success");
if (Success.equals("1")){
hideLoader();
Toast.makeText(Addvehicle.this,"Vehicle Added Successfully",Toast.LENGTH_SHORT).show();
}else if (Success.equals("0")){
hideLoader();
Toast.makeText(Addvehicle.this,"Vehicle Already Exist",Toast.LENGTH_SHORT).show();
}
}catch (JSONException e){
e.printStackTrace();
hideLoader();
Toast.makeText(Addvehicle.this,"Vehicle Added Error"+e.toString(),Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
Toast.makeText(Addvehicle.this,"Vehicle Added Error"+error.toString(),Toast.LENGTH_SHORT).show();
hideLoader();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError{
Map<String, String> params = new HashMap<>();
params.put("plate_number", plate_number);
params.put("vin", vin);
params.put("car_make", car_make);
params.put("car_model", car_model);
params.put("car_year", car_year);
params.put("displacement", displacement);
params.put("fuel_type", fuel_type);
params.put("transmission", transmission);
params.put("mileage", mileage);
params.put("owner_name", owner_name);
params.put("address", address);
params.put("phone_number", phone_number);
params.put("email_adress", email_adress);
params.put("facebook", facebook);
params.put("photo", stringImage);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void showLoader(){
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Adding Vehicle...");
progressDialog.show();
}
public void hideLoader(){
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.hide();
}
public String getStringImage(Bitmap bitmap){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] imageByteArray = byteArrayOutputStream.toByteArray();
String encodedImage = Base64.encodeToString(imageByteArray, Base64.DEFAULT);
return encodedImage;
}
private void requestMultiplePermissions(){
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
Toast.makeText(getApplicationContext(), "All permissions are granted by user!", Toast.LENGTH_SHORT).show();
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// show alert dialog navigating to Settings
//openSettingsDialog();
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).
withErrorListener(new PermissionRequestErrorListener() {
#Override
public void onError(DexterError error) {
Toast.makeText(getApplicationContext(), "Some Error! ", Toast.LENGTH_SHORT).show();
}
})
.onSameThread()
.check();
}
This is my server api file (mysqli) which is giving me the error response from logcat with this url : "http://abcde/server/api/addvehicle.php"
error_reporting(E_ALL); ini_set('display_errors', 1);
require '../core/connect.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$plate_number=$_POST['plate_number'];
$vin=$_POST['vin'];
$car_make=$_POST['car_make'];
$car_model=$_POST['car_model'];
$car_year=$_POST['car_year'];
$displacement=$_POST['displacement'];
$fuel_type=$_POST['fuel_type'];
$transmission=$_POST['transmission'];
$mileage=$_POST['mileage'];
$owner_name=$_POST['owner_name'];
$address=$_POST['address'];
$phone_number=$_POST['phone_number'];
$email_adress=$_POST['email_adress'];
$facebook=$_POST['facebook'];
$adddate = date("d/m/Y");
$photo = $_POST['photo'];
$id=uniqid();
$path = "vehicle_upload/$id.jpeg";
$finalpath =
"http://abcde/server/api/addvehicle.php".$path;
$sql1=mysqli_query($connect,"SELECT * FROM _addvehicle WHERE
PlateNumber='$plate_number'");
if (mysqli_num_rows($sql1) > 0) {
$result['success'] = "0";
$result['message'] = "error";
echo json_encode($result);
}else{
$sql = mysqli_query($connect, "INSERT IGNORE INTO
_addvehicle(PlateNumber, Vin, Make, Model, Year, Displacement, FuelType,
Transmission, Mileage, OwnerorCompany, HomeorCompanyAddress, ContactNumber,
EmailAddress, FacebookID, AddDate, vehicleImage)VALUES('$plate_number','$vin','$car_make','$car_model','$car_year','$displacement','$fuel_type','$transmission','$mileage','$owner_name','$address','$phone_number','$email_adress','$facebook','$adddate','$finalpath')");
if ($sql) {
if (file_put_contents($path, base64_decode($photo))) {
$result['success'] = "1";
$result['message'] = "success";
echo json_encode($result);
//mysqli_close($connect);
}
}
}
I am having a hard time identifying what went wrong. Although I am seeing that logcat points me to the php file, it doesn't specifically tell me what to change. This page was working a couple of days ago.
Please help me. I can not create download URL Firebase storage. I want to when a pic upload into Firebase Storage, it save the URL to Firebase database. I tried a lot of way. But I didn't it. At the web of Firebase Database is not URL.
It show look this; imageUrl: "images/67824cbe-916e-4c74-82df-44227aa1d125". Its the name of Storage pics name.
My Upload Firebase Storage and Firebase Database activity is here;
package com.eraykalelioglu.ki_ta;
//imports here
public class BookActivity extends AppCompatActivity {
EditText editTextisim;
EditText editTextyazar;
Button buttonkitabikaydet;
Spinner spinnerGenres;
ImageView imageViewkitapkapakresmi;
DatabaseReference databaseKitaplar;
private Uri filePath;
private final int PICK_IMAGE_REQUEST = 1;
FirebaseStorage storage;
StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
databaseKitaplar = FirebaseDatabase.getInstance().getReference("Kitaplar");
editTextisim = (EditText) findViewById(R.id.editTextisim);
editTextyazar = (EditText) findViewById(R.id.editTextyazar);
imageViewkitapkapakresmi = (ImageView) findViewById(R.id.imageViewkitapkapakresmi);
buttonkitabikaydet = (Button) findViewById(R.id.buttonkitabikaydet);
spinnerGenres = (Spinner) findViewById(R.id.spinnerGenres);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference("images/");
buttonkitabikaydet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Kaydet();
}
});
imageViewkitapkapakresmi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chooseImage();
}
});
}
private void Kaydet(){
imageViewkitapkapakresmi.setDrawingCacheEnabled(true);
imageViewkitapkapakresmi.buildDrawingCache();
Bitmap bitmap = ((BitmapDrawable) imageViewkitapkapakresmi.getDrawable()).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] data = byteArrayOutputStream.toByteArray();
String mImageUrl = "images/" +UUID.randomUUID().toString();
final StorageReference storageReference = storage.getReference(mImageUrl);
UploadTask uploadTask = storageReference.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(BookActivity.this, "Yükleme Başarısız"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> downloadUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl();
Log.d("onSuccess", "" + downloadUrl);
}
});
String isim = editTextisim.getText().toString().trim();
String yazar = editTextyazar.getText().toString().trim();
String genre = spinnerGenres.getSelectedItem().toString();
if (!TextUtils.isEmpty(isim) && !TextUtils.isEmpty(yazar)){
String id = databaseKitaplar.push().getKey();
Kitaplar kitaplar = new Kitaplar (id, isim, yazar, genre, mImageUrl);
databaseKitaplar.child(id).setValue(kitaplar);
Toast.makeText(this, "Kitabınız Başarıyla Kaydedildi", Toast.LENGTH_LONG).show();
startActivity(new Intent(BookActivity.this, Listesayfahali.class));
} else {
Toast.makeText(this, "Kitabın İsmi ve Yazarı Doldurulması Gereklidir", Toast.LENGTH_SHORT).show();
}
}
private void chooseImage(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Kitaba ait resmi seçin"), PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){
filePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageViewkitapkapakresmi.setImageBitmap(bitmap);
}
catch (IOException e){
e.printStackTrace();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuLogout:
FirebaseAuth.getInstance().signOut();
finish();
startActivity(new Intent(BookActivity.this, MainActivity.class));
break;
}
switch (item.getItemId()){
case R.id.menuKitaplar:
startActivity(new Intent(BookActivity.this, Listesayfahali.class));
}
return true;
}
}
My Database activity is here;
package com.eraykalelioglu.ki_ta;
public class Kitaplar {
String kitaplarId;
String kitaplarisim;
String kitaplaryazar;
String kitaplarGenre;
String mImageUrl;
public Kitaplar() {
}
public Kitaplar(String kitaplarId, String kitaplarisim, String kitaplaryazar, String kitaplarGenre, String imageUrl) {
this.kitaplarId = kitaplarId;
this.kitaplarisim = kitaplarisim;
this.kitaplaryazar = kitaplaryazar;
this.kitaplarGenre = kitaplarGenre;
mImageUrl =imageUrl;
}
public String getKitaplarId() {
return kitaplarId;
}
public String getKitaplarisim() {
return kitaplarisim;
}
public String getKitaplaryazar() {
return kitaplaryazar;
}
public String getKitaplarGenre() {
return kitaplarGenre;
}
public String getImageUrl() {return mImageUrl ; }
public void setImageUrl(String imageUrl){ this.mImageUrl= imageUrl; }
}`
When I'm taking an image from gallery and want to insert into server, it puts the image with zero byte size. And in the table I have two columns, rollno and image. I get the rollno value from shared preference but it does not put the rollno in the database table, rollno column shows empty.
Help me to resolve this.
Here is my code
public class ImageEditActivity extends AppCompatActivity implements View.OnClickListener {
ImageView image;
Button btn_cancel_edit,btn_done_edit;
Bitmap bitmap;
SharedPreferences sp;
String rollno;
String KEY_Rollno = "rollno";
String KEY_IMAGE = "image";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_edit);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
image=(ImageView)findViewById(R.id.image);
bitmap=ProfileActivity.bitmap;
image.setImageBitmap(bitmap);
btn_done_edit = (Button) findViewById(R.id.btn_done_edit);
btn_cancel_edit = (Button) findViewById(R.id.btn_cancel_edit);
btn_done_edit.setOnClickListener(this);
btn_cancel_edit.setOnClickListener(this);
sp=getSharedPreferences("rajput",MODE_PRIVATE);
rollno=sp.getString("rollno",null);
}
#Override
public void onClick(View v) {
if(v == btn_done_edit){
uploadImage();
}
if(v == btn_cancel_edit){
onBackPressed();
}
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void uploadImage() {
String UPLOAD_URL ="http://aptronnoida.com/applock/image_insert.php";
final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
StringRequest stringRequest = new StringRequest(Request.Method.GET, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
//Disimissing the progress dialog
loading.dismiss();
//Showing toast message of the response
Toast.makeText(ImageEditActivity.this, s , Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
loading.dismiss();
//Showing toast
Toast.makeText(ImageEditActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
String image = getStringImage(bitmap);
//Creating parameters
Map<String,String> params = new Hashtable<String, String>();
//Adding parameters
params.put(KEY_Rollno,rollno);
params.put(KEY_IMAGE, image);
//returning parameters
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
public void onBackPressed(){
super.finish();
}
}
Please try below working code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button buttonChoose;
private Button buttonUpload;
private ImageView imageView;
private EditText editTextName;
private Bitmap bitmap;
private int PICK_IMAGE_REQUEST = 1;
private String UPLOAD_URL = "http://coderzheaven.com/sample_file_upload/upload_image.php";
private String KEY_IMAGE = "image";
private String KEY_NAME = "name";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
editTextName = (EditText) findViewById(R.id.editText);
imageView = (ImageView) findViewById(R.id.imageView);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void uploadImage() {
//Showing the progress dialog
final ProgressDialog loading = ProgressDialog.show(this, "Uploading...", "Please wait...", false, false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
//Disimissing the progress dialog
loading.dismiss();
//Showing toast message of the response
Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
loading.dismiss();
//Showing toast
Toast.makeText(MainActivity.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
String image = getStringImage(bitmap);
//Getting Image Name
String name = editTextName.getText().toString().trim();
//Creating parameters
Map<String, String> params = new Hashtable<String, String>();
//Adding parameters
params.put(KEY_IMAGE, image);
params.put("Roll_NO", "5");
//returning parameters
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting the Bitmap to ImageView
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onClick(View v) {
if (v == buttonChoose) {
showFileChooser();
}
if (v == buttonUpload) {
uploadImage();
}
}
}
Reference source: http://www.coderzheaven.com/2011/04/25/android-upload-an-image-to-a-server/
Try changing it to PNG and reduce the compression in the following line
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
To
bmp.compress(Bitmap.CompressFormat.PNG, 80, baos);
In my app, the user can upload the image to the server, but in some devices such as phones of version (4.4.4. 5.0.1 and 5.1.1) or even for all devices when selecting the image from "gallery" the app crashes. But when I choose the option "photos" and select photo and upload it, it works normally, so how can fix this problem and can select the photo from gallery or any album without crashing also upload it without any problem?
Given below is the full code of uploading the image:
public class send extends AppCompatActivity {
private Button buttonChoose;
private Button buttonUpload;
private ImageView imageView;
private EditText editTextName;
private EditText editTextPhone;
private EditText editTextText;
private Bitmap bitmap;
private int PICK_IMAGE_REQUEST = 1;
private static String host=PathConfig.hostName;
private String UPLOAD_URL ="http://"+host+"/upload.php";
private String KEY_IMAGE = "image";
private String KEY_NAME = "name";
private String KEY_PHONE = "phone";
private String KEY_TEXT = "text";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.arrowb);
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // setting the back arrow in the toolbar
getSupportActionBar().setDisplayShowHomeEnabled(true);
setTitle("إرسال شكوى أو إقتراح");
buttonChoose = (Button) findViewById(R.id.chooseButton);
buttonUpload = (Button) findViewById(R.id.sendButton);
editTextName = (EditText) findViewById(R.id.name);
editTextPhone= (EditText) findViewById(R.id.phone);
editTextText= (EditText) findViewById(R.id.text);
imageView = (ImageView) findViewById(R.id.imageView4);
buttonChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFileChooser();
}
});
buttonUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadImage();
}
});
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if(bmp!=null){
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
}
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void uploadImage() {
final String name = editTextName.getText().toString().trim();
final String phone = editTextPhone.getText().toString().trim();
final String text = editTextText.getText().toString().trim();
if (name.matches("") || phone.matches("") || text.matches("")) {
Toast.makeText(this, " عذرا, لا يمكن ترك حقول فارغة", Toast.LENGTH_SHORT).show();
} else {
//Showing the progress dialog
final ProgressDialog loading = ProgressDialog.show(this, "جاري الإرسال...", "الرجاء الإنتظار...", false, false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
//Disimissing the progress dialog
loading.dismiss();
//Showing toast message of the response
Toast.makeText(send.this, s, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
loading.dismiss();
//Showing toast
Toast.makeText(send.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
String image = getStringImage(bitmap);
//Getting Image Name
//Creating parameters
Map<String, String> params = new HashMap<String, String>();
//Adding parameters
params.put(KEY_IMAGE, image);
params.put(KEY_NAME, name);
params.put(KEY_PHONE, phone);
params.put(KEY_TEXT, text);
//returning parameters
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting the Bitmap to ImageView
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
I think you missing to ask permission.Can you check this is useful for you?
profile_img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT >= 23) {
// Marshmallow+
if (!checkAccessFineLocationPermission() || !checkAccessCoarseLocationPermission() || !checkWriteExternalStoragePermission()) {
requestPermission();
} else {
selectImage();
}
}else{
selectImage();
}
}
});