How to call alertDialog in alertDialog? - java

I have a alert dialog in android that called from javascript interface.
In alert dialog I have two button that when you click on the one of them I want start other alert dialog that include list.but when I click app crashed.
this is my java code :
public void SaveDialog(final String SaveID) {
final SQLiteDatabase mydatabase1 = openOrCreateDatabase("CopyCollection", MODE_PRIVATE, null);
Cursor c = mydatabase1.rawQuery("SELECT * FROM Details WHERE ID="+SaveID+";", null);
if(c.moveToFirst()) {
do {
appName = c.getString(1);
txtClip = c.getString(2);
text_Date = c.getString(3);
} while (c.moveToNext());
}
AlertDialog.Builder myDialog = new AlertDialog.Builder(AndroidHTMLActivity.this);
myDialog.setTitle("ذخیره");
myDialog.setPositiveButton("ذخیره", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//======================================================
String names[] ={"A","B","C","D"};
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(AndroidHTMLActivity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.main, null);
alertDialog.setView(convertView);
alertDialog.setTitle("List");
ListView lv = (ListView) convertView.findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(AndroidHTMLActivity.this,android.R.layout.simple_list_item_1,names);
lv.setAdapter(adapter);
alertDialog.show();
}
});
myDialog.setNegativeButton("اشتراک گذاری", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = txtClip;
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
});
myDialog.show();
}
and this is logcat :
03-24 02:22:58.146 5499-5499/com.exercise.AndroidHTML W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb0cf3b20)03-24 02:22:58.156 5499-5499/com.exercise.AndroidHTML E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.exercise.AndroidHTML, PID: 5499
java.lang.IllegalStateException: Calling View methods on another thread than the UI thread.
at com.android.webview.chromium.WebViewChromium.createThreadException(WebViewChromium.java:268)
at com.android.webview.chromium.WebViewChromium.checkThread(WebViewChromium.java:284)
at com.android.webview.chromium.WebViewChromium.setLayoutParams(WebViewChromium.java:1618)
at android.webkit.WebView.setLayoutParams(WebView.java:2099)
at android.view.ViewGroup.addViewInner(ViewGroup.java:3577)
at android.view.ViewGroup.addView(ViewGroup.java:3415)
at android.view.ViewGroup.addView(ViewGroup.java:3391)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:759)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at com.exercise.AndroidHTML.AndroidHTMLActivity$MyJavaScriptInterface.SaveDialog(AndroidHTMLActivity.java:198)
at com.android.org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method)
at com.android.org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:27)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.os.HandlerThread.run(HandlerThread.java:61)

JavaScript runs on a separate thread other than main thread, which you can't show dialog directly on. Instead, you can show your dialog as following:
First, add a method to your MyJavaScriptInterface class:
public void showDialog(final String SaveID){
// create a Handler with the main Looper and
// post the dialog showing work to main thread.
new Handler(Looper.getMainLooper()).post(new Runnable(){
SaveDialog(SaveID);
});
}
Then, call showDialog() method instead of SaveDialog().

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

Android Create View Crash

I'm trying to add Layout with this code:
LayoutInflater layoutInflater = (LayoutInflater) activity.getSystemService(LAYOUT_INFLATER_SERVICE);
mYouTubePlayerLayout = (ConstraintLayoutKeyDispatchWrapper) layoutInflater.inflate(R.layout.background_player_layout, null, false);
mYouTubePlayerLayout.setOnDispatchKeyEventListener(this);
mWindowManager = (WindowManager) activity.getSystemService(WINDOW_SERVICE);
createWindowParams(true);
mWindowManager.addView(mYouTubePlayerLayout, mWindowParams);
I understand that I need to get permissions from the user for 23 version and above, so I'm asking the user for the permission with this code:
if (Build.VERSION.SDK_INT >= 23 && !Settings.canDrawOverlays(this)) {
isAppPlayStorePermission = true;
AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
dialog.setCancelable(false);
dialog.setIcon(R.drawable.ic_launcher);
dialog.setTitle(R.string.dialog_need_playstore_permissions_title);
dialog.setMessage(R.string.dialog_need_playstore_permissions_description);
dialog.setPositiveButton(R.string.button_exit, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
AndroidUtils.exitApp(activity);
}
});
dialog.setNegativeButton(R.string.button_settings, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, 0);
}
});
dialog.show();
}
but now I'm getting a crash from Fabric:
Fatal Exception: java.lang.RuntimeException
Unable to create service ***: android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W#c7450fc -- permission denied for this window type
The crash is only for users with Android OS of 7 and below.
Any idea what is the problem?

Android Oncreate load a listview in AsyncTask and show loader

I have a Custom List View which is loaded in Oncreate of my activity but in Async Task. I want to display the activity screen initially with a loader while the list is populated.
Activity OnCreate
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_word);
viewFlipper = new ViewFlipper(this);
viewFlipper.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
TextView txt = (TextView) findViewById(R.id.phraseListHeading);
Typeface font = Typeface.createFromAsset(WordActivity.this.getAssets(), "fonts/NotoSans-Regular.ttf");
String categoryName = getIntent().getExtras().getString("categoryName").toUpperCase();
category_obj = (categories) getIntent().getSerializableExtra("category_obj");
asyncLoadWordList task2 = new asyncLoadWordList(getApplicationContext());
task2.execute();}
My Async Task Class
public class asyncLoadWordList extends AsyncTask<ArrayList<word>, Void, ArrayList<word>>{
private Context mContext;
public asyncLoadWordList(Context context) {
mContext = context;
}
protected void onPreExecute() {
//Start the splash screen dialog
if (pleaseWaitDialog == null)
pleaseWaitDialog= ProgressDialog.show(WordActivity.this,
"PLEASE WAIT",
"Getting results...",
false);
}
#Override
protected ArrayList<word> doInBackground(ArrayList<word>... params) {
wordDb = new wordDB(mContext);
category_obj = (categories) getIntent().getSerializableExtra("category_obj");
ArrayList<word> words = new ArrayList<word>();
Cursor row = wordDb.selectWordList(category_obj.getCsvCategoryId().toString());
words.add(new word("-1", "-1", "", "", "", "", "", "", "x.mp3", ""));
words.add(new word("-2", "-2", "", "", "", "", "", "", "x.mp3", ""));
row.moveToFirst();
while (!row.isAfterLast()) {
//Log.d("Data id: ", row.getString(2));
words.add( new word(row.getString(0),row.getString(1),row.getString(2),row.getString(3),row.getString(4),row.getString(5),row.getString(6),row.getString(7),row.getString(8),row.getString(9)));
row.moveToNext();
}
row.close();
return words;
}
protected void onPostExecute(ArrayList<word> result) {
adapter = new WordAdapter(WordActivity.this, result);
ListView listView = (ListView) findViewById(R.id.list_view_word);
listView.setAdapter(adapter);
if (pleaseWaitDialog != null) {
pleaseWaitDialog.dismiss();
pleaseWaitDialog = null;
}
asyncFlipperView task = new asyncFlipperView(getApplicationContext());
task.execute(new String[]{category_obj.getCsvCategoryId().toString()});
}
}
I am getting
04-04 14:10:41.889 31208-31208/thai.phrasi.ctech.com.phrasi E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: thai.phrasi.ctech.com.phrasi, PID: 31208
java.lang.RuntimeException: Unable to start activity ComponentInfo{thai.phrasi.ctech.com.phrasi/thai.phrasi.ctech.com.phrasi.WordActivity}: android.view.WindowManager$BadTokenException: Unable to add window -- token android.app.LocalActivityManager$LocalActivityRecord#42169328 is not valid; is your activity running?
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.startActivityNow(ActivityThread.java:2024)
at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:135)
at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:347)
at thai.phrasi.ctech.com.phrasi.CategoryActivity$1.onItemClick(CategoryActivity.java:95)
at android.widget.AdapterView.performItemClick(AdapterView.java:299)
at android.widget.AbsListView.performItemClick(AbsListView.java:1113)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:2911)
at android.widget.AbsListView$3.run(AbsListView.java:3645)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token android.app.LocalActivityManager$LocalActivityRecord#42169328 is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:532)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:259)
at
How do I show the initial Screen with loader???
First of all you are setting a context of a class which is not initialize:
adapter = new WordAdapter(WordActivity.this, result);
Second you shouldn't manipulate views in a different thread.
To solved It you could create a handler to send the data to the uithread:
public class YourHandler extends Handler {
public YourHandler() {
super();
}
public synchronized void handleMessage(Message msg) {
ArrayList<word> data = (ArrayList<word> )msg.obj;
adapter = new WordAdapter(mContext, data);
ListView listView = (ListView) findViewById(R.id.list_view_word);
listView.setAdapter(adapter);
listView.notifyDataSetChanged();
}
}
And Send the data from onpostexecute:
protected void onPostExecute(ArrayList<word> result) {
msg = Message.obtain();
msg.obj = mResponse;
mYourHandler.sendMessage(msg);
}
THe handler is a inner class inside the activity, and don't forget to create mContext variable in your activity:
private Context mContext = this;
try to use this intead of getApplicationContext()
asyncLoadWordList task2 = new asyncLoadWordList(this);

Android App crashes on Lollipop

hi I am using google license checker on my app it works on API 19 and below but crashes on lollipop. I saw the code that has to be add to my license check code but I don't know where to put this code or what should I edit. here is my code
log:
java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=com.android.vending.licensing.ILicensingService }
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=com.android.vending.licensing.ILicensingService }
at android.app.ContextImpl.validateServiceIntent(ContextImpl.java:1674)
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1773)
at android.app.ContextImpl.bindService(ContextImpl.java:1751)
at android.content.ContextWrapper.bindService(ContextWrapper.java:538)
at com.google.android.vending.licensing.LicenseChecker.checkAccess(LicenseChecker.java:150)
at appinventor.ai_drsalmanshah165.Clinical_Examination.Splash.doCheck(Splash.java:103)
at appinventor.ai_drsalmanshah165.Clinical_Examination.Splash.onCreate(Splash.java:51)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
... 10 more
Java code:
public class Splash extends Activity {
MyLicenseCheckerCallback mLicenseCheckerCallback;
LicenseChecker mChecker;
byte[] SALT = new byte[] {
my salt no. };
//Handler mHandler;
String BASE64_PUBLIC_KEY="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoxvDF3HGQtrRch14wCPN6nAxasak8X4shJM6bCumNS+6xRXTnRZOSyAvHNa1145KlE/i1sy/";
Context mContext;
IBinder serviceBinder;
String deviceId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash);
mLicenseCheckerCallback = new MyLicenseCheckerCallback();
deviceId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
// Construct the LicenseChecker with a policy.
mChecker = new LicenseChecker(
this, (Policy) new ServerManagedPolicy(Splash.this, new AESObfuscator(SALT, getPackageName(), deviceId)),
BASE64_PUBLIC_KEY);
doCheck();
}
private class MyLicenseCheckerCallback implements LicenseCheckerCallback {
#Override
public void allow(int reason) {
// TODO Auto-generated method stub
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
// Toast.makeText(Splash.this, "License Verified", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(Splash.this,Home.class);
startActivity(intent);
finish();
// Should allow user access.
// so do nothing
}
#Override
public void dontAllow(int reason) {
// TODO Auto-generated method stub
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
// Toast.makeText(Splash.this, "License Verification Failed", Toast.LENGTH_SHORT).show();
createDialog();
}
#Override
public void applicationError(int errorCode) {
// TODO Auto-generated method stub
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mChecker.onDestroy();
}
private void doCheck() {
// mCheckLicenseButton.setEnabled(false);
setProgressBarIndeterminateVisibility(true);
/// mStatusText.setText(R.string.checking_license);
mChecker.checkAccess(mLicenseCheckerCallback);
}
public void createDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("PIRACY WARNING");
builder.setMessage("This application is not licensed. Please purchase it from Android Market. If you received this message in error, please contact Support.");
builder.setPositiveButton("Buy Now", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(
"http://market.android.com/details?id=" + getPackageName()));
startActivity(marketIntent);
}
});
builder.setNegativeButton("Quit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
and here is the other code which I got that this can solve my problem. but don't know where to put it.
Intent serviceIntent = new Intent(
new String(Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")));
serviceIntent.setPackage("com.android.vending");
boolean bindResult = mContext
.bindService(
serviceIntent,
this, // ServiceConnection.
Context.BIND_AUTO_CREATE);
Waiting for an official solution, the current solution consists in patching Google's LicenseChecker class
com.google.android.vending.licensing.LicenseChecker.checkAccess(LicenseChecker.java:150)
like this:
new String(
- Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U="))),
+ Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")))
+ .setPackage("com.android.vending"), // this fix the 'IllegalArgumentException: Service Intent must be explicit'
this, // ServiceConnection.
Adding package name with statement setPackage("com.android.vending") makes the Intent explicit, i.e., 'safe' (as requested by Android Lollipop )
Note:
Please pay attention as after modifying LicenseChecker class you must change the min sdk version from 3 to 4 (thanks russellhoff)
Source:
https://code.google.com/p/android/issues/detail?id=78505#c19

NullPointerException with getActivity() and not sure how to do intents

Hi I'm a complete beginner at Android development so I don't really know too much of what I'm doing. I keep getting nullpointerexecption and my program crashes whenever getActivity() is called. This includes in toast messages as well as when I try to start another activity with an intent. I'm not entirely sure how to use intents either so if that could be explained that would be great.
Here is the class that has the getActivity() calls as well as intent:
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;
public class loginDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.loginw)
.setItems(R.array.account_types, new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which){
if(which==0){
Toast.makeText(getActivity(),"todo",Toast.LENGTH_SHORT).show();
}else if(which==1){
Toast.makeText(getActivity(),"todo",Toast.LENGTH_SHORT).show();
}else if(which==2){
AlertDialog.Builder builder1=new AlertDialog.Builder(getActivity());
LayoutInflater inflater=getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.login_dialog,null);
builder1.setView(view);
builder1.setTitle("Login with Email Address");
builder1.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog1, int which) {
//Toast.makeText(getActivity(), "Cancel", Toast.LENGTH_SHORT).show(); //Force Closes. Nullpointer Exception? Probably because of getActivity()
//dialog1.dismiss();
}
});
builder1.setNeutralButton("Forgot Password",new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog1, int which){
dialog1.dismiss();
AlertDialog.Builder builder2=new AlertDialog.Builder(getActivity());
builder2.setTitle("Forgot Password");
builder2.setMessage("Enter your Email Address");
builder2.setPositiveButton("OK",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//TODO
}
});
builder2.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//TODO
}
});
builder2.show();
}
});
builder1.setPositiveButton(R.string.login, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog1, int which) {
//Toast.makeText(getActivity(),"Login complete",Toast.LENGTH_SHORT).show(); //Force Closes. Nullpointer Exception? Probably because of getActivity()
dialog1.dismiss();
Intent intent = new Intent(getActivity(),Groups.class);
startActivity(intent);
}
});
Dialog dialog1 = builder1.create();
dialog1.show();
}
}
});
Dialog dialog=builder.create();
return dialog;
}
}
Here is the logcat (note this is only for the intent call because the other getActivity()s are commented out):
java.lang.NullPointerException
at android.content.ComponentName.<init>(ComponentName.java:77)
at android.content.Intent.<init>(Intent.java:3813)
at com.app.u.loginDialog$1$3.onClick(loginDialog.java:67)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
You should call getActivity after the onActivityCreated method has returned in the Overriden dialogfragment class. in ur case loginDialog class. that is the safe place to call getActivity
public class LoginDialog extends DialogFragment {
Activity mAct;
#Override
public void onAttach(Activity act) {
super.onAttach(act);
mAct = act; // use this mAct instead of getActivity() function
}
You cannot create the Intent inside the dialogue popup message So you should use like this Or declare inside your dialogue Like this it will help you Definitely...All the best
Context context = activity.getApplicationContext();
Intent intent = new Intent(context, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
Try using getApplicationContext() instead
Intent intent = new Intent(getApplicationContext(), Groups.class);
startActivity(intent);
And remember to declare your new activity in your AndroidManifest file!
<activity android:name=".Groups"/>

Categories

Resources