java – 为什么函数不能从android中的php获取数据?

前端之家收集整理的这篇文章主要介绍了java – 为什么函数不能从android中的php获取数据?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我希望在发布数据后得到响应,但它失败了.我想创建一个登录系统,我已成功将数据提交到PHP文件,一切正常,我想从同一个函数得到响应,但我不知道问题出在哪里.

Here is the Java function:

public class PostDataGetRes extends AsyncTask<String,String,String> {

        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... strings) {
            try {


                postRData();


            } catch (NullPointerException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String lenghtOfFile) {
            // do stuff after posting data
        }
    }

    public void postRData() {
        String result = "";
        InputStream isr = null;
        final String email = editEmail.getText().toString();
        final String pass = editPass.getText().toString();
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://website.com/appservice.PHP");

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("id",email));
            nameValuePairs.add(new BasicNameValuePair("stringdata",pass));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            resultView.setText("Inserted");
            HttpEntity entity = response.getEntity();
            isr = entity.getContent();

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

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

            //parse json data
            try {
                String s = "";
                JSONArray jArray = new JSONArray(result);

                for(int i=0; i<jArray.length();i++){
                    JSONObject json = jArray.getJSONObject(i);
                    s = s +
                            "Name : "+json.getString("first_name")+"\n\n";

                    //"User ID : "+json.getInt("user_id")+"\n"+
                    //"Name : "+json.getString("first_name")+"\n"+
                    //"Email : "+json.getString("email")+"\n\n";
                }

                resultView.setText(s);

            } catch (Exception e) {
                // TODO: handle exception
                Log.e("log_tag","Error Parsing Data "+e.toString());
            }


        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
        resultView.setText("Done");
    }

And here is PHP code:

if($id){
        $query =  MysqL_query("SELECT first_name FROM users where email = '$id' ");
        while($row=MysqL_fetch_assoc($query)){
            $selectedData[]=$row;
        }
        print(json_encode($selectedData));
    }

请帮助我,到目前为止我已经尝试过,但无法取得任何成果.请帮助我如何在查询执行后从PHP文件中获得响应.

解决方法

首先要确保从您的网站获得正确的JSON对象 – 尝试将其打印为Toast.makeText().到目前为止,Web浏览器保留了html注释,android将其作为响应.

AsyncTask对象和类的设计不是按照您提供的方式进行的,也不能在doInBackground()中进行任何UI操作. AsyncTask的制作方式是不阻止GUI.
以下是使用AsyncTask类中的方法的一个不同的示例:

class Logging extends AsyncTask<String,Void>{
    JSONObject json=null;
    String output="";
    String log=StringCheck.buildSpaces(login.getText().toString());
    String pas=StringCheck.buildSpaces(password.getText().toString());
    String url="http://www.mastah.esy.es/webservice/login.PHP?login="+log+"&pass="+pas;

    protected void onPreExecute() {
        Toast.makeText(getApplicationContext(),"Operation pending,please wait",Toast.LENGTH_SHORT).show();
     }

    @Override
    protected Void doInBackground(String... params) {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        request.addHeader("User-Agent","User-Agent");
        HttpResponse response;
        try {
            response = client.execute(request);
            BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String line="";
            StringBuilder result = new StringBuilder();
            while ((line = br.readLine()) != null) {
                result.append(line);
            }
            output=result.toString();
        } catch (ClientProtocolException e) {
            Toast.makeText(getApplicationContext(),"Connection problems",Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            Toast.makeText(getApplicationContext(),"Conversion problems",Toast.LENGTH_LONG).show();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void w) {
        try {
            json = new JSONObject(output);
            if(json.getInt("err")==1){
                Toast.makeText(getApplicationContext(),json.getString("msg"),Toast.LENGTH_LONG).show();
            }else{
                String id_user="-1";
                Toast.makeText(getApplicationContext(),Toast.LENGTH_LONG).show();
                JSONArray arr = json.getJSONArray("data");
                for(int i =0;i<arr.length();i++){
                    JSONObject o = arr.getJSONObject(i);
                    id_user = o.getString("id_user");
                }
                User.getInstance().setName(log);
                User.getInstance().setId(Integer.valueOf(id_user));
                Intent i = new Intent(getApplicationContext(),Discover.class);
                startActivity(i);
            }
        } catch (JSONException e) {
        }
        super.onPostExecute(w);
    }   
}

PHP文件内容

$data = array(
    'err' => 0,'msg' => "",'data' => array(),);

$MysqLi = new MysqLi($dbhost,$dbuser,$dbpass,$dbname);
if($MysqLi->connect_errno){
    $data['err'] = 1;
    $data['msg'] = "Brak polaczenia z baza";
    exit(json_encode($data));
}

if(isset($_GET['login']) && isset($_GET['pass'])){
    $MysqLi->query("SET CHARACTER SET 'utf8';");
    $query = $MysqLi->query("SELECT banned.id_user FROM banned JOIN user ON user.id_user = banned.id_user WHERE user.login ='{$_GET['login']}' LIMIT 1;");
    if($query->num_rows){
        $data['err']=1;
        $data['msg']="User banned";
        exit(json_encode($data));
    }else{
        $query = $MysqLi->query("SELECT login FROM user WHERE login='{$_GET['login']}' LIMIT 1;");
        if($query->num_rows){
            $query = $MysqLi->query("SELECT pass FROM user WHERE pass ='{$_GET['pass']}' LIMIT 1;");
            if($query->num_rows){
                $data['msg']="Logged IN!";
                $query = $MysqLi->query("SELECT id_user FROM user WHERE login='{$_GET['login']}' LIMIT 1;");
                $data['data'][]=$query->fetch_assoc();
                exit(json_encode($data));
            }else{
                $data['err']=1;
                $data['msg']="Wrong login credentials.";
                exit(json_encode($data));
            }
        }else{
            $data['err']=1;
            $data['msg']="This login doesn't exist.";
            exit(json_encode($data));
        }
    }
}else{
    $data['err']=1;
    $data['msg']="Wrong login credentials";
    exit(json_encode($data));
}

我为我的应用程序创建了小字典$data.我使用它的err键作为标志来知道是否出现任何错误,msg通知用户有关操作结果和发送JSON对象的数据.

你想要if(response == true),如果它存在的东西类似于我在AsyncTask中的onPostExecute(Void w)方法中使用的构造:

if(json.getInt("err")==1){
    //something went wrong
}else{
    //everything is okay,get JSON,inform user,start new Activity
}

这也是我使用$data [‘data’]获取JSON响应的方式:

if($query->num_rows){
        while($res=$query->fetch_assoc()){
            $data['data'][]=$res;
        }
        exit(json_encode($data));
}

猜你在找的Android相关文章