I want to show the floating layout on top of the screen when service Alarm or Call happened. Normally, when the app opens or it is in the background (before swiping it out) it shows and works well. even if I kill the app it still shows (kill = swipe the app)and it is still working. but, if the app is killed and not opened it tries to show (from service of alarm for example) it crashes and I cant even see the crash log in the android studio after terminating the app.
how can I fix that or find the issue?
my code Alarm BroadCast where it called: (the alarm broadcast called as needed)
public class BroadcastManager extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent intent = new Intent(context,FloatingWindow.class);
startService(intent);
}
my floating view code :
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.greenbook.greenlids.MainActivity;
import com.example.greenbook.greenlids.R;
public class FloatingWindow extends Service {
private WindowManager windowManager;
private LinearLayout layout;
private TextView txt;
private Button bttn1 , exitBttn;
private Context context;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#SuppressLint("ClickableViewAccessibility")
#Override
public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
layout = new LinearLayout(this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
layout.setBackgroundColor(Color.argb(255,0,0,255));
layout.setLayoutParams(layoutParams);
final WindowManager.LayoutParams windowParams;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
windowParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_PHONE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);
windowParams.x = 0;
windowParams.y = 0;
windowParams.gravity = Gravity.CENTER;
}else{
windowParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);
windowParams.x = 0;
windowParams.y = 0;
windowParams.gravity = Gravity.CENTER;
}
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
if (layoutInflater != null) {
layout = (LinearLayout) layoutInflater.inflate(R.layout.linear_layout_floating_window, null);
}
layout.setBackgroundColor(Color.argb(255,240,240,255));
bttn1 = layout.findViewById(R.id.LLbutton);
exitBttn = layout.findViewById(R.id.exitBttn);
txt = layout.findViewById(R.id.noteTxt);
txt.setTextSize(18);
txt.setText("Natan");
exitBttn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
windowManager.removeView(layout);
stopSelf();
}
});
bttn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean handler = new Handler().postDelayed(new Runnable() {
#Override
public void run() {
txt.setText("Natan The King");
}
}, 1000*5);
}
});
windowManager.addView(layout,windowParams);
layout.setOnTouchListener(new View.OnTouchListener() {
private WindowManager.LayoutParams updateParam = windowParams;
int x , y;
float touchedX , touchedY;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
x = updateParam.x;
y = updateParam.y;
touchedX = event.getRawX();
touchedY = event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
updateParam.x = (int) (x+event.getRawX() - touchedX);
updateParam.y = (int) (y+event.getRawY() - touchedY);
windowManager.updateViewLayout(layout,updateParam);
break;
}
return false;
}
});
}
}
logcat updated:
06-18 11:59:00.263 6722-6722/? E/Zygote: isWhitelistProcess - Process is Whitelisted
06-18 11:59:00.264 6722-6722/? E/libpersona: scanKnoxPersonas
Couldn't open the File - /data/system/users/0/personalist.xml - No such file or directory
06-18 11:59:00.268 6722-6722/? W/SELinux: SELinux selinux_android_compute_policy_index : Policy Index[2], Con:u:r:zygote:s0 RAM:SEPF_SM-G935F_8.0.0_0007, [-1 -1 -1 -1 0 1]
06-18 11:59:00.269 6722-6722/? I/SELinux: SELinux: seapp_context_lookup: seinfo=untrusted, level=s0:c512,c768, pkgname=com.example.greenbook.greenlids
06-18 11:59:00.275 6722-6722/? I/zygote64: Late-enabling -Xcheck:jni
06-18 11:59:00.341 6722-6722/? D/TimaKeyStoreProvider: TimaKeyStore is not enabled: cannot add TimaSignature Service and generateKeyPair Service
06-18 11:59:00.341 6722-6722/? D/ActivityThread: Added TimaKeyStore provider
06-18 11:59:00.422 6722-6722/com.example.greenbook.greenlids I/zygote64: no shared libraies, dex_files: 1
06-18 11:59:00.723 6722-6722/com.example.greenbook.greenlids I/InstantRun: starting instant run server: is main process
06-18 11:59:00.750 6722-6722/com.example.greenbook.greenlids D/AndroidRuntime: Shutting down VM
--------- beginning of crash
06-18 11:59:00.755 6722-6722/com.example.greenbook.greenlids E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.greenbook.greenlids, PID: 6722
java.lang.RuntimeException: Unable to start receiver com.example.greenbook.greenlids.models.BroadcastManager: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=com.example.greenbook.greenlids/.floating_window.FloatingWindow }: app is in background uid UidRecord{1651455 u0a451 RCVR idle procs:1 seq(0,0,0)}
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3399)
at android.app.ActivityThread.-wrap18(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1780)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Caused by: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=com.example.greenbook.greenlids/.floating_window.FloatingWindow }: app is in background uid UidRecord{1651455 u0a451 RCVR idle procs:1 seq(0,0,0)}
at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1538)
at android.app.ContextImpl.startService(ContextImpl.java:1484)
at android.content.ContextWrapper.startService(ContextWrapper.java:663)
at android.content.ContextWrapper.startService(ContextWrapper.java:663)
at com.example.greenbook.greenlids.models.BroadcastManager.onReceive(BroadcastManager.java:40)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3392)
at android.app.ActivityThread.-wrap18(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1780)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Under certain circumstances, a background app is placed on a temporary whitelist for several minutes. While an app is on the whitelist, it can launch services without limitation, and its background services are permitted to run. An app is placed on the whitelist when it handles a task that's visible to the user, such as:
Handling a high-priority Firebase Cloud Messaging (FCM) message.
Receiving a broadcast, such as an SMS/MMS message.
Executing a PendingIntent from a notification.
Starting a VpnService before the VPN app promotes itself to the foreground.
taked from the link below
i found the answer here:
https://stackoverflow.com/a/46445436/8675712
https://stackoverflow.com/a/47654126/8675712
Related
I'm working with firebase and i'm trying to click the login button but the home page doesn't show up it just says "please waiting!!!" run forever like:
. I can't find a solution to fix it. Help me please.
My realtime Database:
https://drive.google.com/file/d/1ckzM7NitXdPKGdIG6dbAv0IWhl1WgtZk/view?usp=sharing
In SignIn Class:
package com.example.eatit_new;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import com.example.eatit_new.Common.Common;
import com.example.eatit_new.Model.User;
import com.google.android.material.snackbar.Snackbar;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.eatit_new.databinding.ActivitySignInBinding;
import com.google.firebase.auth.OAuthCredential;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.rengwuxian.materialedittext.MaterialEditText;
public class SignIn extends AppCompatActivity {
EditText editPhone, editPassword;
Button btnSignIn;
#Override
protected void onCreate (Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_sign_in);
editPassword=(MaterialEditText)findViewById(R.id.editPassword);
editPhone= (MaterialEditText)findViewById(R.id.editPhone);
btnSignIn = (Button) findViewById(R.id.btnSignIn);
//init Database
final FirebaseDatabase database= FirebaseDatabase.getInstance();
final DatabaseReference table_user=database.getReference("User");
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final ProgressDialog mDialog = new ProgressDialog(SignIn.this);
mDialog.setMessage("Please waiting....");
mDialog.show();
table_user.addValueEventListener( new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//Check if user not exist in database
if (dataSnapshot.child(editPhone.getText().toString()).exists()) {
//Get User Information
mDialog.dismiss();
User user = dataSnapshot.child(editPhone.getText().toString()).getValue(User.class);
if (user.getPassword().equals(editPassword.getText().toString())) {
Intent homeIntent= new Intent(SignIn.this,Home.class);
Common.currentUser= user;
startActivity(homeIntent);
finish();
} else {
Toast.makeText(SignIn.this, "Wrong password!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(SignIn.this, "User not exists!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
}
}
Error In Run:
W/Parcel: Expecting binder but got null!
E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 324)
W/GmsClient: IGmsServiceBroker.getService failed
android.os.DeadObjectException: Transaction failed on small parcel; remote process probably died, but this could also be caused by running out of binder buffe
at android.os.BinderProxy.transactNative(Native Method)
at android.os.BinderProxy.transact(BinderProxy.java:584)
at com.google.android.gms.common.internal.zzac.getService(com.google.android.gms:play-services-basement##18.1.0:8)
at com.google.android.gms.common.internal.BaseGmsClient.getRemoteService(com.google.android.gms:play-services-basement##18.1.0:14)
at com.google.android.gms.common.internal.BaseGmsClient$LegacyClientCallbackAdapter.onReportServiceBinding(com.google.android.gms:play-services-basement##18.1.0:2)
at com.google.android.gms.common.internal.zzg.zzd(com.google.android.gms:play-services-basement##18.1.0:1)
at com.google.android.gms.common.internal.zza.zza(com.google.android.gms:play-services-basement##18.1.0:4)
at com.google.android.gms.common.internal.zzc.zze(com.google.android.gms:play-services-basement##18.1.0:3)
at com.google.android.gms.common.internal.zzb.handleMessage(com.google.android.gms:play-services-basement##18.1.0:31)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7898)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
D/FA: Service connection suspended
V/FA: Recording user engagement, ms: 6704
V/FA: onActivityCreated
V/FA: Connection attempt already in progress
V/FA: Connection attempt already in progress
V/FA: Activity paused, time: 31916685
D/AutofillManager: Fill dialog is enabled:false, hints=[]
V/FA: Activity resumed, time: 31916803
V/FA: Connection attempt already in progress
V/FA: Connection attempt already in progress
W/Parcel: Expecting binder but got null!
D/TrafficStats: tagSocket(107) with statsTag=0xffffffff, statsUid=-1
D/CompatibilityChangeReporter: Compat change id reported: 171228096; UID 10157; state: ENABLED
W/Parcel: Expecting binder but got null!
D/EGL_emulation: app_time_stats: avg=30.81ms min=2.94ms max=450.90ms count=28
Recently I have been working on android studio, I built a python image classification model and want to integrate it with an app. But when I click on predict button, the app crashes. Would be helpful if I can get the idea as to where things are going wrong.
Attached is the code and the error it throws -
Activitymain.java :-
package com.example.uni;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.example.uni.ml.ConvertedModel;
import org.tensorflow.lite.DataType;
import org.tensorflow.lite.support.image.TensorImage;
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer;
import java.io.IOException;
import java.nio.ByteBuffer;
public class MainActivity extends AppCompatActivity {
private ImageView imgView;
private Button predict;
private Button select;
private TextView tv;
private Bitmap img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgView = (ImageView) findViewById(R.id.imageView);
tv = (TextView) findViewById(R.id.textView);
select = (Button) findViewById(R.id.button);
predict = (Button) findViewById(R.id.button2);
select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent,12);
}
});
predict.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
img = Bitmap.createScaledBitmap(img,
500,
500,
true);
try {
ConvertedModel model = ConvertedModel.newInstance(getApplicationContext());
// Creates inputs for reference.
TensorBuffer inputFeature0 = TensorBuffer.createFixedSize(new int[]{1, 500, 500, 3}, DataType.FLOAT32);
TensorImage tensorImage = new TensorImage(DataType.FLOAT32);
tensorImage.load(img);
ByteBuffer byteBuffer = tensorImage.getBuffer();
inputFeature0.loadBuffer(byteBuffer);
// Runs model inference and gets result.
ConvertedModel.Outputs outputs = model.process(inputFeature0);
TensorBuffer outputFeature0 = outputs.getOutputFeature0AsTensorBuffer();
// Releases model resources if no longer used.
model.close();
tv.setText((int) outputFeature0.getFloatArray()[0]);
} catch (IOException e) {
/* TODO Handle the exception */
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 100)
{
imgView.setImageURI(data.getData());
Uri uri = data.getData();
try {
img = MediaStore.Images.Media.getBitmap(this.getContentResolver(),uri);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
In logcat I see this -
2021-11-05 13:23:38.040 24027-24027/com.example.uni I/tflite: Initialized TensorFlow Lite runtime.
2021-11-05 13:23:38.090 24027-24027/com.example.uni E/libc: Access denied finding property "ro.hardware.chipname"
2021-11-05 13:23:38.081 24027-24027/com.example.uni W/com.example.uni: type=1400 audit(0.0:232245): avc: denied { read } for name="u:object_r:vendor_default_prop:s0" dev="tmpfs" ino=14249 scontext=u:r:untrusted_app:s0:c48,c257,c512,c768 tcontext=u:object_r:vendor_default_prop:s0 tclass=file permissive=0
2021-11-05 13:23:38.841 24027-24027/com.example.uni E/com.example.un: Invalid ID 0x00000000.
2021-11-05 13:23:38.842 24027-24027/com.example.uni D/AndroidRuntime: Shutting down VM
2021-11-05 13:23:38.843 24027-24027/com.example.uni E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.uni, PID: 24027
android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.content.res.Resources.getText(Resources.java:381)
at android.content.res.MiuiResources.getText(MiuiResources.java:97)
at android.widget.TextView.setText(TextView.java:6397)
at com.example.uni.MainActivity$2.onClick(MainActivity.java:85)
at android.view.View.performClick(View.java:7189)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View.performClickInternal(View.java:7166)
at android.view.View.access$3500(View.java:819)
at android.view.View$PerformClick.run(View.java:27682)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7592)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
2021-11-05 13:23:38.887 24027-24027/com.example.uni I/Process: Sending signal. PID: 24027 SIG: 9
Need suggestions as to what's going on and how to resolve it. I'm using android studio arctic fox 2020.3.1 patch 3.
The logcat already told you that it crashed at the setText() call. You called
tv.setText((int) outputFeature0.getFloatArray()[0]);
The int in setText(int) refers to a Resource ID defined in the string.xml (R.string.xxx).
If you are not getting the string from res, you should use setText(CharSequence) instead.
You probably want
tv.setText(String.format("%f",outputFeature0.getFloatArray()[0]));
(change "%f" to any decimal points or format you want)
My app keeps crashing since I started using a TextWatcher...
As you can see below i made a TextWatcher to 3 EditText fields...
And i made a button which listens to the 3 EditText..
If they are empty the button become disabled.
When the fields are filled the button should become enabled..
package com.example.magazijnapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.MenuPopupWindow;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.sql.Array;
public class MainActivity extends AppCompatActivity {
Spinner spinnermagazijn;
Button knop;
private EditText EditTextregisternummerbalk;
private EditText EditTextticketnummerbalk;
private EditText EditTextartikelnummerbalk;
private Button knopconfirm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditTextregisternummerbalk = findViewById(R.id.registernummerbalk);
EditTextticketnummerbalk = findViewById(R.id.ticketnummerbalk);
EditTextartikelnummerbalk = findViewById(R.id.artikelnummerbalk);
knopconfirm = findViewById(R.id.knop);
EditTextregisternummerbalk.addTextChangedListener(invulTextWatcher);
EditTextticketnummerbalk.addTextChangedListener(invulTextWatcher);
EditTextartikelnummerbalk.addTextChangedListener(invulTextWatcher);
}
private TextWatcher invulTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String registernummerinput = EditTextregisternummerbalk.getText().toString().trim();
String ticketnummerinput = EditTextticketnummerbalk.getText().toString().trim();
String artikelnummerinput = EditTextartikelnummerbalk.getText().toString().trim();
knopconfirm.setEnabled(!registernummerinput.isEmpty() && !ticketnummerinput.isEmpty() &&! artikelnummerinput.isEmpty());
}
#Override
public void afterTextChanged(Editable s) {
}
};
{
spinnermagazijn = findViewById(R.id.spinnermagazijn);
knop = findViewById(R.id.knop);
populatespinnermagazijn();
// Dit is het stukje voor de Knop afboeken waarmee je een melding genereerd, String aanpassen voor ander resultaat.
knop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, (R.string.succes), Toast.LENGTH_SHORT) .show();
}
});
}
// Dit gedeelte is voor de spinner.
private void populatespinnermagazijn() {
ArrayAdapter<String> magazijnenAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.steunpunten));
magazijnenAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnermagazijn.setAdapter(magazijnenAdapter);
}
}
And this is my logcat...
03-19 21:04:06.293 21151-21151/? E/libprocessgroup: failed to make and chown /acct/uid_10060: Read-only file system
03-19 21:04:06.293 21151-21151/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
03-19 21:04:06.293 21151-21151/? I/art: Not late-enabling -Xcheck:jni (already on)
03-19 21:04:06.313 21151-21161/? I/art: Debugger is no longer active
03-19 21:04:06.351 21151-21151/? D/AndroidRuntime: Shutting down VM
03-19 21:04:06.354 21151-21151/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.magazijnapp, PID: 21151
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.magazijnapp/com.example.magazijnapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:149)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:99)
at android.content.Context.obtainStyledAttributes(Context.java:437)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
at com.example.magazijnapp.MainActivity.<init>(MainActivity.java:73)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
03-19 21:04:07.996 21151-21151/? I/Process: Sending signal. PID: 21151 SIG: 9
There are two findViewById(R.id.knop);
remove this line:
knop = findViewById(R.id.knop);
and change :
knopconfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, (R.string.succes), Toast.LENGTH_SHORT) .show();
}
});
You are saying your app is crashing since you started using TextWatcher. So why don't you stop using it?
you can achieve the same thing without using TextWatcher by doing this.
knop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String registernummerinput = EditTextregisternummerbalk.getText().toString().trim();
String ticketnummerinput = EditTextticketnummerbalk.getText().toString().trim();
String artikelnummerinput = EditTextartikelnummerbalk.getText().toString().trim();
if((!registernummerinput.isEmpty() && !ticketnummerinput.isEmpty() &&! artikelnummerinput.isEmpty())) {
Toast.makeText(MainActivity.this, (R.string.succes), Toast.LENGTH_SHORT) .show();
}
}
});
you will not need any TextWathcer just modify the listner
I'm try to play a loading animation on my loading screen, and I read somewhere that android doesn't support gifs so either you have to break in into frames and then play it or we can use the Movie class.
Heres the leading activity -
package com.myapp.mehul.login.activity;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import com.myapp.mehul.login.MYGIFView;
import com.myapp.mehul.login.MainActivity;
import com.myapp.mehul.login.R;
import com.myapp.mehul.login.app.Constants;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URISyntaxException;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
/**
* Created by mehul on 2/6/16.
*/
public class LoadingScreen extends Activity {
/** Duration of wait **/
private final int SPLASH_DISPLAY_LENGTH = 1000;
/** Called when the activity is first created. */
private Socket mSocket;
String you;
String opponentId;
String username;
{
try {
mSocket = IO.socket(Constants.CHAT_SERVER_URL);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(new MYGIFView(getApplicationContext()));
//initialise the socket
mSocket.connect();
//call add user
mSocket.emit("add user");
//start a listener for opponent
mSocket.on("opponent", onOpponent);
//initialise the username
username = getIntent().getExtras().getString("username");
}
private Emitter.Listener onOpponent = new Emitter.Listener(){
#Override
public void call(final Object... args){
LoadingScreen.this.runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
try {
you = data.getString("you");
opponentId = data.getString("opponent");
Log.d("LoadingScreen", data.toString());
//setResult(RESULT_OK, i);
finish();
} catch (JSONException e) {
return;
}
Intent i = new Intent(LoadingScreen.this, MainActivity.class);
i.putExtra("opponentId", opponentId);
i.putExtra("you", you);
i.putExtra("username", username);
Log.d("goToChat", username);
startActivity(i);
}
});
}
};
#Override
public void onBackPressed(){
AlertDialog.Builder builder = new AlertDialog.Builder(LoadingScreen.this);
builder.setMessage("I knew you didn't have BALLS.").setCancelable(
false).setPositiveButton("I am a LOSER",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//send the logout information to the server
JSONObject discon = new JSONObject();
try {
discon.put("opponent", opponentId);
discon.put("you", you);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mSocket.emit("discon", discon);
mSocket.disconnect();
//finish the current activity.
Intent intent = new Intent(LoadingScreen.this, MainMenu.class);
startActivity(intent);
LoadingScreen.this.finish();
}
}).setNegativeButton("I'll fkin face it",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
In the above code I've set content view by passing it an instance of MYGIFView.class -
Heres MYGIFView.class
package com.myapp.mehul.login;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Movie;
import android.view.View;
import java.io.InputStream;
/**
* Created by mehul on 2/7/16.
*/
public class MYGIFView extends View{
Movie movie,movie1;
InputStream is=null,is1=null;
long moviestart;
public MYGIFView(Context context) {
super(context);
is=context.getResources().openRawResource(+ R.drawable.loading);
movie=Movie.decodeStream(is);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
super.onDraw(canvas);
long now=android.os.SystemClock.uptimeMillis();
System.out.println("now="+now);
if (moviestart == 0) { // first time
moviestart = now;
}
System.out.println("\tmoviestart="+moviestart);
int relTime = (int)((now - moviestart) % movie.duration()) ;
System.out.println("time="+relTime+"\treltime="+movie.duration());
movie.setTime(relTime);
movie.draw(canvas,this.getWidth()/2-20,this.getHeight()/2-40);
this.invalidate();
}
}
The loading activity IS creating an instance of MYGIFView.class and it logs the data but then it gives fatal signal 11. I tried to search but I didn't get any answer.
console log -
02-07 12:22:30.321 29092-29092/? I/art: Late-enabling -Xcheck:jni
02-07 12:22:30.341 29092-29102/? I/art: Debugger is no longer active
02-07 12:22:30.422 29092-29092/? D/SQLiteHandler: Fetching user from Sqlite: {username=Harsh}
02-07 12:22:30.422 29092-29092/? D/LoginActivity: already logged in
02-07 12:22:30.425 29092-29092/? I/Timeline: Timeline: Activity_launch_request id:com.myapp.mehul.login time:71360781
02-07 12:22:30.487 29092-29092/? D/MainMenu: painted again
02-07 12:22:30.490 29092-29092/? D/SQLiteHandler: Fetching user from Sqlite: {username=Harsh}
02-07 12:22:30.554 29092-29149/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
02-07 12:22:30.559 29092-29092/? D/Atlas: Validating map...
02-07 12:22:30.596 29092-29149/? I/Adreno-EGL: <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.01.00.042.030_msm8974_LA.BF.1.1.1_RB1__release_AU ()
OpenGL ES Shader Compiler Version: E031.25.03.06
Build Date: 04/15/15 Wed
Local Branch: mybranch9068252
Remote Branch: quic/LA.BF.1.1.1_rb1.19
Local Patches: NONE
Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.01.00.042.030 + NOTHING
02-07 12:22:30.597 29092-29149/? I/OpenGLRenderer: Initialized EGL, version 1.4
02-07 12:22:30.611 29092-29149/? D/OpenGLRenderer: Enabling debug mode 0
02-07 12:22:30.660 29092-29092/? I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#387f1572 time:71361016
02-07 12:22:31.898 29092-29092/com.myapp.mehul.login D/go to chat: was called
02-07 12:22:31.899 29092-29092/com.myapp.mehul.login I/Timeline: Timeline: Activity_launch_request id:com.myapp.mehul.login time:71362255
02-07 12:22:31.997 29092-29092/com.myapp.mehul.login I/System.out: now=71362353
02-07 12:22:31.997 29092-29092/com.myapp.mehul.login I/System.out: moviestart=71362353
02-07 12:22:31.997 29092-29092/com.myapp.mehul.login I/System.out: time=0 reltime=1850
02-07 12:22:32.007 29092-29092/com.myapp.mehul.login A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0x0 in tid 29092 (app.mehul.login)
02-07 12:22:32.541 29092-29092/com.myapp.mehul.login W/app.mehul.login: type=1701 audit(0.0:302): auid=4294967295 uid=10250 gid=10250 ses=4294967295 subj=u:r:untrusted_app:s0 reason="memory violation" sig=11
I received a batch for this question which means its being viewed a lot, so I'll answer this question -
What I figured out was the line below was throwing the error -
movie.draw(canvas,this.getWidth()/2-20,this.getHeight()/2-40);
Now the problem is that this error specifically can be caused by lots of reasons, its never a specific reason.. the reason mine wasn't working out was because my device didn't work well with hardware acceleration, so I just had to disable it in the manifest application, like this -
<android:hardwareAccelerated="false">
Now its possible that the reason might not be the same....but the core reason is the same, its memory related, and most chances are its a bug in the firmware of the device or emulator you are testing upon.
In the Manifest set in your activity :
<activity
android:name="LoadingScreen"
android:hardwareAccelerated="false">
</activity>
I got here with the exact same problem but in React Native, so I will put a solution for those who need it too. The error may be triggered by react-native-webview and/or React Navigation. In some cases, like me, you don't want to disable Hardware Acceleration on the whole app, so here's a workaround:
react-native-webview
<WebView
androidHardwareAccelerationDisabled
source={source}
/>
React Navigation 5
<NavigationContainer>
<Stack.Navigator initialRouteName="HomeScreen">
<Stack.Screen
name="HomeScreen"
component={HomeScreen}
options={{
animationEnabled: false,
}}
/>
</Stack.Navigator>
</NavigationContainer>
https://github.com/react-native-webview/react-native-webview/issues/575
i am new to android development and i am writing an app for my college project .The app transmits a string of data stored in shared preferences .The data is stored by one time setup screen which is never shown again.The issue is after first time,when app is started again it shows that "app has unfortunately stopped working "and when i click ok the app starts.Can anybody tell me why this is happening?
Code:
package com.example.homeautomation.zigbeehomeauto;
import android.annotation.TargetApi;
import android.content.SharedPreferences;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Toast;
public class MainScreen extends ActionBarActivity {
NdefMessage msg;
NfcAdapter nfcadapter;
public static final String PREFS_NAME = "MyPrefsFile";
public String pass2 ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
SharedPreferences check = getSharedPreferences(PREFS_NAME, 0);
String Pass = check.getString("Str", "Nothing");
pass2 = Pass;
nfcadapter = NfcAdapter.getDefaultAdapter(this);
if (nfcadapter == null) {
Toast.makeText(this, "NFC is not available User", Toast.LENGTH_LONG)
.show();
finish();
}
}
public void ExApp(View v) {
finish();
System.exit(0);
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void Nsend(View v)
{
byte[] stringBytes = pass2.getBytes();
nfcadapter.setNdefPushMessage(msg = new NdefMessage(new NdefRecord[]{NdefRecord.createMime("text/plain", stringBytes)
}),this);
}
}
Logcat Ouput:
04-07 12:04:38.478 10836-10836/com.example.homeautomation.zigbeehomeauto E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.homeautomation.zigbeehomeauto, PID: 10836
android.util.SuperNotCalledException: Activity {com.example.homeautomation.zigbeehomeauto/com.example.homeautomation.zigbeehomeauto.SetupScreen} did not call through to super.onCreate()
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2510)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2603)
at android.app.ActivityThread.access$900(ActivityThread.java:174)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5752)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Check in your SetupScreen.java do you have super.onCreate(savedInstanceState);
after onCreate() Method is starts .
post your SetupScreen.java code also ..
Your onCreate() method of class SetupScreen do not call the super.onCreate(). Add the statement and the error should go away.