Custom error message for phonegap in android - android

I'm using phonegap for my android app. My app loads a webpage from remote server. Now i need to generate a custom error message if the connection was unsuccesful.
Phonegap already contains a default error alert using an Alertbox
Application Error
The connection to the sever was unsuccessful. (http://yoursite.com)
Can i customize this error message?

use this `
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.customdialoglayout);
TextView dialogbody=(TextView) dialog.findViewById(R.id.dialogbody);
Button dialogok=(Button) dialog.findViewById(R.id.dialogok);
dialogok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialogbody.setText(displayText);
dialog.show();`

Related

android Custom Dialog title doesnot show

Im new at android app development so i was following a youtuber on making a Database, im doing same as he is, but problem is that i can make db successfully but custom dialog title doesnt show but error mesage & textview text is visible in my app.
Im attaching screenshot of successful code on youtube.
screenshot
btninsert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean boolln=true;
try {
String firstname = firstnam.getText().toString();
String lstname = lastnam.getText().toString();
db1.insertname(firstname, lstname);
}catch (Exception ex){
boolln=false;
String error=ex.toString();
Dialog dl=new Dialog(Activity_DB.this);
dl.setTitle("Uncuceesful");
TextView tx=new TextView(Activity_DB.this);
tx.setText(error);
dl.setContentView(tx);
dl.show();
}finally {
if (boolln){
Dialog dl1=new Dialog(Activity_DB.this);
dl1.setTitle("succesful? YES");
TextView tx=new TextView(Activity_DB.this);
tx.setText("sucesss");
dl1.setContentView(tx);
dl1.show();
}
}
Solved this problem by adding AlerDialog.builder instead of using Dialog, now it works perfectly.
boolln=false;
String error=ex.toString();
AlertDialog.Builder dl=new AlertDialog.Builder(Activity_DB.this);
dl.setCancelable(true);
dl.setTitle("Uncuceesful");
dl.setMessage("No entry found. \n"+error);
dl.show()

Forcing the users to update my app

how can i force user to update my app by going to Google play store? if there's a new update a dialog will show which will have 2 buttons either update app or exit app.
Wont allow app to run unless latest version.
I am using eclipse and i cant migrate to android studio because of some project issues .
please help
Use Dialogs when your main Activity starts. Just redirect the user to the URL of your app on the PlayStore if he accepts, and exit the app (here are examples on how doing it).
Took from Anrdoid documentation :
public class YourDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.please_update)
.setPositiveButton(R.string.Ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// launch a browser with your PlayStore APP URL
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Exit the app
android.os.Process.killProcess(android.os.Process.myPid());
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
Now, when you create an instance of this class and call show() on that object, the dialog appears as shown in figure 1.
Just create an instance of it and use the show() method in your onCreateDialog from your MainActivity.
Note that Dialogs uses Fragments, which requieres API level 11. (You should be able to check the API level you're building to in your build.gradle file)
Use dialogs as mentioned by Noafix. Call an alert dialog when your version mismatches.
Also set dialog cancelable to false so that user cant remove dialog by pressing back!
private void showDialog()
{
final android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Update");
alertDialogBuilder.setMessage("Please update to continue?");
alertDialogBuilder.setIcon(R.drawable.warning);
alertDialogBuilder.setCancelable(false)
alertDialogBuilder.setPositiveButton("Confirm",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
});
// Add a negative button and it's action. In our case, just hide the dialog box
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finishAffinity();
}
});
// Now, create the Dialog and show it.
final android.app.AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
You could get your version name as:
versionName = getApplicationContext().getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0).versionName;
Now get your current version from your server using any rest client http calls and check with your version:
if(!versionName.equals(version)){showDialog();}
Note: For this you should implement a version file in server in which you must add new version in that file so that using http calls your app can get the new version name and check with app version!
Implement a way for the app to check if it is the latest version or not.
You can do this by hosting an update file that contains information on what the latest version is. This file is commonly in json format but can also be in any format you prefer. The app would have to query this update file and if the current version of the app is less than the version indicated in the update file, then it would show the update prompt.
If the app determines that an update is needed, open a dialog prompt then open the app's play store page
To launch a dialog prompt refer to the official Dialogs guide. Given that the question is not "how to launch a dialog" I will focus on discussing how to update the app.
To open google play store to a particular app page you must launch an intent with the View action and Market scheme uri like so
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
Be wary that if the device does not have google play store installed, then this will throw an exception. It is also possible for other apps to receive this type of intent and in the case where multiple apps can receive the intent, an app picker dialog will appear.
Challenges:
If the app must check for updates and can only run if it is the latest version, then the app cannot run if the device is not connected to the internet.
The app will have a hard dependency on google play store and cannot run if an update is needed and there is no play store on the device
If the update file is unavailable for any reason then the app will not run as well
You absolutely need the users to update to continue using the app, you could provide a simple versioning API. The API would look like this:
versionCheck API:
->Request parameters:
int appVersion
-> Response
boolean forceUpgrade
boolean recommendUpgrade
When your app starts, you could call this API that pass in the current app version, and check the response of the versioning API call.
If forceUpgrade is true, show a popup dialog with options to either let user quit the app, or go to Google Play Store to upgrade the app.
Else if recommendUpgrade is true, show the pop-up dialog with options to update or to continue using the app.
Even with this forced upgrade ability in place, you should continue to support older versions, unless absolutely needed.
try this: First you need to make a request call to the playstore link, fetch current version from there and then compare it with your current version.
String currentVersion, latestVersion;
Dialog dialog;
private void getCurrentVersion(){
PackageManager pm = this.getPackageManager();
PackageInfo pInfo = null;
try {
pInfo = pm.getPackageInfo(this.getPackageName(),0);
} catch (PackageManager.NameNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
currentVersion = pInfo.versionName;
new GetLatestVersion().execute();
}
private class GetLatestVersion extends AsyncTask
{
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... params) {
try {
Document doc = Jsoup.connect(urlOfAppFromPlayStore).get();
latestVersion = doc.getElementsByAttributeValue
("itemprop","softwareVersion").first().text();
}catch (Exception e){
e.printStackTrace();
}
return new JSONObject();
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
if(latestVersion!=null) {
if (!currentVersion.equalsIgnoreCase(latestVersion)){
if(!isFinishing()){
showUpdateDialog();
}
}
}
else
background.start();
super.onPostExecute(jsonObject);
}
}
private void showUpdateDialog(){
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("A New Update is Available");
builder.setPositiveButton("Update", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse
("market://details?id=yourAppPackageName")));
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
background.start();
}
});
builder.setCancelable(false);
dialog = builder.show();
}

Changing "Unfortunately app has stopped message" to some other text

I have a app which requests for a lot of JSON arrays, if there is no internet signal , JSON is a null pointer reference due to which my app crashes. Instead of writing a function to check if the JSONArray is null, can I change the text of Unfortunately app stopped working to Cannot connect to internet?
Is this possible?
You can't change the text of the NullPointerException unless you develop your own Exception class and a SDK.
But for now this is what you can do.
try
{
// try to parse your json here
}
catch(NullPointerException npe)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Cannot connect to internet")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish(); // Close your app
}
});
AlertDialog alert = builder.create();
alert.show();
}

a line is drown over alertDialog.setButton in MainActivity.java

I am doing alert dialog demo. It work fine but I found a line over "setButton" in MainActivity.java file. Hear is my code:
#SuppressWarnings("deprecation")
public void onClick(View arg0) {
// Creating alert Dialog with one Button
AlertDialog alertDialog = new AlertDialog.Builder(
MainActivity.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("Welcome to AndroidHive.info");
// Setting Icon to Dialog
// I got line hear........ over setButtob .........
alertDialog.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// Write your code here to execute after dialog
// closed
Toast.makeText(getApplicationContext(),
"You clicked on OK", Toast.LENGTH_SHORT)
.show();
}
});
// Showing Alert Message
alertDialog.show();![enter image description here][1]
}
});`
You cab see the image here and get more idea of what I mean to say.
You mean you got a warning saying the method is deprecated?
That's because setButton is not used anymore, it's deprecated, instead you should be doing something like this:
alertDialog.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// blablabla
}
});
Also notice you can get the String "OK" like thing as well : android.R.string.ok , which is the recommended way ;)
I went through the url image, which made your question clear. This is showing because that method( setButton) is depreciated. You are using
#SuppressWarnings("deprecation")
at the top. This prevents is from giving the warning message and you cannot read the warning message( which probably is that: This method has been depreciated). If you remove the top line, then it will tell you why it shows cross line over setButton. See here. It says that this method was depreciated in API level 3.
For seeing how use use it in proper way, you can go through this official documentation page of using Alert Dialog. You can also see the tutorial here.

Webview database corruption on Android

I'm developing an Android app which uses a webview to display a webpage. Most of my code is related to the webview. My main activity contains a webview which displays an specific web site.
I'm trying to prevent an error when my webview.db is corrupted. I know that is not a common situation but I would like to make sure that my app will not crash.
Attempting to access the webview database when it has been
corrupted will result in a crash.
I added the method setUncaughtExceptionHandler to handle the exception. I can catch the exeption but when I tried to restart my app the webview never finishes loading.
I tried the follow code to "restart" my app:
Intent i = new Intent(context, Error.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
My last try was unsuccessfully then I added some code which displays an error message, removes the webview databases and closes the app.
AlertDialog alertDialog = new AlertDialog.Builder(
DiscoverMobile.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Application files have been deleted or corrupted. The app will close to fix this issue. You can restart the app later");
alertDialog.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
webview.getContext().deleteDatabase(
"webview.db");
webview.getContext().deleteDatabase(
"webviewCache.db");
WebViewDatabase webViewDB = WebViewDatabase
.getInstance(getBaseContext());
System.exit(0);
}
});
alertDialog.show();
Could this be a good solution?
Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.clearCache(true);
}
Maybe you tried this, but maybe also set the WebView Cache size to something small. I'm not sure if 0 will work, so maybe 1:
webview.getSettings().setAppCacheMaxSize(1);

Categories

Resources