无法使用php连接mysql数据库

时间:2014-03-23 09:35:42

标签: php android mysql json

我正在尝试连接我的Android应用程序,该应用程序使用php连接到数据库的Login页面。它正在连接到DB。但它没有从表中检索所有颜色。相反,只取出两个颜色。以下是代码

    package com.example.hell;
    public class MainActivity extends Activity {
    Button btn;
    EditText ed;
     EditText ed1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        final
    StrictMode.ThreadPolicy policy = new        StrictMode.ThreadPolicy.Builder().permitAll().build();

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ed=(EditText)findViewById(R.id.editText1);
        ed1= (EditText)findViewById(R.id.editText2);
        btn=(Button)findViewById(R.id.button1);

        btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
             String result = null;
             InputStream is = null;
             EditText editText = (EditText)findViewById(R.id.editText1);
             String v1 = editText.getText().toString();
             EditText editText1 = (EditText)findViewById(R.id.editText2);
             String v2 = editText1.getText().toString();

             ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

             nameValuePairs.add(new BasicNameValuePair("id",v1));
             nameValuePairs.add(new BasicNameValuePair("password",v2));
             StrictMode.setThreadPolicy(policy);
             try{
                 HttpClient httpclient=new DefaultHttpClient();
                 HttpPost httppost=new HttpPost("http://10.0.2.2/login.php");
                 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                 HttpResponse response = httpclient.execute(httppost); 
                 HttpEntity entity = response.getEntity();
                 is = entity.getContent();

                 Log.e("log_tag", "connection success ");
                 Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
             }
             catch(Exception e)
             {
                 Log.e("log_tag", "Error in http connection "+e.toString());
                  Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
             }
             try{
                 BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                 StringBuilder sb = new StringBuilder();
                 String line = null;
                 while ((line = reader.readLine()) != null) 
                 {
                         sb.append(line + "\n");
                         Intent i = new Intent(getBaseContext(),Menu.class);
                         startActivity(i);
                 }

                 is.close();
                 result=sb.toString();
         }
         catch(Exception e)
         {
                Log.e("log_tag", "Error converting result "+e.toString());
            }

             try{


                JSONObject object = new JSONObject(result);
                 String ch=object.getString("re");
                 Toast.makeText(getApplicationContext(), ch, Toast.LENGTH_SHORT).show();

                 if(ch.equals("success"))
                 {

                   Intent i=new Intent("com.example.hell.MainActivity");
                   startActivity(i);
                 }


                 else
                 {

                     Toast.makeText(getApplicationContext(), "Record is not available.. Enter valid number", Toast.LENGTH_SHORT).show();

                 }


         }
         catch(JSONException e)
         {
                 Log.e("log_tag", "Error parsing data "+e.toString());
                 Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
         }  


        }
        });
      }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

请帮我解决问题。

这是登录表单的PHP代码

<?php
session_start();
$id=$_REQUEST["id"];
$password=$_REQUEST["password"];
if($id==NULL&& $password==NULL)
 {
    $r["re"]="Enter the Registered Id and password!!!";
                 print(json_encode($r));
                die('Could not connect: ' . mysql_error());
 }
 else
 {
  $connect=mysql_connect("localhost","root","") or die("couldn't connect");
  mysql_select_db("android") or die("couldn't find database");
  $query=mysql_query("SELECT * From profile WHERE username='$email'");
  $numrows=mysql_num_rows($query);
   while($rows=mysql_fetch_assoc($query))
    {
      $dbusername=$rows['id'];
      $dbpassword=$rows['password'];
    }
      if($id==$dbusername && $password==$dbpassword)
      {
   //  echo("you're in! <a href='member.php'>click</a>here to enter");
     //   $_SESSION ['email']=$dbusername;
     $r["re"]="success";
     print(json_encode($r));
      }
      else
      {
         $r["re"]="fail";
     print(json_encode($r));
      }
   }


?>

我的logcat显示以下错误。

03-23 05:50:37.970: E/AndroidRuntime(904): FATAL EXCEPTION: main
03-23 05:50:37.970: E/AndroidRuntime(904): Process: com.example.hell, PID: 904
03-23 05:50:37.970: E/AndroidRuntime(904): java.lang.NullPointerException
03-23 05:50:37.970: E/AndroidRuntime(904):  at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
03-23 05:50:37.970: E/AndroidRuntime(904):  at org.json.JSONTokener.nextValue(JSONTokener.java:94)
03-23 05:50:37.970: E/AndroidRuntime(904):  at org.json.JSONObject.<init>(JSONObject.java:155)
03-23 05:50:37.970: E/AndroidRuntime(904):  at org.json.JSONObject.<init>(JSONObject.java:172)
03-23 05:50:37.970: E/AndroidRuntime(904):  at com.example.hell.MainActivity$1.onClick(MainActivity.java:100)
03-23 05:50:37.970: E/AndroidRuntime(904):  at android.view.View.performClick(View.java:4424)
03-23 05:50:37.970: E/AndroidRuntime(904):  at android.view.View$PerformClick.run(View.java:18383)
03-23 05:50:37.970: E/AndroidRuntime(904):  at android.os.Handler.handleCallback(Handler.java:733)
03-23 05:50:37.970: E/AndroidRuntime(904):  at android.os.Handler.dispatchMessage(Handler.java:95)
03-23 05:50:37.970: E/AndroidRuntime(904):  at android.os.Looper.loop(Looper.java:137)
03-23 05:50:37.970: E/AndroidRuntime(904):  at android.app.ActivityThread.main(ActivityThread.java:4998)
03-23 05:50:37.970: E/AndroidRuntime(904):  at java.lang.reflect.Method.invokeNative(Native Method)
03-23 05:50:37.970: E/AndroidRuntime(904):  at java.lang.reflect.Method.invoke(Method.java:515)
03-23 05:50:37.970: E/AndroidRuntime(904):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
03-23 05:50:37.970: E/AndroidRuntime(904):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
03-23 05:50:37.970: E/AndroidRuntime(904):  at dalvik.system.NativeStart.main(Native Method)


thank u...but it shows stop working after click submit button

谢谢你......但是点击提交按钮后显示停止工作 我需要检索要在android模拟器上显示的数据

package com.example.main; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.text.NumberFormat; import java.util.ArrayList;

import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; 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 android.annotation.SuppressLint; import android.app.Activity; import android.os.Bundle; import android.os.StrictMode; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast;

@SuppressLint(“NewApi”)public class select extends Activity {     @SuppressLint(“NewApi”)StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()。permitAll()。build();

 @SuppressLint("NewApi")    public void onCreate(Bundle savedInstanceState)
 {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.select);

        Button button = (Button) findViewById(R.id.button1);
        StrictMode.setThreadPolicy(policy); 

        button.setOnClickListener(new View.OnClickListener()
        {
        public void onClick(View view)
          {
             String result = null;
            InputStream is = null;
            EditText editText = (EditText)findViewById(R.id.e1);
            String v1 = editText.getText().toString();
            EditText editText1 = (EditText)findViewById(R.id.e2);

            EditText editText2 = (EditText)findViewById(R.id.e3);

      ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

            nameValuePairs.add(new BasicNameValuePair("f1",v1));
                try
                {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("http://10.0.2.2/select.php");
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost); 
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();

                    Log.e("log_tag", "connection success ");


                }
            catch(Exception e)
                {
                    Log.e("log_tag", "Error in http connection "+e.toString());
                    Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();

                }
            //convert response to string
                try{
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) 
                    {
                            sb.append(line + "\n");

                    }
                    is.close();

                    result=sb.toString();
                }
                catch(Exception e)
                {
                   Log.e("log_tag", "Error converting result "+e.toString());

                Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();

                }

            //parse json data
            try{


                    JSONObject object = new JSONObject(result);
                    String ch=object.getString("re");
                    if(ch.equals("success"))
                    {

                       JSONObject no = object.getJSONObject("0");
                    String w= no.getString("f2");
                    long e=no.getLong("f3");

                    editText1.setText(w);
                   String myString = NumberFormat.getInstance().format(e);


                    editText2.setText(myString);

                      }


                    else
                    {

                        Toast.makeText(getApplicationContext(), "Record is not available.. Enter valid number", Toast.LENGTH_SHORT).show();

                    }


            }
            catch(JSONException e)
            {
                    Log.e("log_tag", "Error parsing data "+e.toString());
                    Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
            }


       }
       });



 }

}

1 个答案:

答案 0 :(得分:0)

行。我在PHP代码中看到你只返回$ r给客户端,所以它不包含任何有关配置文件的东西。
所以你应该返回$ row(编码成json)