在我的Android的项目,我需要检索从MySQL通过PHP的一些数据..我不知道是否有比这更好的办法,这是我的代码:这是更好的方式连接到Android的MySQL数据库?
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);
}
}
}}
有没有错码。
但是请注意,在每一个活动中,如果它需要获取一些数据,我会在其中放置一个AsyncTask ..我没有太多的android和java经验。 是我的HTTP连接有问题,因为我看到一些使用HTTPClient和URI而不是URL的例子! setRequset方法GET和POST有什么不同?
在此先感谢我欣赏任何帮助:)!
你没有连接到任何MySQL数据库在此代码其他HTTP库。您正在对一些PHP脚本执行常规HTTP请求。 –
创建将执行HTTP请求,让您用自己的听众的帮助下,响应我猜 –
一个更好的办法是彻底的一个实际的HTTP库摆脱的AsyncTask的...排球,改造,离子共同类, AsyncHttpClient等... –