Simple Media Player in Android - java

I am trying to create a media player without MediaPlayer class, just a very basic VideoView which selects a file from device and plays it. But I am receiving an error
Can't play this video.
Here's my code:
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;
import android.widget.VideoView;
public class PlayerActivity extends AppCompatActivity {
VideoView videoPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoPlayer = findViewById(R.id.videoView);
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, 7);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 7:
if (resultCode == RESULT_OK) {
String PathHolder = data.getData().getPath();
Toast.makeText(this, PathHolder, Toast.LENGTH_SHORT).show();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
videoPlayer.setVideoURI(Uri.parse(PathHolder));
videoPlayer.requestFocus();
videoPlayer.start();
}
}
}
}
XML file:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:tools="http://schemas.android.com/tools"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent">
<VideoView
android:id="#+id/videoView"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="318dp"
tools:layout_editor_absoluteY="716dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is what logcat shows (i guess this contains the error):
2020-08-09 12:55:37.585 21894-21894/com.phantom.player W/MediaPlayer:
Couldn't open /document/primary:WhatsApp/Media/WhatsApp
Video/VID-20191031-WA0041.mp4
java.io.FileNotFoundException: No content provider: /document/primary:WhatsApp/Media/WhatsApp
Video/VID-20191031-WA0041.mp4
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1680)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1510)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1427)
at android.media.MediaPlayer.attemptDataSource(MediaPlayer.java:1149)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1121)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1145)
at android.widget.VideoView.openVideo(VideoView.java:412)
at android.widget.VideoView.access$2200(VideoView.java:83)
at android.widget.VideoView$7.surfaceCreated(VideoView.java:694)
at android.view.SurfaceView.updateSurface(SurfaceView.java:926)
at android.view.SurfaceView.windowStopped(SurfaceView.java:315)
at android.view.ViewRootImpl.setWindowStopped(ViewRootImpl.java:1973)
at android.view.WindowManagerGlobal.setStoppedState(WindowManagerGlobal.java:709)
at android.app.Activity.performRestart(Activity.java:8039)
at android.app.ActivityThread.handleSleeping(ActivityThread.java:5007)
at android.app.ActivityThread.access$2500(ActivityThread.java:268)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2080)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7807)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1047)
I am not used to content provider.Please help.

I didn't understand what was the problem.But it was solved when I changed onActivityResult to
switch (requestCode) {
case 7:
if (resultCode == RESULT_OK) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
videoPlayer.setVideoURI(data.getData());
videoPlayer.requestFocus();
videoPlayer.start();
}
}

Try to set orientation with object of video player
case 7:
if (resultCode == RESULT_OK) {
String PathHolder = data.getData().getPath();
Toast.makeText(this, PathHolder, Toast.LENGTH_SHORT).show();
videoPlayer.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
videoPlayer.setVideoURI(Uri.parse(PathHolder));
videoPlayer.requestFocus();
videoPlayer.start();
}

Related

Android Gotev Upload Image Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification

I'm creating image uploader using gotev/android-upload-service. everything work fine until choose image, and previewing image. But when I click "send" button, my app become crash with this error log
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.pmb, PID: 25379
android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x42 color=0x00000000 groupKey=net.gotev vis=PRIVATE semFlags=0x0 semPriority=0 semMissedCount=0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1881)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
here my permission in AndroidManifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
here my build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.example.pmb"
minSdkVersion 15
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.android.volley:volley:1.1.1'
implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'androidx.viewpager:viewpager:1.0.0'
implementation 'net.gotev:uploadservice:2.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}
here my Upload.java
package com.example.pmb;
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.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
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.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.UploadNotificationConfig;
import java.io.IOException;
import java.util.UUID;
public class Upload extends AppCompatActivity implements SingleUploadBroadcastReceiver.Delegate{
private ProgressDialog dialog;
private final SingleUploadBroadcastReceiver uploadReceiver = new SingleUploadBroadcastReceiver();
LinearLayout linear_upload;
//Declaring views
private Button buttonUpload;
private ImageView imageView;
private EditText editText;
//Image request code
private static final int PICK_IMAGE_REQUEST = 1;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
//Bitmap to get image from gallery
private Bitmap bitmap;
//Uri to store the image uri
private Uri filePath;
DatePickerDialog picker;
String nama_dokumen,nopen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upload);
linear_upload = (LinearLayout)findViewById(R.id.linear_upload);
dialog = new ProgressDialog(Upload.this);
//Requesting storage permission
requestStoragePermission();
Intent pindahan = getIntent();
nama_dokumen = pindahan.getStringExtra("nama_dokumen");
nopen = pindahan.getStringExtra("nopen");
getSupportActionBar().setTitle("Upload "+nama_dokumen);
//Initializing views
buttonUpload = (Button) findViewById(R.id.buttonUpload);
imageView = (ImageView)findViewById(R.id.imageView);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFileChooser();
}
});
buttonUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonUpload.setVisibility(v.GONE);
uploadMultipart();
}
});
}
#Override
protected void onResume() {
super.onResume();
uploadReceiver.register(this);
}
#Override
protected void onPause() {
super.onPause();
uploadReceiver.unregister(this);
}
/*
* This is the method responsible for image upload
* We need the full image path and the name for the image in this method
* */
public void uploadMultipart() {
//getting name for the image
//getting the actual path of the image
String path = getPath(filePath);
//Uploading code
try {
String uploadId = UUID.randomUUID().toString();
uploadReceiver.setDelegate(this);
uploadReceiver.setUploadID(uploadId);
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, Konfigurasi.url_dokumen_upload)
.addFileToUpload(path, "file_dokumen") //Adding file
.addParameter("apikey", Konfigurasi.apikey)
.addParameter("nopen", nopen)
.addParameter("nama_dokumen", nama_dokumen)
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, "gagal upload ya "+exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
//method to show file chooser
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);
}
//handling the image chooser activity result
#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 = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
// set padding linear layout to nol
linear_upload.setPadding(0,0,0,0);
} catch (IOException e) {
e.printStackTrace();
}
}
}
//method to get the file path from uri
public 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.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
}
//Requesting permission
private void requestStoragePermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onProgress(int progress) {
//your implementation
}
#Override
public void onProgress(long uploadedBytes, long totalBytes) {
//your implementation
dialog.setMessage("uploading...");
dialog.show();
}
#Override
public void onError(Exception exception) {
//your implementation
}
#Override
public void onCompleted(int serverResponseCode, byte[] serverResponseBody) {
//your implementation
dialog.dismiss();
Intent mv = new Intent(Upload.this,Dokumen.class);
mv.putExtra("nopen",nopen);
startActivity(mv);
finish();
}
#Override
public void onCancelled() {
//your implementation
}
}
and here my upload.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#fff"
tools:context=".Upload">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp"
android:background="#e1e1e1"
android:layout_marginBottom="30dp"
android:id="#+id/linear_upload"
android:orientation="vertical">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/drop_image"
android:layout_gravity="center_horizontal"
android:adjustViewBounds="true" />
</LinearLayout>
<Button
android:id="#+id/buttonUpload"
android:layout_width="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_height="40dp"
android:textSize="12sp"
android:background="#color/colorAccent"
android:textColor="#fff"
android:paddingLeft="50dp"
android:paddingRight="50dp"
android:drawableLeft="#drawable/ic_kirim"
android:drawablePadding="5dp"
android:text="Kirim" />
</LinearLayout>
</ScrollView>
I've trying to check on gotev github, but I found kotlin tutorial only.
how to use gotev image upload in my Upload.java or solving my problem?
change the dependency to newer version implementation 'net.gotev:uploadservice:3.4'
and then add NameSpace
`public class Initializer extends Application {
#Override
public void onCreate() {
super.onCreate();
// setup the broadcast action namespace string which will
// be used to notify upload status.
// Gradle automatically generates proper variable as below.
UploadService.NAMESPACE = BuildConfig.APPLICATION_ID;
// Or, you can define it manually.
UploadService.NAMESPACE = "com.example.yourapp";
}
}`
In Manifest application tag add
android:name=".Initializer"

Can't load image from uri after reload app

*//Sorry for bad eng, but in stackoverflow.ru I have no answers you my last chance*
I have app with 1 activity, which should take image\photo from galery, save uri of this image\photo in sharedPreferences, and after reload, app load image from saved uri in imageView
So, after reload uri successfully saved and load in app, but app can't load photo from uri and instead image I have empty space, but ImageView exist and with loaded uri all ok(I compare loaded uri and uri from galery, they equals).
Below I attach my code and screenshots:
xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="ua.bellkross.testapp.MainActivity">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
app:srcCompat="#drawable/myphoto2" />
</LinearLayout>
java:
package ua.bellkross.testapp;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
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.ImageView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
ImageView imageView;
SharedPreferences sharedPreferences;
String photoUri;
boolean can;
final int GALLERY_REQUEST = 1;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
loadPhoto();
imageView.setOnClickListener(this);
}
#Override
protected void onStop() {
super.onStop();
savePhoto();
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.imageView :
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, GALLERY_REQUEST);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri selectedImage = data.getData();
imageView.setImageURI(selectedImage);
photoUri = selectedImage.toString();
Log.d("myLog", "savedURI == " + photoUri);
can = true;
}
private void savePhoto(){
sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("uri",photoUri);
editor.putBoolean("edited",can);
editor.commit();
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void loadPhoto(){
sharedPreferences = getPreferences(MODE_PRIVATE);
if(sharedPreferences.getBoolean("edited",false)) {
String savedURI = sharedPreferences.getString("uri", null);
if (!savedURI.equals(null)) {
Log.d("myLog", "savedURI!=null");
imageView.setImageURI(Uri.parse(savedURI));
Log.d("myLog", "savedURI == " + savedURI);
}
}
can = false;
}
}
//I have no reputation to post images and more than 2 links
https://i.stack.imgur.com/hveS0.jpg - start app
https://i.stack.imgur.com/UrzHF.jpg - take image from galery
https://i.stack.imgur.com/Cwy37.jpg - after reload app
That I did for fix it?
1)Check saved and loaded uri with uri from galery - they equals, I did this with logs
05-09 22:05:24.893 524-524/ua.bellkross.testapp D/myLog: savedURI(OnActivityResult) == content://media/external/images/media/16493
05-09 22:05:29.505 1294-1294/? D/myLog: savedURI!=null
05-09 22:05:29.510 1294-1294/? D/myLog: savedURI == content://media/external/images/media/16493
2)Try use getSharedPreferences instead sharedPreferences - it's don't help
3)Try use imageView.setImageURI(null), imageView.invalidate(), imageView.postInvalidate(), before load of image - don't help.
4)Checked version of my Android and version from #RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) - they equals, all ok
5)Try change uri from content://media/external/images/media/16493 to media/external/images/media/16493 - didn't help
6)Try use onRestoreInstanceState and onSaveInstanceState - it's don't help and onRestoreInstanceState started only when you change orientation of screen, but not after reload.
Maybe, if u run it yourself or just write similar app(it takes 5-10 min) and this app will work - in compare becomes clear, which mistake I have.
Guys, I find answer, thank for this - greenapps
I try open stream InputStream is = getContentResolver().openInputStream(uri);
and get stack trace and found some string
05-10 16:13:40.081 1264-1286/? E/DatabaseUtils: Writing exception to parcel
java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/18553 from pid=8465, uid=10268 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
So, just write in AndroidManifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
try to set imageView to null at first and then set it normally like this:
imageView.setImageURI(null);
imageView.setImageURI(Uri.parse(savedURI));
I try open stream InputStream is = getContentResolver().openInputStream(uri);
and get stack trace and found some string
05-10 16:13:40.081 1264-1286/? E/DatabaseUtils: Writing exception to parcel
java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/18553 from pid=8465, uid=10268 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
So, just write in AndroidManifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>

Photo by Camera Upload Exception (Firebase Storage)

I'm trying to upload an image taken by the camera in an android application to Firebase storage. The problem is that after I take the picture, in the confirmation activity, I pressed the confirm button and it says that "Unfortunately the application stopped".
This is the image when I press the check button, and the app crashes...
This is my code, the application has the option to upload pictures using the gallery and the camera.
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
public class MainActivity extends AppCompatActivity {
// Note: Your consumer key and secret should be obfuscated in your source code before shipping.
private Button selectImage;
private Button selectImageByCamera;
private ImageView imageView;
private StorageReference storageReference;
private ProgressDialog progressDialog;
private static final int CAMERA_REQUEST_CODE = 1;
private static final int GALLERY_INTENT= 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
storageReference=FirebaseStorage.getInstance().getReference();
/*
* Code section to upload an image using the Gallery.
*/
selectImage=(Button)findViewById(R.id.btn_uploadImg);
progressDialog = new ProgressDialog(this);
selectImage.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
}
});
/*
* Code section to upload an image using the Camera.
*/
selectImageByCamera=(Button)findViewById(R.id.btn_uploadImgCamera);
imageView=(ImageView)findViewById(R.id.imageView);
selectImageByCamera.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode,resultCode,data);
//Upload the image to Firebase Update
if(requestCode==GALLERY_INTENT && resultCode == RESULT_OK)
{
progressDialog.setMessage("Uploading Image...");
progressDialog.show();
Uri uri = data.getData();
StorageReference filepath = storageReference.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Upload done", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
});
}
//Code to upload image taken by the camera to firebase storage
if(requestCode==CAMERA_REQUEST_CODE && resultCode == RESULT_OK)
{
progressDialog.setMessage("Uploading Image...");
progressDialog.show();
Uri uri2 = data.getData();
StorageReference filepath = storageReference.child("Photos").child(uri2.getLastPathSegment());
filepath.putFile(uri2).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
{
Toast.makeText(MainActivity.this, "Upload done", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
}
});
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I have this USER PERMISSIONS in AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
I have this Firebase dependencies in app/build.gradle
compile 'com.google.firebase:firebase-core:9.8.0'
compile 'com.google.firebase:firebase-database:9.8.0'
compile 'com.google.firebase:firebase-storage:9.8.0'
compile 'com.google.firebase:firebase-auth:9.8.0'
And finally this is the exception thrown when I run the app in my Moto G4 6.0.1 (The app has permissions to use Camera and Gallery)
FATAL EXCEPTION: main
Process: mx.com.jamba.jamba, PID: 16543
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=inline-data (has extras) }} to activity {mx.com.jamba.jamba/mx.com.jamba.jamba.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3720)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3763)
at android.app.ActivityThread.access$1400(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1403)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
at mx.com.jamba.jamba.MainActivity.onActivityResult(MainActivity.java:186)
at android.app.Activity.dispatchActivityResult(Activity.java:6470)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3716)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3763) 
at android.app.ActivityThread.access$1400(ActivityThread.java:154) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1403) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5443) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
I don't know what to do, it would be great if you guys to help me :)
Thank you!
The exception occurs because the Uri in onActivityResult() is null:
Uri uri = data.getData();
The documentation for capturing a camera image explains:
The Android Camera application saves a full-size photo if you give it
a file to save into. You must provide a fully qualified file name
where the camera app should save the photo.
Follow the example in the documentation to create a file Uri and add it to the intent for the camera app.
Please try this
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
if(requestCode == CAMERA_REQUEST && resultCode == RESULT_OK){
Bitmap mImageUri = (Bitmap) data.getExtras().get("data");
select.setImageBitmap(mImageUri);
}
then start posting

Image disappears from ImageView in Android App

I am absolutely new to Android as well as Java (only some basic knowledge). I am trying to develop a simple app as per a youtube video. In this app, I have a button which is clickable and call the method launchCamera(). The image captured by the camera has to be displayed in the ImageView.
PROBLEM: I installed the .apk file in my mobile. When I click the "Take Photo" button, my camera starts. When I capture a image from my camera and save it, that image gets displayed in the ImageView only for a second (even less then a second). How can I keep that photo in the ImageView till the user does not press the "Take Photo" button again?
UPDATE: With the same code, I just noticed something strange. Mostly the image captured while holding the phone vertically rotates itself inside the ImageView and disappears. But sometimes it stays in the ImageView vertically and doesn't get disappeared till the "Take Photo" button is pressed again (Desired case).
My Code:
package com.siddexample.buttonimage;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.content.pm.PackageInfo;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class ButtonImageMainActivity extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
ImageView siddImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_button_image_main);
Button siddButton = (Button) findViewById(R.id.siddButton);
siddImageView = (ImageView) findViewById(R.id.siddImageView);
}//////-------------///////////////
public void launchCamera(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//Take a picture by your intent
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap photo = (Bitmap) extras.get("data");
siddImageView.setImageBitmap(photo);
}
}
}
Try using this tutorial here , as follows:
Taking a picture:
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
Receiving the picture:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
}
and displaying the picture:
/*
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// hide video preview
videoPreview.setVisibility(View.GONE);
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
As #stkent said, maybe the onActivityResult is called twice.

Android Device Policy Manager not working

I'm trying to make a simple app that'll lock the screen of the device when an incoming call is accepted. For this, I'm made a custom device admin with the help of this tutorial. But, when I click the "Enable" button in my app, the Device Policy Manager activity does not open at all! And I get output in the logcat window that says that my ComponentName is invalid. However, I do not find any problems in my project what so ever!
MainActivity.java
package com.swap.delay;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
DevicePolicyManager devicePolicyManager;
ActivityManager activityManager;
ComponentName componentName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
componentName = new ComponentName(this, LockAdmin.class);
}
public void OnClickActivate(View view) {
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Lock Admin by Swap");
startActivityForResult(intent, 1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
Toast.makeText(getBaseContext(), "Lock Admin by Swap added successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Failed!", Toast.LENGTH_SHORT).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
}
LockAdmin.java
package com.swap.delay;
import android.app.admin.DeviceAdminReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.Toast;
public class LockAdmin extends DeviceAdminReceiver{
static SharedPreferences getSamplePreferences(Context context) {
return context.getSharedPreferences(DeviceAdminReceiver.class.getName(), 0);
}
static String PREF_PASSWORD_QUALITY = "password_quality";
static String PREF_PASSWORD_LENGTH = "password_length";
static String PREF_MAX_FAILED_PW = "max_failed_pw";
void showToast(Context context, CharSequence message) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
#Override
public void onEnabled(Context context, Intent intent) {
showToast(context, "Lock Admin Enabled");
}
#Override
public void onPasswordFailed(Context context, Intent intent) {
showToast(context, "Lock Admin: Wrong Password");
}
#Override
public void onPasswordSucceeded(Context context, Intent intent) {
//showToast(context, "Sample Device Admin: pw succeeded");
}
}
policies.xml
<device-admin xmlns:android="http://schemas.android.com/apk/res/auto">
<uses-policies>
<force-lock>
</force-lock>
</uses-policies>
</device-admin>
Receiver(Added to manifest.xml)
<receiver android:name=".LockAdmin" android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data android:name="android.app.device_admin" android:resource="#xml/policies">
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED">
</action></intent-filter>
</meta-data></receiver>
Logcat output -
08-25 12:52:40.103 652-1906/? I/ActivityManager﹕ START u0 {act=android.app.action.ADD_DEVICE_ADMIN cmp=com.android.settings/.DeviceAdminAdd (has extras)} from uid 10172 on display 0
08-25 12:52:40.162 652-1070/? I/ActivityManager﹕ Start proc com.android.settings for activity com.android.settings/.DeviceAdminAdd: pid=6313 uid=1000 gids={41000, 9997, 3002, 3001, 3003, 1028, 1015, 1000, 1021, 3004, 3005, 3009, 1023, 1010, 1007} abi=arm64-v8a
08-25 12:52:40.332 6313-6313/? W/DeviceAdminAdd﹕ Request to add invalid device admin: ComponentInfo{com.swap.delay/com.swap.delay.LockAdmin}
P.s. - I tested out the app on two different devices on based on AOSP KitKat(4.4.2) and another one CyanogenOS 12.0(5.0.2), it didn't work on either of them.

Categories