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

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

概述我希望在发布数据后得到响应,但它失败了.我想创建一个登录系统,我已成功将数据提交到php文件,一切正常,我想从同一个函数得到响应,但我不知道问题出在哪里. Here is the Java function: public class PostDataGetRes extends AsyncTask<String, String, String> { protected void 我希望在发布数据后得到响应,但它失败了.我想创建一个登录系统,我已成功将数据提交到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");    }@H_403_7@  

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

请帮助我,到目前为止我已经尝试过,但无法取得任何成果.请帮助我如何在查询执行后从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);    }   }@H_403_7@  

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

我为我的应用程序创建了小字典$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}@H_403_7@  

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

if($query->num_rows){        while($res=$query->fetch_assoc()){            $data['data'][]=$res;        }        exit(Json_encode($data));}@H_403_7@                  总结       

以上是内存溢出为你收集整理的java – 为什么函数不能从android中的php获取数据?全部内容,希望文章能够帮你解决java – 为什么函数不能从android中的php获取数据?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1148252.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存