Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't the function get data from php in android?

I want to get response after post data but it fails. I want to create a login system, I have successfully submited data to php file, everything is working fine now I want to get response from same function but I'm unable to know where the issue is.

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

Please help me I have tried so far but could not achieve any results. Please help me how can I get response from php file after query execution.

like image 506
Ayaz Shah Avatar asked Aug 19 '15 10:08

Ayaz Shah


1 Answers

At first be sure you get correct JSON object from your website - try printing it as Toast.makeText(). As far the web browsers keep the html comments away, android gets it in response.

AsyncTask objects and classes aren't designed to be made the way u provided and also you can't make any UI operations in doInBackground(). AsyncTask is made in a way to not to block GUI. Here is a not much different example how it uses methods you have in AsyncTask class:

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 file content:

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

I have created there small dictionary $data for my app. I used its err key as a flag to know if any error appeared, msg to inform user about operation results and data to send JSON objects.

Thing you would want to do with if(response == true) if it had exist is similar to construction i used in my onPostExecute(Void w) method in AsyncTask:

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

Also here is the way I used $data['data'] to get JSON response:

if($query->num_rows){
        while($res=$query->fetch_assoc()){
            $data['data'][]=$res;
        }
        exit(json_encode($data));
}
like image 107
itwasntme Avatar answered Nov 15 '22 00:11

itwasntme