Pose detection from a gallery video - android

i'm trying to run ML Kit pose detection on a video from the phone gallery by using the following code (i tried to follow the documentation Detect Poses with ML KIT):
public class MainActivity extends AppCompatActivity {
Button pick;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pick = findViewById(R.id.elegir);
videoView = findViewById(R.id.video);
mc = new MediaController(MainActivity.this);
videoView.setMediaController(mc);
pick.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent pickintent = new Intent(Intent.ACTION_GET_CONTENT);
pickintent.setType("video/*");
startActivityForResult(pickintent, 1);
}
});
}
#Override
public void onActivityResult(int requestcode, int resultcode, Intent data){
super.onActivityResult(requestcode, resultcode, data);
if(requestcode == 1 ){
Uri videouri = data.getData();
PoseDetectorOptions options =
new PoseDetectorOptions.Builder()
.setDetectorMode(PoseDetectorOptions.STREAM_MODE)
.build();
PoseDetector poseDetector = PoseDetection.getClient(options);
InputImage image = null;
try {
image = InputImage.fromFilePath(getApplicationContext(), videouri);
} catch (IOException e) {
e.printStackTrace();
}
Task<Pose> result =
poseDetector.process(image)
.addOnSuccessListener(
new OnSuccessListener<Pose>() {
#Override
public void onSuccess(Pose pose) {
// Task completed successfully
// ...
}
})
.addOnFailureListener(
new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Task failed with an exception
// ...
}
});
}
}
}
Error log:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mlkit, PID: 11193
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/video:31 flg=0x1 }} to activity {com.example.mlkit/com.example.mlkit.MainActivity}: java.lang.NullPointerException: InputImage can not be null
at android.app.ActivityThread.deliverResults(ActivityThread.java:5015)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5056)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: InputImage can not be null
at com.google.android.gms.common.internal.Preconditions.checkNotNull(com.google.android.gms:play-services-basement##17.6.0:2)
at com.google.mlkit.vision.common.internal.MobileVisionBase.processBase(com.google.mlkit:vision-common##16.5.0:11)
at com.google.mlkit.vision.pose.internal.PoseDetectorImpl.process(com.google.mlkit:pose-detection-common##17.1.0-beta3:2)
at com.example.mlkit.MainActivity.onActivityResult(MainActivity.java:93)
at android.app.Activity.dispatchActivityResult(Activity.java:8310)
at android.app.ActivityThread.deliverResults(ActivityThread.java:5008)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5056) 
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
I would like to know the proper way to run pose detection in this context. I understand something is going wrong with the InputImage, but i dont know how to fix it

The class is called InputImage instead of InputVideo, so when you use fromFilePath, it expects a file for image instead of video.
Here are some answers on Github about using video file as input: https://github.com/googlesamples/mlkit/issues?q=is%3Aissue+in%3Atitle+%22video+file%22+
Basically, you will need to break the video into separate frames and construct InputImage for each frame.

Related

Attempt to invoke virtual method 'internal.policy.DecorView.getWindowInsetsController()' on a null object reference

My application is giving an Error in the opening file. But this bug is only api 30 channel. This is the fault:
Attempt to invoke virtual method 'android.view.WindowInsetsController com.android.internal.policy.DecorView.getWindowInsetsController()' on a null object reference
When I put the application in the Goggle Robo test, it gives the following error. But this error occurs only in the api 30s. It works correctly in other apes. I would be glad if you could help. Thank you.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobilprogramlar.bilmecebahcesi/com.mobilprogramlar.bilmecebahcesi.AcilisEkrani}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.WindowInsetsController com.android.internal.policy.DecorView.getWindowInsetsController()' on a null object reference
FATAL EXCEPTION: main
Process: com.mobilprogramlar.bilmecebahcesi, PID: 13816
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobilprogramlar.bilmecebahcesi/com.mobilprogramlar.bilmecebahcesi.AcilisEkrani}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.WindowInsetsController com.android.internal.policy.DecorView.getWindowInsetsController()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.WindowInsetsController com.android.internal.policy.DecorView.getWindowInsetsController()' on a null object reference
at com.android.internal.policy.PhoneWindow.getInsetsController(PhoneWindow.java:3880)
at com.mobilprogramlar.bilmecebahcesi.AcilisEkrani.onCreate(AcilisEkrani.java:18)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
... 11 more
java.util.ConcurrentModificationException
FATAL EXCEPTION: main
Process: com.google.android.googlequicksearchbox:search, PID: 9903
java.util.ConcurrentModificationException
at java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:966)
at java.util.LinkedList$ListItr.next(LinkedList.java:888)
at com.google.android.apps.gsa.shared.util.debug.a.g.a(SourceFile:30)
at com.google.android.apps.gsa.shared.util.debug.a.g.a(SourceFile:135)
at com.google.android.apps.gsa.contentprovider.initializer.c.dump(SourceFile:6)
at android.app.ActivityThread.handleDumpProvider(ActivityThread.java:4307)
at android.app.ActivityThread.access$2400(ActivityThread.java:237)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2013)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
The opening file is the file with the error.
public class AcilisEkrani extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//requestWindowFeature(Window.FEATURE_NO_TITLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
**final WindowInsetsController insetsController = getWindow().getInsetsController();**
if (insetsController != null) {
insetsController.hide(WindowInsets.Type.statusBars());
}
} else {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
setContentView(R.layout.acilisekrani);
// Thread
Thread timer = new Thread() {
#Override
public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
Log.i("tago","Zamanlayıcı Çalışmadı");
} finally {
Intent i = new Intent(AcilisEkrani.this,UygulamaUrunlerimiz.class);
startActivity(i);
AcilisEkrani.this.finish();
finish();
}
}
};
// Thread
timer.start();
}
#Override
protected void onPause() {
super.onPause();
finish();
}
}
You probably should call setContentView() before you try to access the window. According to official documentation, NullPointerException will only be if the is nothing to render.
put your logic inside => onWindowFocusChanged
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
WindowInsetsController controller = getWindow().getInsetsController();
if(controller != null) {
controller.setSystemBarsAppearance(WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS, WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS);
// controller.setSystemBarsBehavior(WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS);
}
} else {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false);
// make fully Android Transparent Status bar
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
}

RuntimeException: Unable to start activity for retrofit in main activity in android

hi i'm a bit new to android studio
i'm coding with java and i need help, the thing is that when i put my retrofit codes to Call in mainactivity it won't response;here's my code in Mainactivity how ever I put my codes it gives me these errors in build.
oh and I have already googled it but couldn't find cananyone help please,thanks.
Mainactivity:
public class MainActivity extends ParentActivity {
Call<HealthServices>call;
final String TAG="here";
ArrayList<HealthServices> healthServices;
Button btn_signin, btn_signup;
EditText enter_eamil, enter_pass;
public static final String MY_PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(!getUserHelper().hasUser()){
openActivity(Activity_Register.class, true);
} else {
openActivity(HomeActivity.class, true);
}
// test kon
init();
login();
register();
HealthServices healthServices=APIUtils.getHealthServices();
Call<HList>call=healthServices.getInfoo("JSON","");
Log.d(TAG, "onResponse: "+"TEST");
call.enqueue(new Callback<HList>() {
#Override
public void onResponse(Call<HList> call, Response<HList> response) {
HList hList=response.body();
}
#Override
public void onFailure(Call<HList> call, Throwable t) {
Log.d(TAG+" ERROR", t.getMessage());
}
});
}
private void register() {
btn_signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Activity_Register.class);
startActivity(intent);
}
});
}
private void login() {
btn_signin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mainPass = enter_pass.getText().toString().trim();
String mainMail = enter_eamil.getText().toString().trim();
if (isValidInput(mainMail, mainPass)) {
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(intent);
finish();
}
}
});
}
private void init() {
btn_signin = findViewById(R.id.main_btn_signin);
btn_signup = findViewById(R.id.main_btn_signup);
enter_eamil = findViewById(R.id.main_et);
enter_pass = findViewById(R.id.main_pass);
}
private boolean isValidInput(String mail, String pass) {
//get data of memory
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String emails = prefs.getString("EMAIL", "");
String pass1 = prefs.getString("PASS", "");
if (isEmpty(mail)) {
return false;
}
if (isEmpty(pass)) {
return false;
}
if (!mail.equals(emails)) {
return false;
}
if (!pass.equals(pass1)) {
return false;
}
return true;
}
}
and heres's my errors comes up in build:
02/22 22:20:16: Launching 'app' on Pixel 2 API 29.
$ adb shell am start -n "com.example.najmidpi/com.example.najmidpi.activity.MainActivity" -a
android.intent.action.MAIN -c android.intent.category.LAUNCHER
Waiting for process to come online...
Connected to process 30993 on device 'Pixel_2_API_29 [emulator-5554]'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the
"Logcat output" section of the "Debugger" settings page.
D/libEGL: Emulator has host GPU support, qemu.gles is set to 1.
W/RenderThread: type=1400 audit(0.0:114): avc: denied { write } for name="property_service"
dev="tmpfs" ino=849 scontext=u:r:untrusted_app_27:s0:c134,c256,c512,c768
tcontext=u:object_r:property_socket:s0 tclass=sock_file permissive=0
W/libc: Unable to set property "qemu.gles" to "1": connection failed; errno=13 (Permission
denied)
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
W/xample.najmidp: Accessing hidden method Landroid/view/View;-
>computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection,
allowed)
W/xample.najmidp: Accessing hidden method Landroid/view/ViewGroup;-
>makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.najmidpi, PID: 30993
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.najmidpi/com.example.najmidpi.activity.MainActivity}:
java.lang.IllegalArgumentException: baseUrl must end in /: http://teslam.ir/json%20files
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.IllegalArgumentException: baseUrl must end in /: http://teslam.ir/json%20files
at retrofit2.Retrofit$Builder.baseUrl(Retrofit.java:527)
at retrofit2.Retrofit$Builder.baseUrl(Retrofit.java:470)
at com.example.najmidpi.retrofit.remote.RetroClient.getClient(RetroClient.java:18)
at com.example.najmidpi.retrofit.remote.APIUtils.getHealthServices(APIUtils.java:12)
at com.example.najmidpi.activity.MainActivity.onCreate(MainActivity.java:56)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:7356) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 
Process 30993 terminated.
and the Logcat is clear.
what should I do?Can someone tell plz?
The message looks quite clear to me
http://teslam.ir/json%20files
Basically you have to add a /
as so:
http://teslam.ir/json%20files/
the place should be where you have the Call or Observe interface, is called an endpoint

startActivityForResult should be used error only in dark mode

I am implementing dark mode on my app, and I am facing a peculiar(to me) problem. Below is the logcat of the crash, which I am facing only in dark mode, no error/warning in Light/Default (I am in SDK<=29, so my default is battery saver) mode. Even when battery saver is on, i.e. the app is essentially in dark mode, this crash does not occur.
Log of the error:
2020-02-20 11:20:59.726 16666-16666/com.example.trial E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.trial, PID: 16666
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.trial/com.google.android.libraries.places.widget.AutocompleteActivity}: java.lang.IllegalStateException: Cannot find caller. startActivityForResult should be used.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.ActivityThread.handleRelaunchActivityInner(ActivityThread.java:5279)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:5187)
at android.app.servertransaction.ActivityRelaunchItem.execute(ActivityRelaunchItem.java:69)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ClientTransactionHandler.executeTransaction(ClientTransactionHandler.java:57)
at android.app.ActivityThread.handleRelaunchActivityLocally(ActivityThread.java:5238)
at android.app.ActivityThread.access$3400(ActivityThread.java:219)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2026)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.IllegalStateException: Cannot find caller. startActivityForResult should be used.
at com.google.android.libraries.places.internal.zzft.zzb(com.google.android.libraries.places:places##2.2.0:11)
at com.google.android.libraries.places.widget.AutocompleteActivity.onCreate(com.google.android.libraries.places:places##2.2.0:8)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409) 
at android.app.ActivityThread.handleRelaunchActivityInner(ActivityThread.java:5279) 
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:5187) 
at android.app.servertransaction.ActivityRelaunchItem.execute(ActivityRelaunchItem.java:69) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ClientTransactionHandler.executeTransaction(ClientTransactionHandler.java:57) 
at android.app.ActivityThread.handleRelaunchActivityLocally(ActivityThread.java:5238) 
at android.app.ActivityThread.access$3400(ActivityThread.java:219) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2026) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:7356) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 
This crash is happening only when (with explicit dark mode), when I am calling this (called in MainActivity, not in the Fragment):
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_searchplace:
onSearchCalled();
return true;
....
*other cases does not show this error*
...
}
public void onSearchCalled() {
// Set the fields to specify which types of place data to return.
List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.ADDRESS, Place.Field.LAT_LNG);
// Start the autocomplete intent.
Intent intent = new Autocomplete.IntentBuilder(
AutocompleteActivityMode.OVERLAY, fields) //no .setCountry...Search whole world
.build(this);
startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Place place = Autocomplete.getPlaceFromIntent(data);
if (place.getLatLng() !=null) {
Lat = place.getLatLng().latitude;
Long = place.getLatLng().longitude;
// Toast.makeText(MainActivity.this, ""+Lat, Toast.LENGTH_LONG).show();
setupViewPager();
} else {
Toast.makeText(this, getString(R.string.location_not_found), Toast.LENGTH_LONG).show();
}
} else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
// TODO: Handle the error.
Status status = Autocomplete.getStatusFromIntent(data);
Toast.makeText(MainActivity.this, "Error: " + status.getStatusMessage(), Toast.LENGTH_LONG).show();
// Log.i("LocationSearch", status.getStatusMessage());
}
}
and I have explicitly called for checking night mode in my fragments, like:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
}
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(mContext);
// AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
String theme = sharedPref.getString("theme", "Default");
// Toast.makeText(this, theme, Toast.LENGTH_LONG).show();
if (theme.equals("Dark")) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
} else if (theme.equals("Light")) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
}
}
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_sun, container, false);
....
....
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
mContext = context;
}
I need this checking because, if I don't put this, then the cards of this fragment is light on start. I also have this code in MainActivity's onCreate, but that is not creating any error.
I am totally confused why I am getting this.
Kindly help.

FlashLight App Fail to connect to camera service

Here Is my Code:
I have Added a github Permission code But it still Crashes
I have done every thing but it crashes Every Time
I also have added Permission for Camera in my manifest
parameter = camera.getParameters();
}
#Override public void onPermissionDenied(PermissionDeniedResponse response) {
Toast.makeText(getApplicationContext(), "Permission Denied", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("App needs permission to access camera")
.setPositiveButton("Granted", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent myAppSettings = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + getPackageName()));
myAppSettings.addCategory(Intent.CATEGORY_DEFAULT);
myAppSettings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(myAppSettings);
}
}).setNegativeButton("Denied", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
}).create().show();
}
#Override public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token)
{[enter image description here][1]
token.continuePermissionRequest();
}
}).check();
//getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
textview = (TextView) findViewById(R.id.textView);
flashLight = (ImageButton) findViewById(R.id.flash_light);
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//askPermission(CAMERA,camera1);
flashLight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isFlashLightOn) {
turnOnTheFlash();
} else {
turnOffTheFlash();
}
}
});
logCat:
09-30 18:59:31.698 11339-11339/inducesmile.com.androidflashlightapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: inducesmile.com.androidflashlightapp, PID: 11339
java.lang.RuntimeException: Unable to resume activity {inducesmile.com.androidflashlightapp/inducesmile.com.androidflashlightapp.MainActivity}: java.lang.RuntimeException: Fail to connect to camera service
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3506)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3546)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2795)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6251)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1073)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)
Caused by: java.lang.RuntimeException: Fail to connect to camera service
at android.hardware.Camera.(Camera.java:647)
at android.hardware.Camera.open(Camera.java:510)
at inducesmile.com.androidflashlightapp.MainActivity.turnOffTheFlash(MainActivity.java:105)
at inducesmile.com.androidflashlightapp.MainActivity.onResume(MainActivity.java:165)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1269)
at android.app.Activity.performResume(Activity.java:6791)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3477)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3546) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2795) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527) 
at android.os.Handler.dispatchMessage(Handler.java:110) 
at android.os.Looper.loop(Looper.java:203) 
at android.app.ActivityThread.main(ActivityThread.java:6251) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1073) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934) 
09-30 18:59:31.804 11339-11347/inducesmile.com.androidflashlightapp I/art: Enter while loop.
I also had created a flashlight sensor based app a few months back. I have created gist for the code of the flashlight activity (both java and xml) and it seems to be working fine. Take a look at the below links and see if it helps:
https://gist.github.com/robillo/b27d37be3262164ee7f5532230c28c5a
https://gist.github.com/robillo/71afef65923138ed9d6011e3bd216249
Also, try doing your processing part of the activity in the if block in onCreate() like:
askForPermissions();
if(checkForPermission()){
//Do your processing here
}
The functions are:
void askForPermissions(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
getActivity().requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
}
boolean checkForPermission(){
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
}
It's tough to tell without seeing your turnOnTheFlash and turnOffTheFlash functions, but I'd guess that you are not properly releasing the camera at some point as shown by the documentation.

Android java.lang.IllegalStateException in onRequestPermissionsResult()

I am working with sd card and so trying to get permission in runtime. Here is the code:
public class MainActivity extends AppCompatActivity implements FileListFragment.OnFragmentInteractionListener {
private static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 111;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
...................
................
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
FileListFragment fileListFragment = FileListFragment.newInstance(0); // **Error line**
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, fileListFragment)
.commit();
} else {
finish();
}
return;
}
}
}
.............................
..................................
..........................
}
As soon as I am allow the permission it is throwing "Failure delivering result ResultInfo{who=#android:requestPermissions:, request=111, result=-1, data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has extras) }} to activity {com.kaushik.fileexplorer/com.kaushik.fileexplorer.MainActivity}: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState". Here is the details logcat:
08-23 16:49:29.497 3215-3215/com.kaushik.fileexplorer E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.kaushik.fileexplorer, PID: 3215
java.lang.RuntimeException: Failure delivering result ResultInfo{who=#android:requestPermissions:, request=111, result=-1, data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has extras) }} to activity {com.kaushik.fileexplorer/com.kaushik.fileexplorer.MainActivity}: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.app.ActivityThread.deliverResults(ActivityThread.java:3699)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1533)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1551)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:696)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:662)
at com.kaushik.fileexplorer.MainActivity.onRequestPermissionsResult(MainActivity.java:76)
at android.app.Activity.dispatchRequestPermissionsResult(Activity.java:6553)
at android.app.Activity.dispatchActivityResult(Activity.java:6432)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3695)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742) 
at android.app.ActivityThread.-wrap16(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
What is problem in that code?
You should add commitAllowingStateLoss()
FileListFragment fileListFragment = FileListFragment.newInstance(0); // **Error line**
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, fileListFragment)
.commitAllowingStateLoss();
Please check this link
This Error is because the Activity State is Not Saved and you are adding Fragment before it.
Use This Code :
FileListFragment fileListFragment = FileListFragment.newInstance(0);
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, fileListFragment)
.commitAllowingStateLoss();
And Override Your onSaveInstanceState() method and remove the super() from it.
using commitAllowingStateLoss() is more like a hacky fix.
This problem is very similar to this one and is well explained here.
Instead it's better to set a boolean flag in onRequestPermissionsResult and use this in onPostResume (for Activitys) or onResume (for Fragments) to commit the transaction.

Categories

Resources