0

I am trying to display a toast in a new thread. I researched into it and apparently I need to run toast in the UI thread. I need this new thread because Android doesn't want me running HTTPclient in the main thread. I can deal with a handler but my problem is, I can't figure a way to get the MainActivity context to the class I am in. It extends SherlockFragment and the constructor probably won't allow it to override.

This is my runnable as of the moment

new Thread(new Runnable() {
    @Override
    public void run() {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("https://www.example.com/API/events/add.php");

        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(16);
            httppost.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

            // Adding data
            nameValuePairs.add(new BasicNameValuePair("token", "admin"));
            nameValuePairs.add(new BasicNameValuePair("eventTitle", title));
            nameValuePairs.add(new BasicNameValuePair("categories", Integer.toString(catId)));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

            String status = EntityUtils.toString(response.getEntity());
            JSONObject jObj = null;

            try {
                jObj = new JSONObject(status);
            } catch (JSONException e) {
                Log.e(MainActivity.class.getName(), "Error Parsing Data: " + e.toString());
            }

            try {
                //Want to toast this string here, jObj.getString("status"))
            } catch (JSONException e) {
                Log.e(MainActivity.class.getName(), "Error Reading Status String: " + e.toString());
            }

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    }
}).start();

Any recommendations to as what I may do?

4

2 回答 2

1

Please refer to this question..

It shows how to let any part of your application access the Context in a static manner.

[Static way to get 'Context' on Android? ]

Why is it not built into the API ? we'll never know..

HTH

于 2013-03-31T01:18:07.193 回答
0

For a fragment activity, in the future you should know you can do Fragment.this.getActivity() to get the Activity instance and thus the context. This will help you with other Activity only methods you will need.

于 2013-03-31T09:37:09.503 回答