.readLine()没有得到任何值,结果为null

时间:2014-04-21 13:38:34

标签: java android eclipse

reader.readLine()返回NULL。

我正在尝试将值从我的android发送到PHP,然后返回结果并显示它但由于此错误而停滞不前。 数据库只有名称和密码。获取具有相同密码的所有用户名。 提前谢谢。

Java代码:

package com.example.my;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
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.JSONObject;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.os.Build;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint("NewApi")
public class MainActivity extends ActionBarActivity {
    String id;
    InputStream is = null;
    String result = null;
    String line = null;
    String name = null;

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_main);
        final EditText et_p = (EditText) findViewById(R.id.etPSWD);
        Button b_go = (Button) findViewById(R.id.bGO);
        System.out.println("YO");
        b_go.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                id = et_p.getText().toString();
                go();
            }
        });
    }

    public void go() {
        ArrayList<NameValuePair> pair = new ArrayList<NameValuePair>();
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://192.168.2.5/login.php");
            pair.add(new BasicNameValuePair("id", id));
            httppost.setEntity(new UrlEncodedFormEntity(pair));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            Log.e("pass 1", "connection success ");
        } catch (Exception e) {
            Log.e("Fail 1", e.toString());
            System.out.println("ERROR IS" + e.toString());
            Toast.makeText(getApplicationContext(), "Invalid IP Address",
                    Toast.LENGTH_LONG).show();
        }
        try {
            int count = 0;
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "ISO-8859-1"), 8);
            System.out.println("READERTOSTRING" + reader.toString());
            StringBuilder sb = new StringBuilder();
            System.out.println("RANDOM");
            /*
             *
             * ERROR AFTER THIS
             *
             */
            line = reader.readLine();
            System.out.println("VALUE OF LINE:"+line);
            while (line != null) {
                sb.append(line + "\n");
                System.out.println("ROUND" + count + "--" + sb.toString());
                count++;
                line = reader.readLine();
            }
            is.close();
            result = sb.toString();
            System.out.println("RESULT IS " + result);
            Log.e("pass 2", "connection success ");
        } catch (Exception e) {
            Log.e("Fail 2", e.toString());
        }
        try {
            System.out.println("HERE0" + result);
            JSONObject json_data = new JSONObject(result);
            System.out.println("HERE1");
            name = (json_data.getString("success"));
            System.out.println("HERE1");
            Toast.makeText(getBaseContext(), "Name : " + name,
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Log.e("Fail 3", e.toString());
        }
    }

    @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;
    }

}

XML代码是: -

<?php
    $con = mysqli_connect("localhost","root","sen","test1");
    if(mysqli_connect_errno($con))
    {
    echo "Failed to connect ".mysqli_connect_error();
    }
    $name=$_GET['name'];
    $password=$_GET['password'];
    $result = mysqli_query($con,"SELECT name FROM users where name='$name' and password='$password'");

    //$result = mysqli_query($con,"SELECT name FROM users");

    while($arr = mysqli_fetch_array($result))
    {
       if (mysql_num_rows($result) > 0) {

    $product=array();
    $product["name"]=$arr["arr"];
    $product["password"]=$arr["password"];
    $response["success"]=1;
    $response["get"]=array();
    array_push($response["get"],$product);
    //IF NOT TRY $output[]=$arr;
    echo json_encode($response);
    }
    else
    {
        $response["success"] = 0;
        $response["message"] = "No product found";
        echo json_encode($response);
    }
    }
    //print(json_encode($product));
    mysqli_close($con);
    ?>

ERROR

04-21 13:10:44.332: I/System.out(1339): READERTOSTRINGjava.io.BufferedReader@5275e610 
04-21 13:10:44.332: I/System.out(1339): RANDOM 
04-21 13:10:44.336: I/System.out(1339): VALUE OF LINE:null 
04-21 13:10:44.336: I/System.out(1339): RESULT IS 
04-21 13:10:44.336: E/pass 2(1339): connection success 
04-21 13:10:44.340: I/System.out(1339): HERE0 
04-21 13:10:44.344: E/Fail 3(1339): org.json.JSONException: End of input at character 0 of 

1 个答案:

答案 0 :(得分:0)

看起来你的PHP代码可能根本没有返回任何值。我不确定这是否重要,但您不应该使用mysqli_num_rows()代替mysql_num_rows()吗?

编辑:$password=$_GET['password'];根据您的错误,您的请求中未发送“密码”值。检查输入错误,并确保实际为密码发送了一个值。

编辑2:您在Android代码(HttpPost)中使用了帖子,但是使用PHP($_GET)。改为将$ _GET更改为$ _REQUEST或$ _POST。

编辑3:

  1. 为您的选择添加密码。您试图从结果数组中访问它而不在SQL中选择它。

  2. $product["name"]=$arr["arr"];应为$product["name"]=$arr["name"];

  3. 编辑4: 在while循环之前移动它:$response["get"]=array();,并在while循环之后移动它:echo json_encode($response);(两者)。那么你应该有一个像这样的JSON结构:

    {
       "success":1,
       "post":[
          {"name":"Abc","password":null},
          {‌​"name":"Def","password":null},
          {"name":"Ghi","password":null‌​},
          {"name":"Jkl","password":null},
          {"na‌​me":"Mno","password":null}
       ]
    }
    

    正如您所看到的,您的结果位于名为“post”的JSONArray(由[]标记表示)中。所以像这样:

    JSONArray results = json_data.getJSONObject("post");
    for (int i = 0; i < results .size(); i++) {
        JSONObject item = results.getJSONObject(i); 
        String name = item.getString("name");
    }