Tuesday, April 3, 2018

Handling an Activity when non JSON data/Empty data is recieved with Alert or Custom Message

1 comment

I followed this to Read JSON data in android

over there I am passing result data to another activity

public class MainAct1 extends Activity {  private static String urlString;  private static final String My_TAG= "Log Status";  @Override protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);     setContentView(R.layout.data);      if(Dcon.isInternetAvailable(this))     {         try {             urlString = "https://example.net/api_json";             new ProcessJSON(this).execute();         }          catch (Exception e) {             AlertDialog.Builder builder = new AlertDialog.Builder(MainAct1.this);             builder.setMessage("Note: Your Server ID is Invalid \n Please check the Server Status");             builder.setTitle("Please Check Server Details");             builder.setPositiveButton("OK",null);              builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {                 @Override                 public void onClick(DialogInterface dialog, int which) {                     dialog.dismiss();                     finish();                 }             });             AlertDialog dialog = builder.create();             dialog.show();         }      }     else     {         AlertDialog alertDialog = new AlertDialog.Builder(MainAct1.this).create();         alertDialog.setTitle("Connection Error !");         alertDialog.setMessage("Internet not available, Check your internet connectivity and try again");          alertDialog.setButton("OK", new DialogInterface.OnClickListener() {             public void onClick(DialogInterface dialog, int which) {                 android.os.Process.killProcess(android.os.Process.myPid());                 System.exit(1);                 finish();             }         });         alertDialog.show();     }  }  private class ProcessJSON extends AsyncTask<Void, Void, Void> {      public Context context;     String FinalJSonResult;      public ProcessJSON(Context context) {         this.context = context;     }      @Override     protected void onPreExecute() {         super.onPreExecute();      }      @Override     protected Void doInBackground(Void... arg0) {     HttpHandler sh = new HttpHandler(urlString);          try {             sh.ExecutePostRequest();             if (sh.getResponseCode() == 200) {                 FinalJSonResult = sh.getResponse();                 if (FinalJSonResult != null) {                     try {                         JSONObject JObject = new JSONObject(FinalJSonResult);                         JSONObject response = JObject.getJSONObject("response");                       if(response.has("status")) {                          String status = response.getString("status");                             MainAct1.this.finish();                             Intent op = new Intent(MainAct1.this, MainRes1.class);                             op.putExtra("mydata", status);                             op.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);                             op.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);                             op.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);                             op.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);                             startActivity(op);                         }                         else {                                 Toast.makeText(context, "No JSON data", Toast.LENGTH_SHORT).show();                                 AlertDialog alertDialog = new AlertDialog.Builder(NSdata.this).create();                                 alertDialog.setTitle("Server Error !");                                 alertDialog.setMessage("No Data Received");                                 alertDialog.setButton("OK", new DialogInterface.OnClickListener() {                                     public void onClick(DialogInterface dialog, int which) {                                         android.os.Process.killProcess(android.os.Process.myPid());                                         System.exit(1);                                         finish();                                     }                                 });                                 alertDialog.show();                             }                     }                     catch (JSONException e) {                          AlertDialog.Builder builder = new AlertDialog.Builder(MainAct1.this);                         builder.setMessage("Note: Your Server ID is Invalid \n Please check the Server Status");                         builder.setTitle("Please Check Server Details");                         builder.setPositiveButton("OK",null);                          builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {                             @Override                             public void onClick(DialogInterface dialog, int which) {                                 dialog.dismiss();                                 finish();                             }                         });                         AlertDialog dialog = builder.create();                         dialog.show();                     }                     catch (JSONException e) {                      }                 }                 else{                     AlertDialog alertDialog = new AlertDialog.Builder(MainAct1.this).create();                     alertDialog.setTitle("User Error !");                     alertDialog.setMessage("No Data Received");                     alertDialog.setButton("OK", new DialogInterface.OnClickListener() {                         public void onClick(DialogInterface dialog, int which) {                             android.os.Process.killProcess(android.os.Process.myPid());                             System.exit(1);                             finish();                         }                     });                     alertDialog.show();                 }             }             else {                 Toast.makeText(context, sh.getErrorMessage(), Toast.LENGTH_SHORT).show();             }         }         catch (Exception e) {             e.printStackTrace();         }         return null;     } } @Override public void onBackPressed() {     moveTaskToBack(false);     Toast.makeText(this, "Please wait for a While.. Don't Go back .!", Toast.LENGTH_SHORT).show();  } } 

this is my JSON Data

{"response":{"status":"Active"}}

or

{"response":{"status":"Active:4 in stock"}}

So now I am facing issue with

1.NonJSON some times json data is not received due to server error

or it will show Just some HTML headings...

I need to data Handle it Can any one suggest me.. on this kind

and

2.Empty JSON Data Some times Result may be Null like

{"response":{"status":""}}

or

{"response":{}}

Can Any Suggest me How to Handle those Kinds I already Given Alerts But its not working.

Now I am handling these two kinds of data but Some times I am getting Empty

Update

For a valid JSON data Its Showing Result in next Activity/page in a Text View...

Valid JSON data {"response":{"status":"Active"}} or {"response":{"status":"Please set the data."}}

I am showing Result... in Next Page

But Sometimes I will get Invalid JSON data like {"response":{"status":}} or Just HTML page with Welcome text... or OOps page not found ...

So I want to Handle them,,, if I get Invalid JSON Data I want to SHOW the Alert to the USER.... so that's what I am trying But its not working Please Help me on this types

7 Answers

Answers 1

Please try this

if(response.has("status")) {         // Key found in Response JsonObject         String status = response.getString("status");     } else {         //Status Key not found in Response JsonObject     } 

Answers 2

I recommend use library like Gson. and through try/catch & JsonSyntaxException will validate data. but original reason of bug is shape of data. rewrite shape of json data in serverside.

Answers 3

JSONObject JObject = new JSONObject(FinalJSonResult);  JSONObject response = JObject.getJSONObject("response");           // Check Key found or Not     if(response.has("status")) {                  String status = response.getString("status");                     // Check if Status Empty or Not                    if(status.isEmpty()){                     }       } else {             //Status Key not found      } 
  • DoInBackground() only gets executed on a different thread other than the main UI thread.
  • So you need to write AlertDialog in onPostExecute.
  • In ProcessJSON class use FinalJSonResult string to handle different situation in onPostExecute().

ProcessJSON Class

private class ProcessJSON extends AsyncTask<Void, Void, Void> {      public Context context;     String FinalJSonResult;      public ProcessJSON(Context context) {         this.context = context;     }      @Override     protected void onPreExecute() {         super.onPreExecute();         FinalJSonResult = "";     }      @Override     protected Void doInBackground(Void... arg0) {         HttpHandler sh = new HttpHandler(urlString);          try {             sh.ExecutePostRequest();             if (sh.getResponseCode() == 200) {                 FinalJSonResult = sh.getResponse();                 if (FinalJSonResult != null) {                     try {                         JSONObject JObject = new JSONObject(FinalJSonResult);                         JSONObject response = JObject.getJSONObject("response");                          if(response.has("status")) {                              String status = response.getString("status");                             MainAct1.this.finish();                             Intent op = new Intent(MainAct1.this, MainRes1.class);                             op.putExtra("mydata", status);                             op.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);                             op.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);                             op.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);                             op.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);                             startActivity(op);                         }                         else {                             FinalJSonResult = "No JSON data";                         }                     }                     catch (JSONException e) {                          FinalJSonResult = "Your Server ID is Invalid";                      }                  }                 else{                      FinalJSonResult = "User Error";                  }             }             else {                 Toast.makeText(context, sh.getErrorMessage(), Toast.LENGTH_SHORT).show();             }         }         catch (Exception e) {             e.printStackTrace();         }         return null;     }      @Override     protected void onPostExecute(Void aVoid) {         super.onPostExecute(aVoid);          if(FinalJSonResult.equalsIgnoreCase("No JSON data")){              // Your AlertDialog code....          }else if(FinalJSonResult.equalsIgnoreCase("Your Server ID is Invalid")){              // Your AlertDialog code....          }else if(FinalJSonResult.equalsIgnoreCase("User Error")){              // Your AlertDialog code....          }       } } 

Answers 4

AsyncTask has 4 methods i.e. onPreExecute(), doInBackground(Params...), onProgressUpdate(Progress...), onPostExecute(Result).

doInBackground() method is used to execute the task in the background. For any update on UI we use onPostExecute() method, but if you want to update the UI from doInBackground() than please try this

runOnUiThread(new Runnable() {  public void run() {     Toast.makeText(<your class name>.this, "Your message", Toast.LENGTH_SHORT).show();   // or you can use your alert dialog here    } }); 

Answers 5

Use isNull method to check weather json key/value is null or not.Add a try catch block to handle unknown data. You can try below code to achieve this.

try{      JSONObject jsonObject = new JSONObject(RESPONSE_STRING);      JSONObject subJson = jsonObject.getJSONObject("response");      if (subJson.isNull("status")) {         /*Do you work*/       }    } catch (JSONException e) {     Toast.makeText(getApplicationContext(), getString(R.string.something_wrong), Toast.LENGTH_SHORT).show();     e.printStackTrace();   } 

Same way you check for "response" as well.

Answers 6

Create an interface with two functions named 'onSuccessJson(Json json)' and 'onFailure(String error)' and while getting the response check if its json or html like the above code, and pass the respective data to the interface functions. You will get the response where the function is implemented. On 'onFailure(String error)' call the alert dialog, or if success response the call will occur on 'onSuccess(Json json)' you can do further. AsyncTask works like thread, don't call the context related thing in 'doInBackground'

Answers 7

You need add “return Code” in your jsonData. Then you judge if HTTP Status Code equal "200" and “return code” equal "success code"

If You Enjoyed This, Take 5 Seconds To Share It

1 comment:

  1. Hello Admin,

    It is working fine while the app is on fore ground. The location is exact on regular interval. But if the app goes to background, the location is not the same, rather is moved from the previous location even though the device is not moved.

    Regards,
    Thanks

    RITU

    ReplyDelete