2012-04-13 24 views
0

断开我创建登录页面。这个登录页面从服务器数据库验证。如果点击登录按钮意味着它可以正常工作,net是可用的。如果我禁用网然后点击登录按钮意味着它显示错误的应用程序没有响应。如何使用我的代码如何避免应用程序没有响应而网络在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") 
      }   

     } 
    }); 

回答

0

在这里补充一个空的检查,以避免这个错误..

response = httpclient.execute(httppost); 

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

        data = new byte[256]; 

,因为当服务器连接失败​​返回null,你需要看到,并确保其不为空..和就像纳雷什说不做服务器通信在MainThtread ..看到AsyncTasks这会得心应手..

+0

我在哪里可以写这行,如果(响应!= NULL){ – Vinoth 2012-04-13 09:54:06

+0

@Vinoth ..看到我的编辑.. – ngesh 2012-04-13 09:56:43

+0

我使用乌尔编辑代码,但同样的错误出现..我能做些什么,请告诉我 – Vinoth 2012-04-13 10:05:09

1

第一件事情,你不应该做哟你在主线程中的网络任务,这看起来像你在做的OnClick。

为避免连接挂起,您需要设置连接超时。易于使用HTTP操作的我已经把一个HTTP库在github上,您可以使用此代码为您的样品参考或使用它作为一个库

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

0

同意纳雷什不使用主线程你的每一个任务。使用ServiceAsyncTask执行长时间运行的网络任务。

+0

我该如何解决我的问题请告诉我 – Vinoth 2012-04-13 10:05:50

+0

这是一个示例... http://stackoverflow.com/questions/2205128/how-to-create-http-connection-using-asynctask-class – 2012-04-13 10:13:52

相关问题