我跟着this来阅读android
中的JSON数据那边我将结果数据传递给另一个活动
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();
}
}
这是我的JSON数据
{"response":{"status":"Active"}}
或
{"response":{"status":"Active:4 in stock"}}
所以现在我面临着
的问题1.NonJSON 有时由于服务器错误而未收到json数据
或者它会显示一些HTML标题......
我需要数据处理它可以任何人建议我......在这种情况下
和
2.Empty JSON数据有时候结果可能是空的
{"response":{"status":""}}
或
{"response":{}}
任何人都可以建议我如何处理我已经发出警报的那些种类但它不起作用。
现在我正在处理这两种数据,但有时我会变空
更新
对于有效的JSON数据,它在文本视图中的下一个活动/页面中显示结果...
有效的JSON数据{"response":{"status":"Active"}}
或{"response":{"status":"Please set the data."}}
我在下一页显示结果...
但有时我会获得无效的JSON数据,例如{"response":{"status":}}
或仅包含欢迎文字的HTML页面...或找不到OOps页面...
所以我想处理它们,,,如果我得到无效的JSON数据我想向用户显示警报....这样我正在尝试但是它不工作 请帮我这个类型
答案 0 :(得分:2)
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()
仅在主UI线程以外的其他线程上执行。onPostExecute
。ProcessJSON
类中使用FinalJSonResult
字符串来处理onPostExecute()中的不同情况。ProcessJSON 类
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....
}
}
}
答案 1 :(得分:1)
请试试这个
if(response.has("status")) {
// Key found in Response JsonObject
String status = response.getString("status");
} else {
//Status Key not found in Response JsonObject
}
答案 2 :(得分:1)
我建议使用像Gson这样的库。并通过try / catch&amp; JsonSyntaxException将验证数据。 但是bug的原因是数据的形状。 在服务器端重写json数据的形状。
答案 3 :(得分:1)
AsyncTask有4个方法,即onPreExecute(),doInBackground(Params ...),onProgressUpdate(Progress ...),onPostExecute(Result)。
doInBackground()方法用于在后台执行任务。对于UI上的任何更新,我们使用onPostExecute()方法,但是如果您想要从doInBackground()更新UI而不是试试这个
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
}
});
对于 JSON ,您可以尝试以下代码:
if (sh.getResponseCode() == 200) {
if(response.has("status")) {
if (!response.isNull("status")){
String status = response.getString("status");
}else{
//Your alert/toast by using runOnUiThread(new Runnable() {...}
}
}else{
//Your alert/toast by using runOnUiThread(new Runnable() {...}
}
}else{
//Your alert/toast by using runOnUiThread(new Runnable() {...}
}
我希望此代码可以帮助您
答案 4 :(得分:1)
您需要在jsonData中添加“return Code”。然后判断HTTP状态码是否等于&#34; 200&#34;和“返回代码”相等&#34;成功代码&#34;
答案 5 :(得分:0)
使用isNull方法检查天气json键/值是否为null。添加try catch块来处理未知数据。您可以尝试以下代码来实现此目的。
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();
}
同样检查“响应”。
答案 6 :(得分:0)
使用名为&#39; onSuccessJson(Json json)&#39;的两个函数创建一个接口。和&#39; onFailure(字符串错误)&#39;并且在获取响应时检查其json或html是否与上面的代码一样,并将相应的数据传递给接口函数。您将获得实现该功能的响应。 On&#39; onFailure(字符串错误)&#39;调用警报对话框,或者如果成功响应,调用将在&#39; onSuccess(Json json)&#39;你可以做得更远。 AsyncTask就像线程一样工作,不要在&#39; doInBackground&#39;中调用与上下文相关的东西。