Application keeps force stopping - java

I'm creating a tic tac toe game using android studio but my application keeps crashing
i tested this app on my emulator and copied the logcat here!
here's my code
public class LoginActivity extends AppCompatActivity {
private TextView twoPlayerLabel;
private TextView optionsLabel;
private MediaPlayer intro;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
twoPlayerLabel = (TextView) findViewById(R.id.two_player_label);
optionsLabel = (TextView) findViewById(R.id.options_label);
}
public void twoPlayer(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
final View layout = inflater.inflate(R.layout.two_player_options, null);
final Intent twoPlayerLocal = new Intent(LoginActivity.this, TwoPlayerActivityLocal.class);
final TextView playerOneName = (TextView) layout.findViewById(R.id.player_one);
final TextView playerTwoName = (TextView) layout.findViewById(R.id.player_two);
final RadioButton localGame = (RadioButton) layout.findViewById(R.id.local_game);
final RadioButton bluetoothGame = (RadioButton) layout.findViewById(R.id.bluetooth_game);
final RadioButton oMarker = (RadioButton) layout.findViewById(R.id.o_marker);
final RadioButton xMarker = (RadioButton) layout.findViewById(R.id.x_marker);
localGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playerTwoName.setVisibility(View.VISIBLE);
oMarker.setVisibility(View.VISIBLE);
xMarker.setVisibility(View.VISIBLE);
}
});
bluetoothGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playerTwoName.setVisibility(View.GONE);
oMarker.setVisibility(View.GONE);
xMarker.setVisibility(View.GONE);
}
});
oMarker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
oMarker.setBackgroundResource(R.drawable.tic_tac_toe_o_black);
xMarker.setBackgroundResource(R.drawable.tic_tac_toe_x);
}
});
xMarker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
xMarker.setBackgroundResource(R.drawable.tic_tac_toe_x_black);
oMarker.setBackgroundResource(R.drawable.tic_tac_toe_o);
}
});
builder.setView(layout)
.setTitle("Two Player Game Options")
.setPositiveButton("Start", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
if (localGame.isChecked()) {
if ((playerOneName.getText().length() > 0) && (playerTwoName.getText().length() > 0)) {
if (oMarker.isChecked()) {
Player playerOne = new Player(playerOneName.getText().toString(), 'o', 0);
Player playerTwo = new Player(playerTwoName.getText().toString(), 'x', 0);
twoPlayerLocal.putExtra("playerOne", playerOne);
twoPlayerLocal.putExtra("playerTwo", playerTwo);
twoPlayerLocal.putExtra("isTurn", playerOne.getPlayerMarker());
startActivity(twoPlayerLocal);
} else if (xMarker.isChecked()) {
Player playerOne = new Player(playerOneName.getText().toString(), 'x', 0);
Player playerTwo = new Player(playerTwoName.getText().toString(), 'o', 0);
twoPlayerLocal.putExtra("playerOne", playerOne);
twoPlayerLocal.putExtra("playerTwo", playerTwo);
startActivity(twoPlayerLocal);
}
else {
Toast.makeText(LoginActivity.this, "Please select the starting marker", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(LoginActivity.this, "Please enter a name for the players", Toast.LENGTH_SHORT).show();
}
} else if (bluetoothGame.isChecked()) {
Intent bluetoothIntent = new Intent(LoginActivity.this, TwoPlayerActivityBluetooth.class);
String playerOne = null;
if (playerOneName.getText().length() > 0) {
playerOne = playerOneName.getText().toString();
bluetoothIntent.putExtra("playerOne", playerOne);
startActivity(bluetoothIntent);
} else {
Toast.makeText(LoginActivity.this, "Please enter a player name", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(LoginActivity.this, "Please Select a game type", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
});
// Create the AlertDialog object and return it
builder.create().show();
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to quit the game?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.create().show();
}
}
and this is logcat!
2019-09-04 22:44:37.659 17644-17644/? I/ir.puzzle.douz: Not late-enabling -Xcheck:jni (already on) 2019-09-04 22:44:37.697 17644-17644/? E/ir.puzzle.douz: Unknown bits set in runtime_flags: 0x8000 2019-09-04 22:44:37.699 17644-17644/? W/ir.puzzle.douz: Unexpected CPU variant for X86 using defaults: x86 2019-09-04 22:44:38.014 17644-17670/ir.puzzle.douz D/libEGL: Emulator has host GPU support, qemu.gles is set to 1. 2019-09-04 22:44:38.036 17644-17670/ir.puzzle.douz W/libc: Unable to set property "qemu.gles" to "1": connection failed; errno=13 (Permission denied) 2019-09-04 22:44:38.023 17644-17644/ir.puzzle.douz W/RenderThread: type=1400 audit(0.0:157): avc: denied { write } for name="property_service" dev="tmpfs" ino=6800 scontext=u:r:untrusted_app:s0:c134,c256,c512,c768 tcontext=u:object_r:property_socket:s0 tclass=sock_file permissive=0 2019-09-04 22:44:38.082 17644-17670/ir.puzzle.douz D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so 2019-09-04 22:44:38.092 17644-17670/ir.puzzle.douz D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so 2019-09-04 22:44:38.129 17644-17670/ir.puzzle.douz D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so 2019-09-04 22:44:38.272 17644-17644/ir.puzzle.douz W/ir.puzzle.douz: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed) 2019-09-04 22:44:38.273 17644-17644/ir.puzzle.douz W/ir.puzzle.douz: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed) 2019-09-04 22:44:38.412 17644-17644/ir.puzzle.douz D/AndroidRuntime: Shutting down VM 2019-09-04 22:44:38.416 17644-17644/ir.puzzle.douz E/AndroidRuntime: FATAL EXCEPTION: main
Process: ir.puzzle.douz, PID: 17644
java.lang.RuntimeException: Unable to start activity ComponentInfo{ir.puzzle.douz/ir.puzzle.douz.view.LoginActivity}: java.lang.IndexOutOfBoundsException: index=0 out of bounds (limit=0, nb=4)
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.IndexOutOfBoundsException: index=0 out of bounds (limit=0, nb=4)
at java.nio.Buffer.checkIndex(Buffer.java:564)
at java.nio.DirectByteBuffer.getInt(DirectByteBuffer.java:570)
at android.graphics.fonts.FontFileUtil.analyzeStyle(FontFileUtil.java:94)
at android.graphics.fonts.Font$Builder.build(Font.java:364)
at android.graphics.Typeface$Builder.build(Typeface.java:596)
at android.graphics.Typeface.createFromAsset(Typeface.java:960)
at ir.puzzle.douz.view.LoginActivity.onCreate(LoginActivity.java:35)
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)
i can't figure out where's the problem of this code that always gets force-closed! can you tell me which part of code is problematic? and how can i fix it?

Related

Another Activity starts on its own

Recently I noticed that my app is not showing the materialAlertDialog. When I checked further. This is what is happening:
When a user signs up then I show a custom alert dialog containing a progress bar but as soon as the sign up process is complete another Alert Dialog is supposed to appear but instead of that the MainActivity starts over it. And i have to press the back button in order to get back to the SignUpActivity and then there is my Dialog being shown.
Also many times before I could press the back button the app would have already crashed.
Here is what I received on debugging:
E/WindowManager: android.view.WindowLeaked: Activity com.infinitystudios.quinovi.RegisterActivity has leaked window DecorView#fb7a1bb[RegisterActivity] that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:1049)
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:1023)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:450)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:114)
at android.app.Dialog.show(Dialog.java:505)
at com.infinitystudios.quinovi.RegisterActivity.StartAccountCreation(RegisterActivity.java:152)
at com.infinitystudios.quinovi.RegisterActivity.ValidateData(RegisterActivity.java:95)
at com.infinitystudios.quinovi.RegisterActivity.lambda$onCreate$0$RegisterActivity(RegisterActivity.java:45)
at com.infinitystudios.quinovi.-$$Lambda$RegisterActivity$9UObv7lMX3EKvsR9ZGkbBlnv9b0.onClick(Unknown Source:2)
at android.view.View.performClick(View.java:8160)
at android.widget.TextView.performClick(TextView.java:16222)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View.performClickInternal(View.java:8137)
at android.view.View.access$3700(View.java:888)
at android.view.View$PerformClick.run(View.java:30236)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:246)
at android.app.ActivityThread.main(ActivityThread.java:8506)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1139)
And:
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.infinitystudios.quinovi, PID: 12215
java.lang.IllegalArgumentException: View=DecorView#fb7a1bb[RegisterActivity] not attached to window manager
at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:604)
at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:508)
at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:146)
at android.app.Dialog.dismissDialog(Dialog.java:676)
at android.app.Dialog.dismiss(Dialog.java:658)
at androidx.appcompat.app.AppCompatDialog.dismiss(AppCompatDialog.java:140)
at com.infinitystudios.quinovi.RegisterActivity.lambda$null$2$RegisterActivity(RegisterActivity.java:171)
at com.infinitystudios.quinovi.-$$Lambda$RegisterActivity$NZHJI1-9H-gfMUEP6ocbSxiYFnk.onSuccess(Unknown Source:6)
at com.google.android.gms.tasks.zzn.run(Unknown Source:4)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:246)
at android.app.ActivityThread.main(ActivityThread.java:8506)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1139)
I did see try the solution which said to show the dialog only if the Activity is not finishing but:
(1) in that case the dialog never appears and it is important to show the dialog
(2) the MainActivity still pops into the screen
UPDATE:
My SignUp/RegisterActivity
public class RegisterActivity extends AppCompatActivity {
private FirebaseAuth auth;
private FirebaseFirestore firestore;
private Button signUpBtn;
private TextView signInTxt;
private TextInputLayout passTil, cpassTil;
private TextInputEditText nameTxtbx, emailTxtbx, passTxtbx, cpassTxtbx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
init();
signUpBtn.setOnClickListener(v -> ValidateData());
signInTxt.setOnClickListener(v -> {
startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
finish();
});
}
private void init() {
auth = FirebaseAuth.getInstance();
firestore = FirebaseFirestore.getInstance();
signUpBtn = findViewById(R.id.ra_signup_btn);
signInTxt = findViewById(R.id.ra_signin_txt);
passTil = findViewById(R.id.ra_password_til);
cpassTil = findViewById(R.id.ra_cpassword_til);
nameTxtbx = findViewById(R.id.ra_name_tiet);
emailTxtbx = findViewById(R.id.ra_email_tiet);
passTxtbx = findViewById(R.id.ra_password_tiet);
cpassTxtbx = findViewById(R.id.ra_cpassword_tiet);
}
private void ValidateData() {
HideSoftKeyboard();
String name, email, pass, cpass;
name = Objects.requireNonNull(nameTxtbx.getText()).toString().trim();
email = Objects.requireNonNull(emailTxtbx.getText()).toString().trim();
pass = Objects.requireNonNull(passTxtbx.getText()).toString().trim();
cpass = Objects.requireNonNull(cpassTxtbx.getText()).toString().trim();
if (!name.isEmpty()) {
if (!email.isEmpty()) {
if (email.contains("#") && email.contains(".")) {
if (!pass.isEmpty()) {
if (pass.length() >= 6) {
if (cpass.equals(pass)) {
StartAccountCreation(name, email, pass);
} else {
cpassTil.setError(getResources().getString(R.string.cpass_not_match));
cpassTxtbx.requestFocus();
}
} else {
passTil.setError(getResources().getString(R.string.password_greater));
passTxtbx.requestFocus();
}
} else {
passTil.setError(getResources().getString(R.string.field_required));
passTxtbx.requestFocus();
}
} else {
emailTxtbx.setError(getResources().getString(R.string.valid_email));
emailTxtbx.requestFocus();
}
} else {
emailTxtbx.setError(getResources().getString(R.string.field_required));
emailTxtbx.requestFocus();
}
} else {
nameTxtbx.setError(getResources().getString(R.string.field_required));
nameTxtbx.requestFocus();
}
}
private void StartAccountCreation(String name, String email, String pass) {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this, R.style.CustomAlertDialogTheme);
LayoutInflater inflater = getLayoutInflater();
#SuppressLint("InflateParams")
View dialogView = inflater.inflate(R.layout.primary_progress_dialog, null);
builder.setView(dialogView);
builder.setCancelable(false);
AlertDialog dialog = builder.create();
dialog.show();
HandleOrientation(true);
auth.createUserWithEmailAndPassword(email, pass)
.addOnSuccessListener(authResult ->
Objects.requireNonNull(auth.getCurrentUser()).sendEmailVerification()
.addOnSuccessListener(aVoid -> {
String CAID = auth.getCurrentUser().getUid();
HashMap<String, Object> accountMap = new HashMap<>();
accountMap.put("date", FieldValue.serverTimestamp());
accountMap.put("name", name);
firestore.collection("Accounts").document(CAID).set(accountMap)
.addOnSuccessListener(aVoid1 -> {
HandleOrientation(false);
dialog.dismiss();
CreateDialog();
})
.addOnFailureListener(e -> {
HandleOrientation(false);
dialog.dismiss();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
});
})
.addOnFailureListener(e -> {
HandleOrientation(false);
dialog.dismiss();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}))
.addOnFailureListener(e -> {
HandleOrientation(false);
dialog.dismiss();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
});
}
private void HideSoftKeyboard() {
RegisterActivity activity = RegisterActivity.this;
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
View view = activity.getCurrentFocus();
if (view == null)
view = new View(activity);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
private void HandleOrientation(boolean intention) {
RegisterActivity activity = RegisterActivity.this;
if (intention) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
}
private void CreateDialog() {
new MaterialAlertDialogBuilder(RegisterActivity.this)
.setTitle(getResources().getString(R.string.verification_sent))
.setMessage(getResources().getString(R.string.verification_sent_msg))
.setPositiveButton(getResources().getString(R.string.ok), (dialog, which) -> dialog.dismiss())
.show();
}
Update 2:
I found out that this only happens when using the app in portrait mode. I always see the dialog appear in landscape but in portrait mode it won't show up, then it would start the main activity and crash immediately.
You have not added the dialog on Sign up activity. Also the context to dialog should be by activity name otherwise this exception occurs
E/WindowManager: android.view.WindowLeaked:
Please share your activity code for further help

Keep media player working in background with screen off

I've an streaming audio (from a server) with Media Player. It works when I turn off the screen and the system goes to sleep mode but after some minutes the phone stop music. This doesn't happen when the cellphone is connected to power (USB cable). So, the system must crash the app due to a power management or a memory management.
Service class:
public class MyService extends Service {
PowerManager powerManager;
PowerManager.WakeLock wakeLock;
WifiManager.WifiLock wifiLock;
private MediaPlayer mediaPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Lock");
wifiLock = ((WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE)).createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");
wakeLock.acquire();
wifiLock.acquire();
mediaPlayer = new MediaPlayer();
mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource("http://mediacontrol.jargon.com.ar:8168/;");
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
return START_REDELIVER_INTENT;
}
#Override
public void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
mediaPlayer.release();
wakeLock.release();
wifiLock.release();
}
}
And this is the class that implements the service:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
setRetainInstance(true); // con esto retenemos los valores pero se elimina el view
View view = inflater.inflate(R.layout.fragment_blank_fragment4, container, false);
play = (ImageButton) view.findViewById(R.id.imageButton);
imagen=(ImageView) view.findViewById((R.id.imageView));
if(comenzar) {
play.setImageResource(R.drawable.play);
}
else {
play.setImageResource(R.drawable.stop);
}
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (comenzar) {
if(isConnectedMobile(getActivity())||
isConnectedWifi(getActivity())) {
play.setImageResource(R.drawable.stop);
getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getActivity().startService(new Intent(getActivity(), MyService.class));
showNotification();
comenzar = false;
release=true;
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("No hay conexión a internet");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
} else {
play.setImageResource(R.drawable.play);
getActivity().stopService(new Intent(getActivity(), MyService.class));
comenzar = true;
NotificationManager mNotificationManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
//getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
release=false;
}
}
});
return view;
}
I also set this permission in the manifest
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
I can't debug it so well because the problem happens when the mobile is not connected but when the audio crash, then I connect it and it runs a one second more when I turn on the screen and after it stops.
I get this:
09-24 18:14:21.480 8539-8539/jaodev.utnfrp W/MediaPlayer: mediaplayer went away with unhandled events
09-24 18:14:24.070 8539-8551/jaodev.utnfrp I/MediaHTTPConnection: proxyName: 0.0.0.0 0
09-24 18:14:24.970 8539-8539/jaodev.utnfrp D/MediaPlayer: setSubtitleAnchor in MediaPlayer
09-24 18:17:57.413 8539-8552/jaodev.utnfrp I/MediaHTTPConnection: proxyName: 0.0.0.0 0
09-24 18:18:30.437 8539-8551/jaodev.utnfrp I/MediaHTTPConnection: proxyName: 0.0.0.0 0
09-24 18:18:34.187 8539-9040/jaodev.utnfrp W/MediaPlayer: info/warning (703, 0)
09-24 18:18:34.188 8539-9040/jaodev.utnfrp W/MediaPlayer: info/warning (701, 0)
09-24 18:19:03.462 8539-9040/jaodev.utnfrp I/MediaHTTPConnection: proxyName: 0.0.0.0 0
09-24 18:19:03.941 8539-9040/jaodev.utnfrp W/MediaHTTPConnection: readAt 1507328 / 32768 => java.net.ProtocolException
09-24 18:19:04.202 8539-8551/jaodev.utnfrp W/MediaPlayer: info/warning (703, 0)
09-24 18:21:51.201 8539-8544/jaodev.utnfrp I/art: Do partial code cache collection, code=40KB, data=62KB
09-24 18:21:51.203 8539-8544/jaodev.utnfrp I/art: After code cache collection, code=40KB, data=62KB
Increasing code cache capacity to 256KB

App crashes when Progress Dialog is open and user changes orientation [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
My application has a Progress Dialog for login process and when the orientation is changed while dialog box is open, app crashes.This all works fine, except when screen orientation changes while the dialog is up. At this point the app crashes. I am figuring out this issue from the last 3 nights but not able to get it, please help.
My fragment:
public class Example extends Fragment {
private static final String TAG = "LoginActivity";
private static final int REQUEST_SIGNUP = 0;
Unbinder unbinder;
#BindView(R.id.input_email) EditText _emailText;
#BindView(R.id.input_password) EditText _passwordText;
#BindView(R.id.btn_login) Button _loginButton;
#BindView(R.id.link_signup) TextView _signupLink;
#Override
public void onDestroyView() {
super.onDestroyView();
// unbind the view to free some memory
unbinder.unbind();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.Example, container, false);
unbinder=ButterKnife.bind(this,rootView);
_loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
}
});
_signupLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Intent create= new Intent(getActivity(),NewAccount.class);
startActivity(create);
}
});
return rootView;
}
public void login() {
Log.d(TAG, "Login");
if (!validate()) {
onLoginFailed();
return;
}
_loginButton.setEnabled(false);
final ProgressDialog progressDialog = new ProgressDialog(getActivity(),
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Authenticating...");
progressDialog.show();
//new YourAsynTask(getActivity()).execute();
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
// TODO: Implement your own authentication logic here.
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
// On complete call either onLoginSuccess or onLoginFailed
onLoginSuccess();
// onLoginFailed();
progressDialog.dismiss();
}
}, 3000);
}
#Override
public void onPause() {
Log.e("DEBUG", "OnPause of loginFragment1");
super.onPause();
}
public void onLoginSuccess() {
_loginButton.setEnabled(true);
Intent i=new Intent(getActivity(),SuccessLogin.class);
startActivity(i);
}
public void onLoginFailed() {
Toast.makeText(getActivity(), "Login failed", Toast.LENGTH_LONG).show();
_loginButton.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
_emailText.setError("enter a valid email address");
valid = false;
} else {
_emailText.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
_passwordText.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
_passwordText.setError(null);
}
return valid;
}
Logcat output:
11-16 19:20:10.955 4022-4022/com.example.a1332931.login_application E/WindowManager: android.view.WindowLeaked: Activity com.example.a1332931.login_application.TabActivity has leaked window com.android.internal.policy.PhoneWindow$DecorView{42b6135 V.E...... R......D 0,0-683,232} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:375)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:299)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.Dialog.show(Dialog.java:319)
at com.example.a1332931.login_application.Example.login(Example.java:156)
at com.example.a1332931.login_application.Example$1.onClick(Example.java:67)
at android.view.View.performClick(View.java:5201)
at android.view.View$PerformClick.run(View.java:21163)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
11-16 19:20:10.957 4022-4095/com.example.a1332931.login_application E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb8aa6c60
11-16 19:20:12.512 4022-4022/com.example.a1332931.login_application E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.a1332931.login_application, PID: 4022
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setEnabled(boolean)' on a null object reference
at com.example.a1332931.login_application.Example.onLoginSuccess(Example.java:200)
at com.example.a1332931.login_application.Example$3.run(Example.java:168)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Add this configuration change in your Android manifest activity:
<activity
android:name="YourActivity"
android:configChanges="orientation|keyboardHidden|screenSize"/>

Adding OnClickListener makes app crash

I'm working on a term project and I'm new to java and android app development. I have experience in other programming languages, though. I'm trying to reverse engineer an app to make it able to connect and send data via bluetooth. I want to make a list with all the available bluetooth devices, a button to turn on/off bluetooth, one for making the phone discoverable for other devices and another to search for unpaired devices. But every time I add an OnClickListener to the onCreate method, the app crashes before it opens. Could anyone help me out?
The source code for the app I am trying to modify can be found here:
https://github.com/pazaan/600SeriesAndroidUploader
Here is the part that seems to makes it crash:
lvNewDevices.setOnItemClickListener(MainActivity.this);
btnONOFF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: enabling/disabling bluetooth.");
enableDisableBT();
}
});
btnStartConnection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startConnection();
}
});
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
byte[] bytes = etSend.getText().toString().getBytes(Charset.defaultCharset());
mBluetoothConnection.write(bytes);
}
});
And here is all of OnCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate called");
super.onCreate(savedInstanceState);
Button btnONOFF = (Button) findViewById(R.id.btnONOFF);
btnEnableDisable_Discoverable = (Button) findViewById(R.id.btnDiscoverable_on_off);
lvNewDevices = (ListView) findViewById(R.id.lvNewDevices);
mBTDevices = new ArrayList<>();
btnStartConnection = (Button) findViewById(R.id.btnStartConnection);
//Broadcasts when bond state changes (ie:pairing)
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mBroadcastReceiver4, filter);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//FUCKUP:
lvNewDevices.setOnItemClickListener(MainActivity.this);
btnONOFF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: enabling/disabling bluetooth.");
enableDisableBT();
}
});
btnStartConnection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startConnection();
}
});
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
byte[] bytes = etSend.getText().toString().getBytes(Charset.defaultCharset());
mBluetoothConnection.write(bytes);
}
});
mRealm = Realm.getDefaultInstance();
RealmResults<PumpStatusEvent> data = mRealm.where(PumpStatusEvent.class)
.findAllSorted("eventDate", Sort.DESCENDING);
if (data.size() > 0)
dataStore.setLastPumpStatus(data.first());
setContentView(R.layout.activity_main);
PreferenceManager.getDefaultSharedPreferences(getBaseContext()).registerOnSharedPreferenceChangeListener(this);
prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
if (!prefs.getBoolean(getString(R.string.preference_eula_accepted), false)) {
stopCgmService();
}
// setup preferences
configurationStore.setPollInterval(Long.parseLong(prefs.getString("pollInterval", Long.toString(MedtronicCnlIntentService.POLL_PERIOD_MS))));
configurationStore.setLowBatteryPollInterval(Long.parseLong(prefs.getString("lowBatPollInterval", Long.toString(MedtronicCnlIntentService.LOW_BATTERY_POLL_PERIOD_MS))));
configurationStore.setReducePollOnPumpAway(prefs.getBoolean("doublePollOnPumpAway", false));
chartZoom = Integer.parseInt(prefs.getString("chartZoom", "3"));
configurationStore.setMmolxl(prefs.getBoolean("mmolxl", false));
configurationStore.setMmolxlDecimals(prefs.getBoolean("mmolDecimals", false));
// Disable battery optimization to avoid missing values on 6.0+
// taken from https://github.com/NightscoutFoundation/xDrip/blob/master/app/src/main/java/com/eveningoutpost/dexdrip/Home.java#L277L298
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
final String packageName = getPackageName();
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (!pm.isIgnoringBatteryOptimizations(packageName)) {
Log.d(TAG, "Requesting ignore battery optimization");
try {
// ignoring battery optimizations required for constant connection
// to peripheral device - eg CGM transmitter.
final Intent intent = new Intent();
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + packageName));
startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.d(TAG, "Device does not appear to support battery optimization whitelisting!");
}
}
}
LocalBroadcastManager.getInstance(this).registerReceiver(
statusMessageReceiver,
new IntentFilter(MedtronicCnlIntentService.Constants.ACTION_STATUS_MESSAGE));
LocalBroadcastManager.getInstance(this).registerReceiver(
new UpdatePumpReceiver(),
new IntentFilter(MedtronicCnlIntentService.Constants.ACTION_UPDATE_PUMP));
mEnableCgmService = Eula.show(this, prefs);
IntentFilter batteryIntentFilter = new IntentFilter();
batteryIntentFilter.addAction(Intent.ACTION_BATTERY_LOW);
batteryIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
batteryIntentFilter.addAction(Intent.ACTION_BATTERY_OKAY);
registerReceiver(batteryReceiver, batteryIntentFilter);
IntentFilter usbIntentFilter = new IntentFilter();
usbIntentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
usbIntentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
usbIntentFilter.addAction(MedtronicCnlIntentService.Constants.ACTION_USB_PERMISSION);
registerReceiver(usbReceiver, usbIntentFilter);
LocalBroadcastManager.getInstance(this).registerReceiver(
usbReceiver,
new IntentFilter(MedtronicCnlIntentService.Constants.ACTION_NO_USB_PERMISSION));
LocalBroadcastManager.getInstance(this).registerReceiver(
usbReceiver,
new IntentFilter(MedtronicCnlIntentService.Constants.ACTION_USB_REGISTER));
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setElevation(0);
getSupportActionBar().setTitle("Nightscout");
}
final PrimaryDrawerItem itemSettings = new PrimaryDrawerItem()
.withName("Settings")
.withIcon(GoogleMaterial.Icon.gmd_settings)
.withSelectable(false);
final PrimaryDrawerItem itemRegisterUsb = new PrimaryDrawerItem()
.withName("Registered devices")
.withIcon(GoogleMaterial.Icon.gmd_usb)
.withSelectable(false);
final PrimaryDrawerItem itemStopCollecting = new PrimaryDrawerItem()
.withName("Stop collecting data")
.withIcon(GoogleMaterial.Icon.gmd_power_settings_new)
.withSelectable(false);
final PrimaryDrawerItem itemGetNow = new PrimaryDrawerItem()
.withName("Read data now")
.withIcon(GoogleMaterial.Icon.gmd_refresh)
.withSelectable(false);
final PrimaryDrawerItem itemUpdateProfile = new PrimaryDrawerItem()
.withName("Update pump profile")
.withIcon(GoogleMaterial.Icon.gmd_insert_chart)
.withSelectable(false);
final PrimaryDrawerItem itemClearLog = new PrimaryDrawerItem()
.withName("Clear log")
.withIcon(GoogleMaterial.Icon.gmd_clear_all)
.withSelectable(false);
final PrimaryDrawerItem itemCheckForUpdate = new PrimaryDrawerItem()
.withName("Check for App update")
.withIcon(GoogleMaterial.Icon.gmd_update)
.withSelectable(false);
assert toolbar != null;
new DrawerBuilder()
.withActivity(this)
.withAccountHeader(new AccountHeaderBuilder()
.withActivity(this)
.withHeaderBackground(R.drawable.drawer_header)
.build()
)
.withTranslucentStatusBar(false)
.withToolbar(toolbar)
.withActionBarDrawerToggle(true)
.withSelectedItem(-1)
.addDrawerItems(
itemSettings,
//itemUpdateProfile, // TODO - re-add when we to add Basal Profile Upload
itemRegisterUsb,
itemCheckForUpdate,
itemClearLog,
itemGetNow,
itemStopCollecting
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
if (drawerItem.equals(itemSettings)) {
openSettings();
} else if (drawerItem.equals(itemRegisterUsb)) {
openUsbRegistration();
} else if (drawerItem.equals(itemStopCollecting)) {
mEnableCgmService = false;
stopCgmService();
finish();
} else if (drawerItem.equals(itemGetNow)) {
// It was triggered by user so start reading of data now and not based on last poll.
sendStatus("Requesting poll now...");
startCgmService(System.currentTimeMillis() + 1000);
} else if (drawerItem.equals(itemClearLog)) {
clearLogText();
} else if (drawerItem.equals(itemCheckForUpdate)) {
checkForUpdateNow();
}
return false;
}
})
.build();
mTextViewLog = (TextView) findViewById(R.id.textview_log);
mScrollView = (ScrollView) findViewById(R.id.scrollView);
mScrollView.setSmoothScrollingEnabled(true);
mChart = (GraphView) findViewById(R.id.chart);
// disable scrolling at the moment
mChart.getViewport().setScalable(false);
mChart.getViewport().setScrollable(false);
mChart.getViewport().setYAxisBoundsManual(true);
mChart.getViewport().setMinY(80);
mChart.getViewport().setMaxY(120);
mChart.getViewport().setXAxisBoundsManual(true);
final long now = System.currentTimeMillis(),
left = now - chartZoom * 60 * 60 * 1000;
mChart.getViewport().setMaxX(now);
mChart.getViewport().setMinX(left);
// due to bug in GraphView v4.2.1 using setNumHorizontalLabels reverted to using v4.0.1 and setOnXAxisBoundsChangedListener is n/a in this version
/*
mChart.getViewport().setOnXAxisBoundsChangedListener(new Viewport.OnXAxisBoundsChangedListener() {
#Override
public void onXAxisBoundsChanged(double minX, double maxX, Reason reason) {
double rightX = mChart.getSeries().get(0).getHighestValueX();
hasZoomedChart = (rightX != maxX || rightX - chartZoom * 60 * 60 * 1000 != minX);
}
});
*/
mChart.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if (!mChart.getSeries().isEmpty() && !mChart.getSeries().get(0).isEmpty()) {
double rightX = mChart.getSeries().get(0).getHighestValueX();
mChart.getViewport().setMaxX(rightX);
mChart.getViewport().setMinX(rightX - chartZoom * 60 * 60 * 1000);
}
hasZoomedChart = false;
return true;
}
});
mChart.getGridLabelRenderer().setNumHorizontalLabels(6);
// due to bug in GraphView v4.2.1 using setNumHorizontalLabels reverted to using v4.0.1 and setHumanRounding is n/a in this version
// mChart.getGridLabelRenderer().setHumanRounding(false);
mChart.getGridLabelRenderer().setLabelFormatter(
new DefaultLabelFormatter() {
DateFormat mFormat = new SimpleDateFormat("HH:mm", Locale.US); // 24 hour format forced to fix label overlap
#Override
public String formatLabel(double value, boolean isValueX) {
if (isValueX) {
return mFormat.format(new Date((long) value));
} else {
return MainActivity.strFormatSGV(value);
}
}
}
);
}
Here is the logcat output:
09-26 12:38:19.826 6324-6324/? I/art: Late-enabling -Xcheck:jni
09-26 12:38:20.157 6324-6324/info.nightscout.android E/Fabric: Failure onPreExecute()
java.lang.IllegalArgumentException: Fabric could not be initialized, API key missing from AndroidManifest.xml. Add the following tag to your Application element
<meta-data android:name="io.fabric.ApiKey" android:value="YOUR_API_KEY"/>
at io.fabric.sdk.android.services.common.ApiKey.logErrorOrThrowException(ApiKey.java:110)
at io.fabric.sdk.android.services.common.ApiKey.getValue(ApiKey.java:61)
at com.crashlytics.android.core.CrashlyticsCore.onPreExecute(CrashlyticsCore.java:219)
at com.crashlytics.android.core.CrashlyticsCore.onPreExecute(CrashlyticsCore.java:207)
at io.fabric.sdk.android.InitializationTask.onPreExecute(InitializationTask.java:44)
at io.fabric.sdk.android.services.concurrency.AsyncTask.executeOnExecutor(AsyncTask.java:611)
at io.fabric.sdk.android.services.concurrency.PriorityAsyncTask.executeOnExecutor(PriorityAsyncTask.java:43)
at io.fabric.sdk.android.Kit.initialize(Kit.java:69)
at io.fabric.sdk.android.Fabric.initializeKits(Fabric.java:440)
at io.fabric.sdk.android.Fabric.init(Fabric.java:384)
at io.fabric.sdk.android.Fabric.setFabric(Fabric.java:342)
at io.fabric.sdk.android.Fabric.with(Fabric.java:313)
at info.nightscout.android.UploaderApplication.onCreate(UploaderApplication.java:32)
at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1046)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5402)
at android.app.ActivityThread.-wrap2(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1541)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
09-26 12:38:20.202 6324-6379/info.nightscout.android E/Fabric: Error dealing with settings
java.lang.IllegalArgumentException: Fabric could not be initialized, API key missing from AndroidManifest.xml. Add the following tag to your Application element
<meta-data android:name="io.fabric.ApiKey" android:value="YOUR_API_KEY"/>
at io.fabric.sdk.android.services.common.ApiKey.logErrorOrThrowException(ApiKey.java:110)
at io.fabric.sdk.android.services.common.ApiKey.getValue(ApiKey.java:61)
at io.fabric.sdk.android.services.settings.Settings.initialize(Settings.java:78)
at io.fabric.sdk.android.Onboarding.retrieveSettingsData(Onboarding.java:124)
at io.fabric.sdk.android.Onboarding.doInBackground(Onboarding.java:99)
at io.fabric.sdk.android.Onboarding.doInBackground(Onboarding.java:45)
at io.fabric.sdk.android.InitializationTask.doInBackground(InitializationTask.java:63)
at io.fabric.sdk.android.InitializationTask.doInBackground(InitializationTask.java:28)
at io.fabric.sdk.android.services.concurrency.AsyncTask$2.call(AsyncTask.java:311)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
09-26 12:38:20.252 6324-6324/info.nightscout.android W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
09-26 12:38:20.349 6324-6324/info.nightscout.android I/MainActivity: onCreate called
09-26 12:38:20.652 6324-6324/info.nightscout.android D/AndroidRuntime: Shutting down VM
09-26 12:38:20.652 6324-6324/info.nightscout.android E/AndroidRuntime: FATAL EXCEPTION: main
Process: info.nightscout.android, PID: 6324
java.lang.RuntimeException: Unable to start activity ComponentInfo{info.nightscout.android/info.nightscout.android.medtronic.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at info.nightscout.android.medtronic.MainActivity.onCreate(MainActivity.java:349)
at android.app.Activity.performCreate(Activity.java:6672)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6123) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) 
Move the code setContentView(R.layout.activity_main);
under the super.onCreate(savedInstanceState);
you are mapping the views before adding layout in your code.
your onCreate() should be
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate called");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Do mapping all views
Your Error log is showing you your solution. The project is using Fabric API. So naturally you need to add Fabric API key to your project.
Do as suggested in Error log. Add following line in Android Manifest.
<meta-data android:name="io.fabric.ApiKey" android:value="YOUR_API_KEY"/>
For your API key, make a project using Fabric account and get your API key.

Why does this code seem not to find the MainActivity?

We are writing an android based Application that tracks several Mobilephone sensors now I tried compiling the code when suddenly this happend
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.max.pswi, PID: 14291
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.max.pswi/com.example.max.pswi.MainActivity}:
java.lang.ClassNotFoundException: Didn't find class "com.example.max.pswi.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.max.pswi-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2555)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.max.pswi.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.max.pswi-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
at android.app.Instrumentation.newActivity(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2545)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767) 
at android.app.ActivityThread.access$900(ActivityThread.java:177) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:5951) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183) 
Suppressed: java.lang.ClassNotFoundException: com.example.max.pswi.MainActivity
at java.lang.Class.classForName(Native Method)
at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
... 13 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
I have no Idea why this error occurs
Im programming on Android Studio
Heres the MainActivity-Code that creates the error:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
int currentVersionCode = 0;
try {
currentVersionCode = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionCode;
} catch (PackageManager.NameNotFoundException e1) {
e1.printStackTrace();
}
final ImageButton export = (ImageButton) findViewById(R.id.export);
final ImageButton clear = (ImageButton) findViewById(R.id.clear);
final ToggleButton toggle = (ToggleButton) findViewById(R.id.anaus);
final ImageButton settingsBtn = (ImageButton) findViewById(R.id.settings);
final ImageButton aktualisieren = (ImageButton) findViewById(R.id.aktualisieren);
final ListView liste = (ListView)findViewById(R.id.infos);
if (CheckIfServiceIsRunning())
toggle.setChecked(true);
Boolean status = CheckIfServiceIsRunning();
aktualisieren.setVisibility(View.VISIBLE);
export.setVisibility(View.VISIBLE);
toggle.setVisibility(View.VISIBLE);
settingsBtn.setVisibility(View.VISIBLE);
/* clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SensorManager.getInstance().clearValues(SensorManager.getInstance().getContext());
}
});
export.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SensorManager.getInstance().exportValues(SensorManager.getInstance().getContext());
}
});
settingsBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent);
}
});
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
Boolean status = CheckIfServiceIsRunning();
ComponentName cn = new ComponentName(getApplicationContext(), NLService.class);
String flat = Settings.Secure.getString(getApplicationContext().getContentResolver(), "enabled_notification_listeners");
final boolean enabled = (flat != null && flat.contains(cn.flattenToString()));
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled
if (!enabled) {
final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setCancelable(false);
alertDialog.setTitle("Notificationlistener aktivieren");
alertDialog.setMessage("Bitte aktivieren sie den Notificationlistener für die App PSWI");
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Aktivieren", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.cancel();
Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent);
Intent i = new Intent(getApplicationContext(), MainService.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startService(i);
status = true;
}
});
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "zurueck", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.cancel();
}
});
alertDialog.show();
} else {
Intent i = new Intent(getApplicationContext(), MainService.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startService(i);
status = true;
}
} else {
// The toggle is disabled
Intent i = new Intent(getApplicationContext(), MainService.class);
getApplicationContext().stopService(i);
status = false;
}
}
});
// SensorManager.getInstance().populateListView(liste);
settings = PreferenceManager.getDefaultSharedPreferences(this);
if (settings.getBoolean("first_start", true)) {
// set initial version code, set first_start true and create ID
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("first_start", false);
editor.putBoolean("SMSSensor:ObserverStarted", false);
editor.putString("CallSensor:lastIntent", null);
editor.putBoolean("serviceStarted", false);
editor.putString("version", "" + currentVersionCode);
editor.putString("ID", ""
+ ((TelephonyManager) getApplicationContext()
.getSystemService(TELEPHONY_SERVICE))
.getDeviceId().hashCode());
editor.apply();
}
// getLoaderManager().initLoader(0, null, (android.app.LoaderManager.LoaderCallbacks<Cursor>) this);
*/
}
I would be glad if someone could take a look at this I'm getting desperate
Have you declared this MainActivity in AndroidManifest file?
Check AndroidManifest.xml
You should see your activity within the application tag like so:
<activity android:name="com.example.max.pswi.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

Categories

Resources