2017-03-12 39 views
-1

在我的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有什么不同?

在此先感谢我欣赏任何帮助:)!

+2

你没有连接到任何MySQL数据库在此代码其他HTTP库。您正在对一些PHP脚本执行常规HTTP请求。 –

+0

创建将执行HTTP请求,让您用自己的听众的帮助下,响应我猜 –

+0

一个更好的办法是彻底的一个实际的HTTP库摆脱的AsyncTask的...排球,改造,离子共同类, AsyncHttpClient等... –

回答

0

我会建议一个网络库,如Android Volley。 (还有其他一些像Retrofit和OkHttp2)

通过使用网络库,它使得它更容易重复使用和读取代码以及许多其他许可,例如不必使用一个AsyncTask。

此行添加到您的项目依赖于库中导入到项目

dependencies { 
    ... 
    compile 'com.mcxiaoke.volley:library:1.0.0' 
} 

有许多在线资源,可以告诉你如何使用这个库,如果谷歌像“我提到的其他示例android volley请求。“

0

但请注意,在每一个活动,我把一个的AsyncTask里面它,如果它需要得到一些数据

所以呢?没有错。您可以选择更好地组织代码,这样您就不会一次又一次复制粘贴所有内容。

是我的HTTP连接有什么不对,因为我看到使用URL

阿帕奇了HTTPClient现在在Android过时的了HTTPClient和URI,而不是一些例子。

是什么setRequsetmethod之间的不同GET和POST

无关与Android ...你想要得到的数据或 “发送” 的数据?就像从数据库读取数据或插入数据库一样?

代码没有问题。

好的,太棒了!但是,你可能要考虑在Android

Comparison of Android networking libraries: OkHTTP, Retrofit, and Volley