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();
}
}
}
Related
I'm a new android developer and trying to make image to text app. I watched some tutorials and pretty sure that i don't make any mistakes. I'm using ML Kit for this project and got error when i tried to convert the image to text.
My main activity
package com.gorkemtand.textrecognition;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.PopupMenu;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.imageview.ShapeableImageView;
import com.google.mlkit.vision.common.InputImage;
import com.google.mlkit.vision.text.Text;
import com.google.mlkit.vision.text.TextRecognition;
import com.google.mlkit.vision.text.TextRecognizer;
import com.google.mlkit.vision.text.latin.TextRecognizerOptions;
import java.io.IOException;
import java.security.Permission;
public class MainActivity extends AppCompatActivity {
private MaterialButton inputImageBtn;
private MaterialButton recognizeTextBtn;
private ShapeableImageView imageIv;
private EditText recognizedTextEt;
private static final String TAG = "MAIN_TAG";
private Uri imageUri = null;
//to handle the result of Camere/Gallery permissions
private static final int CAMERA_REQUEST_CODE = 100;
private static final int STORAGE_REQUEST_CODE = 101;
//arrays of permission required to pick image from Camera,gallery
private String[] cameraPermissions;
private String[] storagePermissions;
private ProgressDialog progressDialog;
private TextRecognizer textRecognizer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputImageBtn = findViewById(R.id.inputImageBtn);
recognizeTextBtn = findViewById(R.id.recognizeBtn);
imageIv = findViewById(R.id.imageIv);
recognizedTextEt = findViewById(R.id.recognizedTextEd);
cameraPermissions = new String[] {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermissions = new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE};
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Please Wait");
progressDialog.setCanceledOnTouchOutside(false);
textRecognizer = TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS);
inputImageBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showInputImageDialog();
}
});
recognizeTextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(imageUri == null){
Toast.makeText(MainActivity.this,"Pick image first...",Toast.LENGTH_SHORT).show();
}
else {
recognizeTextFromImage();
}
}
});
}
private void recognizeTextFromImage() {
Log.d(TAG, "recognizeTextFromImage: ");
progressDialog.setMessage("Preparing image...");
progressDialog.show();
try {
InputImage inputImage = InputImage.fromFilePath(this,imageUri);
progressDialog.setMessage("Recognizing text...");
Task<Text> textTaskResult = textRecognizer.process(inputImage).addOnSuccessListener(new OnSuccessListener<Text>() {
#Override
public void onSuccess(Text text) {
progressDialog.dismiss();
String recognizedText = text.getText();
Log.d(TAG, "onSuccess: recognizedText: "+recognizedText);
recognizedTextEt.setText(recognizedText);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Log.e(TAG, "onFailure: ",e);
Toast.makeText(MainActivity.this,"Failed recognizing text due to"+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
progressDialog.dismiss();
Log.e(TAG, "recognizeTextFromImage: ",e);
Toast.makeText(MainActivity.this,"Failed preparing image due to"+e.getMessage(),Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
private void showInputImageDialog() {
PopupMenu popupMenu = new PopupMenu(this, inputImageBtn);
popupMenu.getMenu().add(Menu.NONE,1,1,"CAMERA");
popupMenu.getMenu().add(Menu.NONE,2,2,"GALLERY");
popupMenu.show();
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
int id = item.getItemId();
if(id == 1){
Log.d(TAG, "onMenuItemClick: Camera Clicked...");
if(checkCameraPermissions()){
pickImageCamera();
}
else{
requestCameraPermissions();
}
}
else if(id == 2){
Log.d(TAG, "onMenuItemClick: Gallery Clicked...");
if(checkStoragePermision()){
pickImageGallery();
}
else{
requestStoragePermission();
}
}
return false;
}
});
}
private void pickImageGallery(){
Log.d(TAG, "pickImageGallery: ");
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
galleryActivityResultLauncher.launch(intent);
}
private ActivityResultLauncher<Intent> galleryActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if(result.getResultCode() == Activity.RESULT_OK){
//image picked
Intent data = result.getData();
imageUri = data.getData();
Log.d(TAG, "onActivityResult: imageUri "+imageUri);
//set to imageview
imageIv.setImageURI(imageUri);
}
else{
Log.d(TAG, "onActivityResult: cancelled");
Toast.makeText(MainActivity.this,"Cancelled...",Toast.LENGTH_SHORT).show();
}
}
}
);
private void pickImageCamera(){
Log.d(TAG, "pickImageCamera: ");
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Sample Title");
values.put(MediaStore.Images.Media.DESCRIPTION, "Sample Description");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
cameraActivityResultLauncher.launch(intent);
}
private ActivityResultLauncher<Intent> cameraActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if(result.getResultCode() == Activity.RESULT_OK){
Log.d(TAG, "onActivityResult: imageUri "+imageUri);
imageIv.setImageURI(imageUri);
}
else{
Log.d(TAG, "onActivityResult: cancelled");
Toast.makeText(MainActivity.this,"Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
);
private boolean checkStoragePermision(){
boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return result;
}
private void requestStoragePermission(){
ActivityCompat.requestPermissions(this,storagePermissions,STORAGE_REQUEST_CODE);
}
private boolean checkCameraPermissions(){
boolean cameraResult = ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED);
boolean storafeResult = ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return cameraResult && storafeResult;
}
private void requestCameraPermissions(){
ActivityCompat.requestPermissions(this,cameraPermissions, CAMERA_REQUEST_CODE);
}
//handle permission results
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case CAMERA_REQUEST_CODE:{
if (grantResults.length>0){
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean storageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if(cameraAccepted && storageAccepted){
pickImageCamera();
}
else {
Toast.makeText(this, "Camera && Storage permissions are required", Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(this,"Cancelled",Toast.LENGTH_SHORT).show();
}
}
break;
case STORAGE_REQUEST_CODE:{
if(grantResults.length>0){
boolean storageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (storageAccepted) {
pickImageGallery();
}
else {
Toast.makeText(this, "Storage permission is required", Toast.LENGTH_SHORT).show();
}
}
}
break;
}
}
}
Also i implemented these two
implementation 'com.google.android.gms:play-services-mlkit-text-recognition:18.0.2'
implementation 'com.google.android.gms:play-services-mlkit-text-recognition-common:18.0.0'
And give the permissions to manifest:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And this is the error i got:
Error
I searched the google and cnat find a solution. If u can help me i will be very happy.
I searched google and can't find anything works.
I solved by implementing com.google.mlkit:text-recognition:16.0.0-beta6
Are you testing on device without play store services? For example on an emulator? In order to use com.google.android.gms:play-services-mlkit-text-recognition:18.0.2 it has to be on a device with play store services.
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.**
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
I am trying to make a camera App for an android phone. The code is showing no error, but when I run it on my phone after launching the app, it crashes, giving this error:
"Unfortunately the app stopped"
package com.my.hp.myapp;
import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class CameraActivity extends AppCompatActivity implements View.OnClickListener {
private static final int REQUEST_CODE_SOME_FEATURES_PERMISSIONS = 1;
private static final int CAMERA_PIC_REQUEST = 2;
private ImageView img;
private Button btn1;
private Uri fileUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
img = findViewById(R.id.image);
btn1 = findViewById(R.id.butt);
btn1.setOnClickListener(this);
}
#RequiresApi(api = Build.VERSION_CODES.M)
private void checkpermission() {
int hasCameraPermission =
checkSelfPermission(Manifest.permission.CAMERA);
int hasStoragePermission =
checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
List<String> permissions = new ArrayList<>();
if (hasCameraPermission != PackageManager.PERMISSION_GRANTED) {
permissions.add(Manifest.permission.CAMERA);
}
if (hasStoragePermission != PackageManager.PERMISSION_GRANTED) {
permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
}
if (!permissions.isEmpty()) {
requestPermissions(permissions.toArray(new String[permissions.size()]),
REQUEST_CODE_SOME_FEATURES_PERMISSIONS);
}
}
#RequiresApi(api=Build.VERSION_CODES.M)
private boolean hasPermission() {
int hasCameraPermission =
checkSelfPermission(Manifest.permission.CAMERA);
int hasStoragePermission =
checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
return (hasCameraPermission==PackageManager.PERMISSION_GRANTED && hasStoragePermission==PackageManager.PERMISSION_GRANTED);
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
switch(view.getId())
{
case R.id.butt:
if(hasPermission())
{
openCamera();
}
else{
checkpermission();
}
break;
}
}
private void openCamera()
{
String timeStamp=new
SimpleDateFormat("yyyyMMdd_HHmms").format(new Date());
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE,"IMG_"+ timeStamp+".jpg");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri =
getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
switch (requestCode) {
case REQUEST_CODE_SOME_FEATURES_PERMISSIONS: {
for (int i = 0; i < permissions.length; i++) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
openCamera();
} else if (grantResults[i] == PackageManager.PERMISSION_DENIED)
{
Log.d("Permissions", "Permission Denied: " + permissions[i]);
}
}
}
break;
default:{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
if (resultCode == RESULT_OK) {
if(data != null){
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
img.setImageBitmap(imageBitmap);
}
}
}
}
}
First check if you added camera and read storage permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
This first part are simple imports, not really relevant to my question.
details details android studio
much details, such wow
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
Declaration of class
public class MainActivity extends Activity {
Variables being declared
private final static int TAKE_PICTURE = 0;
private final static int SAVE_PICTURE = 1;
private final static int TAKE_VIDEO = 2;
private final static int STORAGE_PERMISSION = 3;
private ImageView iv;
private VideoView vv;
private MediaController mc;
private String lastURI;
Basic create method, nothing special here
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView)findViewById(R.id.imageView);
vv = (VideoView)findViewById(R.id.videoView);
mc = new MediaController(this);
mc.setMediaPlayer(vv);
vv.setMediaController(mc);
}
Method that takes picture
public void takePicture(View v){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(intent.resolveActivity(getPackageManager()) != null){
startActivityForResult(intent, TAKE_PICTURE);
}
}
Method that saves picture
public void savePicture(View v){
Log.i("SAVE PICTURE", "save");
if(Build.VERSION.SDK_INT >= 23 &&
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
// request permission!
Log.i("SAVE PICTURE", "asking permission");
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, STORAGE_PERMISSION);
} else {
savePicturePermitted();
}
}
Main method
protected void onActivityResult(int requestCode, int resultCode, Intent data){
Log.wtf("RETURN", requestCode + "");
if(resultCode == Activity.RESULT_OK){
Test cases
switch(requestCode){
case TAKE_PICTURE:
Bundle extra = data.getExtras();
Bitmap image = (Bitmap)extra.get("data");
iv.setImageBitmap(image);
break;
}
}
}
}
It looks like what you have to do is the following:
For the permission part use this:
private void savePicturePermitted(){
// the actual code
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(intent.resolveActivity(getPackageManager()) != null){
File photo = null;
try{
String time = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date());
String name = "GUYZ_" + time;
File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
photo = File.createTempFile(name, ".jpg", directory);
// keep track of the URI
lastURI = photo.getAbsolutePath();
}catch(IOException ioe){
ioe.printStackTrace();
}
if(photo != null){
//intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", photo));
startActivityForResult(intent, SAVE_PICTURE);
}
}
}
Also add a result or feedback so the user knows what's up, this could be done like so:
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == STORAGE_PERMISSION && grantResults[0] == PackageManager.PERMISSION_GRANTED){
savePicturePermitted();
} else {
Toast.makeText(this, "Permission required", Toast.LENGTH_SHORT).show();
}
}
For taking video, the method looks like this:
public void takeVideo(View v){
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if(intent.resolveActivity(getPackageManager()) != null){
startActivityForResult(intent, TAKE_VIDEO);
}
}
Finally, I suggest you add all of these to your test cases so you can test they work. This is how that should look like:
case TAKE_VIDEO:
Uri video = data.getData();
vv.setVideoURI(video);
vv.start();
break;
Noticed you missed a save picture use case:
case SAVE_PICTURE:
Log.wtf("SAVING PICTURE", lastURI);
Bitmap image2 = BitmapFactory.decodeFile(lastURI);
iv.setImageBitmap(image2);
break;
Also I noticed that you were missing some imports, these should appear automatically, but in case they don't, here's what those should be:
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;