1

I'm looking for a way to send POST data to a PHP script and display the result.I want to send POST data of $username to php. This is my php file:

<?php ...// connect $username = $_POST['txtUsername'];// this data $mysqli->query("SET NAMES 'utf8'"); $sql="SELECT * FROM $username"; $result=$mysqli->query($sql); while($e=mysqli_fetch_assoc($result)){ $output[]=$e; } print(json_encode($output)); $mysqli->close(); ?> 

My activities:
DataParser.class

public class DataParser extends AsyncTask<Void,Void,Integer>{ Context c; ListView lv; String jsonData; ProgressDialog pd; ArrayList<Spacecraft> spacecrafts = new ArrayList<>(); public DataParser(Context c, ListView lv, String jsonData) { this.c = c; this.lv = lv; this.jsonData = jsonData; } @Override protected void onPreExecute() { super.onPreExecute(); pd= new ProgressDialog(c); pd.setTitle("Parse"); pd.setMessage("Parsing..Please wait"); pd.show(); } @Override protected Integer doInBackground(Void... voids) { return this.parseData(); } @Override protected void onPostExecute(Integer result) { super.onPostExecute(result); pd.dismiss(); if (result==0){ Toast.makeText(c,"Unable to parse",Toast.LENGTH_SHORT).show(); } else { CustomAdapter adapter = new CustomAdapter(c,spacecrafts); lv.setAdapter(adapter); } } private int parseData(){ try { JSONArray ja = new JSONArray(jsonData); JSONObject jo = null; spacecrafts.clear(); Spacecraft s=null; for (int i=0;i<ja.length();i++){ jo=ja.getJSONObject(i); int id = jo.getInt("id"); String name =jo.getString("name"); String send =jo.getString("send"); String comment =jo.getString("comment"); String date =jo.getString("date"); s=new Spacecraft(); s.setId(id); s.setName(name); s.setSend(send); s.setComment(comment); s.setDate(date); spacecrafts.add(s); } return 1; } catch (JSONException e) { e.printStackTrace(); } return 0; }} 

MainActivity:

public class MainActivity extends AppCompatActivity implements AsyncResponse { String urlAddress="http://mysite/myphp.php"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ListView lv = (ListView) findViewById(R.id.lv) ; Intent intent = getIntent(); final String username = intent.getStringExtra("location"); Downloader d = new Downloader(MainActivity.this,urlAddress,lv); d.execute(); 

And Downloader.class:

public class Downloader extends AsyncTask<Void,Void,String> { Context c; String urlAddress; ListView lv; ProgressDialog pd; public Downloader(Context c, String urlAddress, ListView lv) { this.c = c; this.urlAddress = urlAddress; this.lv = lv; } @Override protected void onPreExecute() { super.onPreExecute(); pd = new ProgressDialog(c); pd.setTitle("Fetch"); pd.setMessage("Fetching...Please wait"); pd.show(); } @Override protected String doInBackground(Void... voids) { return this.downloadData(); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); pd.dismiss(); if(s==null){ Toast.makeText(c,"Unsuccessful,Null,returned",Toast.LENGTH_SHORT).show(); } else { DataParser parser = new DataParser(c,lv,s); parser.execute(); } } private String downloadData(){ HttpURLConnection con = Connector.connect(urlAddress); if (con==null){ return null; } InputStream is=null; try { is=new BufferedInputStream(con.getInputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = null; StringBuffer response = new StringBuffer(); if (br!=null){ while ((line=br.readLine())!=null){ response.append(line+"\n"); } br.close(); } else {return null;} return response.toString(); } catch (IOException e) { e.printStackTrace(); } finally { if(is != null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; }} 

Please help me, Thank you!

2
  • where is the problem? in your java codes or in PHP codes ? Commented Jul 1, 2016 at 23:54
  • Use retrofit square.github.io/retrofit for http requests. Commented Jul 2, 2016 at 4:40

1 Answer 1

1

Based on the code you've provided, it looks like you are downloading data, but it doesn't seem like you are posting any data.

There are a few ways you can send data via HTTP POST. You could try using the Google IO Volley API, which takes care of a lot of the logic of network calls for you.

For example:

RequestQueue queue = Volley.newRequestQueue(this); String url = "https://myurl.com"; JsonRequest postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(JSONObject response) { Log.d(TAG, response.toString()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, error.toString()); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("txtUsername", "mUsername"); return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/x-www-form-urlencoded"); return headers; } }; queue.add(postRequest); 

You could also write your own AsyncTask to perform the post. Here is an example:

public class PostRequestAsyncTask extends AsyncTask<Void, Void, String { Context context; Map<String, String> postParams; /** * Overridden constructor */ public PostRequestAsyncTask(Context context, Map<String, String> postParams) { this.context = context; this.postParams = new LinkedHashMap<String, String>(postParams); } /** * Default constructor */ public PostRequestAsyncTask() {} public byte[] generatePostData() { StringBuilder postData = new StringBuilder(); for (Map.Entry<String, String> dParam : postParams.entrySet()) { if (postData.length() != 0) postData.append('&'); try { postData.append(URLEncoder.encode(dParam.getKey(), "UTF-8")); postData.append('='); postData.append(URLEncoder.encode(String.valueOf(dParam.getValue()), "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } byte[] postDataBytes = null; try { postDataBytes = postData.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return postDataBytes; } @Override protected String doInBackground(Void... params) { /* Set params */ byte[] postDataBytes = generatePostData(); /* Set headers and write */ URL url = null; HttpURLConnection conn = null; try { url = new URL("https://myurl.com"); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); conn.setDoOutput(true); conn.getOutputStream().write(postDataBytes); } catch (MalformedURLException | IOException e) { e.printStackTrace(); } /* Retrieve response */ Reader in = null; String response = new String(); try { in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); response = ""; for (int c = in.read(); c != -1; c = in.read()) { response += (char) c; } } catch (IOException e) { e.printStackTrace(); } return response; } @Override protected void onPostExecute(String resp) { super.onPostExecute(resp); JSONObject jsonResponse = null; try { jsonResponse = new JSONObject(resp); //do something with your json response } catch (JSONException e) { e.printStackTrace(); } } } 

Then execute your AsyncTask like so:

Map<String, String> postParams = new LinkedHashMap<>(); postParams.put("txtUserName", "mUsername"); new PostRequestAsyncTask(MyActivity.this, postParams).execute(); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.