我已经通过两个教程来获取我的这个项目的代码;
通过 PHP 和 JSON 将 Android 连接到远程 mysql
由于我还是初学者并且同时使用了很多代码,因此我已经学习了一定程度的代码。这是我目前所拥有的:
package com.android.history;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class CurrentSeasonDrivers extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.currentseason_drivers);
}
//PARSE JSON ETC
public void parseJSON() {
String result = "";
String drivername = "";
String drivesfor = "";
InputStream is=null;
//HTTP POST REQUEST
try{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.13/testdatabase.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
Toast.makeText(getBaseContext(), "Could not connect", Toast.LENGTH_LONG).show();
}
//CONVERT DATA TO STRING
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
Toast.makeText(getBaseContext(), "Could not convert result", Toast.LENGTH_LONG).show();
}
//PARSE JSON DATA
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
drivername=json_data.getString("Driver_full_name");
drivesfor=json_data.getString("Drives_for");
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getBaseContext(), "Could not parse data", Toast.LENGTH_LONG).show();
}
}
}
现在我没有错误,应用程序工作正常。当我到达这一切都是为之而设的页面时,我什么也没得到。一个空白页。正如您从我的代码中看到的那样,我添加了 toasts 异常,但它们都没有出现。即使我故意关闭我的服务器,这也很奇怪。还有什么我应该做的。正如标题所说,因为 toasts 不起作用,我不知道代码是否真的在做任何事情。我只有一个空白页。
我已将 Internet 添加到我的清单中以允许应用程序访问它。如果我192.168.0.13/testdatabase.php
通过浏览器访问代码 ( ) 中的 URL,则数据库中的数据显示得很好。
编辑:我最终想要的总体结果是显示数据库中的一些数据供我的用户查看。而不是将其作为静态文本放入并且必须更新整个应用程序只是为了更新一些数据。