【问题标题】:unable to connect with mysql database using php无法使用php连接mysql数据库
【发布时间】:2014-04-30 14:41:55
【问题描述】:

我正在尝试连接我的 android 应用程序,该应用程序的登录页面使用 php 连接到数据库。它正在连接到数据库。但它不是从表中检索所有列。相反,仅获取两个列。以下是代码

    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 模拟器上显示

包 com.example.main;导入 java.io.BufferedReader;导入 java.io.InputStream;导入 java.io.InputStreamReader;导入 java.text.NumberFormat;导入 java.util.ArrayList;

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

导入 android.annotation.SuppressLint;导入android.app.Activity;导入android.os.Bundle;导入android.os.StrictMode;导入android.util.Log;导入android.view.View;导入android.widget.Button;导入 android.widget.EditText;导入android.widget.Toast;

@SuppressLint("NewApi") 公共类选择扩展 Activity { @SuppressLint("NewApi") StrictMode.ThreadPolicy 策略 = 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();
            }


       }
       });



 }

}

【问题讨论】:

  • 这是关于 php 代码的。所以你必须显示该信息
  • 谢谢。我刚刚添加了php代码。
  • 谢谢你...但点击提交按钮后显示停止工作
  • 对不起...但我需要知道它对不起我在我的 php 代码中将我的代码写为 print (json_encode($row)) 再次显示错误,因为 jsonarray 失败...跨度>

标签: php android mysql json


【解决方案1】:

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

【讨论】:

  • 对不起...但我需要知道它对不起我在我的 php 代码中将我的代码写为 print (json_encode($row)) 再次显示错误,因为 jsonarray 失败...跨度>
  • @ArjunViswanathan 你在哪里做的?退出while循环?请记住 $row 仅存在于 while 循环中。请检查
  • 我需要更多帮助...数据正在从数据库中检索,但它没有显示在 android 模拟器中...
猜你喜欢
  • 1970-01-01
  • 2015-12-29
  • 2016-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-09
  • 2010-10-18
相关资源
最近更新 更多