简体   繁体   English

Android Studio应用向用户显示错误消息

[英]Android Studio app show the error message to user

guys I have a problem with implement error handling in my application. 伙计们,我在应用程序中实现错误处理时遇到问题。 I want to display the error message to the user of my application when the response code from rest is not 200. In other words: If the connection is wrong, I want to display the message, that the user have to check his internet connection and try again. 当其余的响应代码不是200时,我想向我的应用程序用户显示错误消息。换句话说:如果连接错误,我想显示该消息,即用户必须检查其Internet连接,然后再试一次。 If everything is fine I want to do everything as usual so load the content. 如果一切正常,我想照常做所有事情,因此加载内容。

I write something like this: 我写这样的东西:

Toast errorToast = Toast.makeText(NewsActivity.this, "Error, pls chech your internet connection and try again!", Toast.LENGTH_SHORT);
errorToast.show();

and this: 和这个:

if(response.getStatusLine().getStatusCode() == 200){}

But i don't know If this is good code and where should I insert it. 但是我不知道这是否是好的代码,我应该在哪里插入。 I will be very grateful for your help and advice. 感谢您的帮助和建议。

This is this code: 这是这段代码:

public class NewsActivity extends Activity {

private static final String URL = "http://10.0.2.2:8083/rest/aktualnosci";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_news);

    new FetchItems().execute();
}

private class FetchItems extends AsyncTask<String, Void, JSONArray> {

    protected JSONArray doInBackground(String... params) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(URL);
        httpget.setHeader("Content-type", "application/json");

        JSONArray json = new JSONArray();

        try {
            HttpResponse response = httpclient.execute(httpget);
                json = new JSONArray(EntityUtils.toString(response.getEntity()));
                return json;
            }

        } catch (Exception e) {
            Log.v("Błędne wczytanie", e.getMessage());
        }

        return json;
    }

    protected void onPostExecute(JSONArray result) {
        ListView lst = (ListView) findViewById(R.id.aktualnosci_list);
        ArrayList<String> listItems = new ArrayList<String>();
        String contentToEdit;
        String titleContainer;
        TextView newsHeaderTextView = null;
        for (int i = 0; i < result.length(); i++) {
            try {
                titleContainer = result.getJSONObject(i).getString("title").toString();
                listItems.add(titleContainer);
                contentToEdit=result.getJSONObject(i).getString("body").toString();
                contentToEdit= Html.fromHtml(contentToEdit).toString();
                listItems.add(contentToEdit);

            } catch (Exception e) {
                Log.v("Błędne wczytanie1", e.getMessage());
            }
        }

        ArrayAdapter ad = new ArrayAdapter(NewsActivity.this, android.R.layout.simple_list_item_1, listItems);
        lst.setAdapter(ad);
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

} }

You can add this in doInBackground method. 您可以在doInBackground方法中添加它。

   runOnUiThread(new Runnable() {
                        public void run() {
                            if (response.getStatusLine().getStatusCode() != 200) {
                                Toast errorToast = Toast.makeText(NewsActivity.this, "Error, pls chech your internet connection and try again!", Toast.LENGTH_SHORT);
                                errorToast.show();
                            }

                        }
                    });

/* I thought Your Code Working Fine Made Some Changes As Per Need */ / *我认为您的代码可以按需进行一些更改* /

public class NewsActivity extends Activity {

private static final String URL = "http://10.0.2.2:8083/rest/aktualnosci";
String jsonArrayString = "";
String message = "Error, pls check your internet connection and try again!";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_news);

    new FetchItems().execute(this);
}

private class FetchItems extends AsyncTask<Context,Void,String>{
    Context temp;


    @Override
    protected String doInBackground(Context... params) {
        temp = params[0];

        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(URL);
        httpget.setHeader("Content-type", "application/json");

        JSONArray json = new JSONArray();

        try {
            HttpResponse response = httpclient.execute(httpget);

            if(response.getStatusLine().getStatusCode() == 200) {
                json = new JSONArray(EntityUtils.toString(response.getEntity()));
                jsonArrayString += json.toString();
                return jsonArrayString;
            }
            }
            catch (Exception e) {
                Log.v("Błędne wczytanie", e.getMessage());
            }
    return message;
    }

    @Override
    protected void onPostExecute(String s) {
        ListView lst = (ListView) findViewById(R.id.aktualnosci_list);
        ArrayList<String> listItems = new ArrayList<String>();
        String contentToEdit;
        String titleContainer;
        TextView newsHeaderTextView = null;

        if(!message.equals(s))
        {
            JSONArray result = null;
            try {
                result = new JSONArray(s);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < result.length(); i++) {
            try {
                titleContainer = result.getJSONObject(i).getString("title").toString();
                listItems.add(titleContainer);
                contentToEdit=result.getJSONObject(i).getString("body").toString();
                contentToEdit= Html.fromHtml(contentToEdit).toString();
                listItems.add(contentToEdit);

            } catch (Exception e) {
                Log.v("Błędne wczytanie1", e.getMessage());
            }
        }

        ArrayAdapter ad = new ArrayAdapter(NewsActivity.this, android.R.layout.simple_list_item_1, listItems);
        lst.setAdapter(ad);
    }
        else
        {
            Toast.makeText(temp,message,Toast.LENGTH_LONG).show();
        }

    }
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM