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; }
}`
Related
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.
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 :)
I'm working on an app in the Android studio. Click the button in the Fragment to open a dialog box and include a picture and a brief description. (Pictures are taken from your gallery.) Click OK to close the dialog box and include the image and description in the RecyclerView that exists in the Fragment. But this code that I've woven has a description, but it doesn's image. I wanted to hear a solution to this, so I asked you a question.
I'd appreciate your reply!
To briefly explain how my code works, when I receive an image from the dialog box, I send the path (/storage/emulated/0/Pictures/a.jpg) of the file as a toast message, and as soon as the dialog is closed, the imagepath and description are transferred to the String form, and the imagepath is converted from Fragment to uri and changed to Bitmap using it to apply to RecyclerView.
Below is my code.
Fragment.java
btn_addlist = view.findViewById(R.id.btn_addlist);
btn_addlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment_cus dialog = new DialogFragment_cus();
dialog.show(getActivity().getSupportFragmentManager(), "tag");
dialog.setDialogResult(new DialogFragment_cus.OnMyDialogResult() {
// result : uri, result2 : dlg_edtName, result3 : dlg_edtSubtitle
#Override
public void finish(String result, String result2, String result3) {
imageUri = result; RecyclerInputName = result2;
RecyclerInputSubtitle = result3;
Uri uri = Uri.parse("file://" + imageUri);
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
RecyclerItem_cus item = new RecyclerItem_cus(bitmap, RecyclerInputName, RecyclerInputSubtitle);
mArrayList.add(0, item);
mAdapter.notifyDataSetChanged();
Toast.makeText(getActivity(), "finish.", Toast.LENGTH_SHORT).show();
}
});
}
});
DialogFragment.java
dlg_AddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(intent, 1);
}
});
dlg_ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment_cus fragment = new DialogFragment_cus();
String input1 = dlg_edtName.getText().toString();
String input2 = dlg_edtSubtitle.getText().toString();
if(fragment != null) {
if(mDialogResult != null ) {
mDialogResult.finish(name_Str, input1, input2);
}
}
dismiss();
}
});
dlg_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
});
return view;
}
public void setDialogResult(OnMyDialogResult dialogResult){
mDialogResult = dialogResult;
}
public interface OnMyDialogResult{
void finish(String result, String result2, String result3);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
try {
name_Str = getImageNameToUri(data.getData());
InputStream in = getActivity().getContentResolver().openInputStream(data.getData());
Bitmap img = BitmapFactory.decodeStream(in);
in.close();
dlg_ImageView.setImageBitmap(img);
dlg_ImageView.setBackgroundResource(android.R.color.white);
Toast.makeText(getActivity(), "name_Str : "+name_Str , Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public String getImageNameToUri(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(uri, projection, null, null, null);
getActivity().startManagingCursor(cursor);
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(columnIndex);
}
RecyclerView_cusAdapter.java
#Override
public void onBindViewHolder(#NonNull final MyViewHolder myViewHolder, int i) {
final RecyclerItem_cus item = items.get(i);
if (item != null) {
Glide.with(context)
.load(item.getImage())
.asBitmap()
.format(DecodeFormat.PREFER_ARGB_8888)
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
myViewHolder.cus_img.setImageBitmap(resource);
}
});
myViewHolder.cus_title.setText(item.getTitle());
myViewHolder.cus_subtitle.setText(item.getSubTitle());
}
}
#Override
public int getItemCount() {
return this.items.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView cus_title;
TextView cus_subtitle;
ImageView cus_img;
public MyViewHolder(View itemView) {
super(itemView);
cus_title = itemView.findViewById(R.id.cus_title);
cus_subtitle = itemView.findViewById(R.id.cus_subtitle);
cus_img = itemView.findViewById(R.id.cus_img);
}
}
RecyclerItem_cus.java
public class RecyclerItem_cus {
private Bitmap image;
private String title;
private String subTitle;
public RecyclerItem_cus(Bitmap image, String title, String subTitle) {
this.image = image;
this.title = title;
this.subTitle = subTitle;
}
public Bitmap getImage() {
return image;
}
public String getTitle() {
return title;
}
public String getSubTitle() {
return subTitle;
}
You can try to use Glide with the File object directly :
Glide.with(mContext)
.load(new File(item.getImage())) // Uri of the picture
.into(myViewHolder.cus_img);
i build a chat application using firebase and i want to send multiple image to firebase storage.
using this library
compile 'com.github.darsh2:MultipleImageSelect:3474549'
At the top
private StorageReference storageRef;
private FirebaseApp app;
private FirebaseStorage storage;
onCreate()Method
app = FirebaseApp.getInstance();
storage =FirebaseStorage.getInstance(app);
button click action
Gallary.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ChatActivity.this, AlbumSelectActivity.class);
intent.putExtra(Constants.INTENT_EXTRA_LIMIT, 10);
startActivityForResult(intent, Constants.REQUEST_CODE);
pwindo1.dismiss();
}
});
Activity result
if (requestCode == Constants.REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList<Image> images = data.getParcelableArrayListExtra(Constants.INTENT_EXTRA_IMAGES);
Uri uri = Uri.parse(String.valueOf(images));
storageRef = storage.getReference("photos");
final StorageReference photoRef = storageRef.child(uri.getLastPathSegment());
photoRef.putFile(uri)
.addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
String content = downloadUrl.toString();
if (content.length() > 0) {
editWriteMessage.setText("");
Message newMessage = new Message();
newMessage.text = content;
newMessage.idSender = StaticConfig.UID;
newMessage.idReceiver = roomId;
newMessage.timestamp = System.currentTimeMillis();
FirebaseDatabase.getInstance().getReference().child("message/" + roomId).push().setValue(newMessage);
}
}
});
}
Variables
private static final int PICK_IMAGE = 1;
Button chooserBtn, uploaderBtn;
TextView alert;
private Uri ImageUri;
ArrayList ImageList = new ArrayList();
private int upload_count = 0;
private ProgressDialog progressDialog;
ArrayList urlStrings;
onCreate()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uploaderBtn = findViewById(R.id.uploader);
chooserBtn = findViewById(R.id.chooser);
alert = findViewById(R.id.alert);
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Uploading Images please Wait.........!!!!!!");
chooserBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(intent, PICK_IMAGE);
}
});
Uploader Button
uploaderBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
urlStrings = new ArrayList<>();
progressDialog.show();
alert.setText("If Loading Takes to long press button again");
StorageReference ImageFolder = FirebaseStorage.getInstance().getReference().child("ImageFolder");
for (upload_count = 0; upload_count < ImageList.size(); upload_count++) {
Uri IndividualImage = ImageList.get(upload_count);
final StorageReference ImageName = ImageFolder.child("Images" + IndividualImage.getLastPathSegment());
ImageName.putFile(IndividualImage).addOnSuccessListener(
new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
ImageName.getDownloadUrl().addOnSuccessListener(
new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
urlStrings.add(String.valueOf(uri));
if (urlStrings.size() == ImageList.size()){
storeLink(urlStrings);
}
}
}
);
}
}
);
}
}
});
}
This Line of will help us to store Links of All Images under One Node
if (urlStrings.size() == ImageList.size()){
storeLink(urlStrings);
}
Store Links To Firebase Realtime Database
private void storeLink(ArrayList<String> urlStrings) {
HashMap<String, String> hashMap = new HashMap<>();
for (int i = 0; i <urlStrings.size() ; i++) {
hashMap.put("ImgLink"+i, urlStrings.get(i));
}
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("User");
databaseReference.push().setValue(hashMap)
.addOnCompleteListener(
new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Successfully Uplosded", Toast.LENGTH_SHORT).show();
}
}
}
).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
progressDialog.dismiss();
alert.setText("Uploaded Successfully");
uploaderBtn.setVisibility(View.GONE);
ImageList.clear();
}
onActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE) {
if (resultCode == RESULT_OK) {
if (data.getClipData() != null) {
int countClipData = data.getClipData().getItemCount();
int currentImageSlect = 0;
while (currentImageSlect < countClipData) {
ImageUri = data.getClipData().getItemAt(currentImageSlect).getUri();
ImageList.add(ImageUri);
currentImageSlect = currentImageSlect + 1;
}
alert.setVisibility(View.VISIBLE);
alert.setText("You have selected" + ImageList.size() + "Images");
chooserBtn.setVisibility(View.GONE);
} else {
Toast.makeText(this, "Please Select Multiple Images", Toast.LENGTH_SHORT).show();
}
}
}
}
}
It is working fine.
if (requestCode == Constants.REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList<Image> images = data.getParcelableArrayListExtra(Constants.INTENT_EXTRA_IMAGES);
Uri[] uri=new Uri[images.size()];
for (int i =0 ; i < images.size(); i++) {
uri[i] = Uri.parse("file://"+images.get(i).path);
storageRef = storage.getReference("photos");
final StorageReference ref = storageRef.child(uri[i].getLastPathSegment());
ref.putFile(uri[i])
.addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
String content = downloadUrl.toString();
if (content.length() > 0) {
editWriteMessage.setText("");
Message newMessage = new Message();
newMessage.text = content;
newMessage.idSender = StaticConfig.UID;
newMessage.idReceiver = roomId;
newMessage.timestamp = System.currentTimeMillis();
FirebaseDatabase.getInstance().getReference().child("message/" + roomId).push().setValue(newMessage);
}
}
});
}
}
For return list imageUrls with same order of images selected from gallery
don't use for loop for every uri
after you get ArrayList<Uri> imageUriList and you want now upload it to firebase storage then return the list of url for every image in same order your selected it, so i use recursion on below method until upload all uri
private void uploadImages(#NonNull ArrayList<String> imagesUrl,ArrayList<Uri> imageUriList) {
StorageReference storageReference = FirebaseStorage.getInstance().getReference("Products").child(UUID.randomUUID().toString());
Uri uri = imageUriList.get(imagesUrl.size());
storageReference
.putFile(uri).addOnSuccessListener(taskSnapshot ->
storageReference.getDownloadUrl().addOnCompleteListener(task -> {
String url = Objects.requireNonNull(task.getResult()).toString();
imagesUrl.add(url);
//if same size so all image is uploaded, then sent list of url to to some method
if(imagesUrl .size() == imageUriList.size()){
allImageUploadedNow(imagesUrl);
}else {
uploadImages(imagesUrl);
}
}))
.addOnFailureListener(e -> {
Log.e("OnFailureImageListener", Objects.requireNonNull(e.getMessage()));
//some image is fails to upload
});
}
so now after get imageUriList value from OnActivityResult we can call method by this;
uploadImages(new ArrayList<>(),uriFilesList);
and when finish to upload all image you can handle it inside
private void allImageUploadedNow(ArrayList<String> imagesUrl){
//handle imagesUrl
}
This utility class I create it to upload multiple images to firebase storage using kotlin with help of coroutine. if you have any enhancement please tell me.
you need to add these dependencies firstly.
implementation 'com.google.firebase:firebase-storage-ktx:19.1.1'
//Firebase adds support to Coroutines through the kotlinx-coroutines-play-serviceslibrary
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.3.1"
for more info check link, github link
object FirebaseUtils {
suspend fun uploadPhotos(photosUri: ArrayList<File>): List<PhotoUrl> {
val storageRef = Firebase.storage.reference
val photosUrls = ArrayList<PhotoUrl>()
val uploadedPhotosUriLink = withContext(CoroutineScope(Dispatchers.IO).coroutineContext) {
(photosUri.indices).map { index ->
async(Dispatchers.IO) {
uploadPhoto(storageRef, photosUri[index])
}
}
}.awaitAll()
uploadedPhotosUriLink.forEach { photoUriLink -> photosUrls.add(PhotoUrl(photoUriLink.toString())) }
return photosUrls
}
private suspend fun uploadPhoto(storageRef: StorageReference, photoFile: File): Uri {
val fileName = UUID.randomUUID().toString()
val fileUri = Uri.fromFile(photoFile)
return storageRef.child(fileName)
.putFile(fileUri)
.await()
.storage
.downloadUrl
.await()
}
}
In my case of uploading multiple images into firebase I have used forEach(). forEach() method had helped me to upload images successfully into firebase
import { getStorage, ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";
const Product =()=>{
const [file, setFile] =useState([])
Object.values(file).forEach(val => {
const storage = getStorage();
const storageRef = ref(storage, 'images/val.name');
const uploadTask = uploadBytesResumable(storageRef, val);
uploadTask.on('state_changed',
(snapshot) => {
number of bytes to be uploaded
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case 'paused':
console.log('Upload is paused');
break;
case 'running':
console.log('Upload is running');
break;
}
},
(error) => {
},
() => {
getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
console.log('File available at', downloadURL);
});
}
);
})
return (
<button onClick={(e) => setFile(e.target.files)}/>
)
}
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();
}
}
});