I want to allow the user to upload two images,Cover and Logo.Then have them saved in firestore.I get an error at
Picasso.get().load(uri).into(Logo); line saying
no suitable method found for into(Uri)
method RequestCreator.into(Target) is not applicable
(argument mismatch; Uri cannot be converted to Target)
method RequestCreator.into(ImageView) is not applicable
(argument mismatch; Uri cannot be converted to ImageView)
package com.example.littlemarketplaceapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
public class Shop extends AppCompatActivity {
private ImageButton Logoimage;
private ImageButton Cover;
private EditText ShopnameEditText;
private TextView ShowShopName;
private Button SaveButton;
DatabaseReference databaseReference1;
private FirebaseAuth mAuth;
StorageReference storageReference = FirebaseStorage.getInstance().getReference();
StorageReference storageReference1 = FirebaseStorage.getInstance().getReference();
Uri Logo;
Uri coverUri;
private Uri uri;
int coverOrLogo;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shop);
Intent intent = getIntent();
String emaila = intent.getExtras().getString("emaili");
String passworda = intent.getExtras().getString("passwordi");
String fullnamea = intent.getExtras().getString("fullnamei");
String usernamea = intent.getExtras().getString("usernamei");
String mobilea = intent.getExtras().getString("mobilei");
String Shopname;
Logoimage = findViewById(R.id.shoplogobutton);
Cover = findViewById(R.id.coverphotobutton);
ShowShopName = findViewById(R.id.shopname);
ShopnameEditText = findViewById(R.id.shopnameedittext);
Shopname = ShopnameEditText.getText().toString().trim();
String key = databaseReference1.push().getKey();
//Saves Owner's Data
SaveButton.setOnClickListener(v -> {
ForOwner s_owner = new ForOwner(fullnamea, usernamea, emaila, mobilea, passworda, Shopname);
databaseReference1.child(key).setValue(s_owner);
Toast.makeText(getApplicationContext(), "Registration complete", Toast.LENGTH_SHORT).show();
});
//Uploads the Logo
Logoimage.setOnClickListener(view -> {
//open Gallery
Intent openGalleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(openGalleryIntent, 1000);
});
//Uploads the Cover photo
Cover.setOnClickListener(view -> {
//open Gallery
Intent openGalleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(openGalleryIntent, 2000);
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #androidx.annotation.Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1000 && resultCode == Activity.RESULT_OK) {
Uri imageUri1 = data.getData();
Logoimage.setImageURI(imageUri1);
uploadImageToFirebase(imageUri1, 1);
} else if (requestCode == 2000 && resultCode == Activity.RESULT_OK) {
Uri imageUri2 = data.getData();
Cover.setImageURI(imageUri2);
uploadImageToFirebase(imageUri2, 0);
}
}
//}
private <final_fileRef> void uploadImageToFirebase(Uri imageUri1, int coverOrLogo) {
//upload image to firebase
StorageReference fileRef = null;
if (coverOrLogo == 1) {
fileRef = storageReference.child("logo.jpg");
} else if (coverOrLogo == 0) {
fileRef = storageReference.child("cover.jpg");
}
fileRef.putFile(imageUri1).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileRef.putFile(imageUri1).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(Uri uri) {
if (coverOrLogo == 1) {
Picasso.get().load(uri).into(Logo);
}
if (coverOrLogo == 0) {
Picasso.get().load(uri).into(Cover);
}
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Shop.this, "Failed", Toast.LENGTH_SHORT).show();
}
});
}
}
In your code Logo is Uri
You need this:
Picasso.get().load(uri).into(imageView);
where imageView is ImageView object in your layout
Related
I am facing in android studio when i am upload image to the server its upload successfully but when i am select a pdf file and upload to the server the App will be crashed? How could i upload a pdf file to the server?
// #POST("User/UploadFiles?patientID=28609")
#Multipart
#POST("User/UploadFiles")
Call<ResponseBody> uploadFile(#Query("patientID") int patientID,
#Part MultipartBody.Part file);
This is my Code.
package com.maxvecare.itocean.pk.usersactivities;
import static com.maxvecare.itocean.pk.usersactivities.DoctorsActivity.TAG;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.maxvecare.itocean.pk.R;
import com.maxvecare.itocean.pk.apisutilities.ApiInterface;
import com.maxvecare.itocean.pk.apisutilities.ApiUtilities;
import com.maxvecare.itocean.pk.useradapters.DocumentAdapter;
import com.maxvecare.itocean.pk.usermodels.DocumentsClass;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class UploadClinicReports extends AppCompatActivity {
private Button mChooseFileBtn, mSaveFileBtn;
private RecyclerView recyclerView;
List<DocumentsClass> documentsClassList;
RecyclerView.LayoutManager layoutManager;
DocumentAdapter documentAdapter;
private ProgressDialog mProgress;
SharedPreferences sharedPreferences;
// this is the action code we use in our intent,
// this way we know we're looking at the response from our own action
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
ImageView imageView;
private static final int STORAGE_PERMISSION_CODE = 1234;
private int PICK_IMAGE_REQUEST = 1;
private Uri filePath;
private Bitmap bitmap;
TextView tv;
int patientID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_clinic_reports);
mProgress = new ProgressDialog(this);
sharedPreferences = getSharedPreferences("doctorApp", MODE_PRIVATE);
patientID = sharedPreferences.getInt("patientID", 0);
//Toast.makeText(this, "Pat"+patientID, Toast.LENGTH_SHORT).show();
Toolbar toolbar = findViewById(R.id.m_Toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Upload Documents");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.back_button);
mChooseFileBtn = findViewById(R.id.uploadBtn);
mSaveFileBtn = findViewById(R.id.SaveBtn);
tv = findViewById(R.id.showDocs);
imageView = findViewById(R.id.imagefile);
ActivityCompat.requestPermissions(UploadClinicReports.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, PackageManager.PERMISSION_GRANTED);
recyclerView = findViewById(R.id.recyclerViewSaveDocs);
documentsClassList = new ArrayList<>();
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
mChooseFileBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(UploadClinicReports.this);
alertDialog.setTitle("Clinic Report");
alertDialog.setMessage("Upload Your Clinic Report");
alertDialog.setPositiveButton("Image Pick", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// select image file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
});
alertDialog.setNegativeButton("Pdf Pick", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// select a file
Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Pdf"), PICK_IMAGE_REQUEST);
}
});
AlertDialog dialog = alertDialog.create();
dialog.show();
}
});
mSaveFileBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (filePath != null) {
uploadImage();
} else {
Toast.makeText(UploadClinicReports.this, "Please Select a File", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && data != null && data.getData() != null) {
filePath = data.getData();
}
}
private String getPath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Media._ID + "=?", new String[]{document_id}, null);
cursor.moveToFirst();
#SuppressLint("Range") String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;// da se di
}
private void uploadImage() {
mProgress.setMessage("Loading...");
mProgress.show();
String path = getPath(filePath);
try {
String uploadId = UUID.randomUUID().toString();
File imageFile = new File(path); // Create a file using the absolute path of the image
RequestBody reqBody = RequestBody.create(MediaType.parse("*/*"), imageFile);
MultipartBody.Part partImage = MultipartBody.Part.createFormData("file", imageFile.getName(), reqBody);
Call<ResponseBody> upload = ApiUtilities.getService().uploadFile(patientID, partImage);
upload.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
mProgress.dismiss();
Toast.makeText(UploadClinicReports.this, "Image Uploaded", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onResponse: " + response);
} else {
mProgress.dismiss();
Toast.makeText(UploadClinicReports.this, "Failed" + response.code(), Toast.LENGTH_SHORT).show();
Log.d(TAG, "onResponse: " + response);
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
mProgress.dismiss();
Toast.makeText(UploadClinicReports.this, t.getMessage(), Toast.LENGTH_SHORT).show();
Log.d(TAG, "onResponse: " + t.getMessage());
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
**How could I upload a pdf file? I am struggling to get the absolute path of pdf file from URI.
I am facing the following issue when i am upload pdf file to the server in android studio java Using retrofit.**
This question already has answers here:
How to use getdownloadurl in recent versions?
(5 answers)
How to get URL from Firebase Storage getDownloadURL
(13 answers)
Closed 2 years ago.
I make a chatting app with android studio. I want to create settings activity. I successfully load profile image to firebase storage. But when I retrieve profile image from storage it seems end of the onactivityresult. But when I go back to main activity the profile image is disappearing I want when I enter to settings activity profile image is retrieves. I try to do with picasso & glide but not working.
enter code here
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FileDownloadTask;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.io.File;
import java.net.URI;
import java.util.HashMap;
import de.hdodenhof.circleimageview.CircleImageView;
public class SettingsActivity extends AppCompatActivity {
private Toolbar mToolbar;
private CircleImageView set_profile_image;
private EditText set_user_name , set_profile_status;
private Button update_settings_button;
private String CurrentUserID;
private FirebaseAuth mAuth;
private DatabaseReference RootRef;
private static final int GalleryPick = 1;
private StorageReference UserProfileImagesRef;
private ProgressDialog loadingBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
define();
RetrieveUserInfo();
}
private void define() {
set_profile_image = (CircleImageView) findViewById(R.id.set_profile_image);
set_user_name = (EditText) findViewById(R.id.set_user_name);
set_profile_status = (EditText) findViewById(R.id.set_profile_status);
update_settings_button = (Button) findViewById(R.id.update_settings_button);
mAuth = FirebaseAuth.getInstance();
CurrentUserID = mAuth.getCurrentUser().getUid();
RootRef = FirebaseDatabase.getInstance().getReference();
UserProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
loadingBar = new ProgressDialog(this);
}
public void set_profile_image_click(View view){
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent , GalleryPick);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GalleryPick && resultCode == RESULT_OK && data != null){
Uri ImageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1 , 1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK){
loadingBar.setTitle("Set Profile Image");
loadingBar.setMessage("Your Profile Image is Updating...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
final Uri resultUri = result.getUri();
StorageReference FilePath = UserProfileImagesRef.child(CurrentUserID + ".jpg");
FilePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull final Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
Toast.makeText(SettingsActivity.this, "Profile Image Uploaded Successfully", Toast.LENGTH_SHORT).show();
final String downloadUrl = task.getResult().getUploadSessionUri().toString();
RootRef.child("Users").child(CurrentUserID).child("image").setValue(downloadUrl).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(SettingsActivity.this, "Image Uploaded Database Successfully", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message , Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
Glide.with(SettingsActivity.this).load(new File(resultUri.getPath())).into(set_profile_image);
}
}
}
private void RetrieveUserInfo() {
RootRef.child("Users").child(CurrentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("image")))){
String RetrieveUserName = dataSnapshot.child("name").getValue().toString();
String RetrieveProfileStatus = dataSnapshot.child("status").getValue().toString();
String RetrieveProfileImage = dataSnapshot.child("image").getValue().toString();
set_user_name.setText(RetrieveUserName);
set_profile_status.setText(RetrieveProfileStatus);
//Picasso.get().load(RetrieveProfileImage).into(set_profile_image);
Glide.with(SettingsActivity.this).load(new File(RetrieveProfileImage.)).into(set_profile_image);
}
else if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name"))){
String RetrieveUserName = dataSnapshot.child("name").getValue().toString();
String RetrieveProfileStatus = dataSnapshot.child("status").getValue().toString();
set_user_name.setText(RetrieveUserName);
set_profile_status.setText(RetrieveProfileStatus);
}
else{
//set_user_name.setVisibility(View.VISIBLE);
Toast.makeText(SettingsActivity.this, "Please update your profile Settings", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void update_settings_button_click(View view){
UpdateSettings();
}
private void UpdateSettings() {
String setUserName = set_user_name.getText().toString();
String setProfileStatus = set_profile_status.getText().toString();
if (TextUtils.isEmpty(setUserName)){
Toast.makeText(this, "Please write your User Name", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(setProfileStatus)){
Toast.makeText(this, "Please write your Status", Toast.LENGTH_SHORT).show();
}
else {
HashMap<String , String> ProfileMap = new HashMap<>();
ProfileMap.put("uid" , CurrentUserID);
ProfileMap.put("name" , setUserName);
ProfileMap.put("status" , setProfileStatus);
RootRef.child("Users").child(CurrentUserID).setValue(ProfileMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
SendUserToMainActivity();
Toast.makeText(SettingsActivity.this, "Profile Updated Successfully", Toast.LENGTH_SHORT).show();
}else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message , Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(SettingsActivity.this , MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
}
I have two activities SetupActivity , DashboardActivity. I'm Using Firebase Authentication and checking user existence. The flow of application for a new user is
open App->MainActivity->RegisterFragment->SetupActivity->DashboardActivity. This is my SetupActivity.Java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.kloadingspin.KLoadingSpin;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import br.com.simplepass.loadingbutton.customViews.CircularProgressButton;
import de.hdodenhof.circleimageview.CircleImageView;
public class SetupActivity extends AppCompatActivity implements LocationListener, View.OnClickListener {
private static final int REQUEST_LOCATION = 1 ;
private TextInputLayout TIPFullname, TIPCurrentLocation, TIPMobile, TIPBloodGroup, TIPLastDonated;
private TextInputEditText FullName, CurrentLocation, Mobile, BloodGroup, LastDonated;
private AutoCompleteTextView PermanentLocation;
private CircularProgressButton SaveInformationButton;
private CircleImageView ProfileImage;
private SimpleDateFormat dateFormatter;
private LocationManager locationManager;
private LocationListener locationListener;
private DatePickerDialog datePickerDialog;
private FirebaseAuth mAuth;
private DatabaseReference UsersRef;
private StorageReference UserProfileImageRef;
private ValidationHelper validation;
KLoadingSpin a;
String currentUserID;
final static int Gallery_Pick = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup);
String[] cities = getResources().getStringArray(R.array.cities);
// Toast.makeText(this, "First select profile image and then enter details", Toast.LENGTH_LONG).show();
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_LOCATION);
dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
a = findViewById(R.id.KLoadingSpin);
TIPFullname = findViewById(R.id.tip_fullname);
TIPCurrentLocation = findViewById(R.id.tip_curr_location);
TIPBloodGroup = findViewById(R.id.tip_blood_group);
TIPLastDonated = findViewById(R.id.tip_last_donated);
TIPMobile = findViewById(R.id.tip_mobile);
FullName = findViewById(R.id.reg_fullname);
CurrentLocation = findViewById(R.id.reg_curr_location);
Mobile = findViewById(R.id.reg_mobile);
BloodGroup = findViewById(R.id.reg_blood_group);
PermanentLocation = findViewById(R.id.reg_per_location);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.dropdown_menu_popup_item,cities);
PermanentLocation.setAdapter(adapter);
PermanentLocation.setThreshold(2);
LastDonated = findViewById(R.id.reg_last_donated);
LastDonated.setInputType(InputType.TYPE_NULL);
SaveInformationButton = findViewById(R.id.btn_save);
ProfileImage = findViewById(R.id.setup_profile_image);
validation = new ValidationHelper(this);
TIPCurrentLocation.setEndIconOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
getLocation();
}
});
SetDateTimeField();
SaveInformationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkValidation();
SaveAccountSetupInformation();
}
});
ProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, Gallery_Pick);
}
});
UsersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if (dataSnapshot.hasChild("profileimage")) {
String image = dataSnapshot.child("profileimage").getValue().toString();
Picasso.with(SetupActivity.this).load(image).placeholder(R.drawable.default_profile).into(ProfileImage);
} else {
Toast.makeText(SetupActivity.this, "Please select profile image first.", Toast.LENGTH_LONG).show();
tipDisabled();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void SetDateTimeField() {
LastDonated.setOnClickListener(this);
Calendar newCalendar = Calendar.getInstance();
datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
LastDonated.setText(dateFormatter.format(newDate.getTime().toString()));
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
#Override
public void onClick(View view) {
if(view == LastDonated) {
datePickerDialog.show();
}
}
private void checkValidation() {
if (!validation.isEditTextFilled(BloodGroup, TIPBloodGroup, "Enter Blood Group")) {
return;
}
if (!validation.isEditTextBloodGroup(BloodGroup, TIPBloodGroup, "Enter Correct BloodGroup!!")) {
return;
}
}
private void getLocation() {
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_BACKGROUND_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(
this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION},
75
);
}
isLocationEnabled();
Location loc=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
String longitude = "Longitude: " +loc.getLongitude();
String latitude = "Latitude: " +loc.getLatitude();
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc
.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = " "+cityName;
CurrentLocation.setText(s);
}
private boolean isLocationEnabled(){
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(
LocationManager.NETWORK_PROVIDER
);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Gallery_Pick && resultCode == RESULT_OK && data != null) {
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
a.setVisibility(View.VISIBLE);
a.startAnimation();
a.setIsVisible(true);
Uri resultUri = result.getUri();
StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
Toast.makeText(SetupActivity.this, "Please Wait", Toast.LENGTH_SHORT).show();
Task<Uri> result = task.getResult().getMetadata().getReference().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
UsersRef.child("profileimage").setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(SetupActivity.this, "Please Wait", Toast.LENGTH_LONG).show();
Intent selfIntent = new Intent(SetupActivity.this, SetupActivity.class);
startActivity(selfIntent);
tipEnabled();
Toast.makeText(SetupActivity.this, "Your Profile image looks great!!!...", Toast.LENGTH_SHORT).show();
a.stopAnimation();
a.setVisibility(View.GONE);
a.setIsVisible(false);
} else {
String message = task.getException().getMessage();
Toast.makeText(SetupActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
tipDisabled();
a.stopAnimation();
a.setVisibility(View.GONE);
a.setIsVisible(false);
}
}
});
}
});
}
}
});
} else {
Toast.makeText(SetupActivity.this, "Error: Image not selected or not cropped", Toast.LENGTH_SHORT).show();
tipDisabled();
a.stopAnimation();
a.setVisibility(View.GONE);
a.setIsVisible(false);
}
}
}
private void SaveAccountSetupInformation() {
String fullname = FullName.getText().toString();
String currentlocation = CurrentLocation.getText().toString();
String mobile = Mobile.getText().toString();
String permanentlocation = PermanentLocation.getText().toString();
String bloodgroup = BloodGroup.getText().toString();
String lastdonated = LastDonated.getText().toString();
if (TextUtils.isEmpty(currentlocation)) {
Toast.makeText(this, "Please click button and get your current city...", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(mobile)) {
Toast.makeText(this, "Please write your mobile no...", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(permanentlocation)) {
Toast.makeText(this, "Please enter your permanent city...", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(fullname)) {
Toast.makeText(this, "Please enter your full name...", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(bloodgroup)) {
Toast.makeText(this, "Please enter your bloodgroup...", Toast.LENGTH_SHORT).show();
}
else {
a.setVisibility(View.VISIBLE);
a.startAnimation();
a.setIsVisible(true);
SaveInformationButton.startAnimation();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
HashMap userMap = new HashMap();
userMap.put("bloodgroup", bloodgroup);
userMap.put("fullname", fullname);
userMap.put("mobile", mobile);
userMap.put("currentlocation", currentlocation);
userMap.put("permanentlocation", permanentlocation);
userMap.put("timesdonated","0");
userMap.put("lastdonatedon",lastdonated);
UsersRef.updateChildren(userMap).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
SendUserToMainActivity();
Toast.makeText(SetupActivity.this, "your Account is created Successfully.", Toast.LENGTH_LONG).show();
} else {
a.stopAnimation();
a.setVisibility(View.GONE);
a.setIsVisible(false);
SaveInformationButton.revertAnimation();
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
String message = task.getException().getMessage();
Toast.makeText(SetupActivity.this, "Error Occured: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void tipDisabled()
{
TIPCurrentLocation.setEnabled(false);
TIPMobile.setEnabled(false);
TIPBloodGroup.setEnabled(false);
TIPFullname.setEnabled(false);
TIPLastDonated.setEnabled(false);
PermanentLocation.setEnabled(false);
}
private void tipEnabled()
{
TIPCurrentLocation.setEnabled(true);
TIPMobile.setEnabled(true);
TIPBloodGroup.setEnabled(true);
TIPFullname.setEnabled(true);
TIPLastDonated.setEnabled(true);
PermanentLocation.setEnabled(true);
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(SetupActivity.this, DashboardActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
#Override
public void onLocationChanged(Location loc) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this,"Enable Location and Internet to get Location",Toast.LENGTH_LONG);
}
}
` Here i want the user to select the profile picture first and then have to fill text in edittexts. So,i need to disable all the edittexts and after the profile image is set i have to enable them. for this purpose i have written tipdisabled() and tipEnabled() methods. But i donno where to use them correctly. Please Clarify this.
You can merge your code like this:
private void tipEnabled(Boolean isEnabled)
{
TIPCurrentLocation.setEnabled(isEnabled);
TIPMobile.setEnabled(isEnabled);
TIPBloodGroup.setEnabled(isEnabled);
TIPFullname.setEnabled(isEnabled);
TIPLastDonated.setEnabled(isEnabled);
PermanentLocation.setEnabled(isEnabled);
}
To achieve your flow, put tipEnabled(false) inside your choose image click Listener and tipEnabled(true) in the onResult, which i think in your case is onActivityResult().
You should seggerate you code as right now your activity looks like a data dump which is handling too many responsibilities at the moment. Try creating Presenter classes, Controller classes or ViewModel classes to delegate all this functioning to them. You Activity should only act as a container and should not be doing validations or any logical processing but rather doing delegation.
I made a simple android app to upload images on Firebase. everything working fine, image uploading successfully to firebase storage. But, I'm getting this error while fetching URL from firebase.
StorageException has occurred. The object does not exist at the location. Code: -13010 HttpResult: 404
I found out most of the previous questions and answers but they didn't work for me.
thanks in advance.
package com.pk.hotandcool.activities;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.fxn.pix.Options;
import com.fxn.pix.Pix;
import com.fxn.utility.ImageQuality;
import com.fxn.utility.PermUtil;
import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageMetadata;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.pk.hotandcool.R;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.util.ArrayList;
public class Test extends AppCompatActivity {
private static final String TAG = "Test";
private RecyclerView recyclerView;
private MyAdapter myAdapter;
private Options options;
private ArrayList<String> returnValue = new ArrayList<>();
private GridLayoutManager gridLayoutManager;
int imageCount = 0;
private FirebaseAuth mAuth;
private String currentUid;
private DatabaseReference userMediaDb;
private StorageReference filePath;
private StorageMetadata metadata;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_media);
initViews();
initFirebase();
recyclerView.setLayoutManager(gridLayoutManager);
myAdapter = new MyAdapter(this);
options = Options.init()
.setRequestCode(100)
.setCount(9)
.setFrontfacing(false)
.setImageQuality(ImageQuality.LOW)
.setPreSelectedUrls(returnValue)
.setScreenOrientation(Options.SCREEN_ORIENTATION_PORTRAIT)
.setPath("DCIM/pk");
recyclerView.setAdapter(myAdapter);
findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
options.setPreSelectedUrls(returnValue);
Pix.start(Test.this, options);
}
});
}
private void initFirebase() {
currentUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
userMediaDb = FirebaseDatabase.getInstance().getReference().child("Users")
.child(currentUid)
.child("media");
}
private void initViews() {
recyclerView = findViewById(R.id.recyclerView);
gridLayoutManager = new GridLayoutManager(this, 3);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100) {
if (resultCode == Activity.RESULT_OK) {
returnValue = data.getStringArrayListExtra(Pix.IMAGE_RESULTS);
if (returnValue != null) {
myAdapter.addImages(returnValue);
if (returnValue.size() > 0) {
uploadMediaToFirebase(returnValue);
}
}
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NotNull String[] permissions, #NotNull int[] grantResults) {
if (requestCode == PermUtil.REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS) {// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Pix.start(Test.this, options);
} else {
Toast.makeText(Test.this, "Approve permissions to open Pix ImagePicker", Toast.LENGTH_LONG).show();
}
return;
}
}
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<String> list = new ArrayList<>();
private Context context;
MyAdapter(Context context) {
this.context = context;
}
void addImages(ArrayList<String> list) {
this.list.clear();
this.list.addAll(list);
notifyDataSetChanged();
}
#NotNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).
inflate(R.layout.pix_image_layout, parent, false);
return new Holder(v);
}
#Override
public void onBindViewHolder(#NotNull RecyclerView.ViewHolder holder, int position) {
File f = new File(list.get(position));
Bitmap d = new BitmapDrawable(context.getResources(), f.getAbsolutePath()).getBitmap();
((Holder) holder).iv.setImageBitmap(d);
}
#Override
public int getItemCount() {
return list.size();
}
class Holder extends RecyclerView.ViewHolder {
ImageView iv;
Holder(View itemView) {
super(itemView);
iv = itemView.findViewById(R.id.iv);
}
}
}
private void uploadMediaToFirebase(ArrayList<String> images) {
filePath = FirebaseStorage.getInstance().getReference()
.child("users")
.child(currentUid)
.child("media");
metadata = new StorageMetadata.Builder()
.setContentType("image/jpg")
.build();
for (int i = 0; i < images.size(); i++) {
String image = images.get(i);
final File file = new File(image);
uploadImages(filePath, metadata, file);
}
}
private void uploadImages(final StorageReference filePath, StorageMetadata metadata, File file) {
UploadTask uploadTask = filePath.child(file.getName()).putFile(Uri.fromFile(file), metadata);
uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
Log.d(TAG, "onComplete: uploaded successfully" + task.getResult().toString());
} else {
Log.d(TAG, "onComplete: upload failed" + task.getResult().toString());
}
}
});
Task<Uri> task = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
Log.d(TAG, "then: " + task.getResult());
if (task.getException() != null)
throw task.getException();
}
Log.d(TAG, "then: " + filePath.getDownloadUrl().toString());
return filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
Log.d(TAG, "onComplete: download uri" + downloadUri.toString());
} else {
if (task.getException() != null)
Log.e(TAG, "onComplete: getting url failed");
Log.d(TAG, "onComplete: download url : " + task.getResult());
task.getException().printStackTrace();
}
}
});
}
}
I made a mistake i returned task.getDownloadUrl() instead of reference.getDownloadUrl so i changed the line
UploadTask uploadTask = filePath.child(file.getName()).putFile(Uri.fromFile(file), metadata);
into
StorageReference reference = filePath.child(file.getName());
UploadTask uploadTask = reference.putFile(Uri.fromFile(file), metadata);
and return
return filePath.getDownloadUrl();
In your uploadImages () function you are using file.getName (), so it is possible that it can return the same value for different files and your data will be overwritten in Firebase. And this can give rise to the StorageException you encounter.
One way to get rid of this exception is that you can use some unique paths for each of the files. For ex- you can use the value of timestamp (it will be unique every time the files are uploaded).
I am making bluetooth application in which I want to send data using bluetooth. That task I am able to do. But after that I want open any particular file from device. Then How can I do it? I have written the code below.
package com.example.blue;
import java.io.File;
import java.util.List;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int DISCOVER_DURATION=300;
private static final int REQUEST_BLU=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String path="/storage/emulated/0/DCIM/Camera/20141018_152852.jpg";
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File(path);
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext=file.getName().substring(file.getName().indexOf(".")+1);
String type = mime.getMimeTypeFromExtension(ext);
intent.setDataAndType(Uri.fromFile(file),type);
startActivity(intent);
}
public void sendViaBluetooth(View v){
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
if (btAdapter == null)
{
Toast.makeText(this,"Bluetooth not supported" , Toast.LENGTH_LONG).show();
}else
{
enableBluetooth();
}
}
public void enableBluetooth(){
Intent discoveryIntent= new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoveryIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVER_DURATION);
startActivityForResult(discoveryIntent, REQUEST_BLU);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == DISCOVER_DURATION && requestCode == REQUEST_BLU)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");
File f = new File(Environment.getExternalStorageDirectory(),"md5sum.txt");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
PackageManager pm = getPackageManager();
List<ResolveInfo> appsList = pm.queryIntentActivities(intent, 0);
if(appsList.size()>0)
{
String packageName = null;
String className = null;
boolean found = false;
for(ResolveInfo info : appsList)
{
packageName = info.activityInfo.packageName;
if(packageName.equals("com.android.bluetooth"))
{
className = info.activityInfo.name;
found = true;
break;
}
}
if(!found){
Toast.makeText(this,"Bluetooth haven't been found" , Toast.LENGTH_LONG).show();
}else
{
intent.setClassName(packageName, className);
startActivity(intent);
}
}
}else{
Toast.makeText(this,"Bluetooth is cancelled" , Toast.LENGTH_LONG).show();
}
}
}