无法使用模拟器在wampserver localhost中使用android连接mysql

时间:2014-10-20 09:07:28

标签: php android mysql

我的数据库名称是mobildb,它包含一个表androidlogin。它包含id整数
  autoincrement主键,用户文本,密码文本作为其field.my表包含一些登录
 detail.iwant用table.my中的数据检查在android表单中输入的用户名和密码  php文件名是login.php保存在wamp / www /。我不知道给http链接。我测试过   这段代码与我的膝盖ipaddress,127.0.0.1,10.0.2.2,12.34.56.78:80,0.0.0.0:80
  ,127.0.0.1:80,10.0.2.2:80。请帮帮我吗?   我的php文件是

     <?php
     $dbhost="localhost";
     $db="mobiledb";
     $pass="";
     $dbuser="root";
     $con=mysqli_connect("localhost","root","","mobiledb") or die("connection error");
     //mysqli_select_db($con,"mobiledb") or die("database not exists");
     $username=$_POST["username"];
     $password=$_POST["password"];
     $query=mysqli_query($con,"select * from androidlogin where user='$username' AND 
                                                    password='$password'");
     $num=mysqli_num_rows($query);
     if($num==1){
     while($list=mysqli_fetch_array($query) ){
     $output=$list;}
     echo json_encode($output);
      }
     mysqli_close($con);
     ?>

我的活动只包含2个用户名和密码的edittext.a登录按钮

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 android:paddingBottom="@dimen/activity_vertical_margin"
 tools:context=".MyActivity">


 <EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/txtuser"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

 <EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:inputType="textPassword"
    android:ems="10"
    android:id="@+id/pswd"
    android:layout_below="@+id/txtuser"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

 <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Login"
    android:id="@+id/btn"
    android:layout_below="@id/pswd"
    android:layout_centerHorizontal="true"
    android:onClick="btnClick" />
 </RelativeLayout>

我唯一的班级文件是

 package com.example.iyas.loginapp;

  import android.app.Activity;
  import android.os.Bundle;
 import android.view.Menu;
  import android.view.MenuItem;
 import android.view.View;
 import android.widget.Button;
 import android.widget.EditText;
 import android.widget.Toast;

 import org.apache.http.HttpEntity;
 import org.apache.http.HttpResponse;
 import org.apache.http.client.HttpClient;
 import org.apache.http.client.entity.UrlEncodedFormEntity;
 import org.apache.http.client.methods.HttpPost;
 import org.apache.http.impl.client.DefaultHttpClient;
 import org.apache.http.message.BasicNameValuePair;
 import org.json.JSONException;
 import org.json.JSONObject;

 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.util.ArrayList;


  public class MyActivity extends Activity {
String username,password;
EditText user;
EditText pass;
Button btn;
HttpClient httpclient;
HttpPost httppost;
HttpResponse httpresponse;
HttpEntity entity;


ArrayList namevaluepairs;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);
    initialise();
 }
 private void initialise()
 {
    user=(EditText)findViewById(R.id.txtuser);
    pass=(EditText)findViewById(R.id.pswd);
    btn=(Button)findViewById(R.id.btn);

 }
 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 e){
           e.printStackTrace();         }
   }return sb.toString();

   }

 public void btnClick(View v)
  {
 httpclient=new DefaultHttpClient();
 httppost=new HttpPost("http://10.0.2.2:80/login.php");
 username=user.getText().toString();
 password=pass.getText().toString();
 Toast.makeText(getApplicationContext(),"before try",Toast.LENGTH_SHORT).show();
 try{
     namevaluepairs=new ArrayList();
     Toast.makeText(getApplicationContext(),"after try",Toast.LENGTH_SHORT).show();
    namevaluepairs.add(new BasicNameValuePair("username",username));
     namevaluepairs.add(new BasicNameValuePair("password",password));
 Toast.makeText(getApplicationContext(),"after name",Toast.LENGTH_SHORT).show();
          httppost.setEntity(new UrlEncodedFormEntity(namevaluepairs));
     httpresponse=httpclient.execute(httppost);
     if(httpresponse.getStatusLine().getStatusCode()==200){
         entity=httpresponse.getEntity();
         if(entity!=null){
             InputStream instream=entity.getContent();
            JSONObject jsonresponse=new JSONObject(convertStreamToString(instream));
             String retUser= jsonresponse.getString("user");
             String retPass=jsonresponse.getString("password");
             if(username.equals(retUser)&&password.equals(retPass)) {
                Toast.makeText(getApplicationContext(), "success", Toast.LENGTH_SHORT).show();
             }else{
     Toast.makeText(getApplicationContext(),"invalid login",Toast.LENGTH_SHORT).show();}
         }
     }
     }catch(IOException e) {
     e.printStackTrace();


     Toast.makeText(getApplicationContext(),"connection error",Toast.LENGTH_SHORT).show();} 
    catch(JSONException e)
    {  e.printStackTrace(); 

  }
  }

 }

清单文件:

 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.example.iyas.loginapp" >

 <application 
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MyActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
 </application>
 <uses-permission android:name="android.permission.INTERNET"/>
 </manifest>


 my error in logcat after login button clicks:


10-20 04:22:05.593    7672-7672/com.example.iyas.loginapp E/AndroidRuntime﹕ 
       FATAL EXCEPTION: main
               Process: com.example.iyas.loginapp, PID: 7672
             java.lang.IllegalStateException: Could not execute method of the activity
        at android.view.View$1.onClick(View.java:3970)
        at android.view.View.performClick(View.java:4598)
        at android.view.View$PerformClick.run(View.java:19268)
        at android.os.Handler.handleCallback(Handler.java:738)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5070)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:836)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:631)
     Caused by: java.lang.reflect.InvocationTargetException

   Caused by: android.os.NetworkOnMainThreadException
不幸的是,

和app停止了

2 个答案:

答案 0 :(得分:0)

首先确保您拥有互联网权限

<uses-permission android:name="android.permission.INTERNET"/>

然后在线程中放入任何长操作,调用web方法是长操作,所以把它放在Thread

Thread thread = new Thread(new Runnable(){
    @Override
    public void run() {
        try {
            //Your web calling goes here


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});




thread.start(); 

这将起作用

但您也可以尝试将此代码添加到您的班级,以确保每件事情都很好

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy); 

答案 1 :(得分:0)

您可以使用AsyncTask来调用与网络相关的请求。在AsyncTask的doInBackground方法中发出请求。如果您在主线程上执行网络相关请求,则抛出NetworkOnMainThreadException异常