NullPointerException Trouble using camera in android studio app - java

Im trying to transmit phone's camera preview to a textureView in app. When i start the method i get the following error in logcat and the app crashes.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.hardware.camera2.CaptureRequest$Builder android.hardware.camera2.CameraDevice.createCaptureRequest(int)' on a null object reference
This is the code.
try {
//[0] Usually is the back cam but may need to play with it.
ActivityCompat.requestPermissions(CameraActivity.this ,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},PackageManager.PERMISSION_GRANTED);
Log.d("asd","here");
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
Log.d("asd","OOOOOPPPSs");
return;
}
Log.d("asd","BBBBBBBBBBBBBBBBBB");
cameraId=cameraManager.getCameraIdList()[0];
Log.d("asd","AAAAAAAAAAAAAAAAAAAAAAA");
cameraManager.openCamera(cameraId, stateCallbackForCamera, null);
}catch (Exception a){
a.printStackTrace();
}
This is the log output i get.
2022-10-19 12:56:06.227 11217-11217/com.example.testapp D/asd: here
2022-10-19 12:56:06.227 11217-11217/com.example.testapp D/asd: OOOOOPPPSs
If i bypass the permission check by changing the if statement to
ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
The new log output i get becomes this
2022-10-19 12:47:19.959 10777-10777/com.example.testapp D/asd: here
2022-10-19 12:47:19.959 10777-10777/com.example.testapp D/asd: BBBBBBBBBBBBBBBBBB
I have two questions, first; why does the permission check fail? (The app wont show popup to ask for permissions).
Second; I believe the code
cameraId=cameraManager.getCameraIdList()[0];
Is somehow breaking the app, why is that and how can i fix it? Perhaps cameraManager is null?
This is how the cameraManager is assigned, i took this from a video i saw and it was working fine for that person but im not familiar with these concepts so any help is appriciated.
cameraManager = (CameraManager) getSystemService(CAMERA_SERVICE);
EDIT: FOUND THE CAUSE AND FIX FOR MY OWN SITUATION, NOW RAN INTO ANOTHER QUESTION, CHECK MY FIRST ANSWER.

I found the cause; Like the idiot i am, i forgot to add camera permission request to the request line. Once this was added, the app would run perfectly fine. Although i have another question now; The first time i ran the app after adding the camera request, The permission request popped up on the screen and when i accepted it, the camera still wouldnt work for a few seconds then the app reset to the main activity by itself only then on the second try it would work normally. Why is that?
A bit more detail; the app consists of several activities, the main activity is basically empty only with a button and speech recognition, it directs you to the camera activity where everything camera related takes place.

Related

URI to image on activity started blank

API 30
This is going to all sound very scrambled, because I've very conf
The following works perfectly fine, it loads the image into 'imCardImage' widget without problem.
val getContentCardImage = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
imCardImage.setImageURI(uri) // Handle the returned Uri
cImageCardStr = uri.toString()
Log.d("EditCards","URI = "+uri.toString())
Log.d("EditCards","(mydecklist) URI = "+mydecklist[cCardPosition].c_image)
}
The problem appears when, I exit the app and restart it/go to another activity within the same application, all the images are gone it's as if I had temporary permission while the activity was active, in the area where you can select images and revoked the instant that activity is terminated, and yet I've requested permission from the use and been granted it.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I did get this error; Permission Denial: opening provider com.android.providers.media.MediaDocumentsProvider but for some odd reason it's stopped happening for some unknown reason.
override fun onBindViewHolder( holder: ViewHolder, position: Int ) {
holder.cardTitle.text = "[$position] "+mydecklist[position].c_title
holder.cardMessage.text = mydecklist[position].c_message
holder.cardImage.setImageURI(mydecklist[position].c_image.toUri())
}
The above is supposed to load the image from mydecklist[#].c_image in to a RecycleView / CardView, but is blank when starting the app.
14727-14727/com.example.cardgamexxx E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.cardgamexxx, PID: 14727
java.lang.SecurityException: Permission Denial: opening provider com.android.providers.media.MediaDocumentsProvider from ProcessRecord{bc01e1c 14727:com.example.cardgamexxx/u0a734} (pid=14727, uid=10734) requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs
-- error is back, thanks to "mehul bisht" no actually I did want that back :) see my reply to your comment.
// Permissions
permissionsLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
readPermissionGranted = permissions[Manifest.permission.READ_EXTERNAL_STORAGE] ?: readPermissionGranted
}
requestPermissions()
Permission already requested, if there is some other permission I should be asking for I'd love to know.
EDIT 2
Pretty sure I might have an idea, I might be entirely wrong though!
registerForActivityResult()...
Above when the user selects the image the image is resolved? uri is valid? I have permission at this point? no idea why that works but it works.
holder.cardImage.setImageURI(mydecklist[position].c_image.toUri())
That's the deploy line that sends the image to the cardImage widget, but is in a mutable list as a type string which I am converting to a Uri. I suppose that is okay. however it doesn't work when loading the application from a restart or just switching to another activity in the same application and back again, so either I need to resolve the uri so that it's valid again or takepermission to have access to it always.
NB: it would be better if I had my own folder that users could drop files in that I had total access to but I don't know how to do that so, I have to go the overly convoluted obtuse route.

Why does sign-out from Leaderboard result in an application crash?

When I've signed-out from within the Leaderboards by accessing settings, and when I attempt to sign back in, the application crashes. It seems that GameHelper does not register this sign-out.
How does one fix this?
I believe this is a similar issue that was raised on the github repo. Its indicated there that its working as intended.
When you start a GPGS activity, you have to start it with startActivityForResult. If the user clicks on sign-out, the GoogleApiClient is NOT disconnected - it's just in a "signed out" state. The onActivityResult here will return a status RECONNECT_REQUIRED. At this point, the developer should reconnect their client, and life goes on as expected.
Try to modify the RECONNECT_REQUIRED condition block to disconnect, or create a way to handle it specific to your usecase (log-in page?).

Why is an unused activity throwing an exception when uploaded to the Play Store?

I have an app which I recently uploaded to the Play Store, with Crashlytics enabled. Within this app there is an activity called StartQuizActivity, which was created during development but is currently unused. The activity is still declared in the manifest, but there are no intents within the app which invoke it.
I received a crash report with the stack trace suggesting that a device had attempted to launch this activity, which resulted in an IllegalArgumentException, suggesting the required objects weren't passed with the intent:
Fatal Exception: java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.fractalwrench.acidtest/com.fractalwrench.acidtest.activities.StartQuizActivity}:
java.lang.IllegalArgumentException: No extras supplied to
startQuizActivity!
StartQuizActivity.java
#Override protected void onCreate(Bundle savedInstanceState) {
aminoAcid = getIntent().getExtras().getParcelable(AMINO_ACID);
super.onCreate(savedInstanceState);
if (aminoAcid != null) {
// do things
} else {
throw new IllegalArgumentException("No extras supplied to startQuizActivity!");
}
Why would a device be able to launch this activity, given that there is no way to launch StartQuizActivity using the app's UI? I have noticed that the device was a rooted Nexus running API 21, and have seen similar crashes for other activities in the app. I have been unable to reproduce the crashes on any device, even after trying MonkeyRunner.
Is this some form of automated testing by Google or perhaps a user with a very specific device setup? Any thoughts would be appreciated.
AndroidManifest.xml
<activity
android:name=".activities.StartQuizActivity"
android:label="#string/activity_title_prepare_for_quiz" />
When you add an activity to your manifest with android:exported="true" (as is the default for activities), it becomes part of your public API that any app can call.
Understandably so, it is quite rare for other apps to explicitly start a random Activity from another app without reason, but apps such as Tasker do allow end users to do exactly that.
You can either
Remove the activity from the manifest - this obviously removes any ability to start it at all
Add android:exported="false" - this ensures that other apps cannot start the Activity
Call finish() if no extras were supplied, immediately stopping the activity.

bringing up different page when logged in

let me start off by saying happy holidays to everyone!
ok i really just need confirmation and correction if needed.
what im trying to do:
Im using google and facebook "Log-in" feature to sign in for my app to retrieve the data needed like name email etc.
where i Need help:
after signing in i want another activity to be the forefront everytime app opens unless the user signs out then of course, it takes them back to the original main page to sign back in.
now im assuming this takes place in maybe the lifecycle right?
somthing like:
#override
OnResume
{
//if user is signed in cast an Intent to automatically go to another activity?
}
am i on the right track on no? thanks in advance guys
I'm not sure off the top of my head how Google and Facebook's login is implemented... do they have a sample project you're using?
And yep, you're on the right track! Generally speaking you should be able to have a "Main" activity (MainActivity for this example) which checks to see if the login was successful, and if so, kicks you to the activity you want (LoggedInActivity).
This would be in the onCreate() or onResume() method of MainActivity.java
onResume() { // onCreate() should work, too.
if (loggedIn) {
startActivity(new Intent(this, LoggedInActivity.class));
} else {
// send them to login
}
}
If there's not a good way to check if they're logged in, you could save a boolean value or api token using SharedPreferences once the login is successful, and check that value (that'd be the value of loggedIn) every time at launch. You'd obviously need to clear that value any time you logged out.

How to read NFC Tag and call Webservice in Android

I'm now developing an android application with the NFC concept . In that application I need to pick my application if I swipe the NFC card and if I select my application my application must start calling webservice.
when it comes to my problem, If suppose my app crashed ,when I swipe the card next time ,the option to choose the application doesn't open .Instead,my application directly launched and couldn't call the webservice data.
On the whole.I'm getting last page when it crashed .But I need to open as fresh
I came to know that I need to make changes in OnResume() and OnNewIntent().
I used ,
In OnResume()
super.onResume();
mNfcAdapter.enableForegroundDispatch(this, nfcPendingIntent, mNdefExchangeFilters, null);
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
NdefMessage[] msgs = getNdefMessages(getIntent());
byte[] payload = msgs[0].getRecords()[0].getPayload();
//Toast.makeText(this, new String(payload), Toast.LENGTH_LONG).show();
Student=new String(payload);
if(Student.equals(rakesh)
{
new Webservice.execute(""); // Calling SOAP Webservice
}
But,I can't find any changes with my problem .and one more thing that the problem will be resolve after I just open and close an another NFC project
Please help.
Yeah ! I got the solution .I forget a simple thing that I left calling onStop() method and my problem was,when my application stops(when Crashed).It runs in background as the previous activity.
I just tried the following,
public void onStop()
{
super.onStop();
this.finish();
}
This may be helpful to others.
Thanks..

Categories