为什么函数不能从android中获取数据?

我想在发布数据后得到回复,但失败。 我想创建一个登录系统,我已经成功地将数据提交到php文件,一切工作正常,现在我想从相同的功能得到响应,但我无法知道问题出在哪里。

这是Java函数:

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")+"nn";

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

                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");
    }

这里是php代码:

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() 。 到目前为止,网页浏览器保留了html注释,android会对此做出回应。

AsyncTask对象和类不是按照您提供的方式设计的,也不能在doInBackground()进行任何UI操作。 AsyncTask是以不阻止GUI的方式进行的。 这是一个没有太多不同的例子,它使用AsyncTask类中的方法:

class Logging extends AsyncTask<String,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(), json.getString("msg"), 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通知用户有关操作结果和data发送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));
}
链接地址: http://www.djcxy.com/p/87439.html

上一篇: Why doesn't the function get data from php in android?

下一篇: How do I add custom fonts?