NullPointerException with zxing library for QR scanning (android app) [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I need an independent QR scanner in my app, so I've added the zxing library to my Android app - I've followed this link - I added the dependencies in build.gradle, and this is how I call the method:
btnScanQR.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new IntentIntegrator(MainScreenActivity.this).initiateScan(); // `this` is the current Activity
}
});
// Get the results:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
if(result.getContents() == null) {
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
So it's basically exactly like on their github page, so there shouldn't be any problems, right?
However, I get this error when I try to open the scanner through my app, and I can't seem to find any solutions online to this exact problem:
CameraInstance: Configuring camera
W/CameraManager: Failed to set rotation.
W/CameraManager: Camera rejected even safe-mode parameters! No configuration
E/CameraInstance: Failed to configure camera
java.lang.NullPointerException: Attempt to invoke virtual method 'android.hardware.Camera$Parameters android.hardware.Camera.getParameters()' on a null object reference
at com.journeyapps.barcodescanner.camera.CameraManager.setParameters(CameraManager.java:353)
at com.journeyapps.barcodescanner.camera.CameraManager.configure(CameraManager.java:139)
at com.journeyapps.barcodescanner.camera.CameraInstance$4.run(CameraInstance.java:171)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.os.HandlerThread.run(HandlerThread.java:61)
D/CameraPreview: pause()
D/CameraInstance: Closing camera
D/CameraPreview: pause()
What is the cause of this (is it because it fails to rotate?) and how could I fix this? I've tried changing the orientation like it says on zxings github page with this:
<activity
android:name="com.journeyapps.barcodescanner.CaptureActivity"
android:screenOrientation="fullSensor"
tools:replace="screenOrientation" />
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.setOrientationLocked(false);
integrator.initiateScan();
But I keep getting the same error! Please help :(

Following two reasons for this error:
1) You have not initialized camera:
mcamera = mcamera.open();
2) You have not given permissions in androidmanifest.xml file.
<uses-permission android:name="android.permission.CAMERA"/>

Related

Android - Making typeface from file URI doesn't work [duplicate]

This question already has answers here:
Android Kotlin: Getting a FileNotFoundException with filename chosen from file picker?
(5 answers)
Android - Get real path of a .txt file selected from the file explorer
(1 answer)
Closed 1 year ago.
Edit: Whoever gave an -1 to this post, explain how would I improve it instead. Stop the toxicity.
I want to make a font preview fragment in my app (getting the .tff file from Intent and setting a TextView's font to that font).
Here is how I tried to do this:
private void chooseFont(){
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, 1);
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data == null) return;
if (requestCode == 1) {
System.out.println(getFileName(data.getData()));
if (!getFileName(data.getData()).endsWith(".ttf")){
Snackbar.make(chooseFontButton, "Only .ttf files are supported in MIUI.", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
return;
}
fontPreview.setTypeface(Typeface.createFromFile(data.getData().getPath()));
//The line above is giving the error.
//I also tried creating a new File object with data.getData(). Same result.
theTheme.font = new File(data.getData().getPath());
fontName.setText(theTheme.font.getName());
viewModel.setSelectedTheme(theTheme);
}
}
However, this didn't work. Here is the error:
java.lang.RuntimeException: Font asset not found /document/primary:MIUI/open-sans/OpenSans-ExtraBold.ttf
What should I do?

How to get Google-Sign in to work after getting error 10?

I have trying to implement Google Sign In on my app by following the guide.
https://developers.google.com/identity/sign-in/android/start-integrating#add_google_play_services
However, I keep getting error 10 everytime I go to try to log in and I know it means its a developer error but, I cant figure out what I am doing wrong. I implemented all the code, made sure I have the correct packages and updated Android Studio.
I tried different client ids from SHA1 hashes that came from multiple generated signed bundles and apks for my app. I tried the pre generated one that Google gives you for sign-in. Any ideas?
Intent for google sign in
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestIdToken(getString(R.string.server_client_id))
.build();
googleSignInClient = GoogleSignIn.getClient(getActivity(),gso);
Intent signInIntent = googleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, 21);
OnActivityResult function
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 21) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
else if (resultCode == RESULT_CANCELED)
{
Log.d("frag", "intent fired and something went wrong");
}
}
handleSignInResult function
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
// Signed in successfully, show authenticated UI.
Log.d("frag", "Email of account is " + account.getEmail());
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w("ytsignin", "signInResult:failed code=" + e.getStatusCode());
}
}
Check the SHA-1 code and package name in developer console. Most of the time it is what causes the error 10 which is 'DEVELOPER_ERROR'.
Check the SHA-1 in console against the one you get from Android Studio after running signingReport.

Why doesn't startActivityForResult() lead to onActivityResult() execution?

Still trying to make my screen record app. I keep on working with MediaRecorder, as I was told some time ago, so I got stuck with another problem.
I just need to initialize a MediaProjection object to make my code work, that's what I do in onActivityResult(), as it's written in this guide:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECORD_REQUEST_CODE && resultCode == RESULT_OK) {
mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
screenRecorder.setMediaProject(mediaProjection);
}
}
The setMediaProjection() looks like
public void setMediaProject(MediaProjection project) {
mediaProjection = project;
}
, so it shouldnt't cause any trouble.
And that's how I try to call onActivityResult():
/* start transmission */
if(screenRecorder.isRunning()) {
screenRecorder.stopRecord();
} else {
Intent captureIntent = mediaProjectionManager.createScreenCaptureIntent();
startActivityForResult(captureIntent, RECORD_REQUEST_CODE);
}
The fun and crazy thing is that when I first launched the debug, it worked! After startActivityForResult() I got to onActivityResult() and initialized mediaProjection: my phone showed me a dialog window whether I allow to capture the screen or not, so I allowed that and got a special symbol (smth like screen with displayed waves) at my status bar.
But a few moments later I found an issue when stopping the record and restarted the debug session to trace it more exactly. After that onActivityResult() is just ignored: startActivityForResult() is called, the dialog window is shown, but after allowing the record onActivityResult() is completely skipped and mediaProjection is null. The restarting and re-installing the apk with the same code didn't fix anything.
Thank you very much for any suggestions.
Your onActivityResult only does something when the result code is OK, try this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECORD_REQUEST_CODE && resultCode == RESULT_OK) {
mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
screenRecorder.setMediaProject(mediaProjection);
} else {
//TODO: Do something
Toast.makeText(getBaseContext(), "Result code is not RESULT_OK, ", Toast.LENGTH_LONG).show();
}
There was a very simple solution. I just initialized the record service that put null into mediaRecorder's mediaProjection, so after that I was unable to re-initialize it. Putting intent which called onActivivtyResult() into activity's onCreate() before starting the service fixed that.
I got same problem. This could bu about threading. In my project I started an activity and opening activity try to start chrome intent. Chrome is opening in debug mode but not opened real mode.
I added a delay when opening chrome
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
startAuth();
}
}, 100);

onActivityResult Not Being Called For UnityPlayerActivity

I don't have a lot of experience creating Java (.aar) plugins for Unity3d, but I am attempting to setup google authentication with firebase from such a plugin. To give an example of my problem, I begin by opening a unity android application, then I run the c# code below, and get a popup on my display to sign-in with google. I then choose the correct google account, then the google intent/activity disappears, then I receive no indication that "onActivityResult" has been called. No errors occur and I am unable to to do anything with the google account information that I chose.
In the image below, I click submit -> it opens the google sign-in activity in the next picture -> then it returns back to the submit screen (closing the google sign-in activity).
I think my issue is in this line:
activity.startActivityForResult(signInIntent, RC_SIGN_IN);
The "activity" in this case is a UnityPlayerActivity sent from the c# unity code below. I think this is making it so my code is looking for an "onActivityResult" method in the C# unity code rather than the java code. Any help would be greatly appreciated. Let me know if you need any other info or screenshots. Please call me out if I am being a moron.
Here is my code for calling the Google Signin Plugin From C# & Unity3d:
AndroidJNIHelper.debug = true;
using (AndroidJavaClass activityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) {
activity_context = activityClass.GetStatic<AndroidJavaObject>("currentActivity");
}
using (AndroidJavaClass pluginClass = new AndroidJavaClass("com.package.class")) {
if (pluginClass != null) {
GoogleSignInActivity = pluginClass.CallStatic<AndroidJavaObject>("instance");
GoogleSignInActivity.Call("SetContext", activity_context);
GoogleSignInActivity.Call("StartGoogleLogin", activity_context);
activity_context.Call("runOnUiThread", new AndroidJavaRunnable(() => {
GoogleSignInActivity.Call("ShowMessage", "You signed in as " + display_name);
}));
}
}
Here is the code for creating the Google SignIn Activity:
public void StartGoogleLogin(UnityPlayerActivity activity) {
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken("some url")
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(activity, gso);
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
activity.startActivityForResult(signInIntent, RC_SIGN_IN);
Log.d(TAG, "Activity Started; Waiting For Result");
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "Result Received!");
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful
GoogleSignInAccount account = task.getResult(ApiException.class);
someMethod(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.d(TAG, "Google sign in failed", e);
}
setResult(RESULT_OK);
}
}
Thank you for your time.
Well, I solved my own problem of getting Google Authentication to work between the Android .aar plugin and Unity c#. Been working tirelessly and found some kickbutt resources.
First and foremost, I referenced the code written by a guy named cwgtech HERE.
I also went through all of his videos.
Instead of using UnitySendMessage, I was able to use a callback method similar to what CWGTech does to send a googleIdToken back to Unity and sign-in with Google into Firebase. I was also correct in thinking that my mistake was with the statement below:
activity.startActivityForResult(signInIntent, RC_SIGN_IN);
Instead of doing this, I followed CWGTech's advice and removed "activity." portion. I ran the startActivityForResult in a ResultCallback class that extends Activity. If you are still confused, dm me or comment on this post. Thanks!
Here is some of the code I used to send a callback string to Unity via a Java Proxy in written in C#. Information about writing a Java proxy can be found in the cwgtech information above. Writing the java proxy is extremely important if you want to get information to flow from Android activities to Unity C#. CWGTech explains the intricacies of java proxies way better than I could do justice.
public static final String LOGTAG = GoogleSignInActivity.TAG + "_OnResult";
public static GoogleSignInActivity.ShareStringCallback shareStringCallback;
private static final int RC_SIGN_IN = 9001;
private GoogleSignInClient mGoogleSignInClient;
private GoogleSignInOptions gso;
private CallbackManager mCallbackManager;
public void myFinish(String myresult) {
if (shareStringCallback != null) {
shareStringCallback.onLoginComplete(myresult);
}
shareStringCallback = null;
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(LOGTAG, "onCreateBundle");
Intent intent = getIntent();
setContentView(R.layout.login_activity);
findViewById(R.id.buttonFacebookLogin).setOnClickListener(this);
findViewById(R.id.signInButton).setOnClickListener(this);
findViewById(R.id.buttonAnonymousSignIn).setOnClickListener(this);
}
/* GOOGLE SIGN-IN CODE */
public Intent StartGoogleLogin() {
/*
Google Sign In Client Init Code Goes Here
*/
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
return signInIntent;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//Detects some type of result from an activity, in this case Google
String id_result = "Send This To Unity";
myFinish(id_result);
}
Here is a bit more code from a different java class file. The 'Login' method is called from Unity c#.
/* INTERFACES FOR CALLBACK FUNCTIONAILITY */
public interface ShareStringCallback {
public void onLoginComplete(String result);
}
public void Login(final ShareStringCallback callback)
{
mainActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
Log.i(TAG,"Starting Authentication");
try {
try {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setClass(mainActivity,OnResultCallback.class);
OnResultCallback.shareStringCallback = callback;
mainActivity.startActivity(shareIntent);
}
catch (Exception e)
{
e.printStackTrace();
Log.i(TAG,"error sharing intent: " + e);
}
}
catch (Exception e)
{
e.printStackTrace();
Log.i(TAG,"Error getting Uri: " + e);
}
}
catch (Exception e)
{
e.printStackTrace();
Log.i(TAG,"Error writing file: " + e);
}
}
});
}
When you start a activity from UnityPlayerActivity, the onActivityResult will be called when finished, but will have its default return value. What you can do is create a new Activity in Android, and extends UnityPlayerActivity.
In Android, create a new Activity
import com.unity3d.player.UnityPlayer;
public class OverrideUnityPlayerActivity extends UnityPlayerActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public Activity getCurrentActivity(){
return mUnityPlayer.currentActivity;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
switch (resultCode) {
case Activity.RESULT_OK:
//do something
break;
case Activity.RESULT_CANCELED:
//do something
break;
}
}
}
}
You need to set this override activity as launch endpoint in AndroidManifest.XML
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.unity3d.player"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="false"
tools:replace="android:allowBackup">
<activity
android:name="com.example.unitylibrary.manager.OverrideUnityPlayerActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="app_name" android:value="app_value"/>
</activity>
</application>
</manifest>
3.Then in Unity, you can get this activity and context, also get the onActivityResult
AndroidJavaObject overridePlayerActivity;
AndroidJavaObject overrideActivity;
public void init(){
overridePlayerActivity = new AndroidJavaObject("com.example.unitylibrary.manager.OverrideUnityPlayerActivity");
overrideActivity= overridePlayerActivity.Call<AndroidJavaObject>("getCurrentActivity");
}
public void startAct(){
anonymousFunction.Call("StartActForRes", overrideActivity);
}
Hope this will solve your problem.

ZXing QR code scanner embedded pressing back button during scan issue

I have the following scenario :
I used the Maven repository from Gradle to integrate ZXing into my Android app.
In my scan activity, the code looks like this :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scan_layout);
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
integrator.setPrompt(" ");
integrator.setScanningRectangle(700, 700);
integrator.setResultDisplayDuration(0);
integrator.setCameraId(0); // Use a specific camera of the device
integrator.initiateScan();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = null;
scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
String scanContent = scanningResult.getContents();
if(isConnected()) {
requestdata("http://rm360project-001-site1.smarterasp.net/api/endpoint", scanContent);
}else {
Toast.makeText(this, "Internet Connection not available", Toast.LENGTH_LONG).show();
}
} else {
Intent getMainScreen = new Intent(ScanScreen.this, MainActivity.class);//pentru test, de sters
startActivity(getMainScreen);
}
}
The way I want it to work :
1. If I scan a QR code, call the function requestdata
2. If I press back during scan, go to MainActivity
The problem :
Even when I press back on my device, the function requestdata is called, I think because scaningResult is never null. Shouldn't it be null when back is pressed?
Do you have any ideea why this happens?
Thank you!
Don't know if your still interested but...
Simply change this line:
if (scanningResult != null) {
To this:
if (scanningResult != null && resultCode==RESULT_OK) {
For some reason simply scanningResult does not actually return null as suggested by the ZXing team, even when the Intent is canceled.

Categories

Resources