in my android project i need to retrieve some data from mysql through php .. i don't know if there is a better way than this, This is my code:
public class test extends AppCompatActivity {
TextView text;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_activity);
text = (TextView) findViewById(R.id.Name);
AsyncTaskClass asyncTaskClass = new AsyncTaskClass();
asyncTaskClass.execute();
}
private class AsyncTaskClass extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... strings) {
String getNameURL = "http://10.0.2.2/getName.php";
try {
URL url = new URL(getNameURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
try {
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "iso-8859-1"));
StringBuilder result = new StringBuilder();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result.append(line).append("\n");
}
bufferedReader.close();
JSONObject jsonObject = new JSONObject(result.toString());
return jsonObject.getString("Name");
} finally {
httpURLConnection.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
text.setText("Your name is " + result);
}
}
}}
there is nothing wrong with the code.
But note that in every activity I put an AsyncTask inside of it if it needs to get some data .. i don't have too much experience with android and java. is my HTTP connection have something wrong because i saw some examples using HTTPClient and URI instead of URL ! And what is the different between setRequsetmethod GET and POST ?
Thanks in advance I appreciate any help :) !