我想在android中創建一個簡單的登錄界面,但是當我嘗試運行連接時發生了錯誤。我不知道,爲什麼會發生這種情況?Android中的登錄界面給出錯誤
這裏是我的代碼:
public class MainActivity extends Activity{
String username,password;
HttpClient httpclient;
HttpPost httppost;
HttpResponse response;
HttpEntity httpentity;
ArrayList<NameValuePair> namevaluepairs;
EditText etUser,etPass;
Button bLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUser=(EditText) findViewById(R.id.etUser);
etPass=(EditText) findViewById(R.id.etPass);
bLogin=(Button) findViewById(R.id.bSubmit);
bLogin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
httpclient=new DefaultHttpClient();
httppost=new HttpPost("http://192.168.1.107/php_project/checking.php");
username=etUser.getText().toString();
password=etPass.getText().toString();
try {
namevaluepairs=new ArrayList<NameValuePair>();
namevaluepairs.add(new BasicNameValuePair(username, username));
namevaluepairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(namevaluepairs));
response=httpclient.execute(httppost);
if(response.getStatusLine().getStatusCode()==200){
httpentity=response.getEntity();
if(httpentity!=null){
InputStream inputstream=httpentity.getContent();
JSONObject jsonResponse=new JSONObject(convertStreamToString(inputstream));
String retUser=jsonResponse.getString("user");
String retPass=jsonResponse.getString("pass");
if(username.equals(retUser) && password.equals(retPass)){
SharedPreferences sp=getSharedPreferences("logindetails", 0);
SharedPreferences.Editor spedit=sp.edit();
spedit.putString("user", username);
spedit.putString("pass", password);
spedit.commit();
Toast.makeText(getApplicationContext(), "SUCCESS !", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Inavalid Login details", Toast.LENGTH_LONG).show();
}
}
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Connection error", Toast.LENGTH_LONG).show();
}
}
});
}
private static String convertStreamToString(InputStream is){
BufferedReader reader=new BufferedReader(new InputStreamReader(is));
StringBuilder sb=new StringBuilder();
String line=null;
try {
while((line=reader.readLine())!=null){
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
is.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
return sb.toString();
}
}
任何一個可以幫助我解決這個問題.. 當我在模擬器中運行它,它給我敬酒消息,即「連接錯誤」 ...
我簡直不明白,爲什麼我不能讓它成爲登錄... ???
發表您的logcat – 2014-09-06 09:10:11
logcat的:5月9日至6日:35:48.794:W/System.err的(1564):android.os.NetworkOnMainThreadException 5月9日至6日:35:48.804 :W/System.err(1564):\t at android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145) – 2014-09-06 09:39:03
使用無法在UI線程中執行與互聯網相關的任務.. 使用AsynTask進行調用PHP頁面http:///developer.android.com/reference/android/os/AsyncTask.html – 2014-09-06 12:56:05