Android App无法打开警报对话框

时间:2013-08-19 21:54:01

标签: android android-asynctask android-alertdialog

我正在制作一个需要互联网连接的Android应用程序。当我连接到互联网时,该应用程序工作正常。我想要做的是,如果我没有连接到互联网,它必须显示一个警告对话框,通知用户它需要互联网连接。我正在使用Async任务将数据发送到服务器。异步任务代码是:

protected class SendContacts extends AsyncTask<String,Void,String>
{
    @Override 
    protected String doInBackground(String... str) {

        String contactInfo;
        contactInfo=str[0];

        InputStream is = null;
        String result=new String(); 

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://johnconnor.comuf.com/myphp.php");

        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
            nameValuePairs.add(new BasicNameValuePair("fullInfo", contactInfo));
           //   nameValuePairs.add(new BasicNameValuePair("lat",latitude));
           //   nameValuePairs.add(new BasicNameValuePair("lng",longitude));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response= httpclient.execute(httppost);
            Log.i("SendContacts Successful",response.getStatusLine().toString());
            HttpEntity entity = response.getEntity();
            is = entity.getContent(); 

        } catch (ClientProtocolException e) {
            Log.e("log_tag", "Error in http connection "+e.toString());
        } catch (IOException e) {
                        // When not connected to internet, it reach this catch block.How can i implement alert dialog here so that it can be displayed on main UI thread
            Log.e("log_tag","Error in http connection:"+e.toString());

           }
        try {
            BufferedReader reader =
                new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {
        } 

    result=result.substring(0,result.indexOf('\n'));
    return result ;
}

}

这是我的logcat:

08-19 14:48:15.130: D/ActivityThread(10279): setTargetHeapUtilization:0.25

08-19 14:48:15.130: D/ActivityThread(10279): setTargetHeapIdealFree:8388608

08-19 14:48:15.130: D/ActivityThread(10279): setTargetHeapConcurrentStart:2097152

08-19 14:48:15.220: D/AbsListView(10279): Get MotionRecognitionManager

08-19 14:48:15.490: E/log_tag(10279): Error in http connection:java.net.UnknownHostException: Unable to resolve host "johnconnor.comuf.com": No address associated with hostname

08-19 14:48:15.500: W/dalvikvm(10279): threadid=12: thread exiting with uncaught exception (group=0x41c66438)

08-19 14:48:15.510: W/dalvikvm(10279): threadid=11: thread exiting with uncaught exception (group=0x41c66438)

08-19 14:48:15.510: E/AndroidRuntime(10279): FATAL EXCEPTION: AsyncTask #2

08-19 14:48:15.510: E/AndroidRuntime(10279): java.lang.RuntimeException: An error occured while executing doInBackground()

08-19 14:48:15.510: E/AndroidRuntime(10279):    at android.os.AsyncTask$3.done(AsyncTask.java:299)

08-19 14:48:15.510: E/AndroidRuntime(10279):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)

08-19 14:48:15.510: E/AndroidRuntime(10279):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)

08-19 14:48:15.510: E/AndroidRuntime(10279):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)

08-19 14:48:15.510: E/AndroidRuntime(10279):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)

08-19 14:48:15.510: E/AndroidRuntime(10279):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)

08-19 14:48:15.510: E/AndroidRuntime(10279):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)

08-19 14:48:15.510: E/AndroidRuntime(10279):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)

08-19 14:48:15.510: E/AndroidRuntime(10279):    at java.lang.Thread.run(Thread.java:856)

08-19 14:48:15.510: E/AndroidRuntime(10279): Caused by: java.lang.StringIndexOutOfBoundsException: length=0; regionStart=0; regionLength=-1

08-19 14:48:15.510: E/AndroidRuntime(10279):    at java.lang.String.startEndAndLength(String.java:593)

08-19 14:48:15.510: E/AndroidRuntime(10279):    at java.lang.String.substring(String.java:1474)

08-19 14:48:15.510: E/AndroidRuntime(10279):    at com.example.findmyfriend.DatabaseConnection$RegisterMe.doInBackground(DatabaseConnection.java:121)

08-19 14:48:15.510: E/AndroidRuntime(10279):    at com.example.findmyfriend.DatabaseConnection$RegisterMe.doInBackground(DatabaseConnection.java:1)

08-19 14:48:15.510: E/AndroidRuntime(10279):    at android.os.AsyncTask$2.call(AsyncTask.java:287)

08-19 14:48:15.510: E/AndroidRuntime(10279):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)

08-19 14:48:15.510: E/AndroidRuntime(10279):    ... 5 more

2 个答案:

答案 0 :(得分:0)

你可以做两件事:

Way1:您可以在那里使用runOnUIThread()方法,并在其中包含警报对话框的代码。文档说:It runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.

例如:

Your_Activity_Name.this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                // your stuff to update the UI
                showWaitDialog();

            }
        });

<强> Way2: 您可以做的其他事情(并且是首选)是将Boolean变量传递给onPostExecute。成功时变量true,任何失败时变量false。然后你可以相应地显示Dialog。

答案 1 :(得分:0)

您可以覆盖onProgressUpdate的{​​{1}},它在主UI线程上运行。然后从AsyncTask调用doInBackground来触发它。

publishProgress