Why is the function not receiving data from php in android?

I want to receive the answer after messages, but it fails. I want to create a login system, I successfully transferred the data to a php file, everything works fine, now I want to get an answer from the same function, but I can not know where the problem 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 the 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 already tried, but could not achieve any results. Please help me how can I get a response from a php file after executing the request.

+7
java android php android-activity
source share
1 answer

First, make sure you get the correct JSON object from your website - try printing it as Toast.makeText() . While web browsers leave html comments, android gets it in response.

AsyncTask objects and classes are not intended to be executed as you have provided, nor can you perform any user interface operations in doInBackground() . AsyncTask is designed to not block the GUI. Here is a completely different example of how it uses the methods that you have in the 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 contents:

 $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 created there a small $data dictionary for my application. I used his err key as a flag to find out if there was any error, msg , to inform the user about the results of work and data to send JSON objects.

The thing you would like to do with if(response == true) , if it existed, is similar to the construct 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 } 

It also uses the $data['data'] method to get a JSON response:

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

All Articles