如何在没有Internet的情况下处理AsyncTask?

时间:2016-06-25 19:31:25

标签: android android-asynctask

在我的登录页面

当我按下按钮时,应用程序在我离线时崩溃。如何处理?

public class Login extends Activity{

    EditText us,ps;
    String sus,sps,sh1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

     us=(EditText)findViewById(R.id.username);
     ps=(EditText)findViewById(R.id.password);
    Button lgb=(Button)findViewById(R.id.button1);
        lgb.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                sus=us.getText().toString();
                sps=ps.getText().toString();
                SharedPreferences shr=getSharedPreferences("kynum", MODE_WORLD_READABLE);
                SharedPreferences.Editor edd=shr.edit();
                edd.putString("sssnum", sus);
                edd.commit();

                if(sus.equals("")||sps.equals(""))
                {
                    Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
                    return;
                }
                else
                {
                ilog lg =new ilog();
                lg.execute();
                }

            }
        });

    }

    public class ilog extends AsyncTask<Void, Void, Void>
    {
        @Override
        protected Void doInBackground(Void... arg0) {
            // TODO Auto-generated method stub

            try
            {   
                String server = getResources().getString(R.string.server_add);
                DefaultHttpClient h=new DefaultHttpClient();
                ResponseHandler<String> respp=new BasicResponseHandler();
                HttpPost postMethod=new HttpPost(server+"ilogin.php");
                List<NameValuePair>namevaluepairs=new ArrayList<NameValuePair>(2);
                namevaluepairs.add(new BasicNameValuePair("Username", sus));
                namevaluepairs.add(new BasicNameValuePair("Password", sps));
                postMethod.setEntity(new UrlEncodedFormEntity(namevaluepairs));
                sh1=h.execute(postMethod,respp);

            }catch(Exception e)
            {
                System.out.println("Error:"+e);
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub

            if(sh1.contains("success"))
            {
                Toast.makeText(getApplicationContext(), "Successfully Logged in.", Toast.LENGTH_LONG).show();
                Intent i=new Intent(getApplicationContext(), MainActivity.class);
                startActivity(i);

            }
            else
            {
                Toast.makeText(getApplicationContext(), "Usernmae or Password error.", Toast.LENGTH_SHORT).show();
                Toast.makeText(getApplicationContext(), "New User? Register First", Toast.LENGTH_LONG).show();


            }
            super.onPostExecute(result);



        }

    }




}

我也尝试了解决这个问题的方法,但每次崩溃时我的日志猫都是

06-26 00:52:30.020: I/System.out(9732): Error:java.net.UnknownHostException: Unable to resolve host "equipz.orgfree.com": No address associated with hostname
06-26 00:52:30.020: W/System.err(9732): java.net.UnknownHostException: Unable to resolve host "equipz.orgfree.com": No address associated with hostname
06-26 00:52:30.022: W/System.err(9732):     at java.net.InetAddress.lookupHostByName(InetAddress.java:457)
06-26 00:52:30.022: W/System.err(9732):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
06-26 00:52:30.022: W/System.err(9732):     at java.net.InetAddress.getAllByName(InetAddress.java:215)
06-26 00:52:30.022: W/System.err(9732):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:142)
06-26 00:52:30.022: W/System.err(9732):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:169)
06-26 00:52:30.022: W/System.err(9732):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:124)
06-26 00:52:30.022: W/System.err(9732):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:365)
06-26 00:52:30.022: W/System.err(9732):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:560)
06-26 00:52:30.022: W/System.err(9732):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:658)
06-26 00:52:30.023: W/System.err(9732):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:632)
06-26 00:52:30.023: W/System.err(9732):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:621)
06-26 00:52:30.023: W/System.err(9732):     at com.hackbal.custmrmgmt.Login$ilog.doInBackground(Login.java:89)
06-26 00:52:30.023: W/System.err(9732):     at com.hackbal.custmrmgmt.Login$ilog.doInBackground(Login.java:1)
06-26 00:52:30.023: W/System.err(9732):     at android.os.AsyncTask$2.call(AsyncTask.java:292)
06-26 00:52:30.023: W/System.err(9732):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
06-26 00:52:30.023: W/System.err(9732):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
06-26 00:52:30.023: W/System.err(9732):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
06-26 00:52:30.023: W/System.err(9732):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
06-26 00:52:30.023: W/System.err(9732):     at java.lang.Thread.run(Thread.java:818)
06-26 00:52:30.023: W/System.err(9732): Caused by: android.system.GaiException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)
06-26 00:52:30.023: W/System.err(9732):     at libcore.io.Posix.android_getaddrinfo(Native Method)
06-26 00:52:30.023: W/System.err(9732):     at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:55)
06-26 00:52:30.023: W/System.err(9732):     at java.net.InetAddress.lookupHostByName(InetAddress.java:438)
06-26 00:52:30.023: W/System.err(9732):     ... 18 more
06-26 00:52:30.044: E/AndroidRuntime(9732): FATAL EXCEPTION: AsyncTask #5
06-26 00:52:30.044: E/AndroidRuntime(9732): Process: com.hackbal.custmrmgmt, PID: 9732
06-26 00:52:30.044: E/AndroidRuntime(9732): java.lang.RuntimeException: An error occured while executing doInBackground()
06-26 00:52:30.044: E/AndroidRuntime(9732):     at android.os.AsyncTask$3.done(AsyncTask.java:304)
06-26 00:52:30.044: E/AndroidRuntime(9732):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
06-26 00:52:30.044: E/AndroidRuntime(9732):     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
06-26 00:52:30.044: E/AndroidRuntime(9732):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
06-26 00:52:30.044: E/AndroidRuntime(9732):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
06-26 00:52:30.044: E/AndroidRuntime(9732):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
06-26 00:52:30.044: E/AndroidRuntime(9732):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
06-26 00:52:30.044: E/AndroidRuntime(9732):     at java.lang.Thread.run(Thread.java:818)
06-26 00:52:30.044: E/AndroidRuntime(9732): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
06-26 00:52:30.044: E/AndroidRuntime(9732):     at android.os.Handler.<init>(Handler.java:200)
06-26 00:52:30.044: E/AndroidRuntime(9732):     at android.os.Handler.<init>(Handler.java:114)
06-26 00:52:30.044: E/AndroidRuntime(9732):     at android.widget.Toast$TN.<init>(Toast.java:344)
06-26 00:52:30.044: E/AndroidRuntime(9732):     at android.widget.Toast.<init>(Toast.java:100)
06-26 00:52:30.044: E/AndroidRuntime(9732):     at android.widget.Toast.makeText(Toast.java:258)
06-26 00:52:30.044: E/AndroidRuntime(9732):     at com.hackbal.custmrmgmt.Login$ilog.doInBackground(Login.java:95)
06-26 00:52:30.044: E/AndroidRuntime(9732):     at com.hackbal.custmrmgmt.Login$ilog.doInBackground(Login.java:1)
06-26 00:52:30.044: E/AndroidRuntime(9732):     at android.os.AsyncTask$2.call(AsyncTask.java:292)
06-26 00:52:30.044: E/AndroidRuntime(9732):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
06-26 00:52:30.044: E/AndroidRuntime(9732):     ... 4 more
06-26 00:52:32.110: I/Process(9732): Sending signal. PID: 9732 SIG: 9

我想要一个Toast Message。什么是错误,以及如何删除它?

3 个答案:

答案 0 :(得分:0)

您可以注册广播接收器,它可以监听&#39;改变网络状态&#39;事件。如果在处理http请求时发生,请保存此事实并稍后重试

答案 1 :(得分:0)

正如@Alex所说,您可以在尝试连接服务器之前检查网络可用性。

就像,在这里我检查了网络可用性并显示“无连接”snackbar

private boolean isNetworkAvailable() {

getActivity().runOnUiThread(new Runnable() {
    public void run() {
        // Update UI here when network is available.

        ConnectivityManager connectivityManager
                = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        if (!(activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting())) {

            Snackbar snackbar = Snackbar
                    .make(coordinatorLayout, "No internet connection!", Snackbar.LENGTH_INDEFINITE)
                    .setAction("RETRY", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            isNetworkAvailable();
                        }
                    });
            View sbView = snackbar.getView();
            snackbar.setActionTextColor(Color.WHITE);
            sbView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.snackbar_back_color2));
            TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
            //textView.setTextColor(Color.YELLOW);
            snackbar.show();

        }
    }
});

return (activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting());

}

答案 2 :(得分:0)

在我看来,您将网络连接的日志消息与与崩溃相关的日志消息混淆。

未能DefaultHttpClient.execute(抛出仅在日志中打印处理的异常)后,if中的onPostExecute语句会在显示Toast时导致崩溃。< / p>

确保使用右侧Context从右侧线程调用toast。