in android studio doing face detection using opencv. E/AndroidRuntime: FATAL EXCEPTION: main - android-studio

I am doing face detection application using opencv.the app is installed in the phone but due to fatal error it get closed suddenly. this is my MainActivity.java
package com.example.oc2;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraActivity;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Mat;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.JavaCameraView;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2{
JavaCameraView javaCameraView;
File cascfile;
CascadeClassifier facedetector;
private Mat mRgba,mGrey;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(!OpenCVLoader.initDebug())
{
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_4_0,this, baseCallback);
}
else
{
try {
baseCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
} catch (IOException e) {
e.printStackTrace();
}
}
javaCameraView.setCvCameraViewListener(this);
}
#Override
public void onCameraViewStarted(int width, int height) {
mRgba=new Mat();
mGrey=new Mat();
}
#Override
public void onCameraViewStopped() {
mGrey.release();
mRgba.release();
}
#Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
mRgba=inputFrame.rgba();
mGrey=inputFrame.gray();
MatOfRect facedetection= new MatOfRect();
facedetector.detectMultiScale(mRgba,facedetection);
for(Rect rect: facedetection.toArray())
{
Imgproc.rectangle(mRgba,new Point(rect.x,rect.y),new Point(rect.x+rect.width,rect.y+rect.height),new Scalar(255,0,0));
}
return mRgba;
}
private final BaseLoaderCallback baseCallback=new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) throws IOException {
switch (status)
{
case LoaderCallbackInterface.SUCCESS:
{
InputStream is = getResources().openRawResource(R.raw.haarcascade_frontalface_alt2);
File cascadedir=getDir( "cascade" , Context.MODE_PRIVATE);
cascfile= new File(cascadedir, "haarcascade_frontalface_alt2.xml" );
FileOutputStream fos= new FileOutputStream(cascfile);
byte[] buffer=new byte[4096];
int bytesread;
while((bytesread = is.read(buffer))!=-1)
{
fos.write(buffer,0,bytesread);
}
is.close();
fos.close();
facedetector=new CascadeClassifier(cascfile.getAbsolutePath());
if(facedetector.empty())
{
facedetector=null;
}
else
{
cascadedir.delete();
}
javaCameraView.enableView();
}
break;
default:
{
super.onManagerConnected(status);
}
break;
}
}
};
}
this are my errors can anyone help?
D/AndroidRuntime: Shutting down VM E/AndroidRuntime: FATAL EXCEPTION:
main
Process: com.example.oc2, PID: 19468
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.oc2/com.example.oc2.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
org.opencv.android.JavaCameraView.enableView()' on a null object
reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3119)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1839)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6864)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void org.opencv.android.JavaCameraView.enableView()'
on a null object reference
at com.example.oc2.MainActivity$1.onManagerConnected(MainActivity.java:116)
at com.example.oc2.MainActivity.onCreate(MainActivity.java:52)
at android.app.Activity.performCreate(Activity.java:7232)
at android.app.Activity.performCreate(Activity.java:7221)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2964)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3119) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1839) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:201) 
at android.app.ActivityThread.main(ActivityThread.java:6864) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873) 
I/Process: Sending signal. PID: 19468 SIG: 9
if anyone could give steps to resolving the errors it would be very helpful.

I have two feelings about your code:
1 - in your onCreate activity you are missing a line as:
javaCameraView = (CameraBridgeViewBase) findViewById(R.id.java_camera_view);
2 - you are not checking if the camera permission was granted, which may cause you another error later ["it seems that your device does not support camera or it is locked - application will be closed"]
So have a test with this snippet but consider that in order to have it working you will need to enable the camera permission for the app before launching the app [Settings->Apps->YourApp->Permissions->Camera]. The permission part must be rewritten properly, this is just for a quick test
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
javaCameraView = (CameraBridgeViewBase) findViewById(R.id.java_camera_view);
// added for black screen
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Permissions granted");
javaCameraView.setCameraPermissionGranted();
javaCameraView.setCameraIndex(CameraBridgeViewBase.CAMERA_ID_FRONT);
javaCameraView.setVisibility(CameraBridgeViewBase.VISIBLE);
javaCameraView.setCvCameraViewListener(this);
} else {
Log.d(TAG, "Troubles");
}
}

Related

Android studio: How to create BiometricManager and other bugs

So as a homework from collage i have to make a simple login app using fingerprint, i followed this video: How to Make a FingerPrint Authentication System in Android Studio and Java
But im getting some error that aren't explained and i can't find a answer form, this is my code:
package com.example.actividad14;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import android.graphics.Color;
import android.hardware.biometrics.BiometricManager;
import android.hardware.biometrics.BiometricPrompt;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.Executor;
public class MainActivity extends AppCompatActivity {
#RequiresApi(api = Build.VERSION_CODES.Q)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView msg_txt = findViewById(R.id.txt_msg);
Button login_btn = findViewById(R.id.login_btn);
BiometricManager biometricManager = BiometricManager.from(this);
switch (biometricManager.canAuthenticate()){
case BiometricManager.BIOMETRIC_SUCCESS:
msg_txt.setText("You can use the fingerprint sensor to login");
msg_txt.setTextColor(Color.parseColor("#Fafafa"));
break;
case BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE:
msg_txt.setText("The device doesn't have a fingerprint sensor");
login_btn.setVisibility(View.GONE);
break;
case BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE:
msg_txt.setText("The biometric sensor is currently unavailable");
login_btn.setVisibility(View.GONE);
break;
case BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED:
msg_txt.setText("Your device doesn't have any fingerprint saved, please check your security settings");
login_btn.setVisibility(View.GONE);
break;
}
Executor executor = ContextCompat.getMainExecutor(this);
BiometricPrompt biometricPrompt = new BiometricPrompt(MainActivity.this, executor, new androidx.biometric.BiometricPrompt.AuthenticationCallback() {
#Override
public void onAuthenticationError(int errorCode, #NonNull CharSequence errString) {
super.onAuthenticationError(errorCode, errString);
}
#Override
public void onAuthenticationSucceeded(#NonNull androidx.biometric.BiometricPrompt.AuthenticationResult result) {
super.onAuthenticationSucceeded(result);
Toast.makeText(getApplicationContext(),"Login Succes!", Toast.LENGTH_SHORT).show();
}
#Override
public void onAuthenticationFailed() {
super.onAuthenticationFailed();
}
});
final BiometricPrompt.PrompInfo prompInfo = BiometricPrompt.PrompInfo.Builder()
.setTitle("Login")
.setDescription("Use your fingerprint to login in your app")
.setNegativeButtonText("Cancel")
.build();
login_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
biometricPrompt.authenticate(prompInfo);
}
});
}
}
At BiometricManager biometricManager = BiometricManager.from(this); im getting "cannot resolve method 'from' in 'biometricmanager'", but every video i have seen says that you create your BiometricManager this way.
At BiometricPrompt biometricPrompt = new BiometricPrompt(MainActivity.this, executor, new androidx.biometric.BiometricPrompt.AuthenticationCallback() { im getting "'BiometricPrompt' has private access in 'android.hardware.biometrics.BiometricPrompt'".
At final BiometricPrompt.PrompInfo prompInfo = BiometricPrompt.PrompInfo.Builder() im getting "cannot resolve PromptInfo"
And finally at biometricPrompt.authenticate(prompInfo); im getting "cannot resolve method '(authenticate(BiometricPrompt.PrompInfo))'"
Sorry for the inconvinience, i fount out what was wrong, instead of using:
import android.hardware.biometrics.BiometricManager;
import android.hardware.biometrics.BiometricPrompt;
use
import androidx.biometric.BiometricManager;
import androidx.biometric.BiometricPrompt;
in the build.gradle i used
implementation 'androidx.biometric:biometric:1.2.0-alpha04'
But this can depend on new updates, so try with the newer ones also:
https://mvnrepository.com/artifact/androidx.biometric/biometric?repo=google
And finally i had PrompInfo instead of PromptInfo
This other post really helped me:
Android BiometricPrompt: Cannot resolve symbol PromptInfo

What can I change in buttonadd in the section I think there is a problem

package com.example.gymmanagment;
import static com.example.gymmanagment.Trainignactivity2.Training_key;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
public class plandetailsdialogue extends DialogFragment {
private Button buttondismiss,butoonadd;
private TextView txtname;
private EditText edittextmintues;
private Spinner spinnerdayy;
public interface passplaninteface{
void getplan(plan plan);
}
private passplaninteface passplaninteface;
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
View
view=getActivity().getLayoutInflater().inflate(R.layout.dialoguedetails,null);
intiviews(view);
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity())
.setView(view)
.setTitle("enter details");
Bundle bundle=getArguments();
if(null !=bundle){ Training training=bundle.getParcelable(Training_key);
if(null!=training){
txtname.setText(training.getName());
buttondismiss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
}
});
butoonadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String day=spinnerdayy.getSelectedItem().toString();
int
minitues=Integer.valueOf(edittextmintues.getText().toString());
plan plan=new plan(training,minitues,day,false);
try {
passplaninteface=(passplaninteface) getActivity();
passplaninteface.getplan(plan);
dismiss();
}catch (ClassCastException e){
e.printStackTrace();
dismiss();
}}
});
}
}
return builder.create();
}
private void intiviews(View view){
buttondismiss= view.findViewById(R.id.buttondissmiss);
butoonadd= view.findViewById(R.id.onlyadd);
txtname= view.findViewById(R.id.txtname234);
edittextmintues= view.findViewById(R.id.edttxtminutes);
spinnerdayy= view.findViewById(R.id.spinnerdays);
}
}
The error is below:
022-01-29 13:20:54.963 8688-8688/com.example.gymmanagment E/AndroidRuntime: FATAL
EXCEPTION: main
Process: com.example.gymmanagment, PID: 8688
java.lang.NumberFormatException: For input string: ""
at java.lang.Integer.parseInt(Integer.java:627)
at java.lang.Integer.valueOf(Integer.java:801)
at
com.example.gymmanagment.plandetailsdialogue$2.onClick(plandetailsdialogue.java:52)
at android.view.View.performClick(View.java:7448)
at
com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1131)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
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)
Your EditText is probabbly empty. The error shows that input string is: "". You can't assign a value of nothing to an Integer. You should check if EditText isn't empty before casting it to an Integer.
Try something like this:
if(!edittextminutes.getText().toString.isEmpty())
{
//cast to Integer
}

Open new activity by Clicking button in a Fragment

I'm currently working on a mobile app as a final project for my course. I have these two fragments inside a ViewPager2 controlled by a TabLayout. There are buttons inside of these fragments.
The first frag contains 2 buttons. The other frag has only one button. I want them to open an activity but the problem is when I run the app, these buttons won't work. They didn't open the other activity.
Login Fragment
package com.example.biowit;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.blogspot.atifsoftwares.animatoolib.Animatoo;
public class LoginTabFragment extends Fragment {
EditText email, password;
Button btn_login, btn_forpass;
TextView textView;
float v=0;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.login_fragment, container, false);
email = root.findViewById(R.id.input_LI_email);
password = root.findViewById(R.id.input_LI_pass);
btn_forpass = root.findViewById(R.id.btn_FPass);
btn_login = root.findViewById(R.id.btn_LIn);
email.setTranslationX(800);
password.setTranslationX(800);
btn_forpass.setTranslationX(800);
btn_login.setTranslationX(800);
email.setAlpha(v);
password.setAlpha(v);
btn_forpass.setAlpha(v);
btn_login.setAlpha(v);
email.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(300).start();
password.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(300).start();
btn_forpass.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(300).start();
btn_login.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(300).start();
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), HomeScreen.class);
startActivity(intent);
Animatoo.animateFade(getActivity());
getActivity().finish();
}
});
return root;
}
}
LoginScreen (where the fragment locates)
package com.example.biowit;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
import com.google.android.material.tabs.TabItem;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
public class
LoginScreen extends AppCompatActivity {
TabLayout tabLayout;
ViewPager2 viewPager;
float v=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
tabLayout = findViewById(R.id.tab_layout);
viewPager = findViewById(R.id.view_pager);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
LoginAdapter login_adapter = new LoginAdapter(this);
viewPager.setAdapter(login_adapter);
new TabLayoutMediator(tabLayout, viewPager,
new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
switch (position){
case 0:
tab.setText("LOGIN");
break;
case 1:
tab.setText("SIGNUP");
break;
}
}
}).attach();
tabLayout.setAlpha(v);
}
}
Here's the error log(?)
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.biowit, PID: 18551
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.biowit/com.example.biowit.HomeScreen}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.hide()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3754)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3912)
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:2319)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:239)
at android.app.ActivityThread.main(ActivityThread.java:8212)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:626)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1016)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.hide()' on a null object reference
at com.example.biowit.HomeScreen.onCreate(HomeScreen.java:22)
at android.app.Activity.performCreate(Activity.java:8119)
at android.app.Activity.performCreate(Activity.java:8103)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1359)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3727)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3912) 
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:2319) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:239) 
at android.app.ActivityThread.main(ActivityThread.java:8212) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:626) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1016) 
HomeScreen (Activity that supposedly open when clicking the button)
package com.example.biowit;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
public class HomeScreen extends AppCompatActivity {
Button Chap1_btn, Achieve_btn, HowToPlay_btn, LogOut_btn, Settings_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide(); // hides the action bar.
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
Chap1_btn = findViewById(R.id.btn_Chap1);
Achieve_btn = findViewById(R.id.btn_Achievements);
HowToPlay_btn = findViewById(R.id.btn_HowToPlay);
LogOut_btn = findViewById(R.id.btn_Logout);
Settings_btn = findViewById(R.id.btn_Settings);
Chap1_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent open_Chap1 = new Intent(getApplicationContext(), LessonScreen.class);
startActivity(open_Chap1);
}
});
Achieve_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Intent open_Achievements = new Intent(getApplicationContext(), Achievements.class);
}
});
HowToPlay_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Intent open_HowToPlay = new Intent(getApplicationContext().HowToPlay.class);
}
});
LogOut_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
Settings_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent open_Settings = new Intent(getApplicationContext(), Settings.class);
startActivity(open_Settings);
}
});
}
}
getSupportActionBar().hide(); is what's causing the error. You have added it before
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
So it's trying to execute it before the activity is initialised.
Add it after the above 2 lines and it should work.

Why is my App crashing when I drag an element?

I am trying to make an app in which you can drag and drop specific elements and create your own UI. However when I hold that element and try to drag it, the app crashes. The error is occuring at line 59: v.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.SRC_IN);, where I am trying to set a color filter to the background of the current view that is being dragged.
Code:
package com.app.dragndrop;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ClipData;
import android.content.ClipDescription;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.util.Log;
import android.view.DragEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.app.dragndrop.R;
public class MainActivity extends AppCompatActivity implements View.OnDragListener, View.OnLongClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView myText = findViewById(R.id.myText);
myText.setOnLongClickListener(this);
myText.setOnDragListener(this);
}
#Override
public boolean onLongClick(View v) {
ClipData.Item item = new ClipData.Item((CharSequence) v.getTag());
String[] mimeTypes = {ClipDescription.MIMETYPE_TEXT_PLAIN};
ClipData data = new ClipData(v.getTag().toString(), mimeTypes, item);
View.DragShadowBuilder dragshadow = new View.DragShadowBuilder(v);
v.startDrag(data
, dragshadow
, v
, 0
);
return true;
}
#Override
public boolean onDrag(View v, DragEvent event) {
int action = event.getAction();
switch (action) {
case DragEvent.ACTION_DRAG_STARTED:
if (event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
return true;
}
return false;
case DragEvent.ACTION_DRAG_ENTERED:
v.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.SRC_IN);
v.invalidate();
return true;
case DragEvent.ACTION_DRAG_LOCATION:
return true;
case DragEvent.ACTION_DRAG_EXITED:
v.getBackground().clearColorFilter();
v.invalidate();
return true;
case DragEvent.ACTION_DROP:
ClipData.Item item = event.getClipData().getItemAt(0);
String dragData = item.getText().toString();
Toast.makeText(this, "Dragged data is " + dragData, Toast.LENGTH_SHORT).show();
v.getBackground().clearColorFilter();
v.invalidate();
View vw = (View) event.getLocalState();
ViewGroup owner = (ViewGroup) vw.getParent();
owner.removeView(vw);
LinearLayout container = (LinearLayout) v;
container.addView(vw);
vw.setVisibility(View.VISIBLE);
return true;
case DragEvent.ACTION_DRAG_ENDED:
v.getBackground().clearColorFilter();
v.invalidate();
if (event.getResult())
Toast.makeText(this, "The drop was handled.", Toast.LENGTH_SHORT).show();
else
Toast.makeText(this, "The drop didn't work.", Toast.LENGTH_SHORT).show();
return true;
default:
Log.e("DragDrop Example", "Unknown action type received by OnDragListener.");
break;
}
return false;
}
}
Error:
2020-07-21 15:08:15.596 4515-4515/com.app.dragndrop E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.app.dragndrop, PID: 4515
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.drawable.Drawable.setColorFilter(int, android.graphics.PorterDuff$Mode)' on a null object reference
at com.app.dragndrop.MainActivity.onDrag(MainActivity.java:59)
at android.view.View.callDragEventHandler(View.java:24446)
at android.view.ViewRootImpl.setDragFocus(ViewRootImpl.java:6678)
at android.view.View.dispatchDragEvent(View.java:24435)
at android.view.ViewGroup.dispatchDragEvent(ViewGroup.java:1759)
at android.view.ViewGroup.dispatchDragEvent(ViewGroup.java:1759)
at android.view.ViewGroup.dispatchDragEvent(ViewGroup.java:1759)
at android.view.ViewGroup.dispatchDragEvent(ViewGroup.java:1759)
at android.view.ViewGroup.dispatchDragEvent(ViewGroup.java:1759)
at android.view.ViewGroup.dispatchDragEvent(ViewGroup.java:1759)
at android.view.ViewRootImpl.handleDragEvent(ViewRootImpl.java:6557)
at android.view.ViewRootImpl.access$1100(ViewRootImpl.java:141)
at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:4422)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:235)
at android.app.ActivityThread.main(ActivityThread.java:6760)
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:911)
Thanks for the help!

OnDataChanged is not called

I have a problem with comunication between my phone and wear device. I decided to add wear module to my app. Wear app has just one class (MainActivity)
package cz.johrusk.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.wearable.view.WatchViewStub;
import android.util.Log;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.PutDataMapRequest;
import com.google.android.gms.wearable.PutDataRequest;
import com.google.android.gms.wearable.Wearable;
public class MainActivity extends Activity implements GoogleApiClient.OnConnectionFailedListener,DataApi.DataListener {
GoogleApiClient mGoogleApiClient;
private TextView mTextView;
static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
mTextView = (TextView) stub.findViewById(R.id.text);
}
});
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle connectionHint) {
Log.d(TAG, "onConnected: " + connectionHint);
sendNumber(1);
Log.d(TAG,"BBBBBBBB");
}
#Override
public void onConnectionSuspended(int cause) {
Log.d(TAG, "onConnectionSuspended: " + cause);
}
})
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
Log.d(TAG,"mGoogleApiClient connected;");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG,"FAILE" + connectionResult);
}
public void sendNumber(int number) {
PutDataMapRequest putDataMapRequest = PutDataMapRequest.create("/number");
putDataMapRequest.getDataMap().putInt("number",number);
putDataMapRequest.getDataMap().putLong("Time",System.currentTimeMillis());
PutDataRequest putDataReq = putDataMapRequest.asPutDataRequest();
putDataReq.setUrgent();
Wearable.DataApi.putDataItem(mGoogleApiClient, putDataReq)
.setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
#Override
public void onResult(#NonNull DataApi.DataItemResult dataItemResult) {
if (!dataItemResult.getStatus().isSuccess()) {
Log.d(TAG,"Fail");
}
else{
Log.d(TAG,"Succes");
}
}
});
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onDataChanged(DataEventBuffer dataEventBuffer) {
Log.d(TAG,"TEST");
}
}
I quess that "Wearable.DataApi.putDataItem" should call WearableListenerService in my phone app. Here is that service:
package cz.johrusk.showsmscode.service;
import android.util.Log;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.DataEvent;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.DataMap;
import com.google.android.gms.wearable.DataMapItem;
import com.google.android.gms.wearable.Wearable;
import com.google.android.gms.wearable.WearableListenerService;
public class WatchListener_service extends WearableListenerService {
#Override
public void onCreate() {
super.onCreate();
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onDataChanged(DataEventBuffer dataEventBuffer) {
Log.d("prijato","number is: ");
for (DataEvent dataEvent : dataEventBuffer) {
if (dataEvent.getType() == DataEvent.TYPE_CHANGED) {
DataMap dataMap = DataMapItem.fromDataItem(dataEvent.getDataItem()).getDataMap();
String path = dataEvent.getDataItem().getUri().getPath();
if (path.equals("/number")){
int number = dataMap.getInt("numa");
long time = dataMap.getInt("timestamp");
Log.d("received","number is: " + number);
}
}
}
}
}
However, onDataChanged method in WatchListener_service isn't called. onResult method inside ResultCallbacks print "Succes" so it seems that DataItem is send correctly.
I already find many similar problems on Stackoverlflow so I checked all these things:
Both modules has same applicationId
Both modules use 'com.google.android.gms:play-services-wearable:9.0.0'
SetUrgent is used to putDataRequest so there shouldnt be any delay.
WearableListenerService has declared correct intent filter in Manifest :
action android:name="com.google.android.gms.wearable.DATA_CHANGED"
data android:scheme="wear" android:host="*"
Both phone and Wear app run on physical device. My question is... What should I do to fix this issue?
Thanks
Check if both apps have the same debug key. I had some problems with that and problem was different keys for both apps (wear and mobile).
PS: The Android Wear API is ridiculous. I quit developing for Wear because of how terrible is that API that doest not work as they say this should.

Resources