如何在android中断开网络时避免应用程序没有响应

时间:2012-04-13 09:40:25

标签: android

我创建登录页面。此登录页面从服务器数据库验证。如果可用,则表示如果单击登录按钮表示它正常工作。如果我禁用网络然后单击登录按钮意味着它显示错误应用程序没有响应..如何使用我的代码避免此错误

      i try this code
          login.setOnClickListener(new View.OnClickListener()
    {

        public void onClick(View v)
        {
            name = username.getText().toString();
            pass = password.getText().toString();
            String Str_check2 = app_preferences.getString("checked", "no");
            if(Str_check2.equals("yes"))
            {
                SharedPreferences.Editor editor = app_preferences.edit();
                editor.putString("username", name);
                editor.putString("password", pass);
                 editor.commit();
            }
            if(name.equals("") || pass.equals(""))
            {
                 Toast.makeText(Main.this, "Please Enter Username and Password", Toast.LENGTH_LONG).show();
            }

            else

            try {
                httpclient = new DefaultHttpClient();
                httppost = new HttpPost("url/login.php");
                // Add your data
                nameValuePairs = new ArrayList<NameValuePair>(2);
               nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
                nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // Execute HTTP Post Request
                response = httpclient.execute(httppost);
                inputStream = response.getEntity().getContent();

                data = new byte[256];

                buffer = new StringBuffer();
                int len = 0;
                while (-1 != (len = inputStream.read(data)) )
                {
                    buffer.append(new String(data, 0, len));
                }

                inputStream.close();
            }

            catch (IOException e) {
                 System.out.println(e);

                 //alertDialog.cancel();

            }
            if(buffer.charAt(0)=='Y')
            {

                Intent intent=new Intent(getApplicationContext(),another.class);
                startActivity(intent);
            }
            else
            {
                 System.out.println("Invalid username and password")
            }         

        }
    });

3 个答案:

答案 0 :(得分:1)

首先,您不应该在主线程中执行您的网络任务,这似乎就像您在OnClick中所做的那样。

为避免连接挂起,您需要设置连接超时。为了便于使用http操作,我已经在github中组合了一个http库,您可以使用此代码作为示例引用或将其用作库

https://github.com/nareshsvs/android-libraries

答案 1 :(得分:0)

在这里添加一个空检查..

response = httpclient.execute(httppost);

    if(response != null){
    inputStream = response.getEntity().getContent();

                    data = new byte[256];

因为当服务器连接失败时execute()返回null并且您需要查看并确保它不为空...就像Naresh所说不要在MainThtread中进行服务器通信..请参阅AsyncTasks方便..

答案 2 :(得分:0)

同意Naresh不要使用主线程来完成您的每项任务。使用ServiceAsyncTask执行长时间运行的网络任务。