【发布时间】:2015-04-09 18:53:22
【问题描述】:
我正在尝试在我的 Android 应用程序中建立与 MYSQL 数据库的连接。
我一直在关注这个教程:http://www.trustingeeks.com/connect-android-app-to-mysql-database/
基本上它从 JSON 请求填充文本视图。
不同之处在于我需要让数据连接在片段中工作。
这是我有问题的地方,没有任何事情发生。下面是我尝试将教程实现为片段:
public class FragmentFour extends Fragment{
private String jsonResult;
private String url = "http://cpriyankara.coolpage.biz/employee_details.php";
private TextView resultView;
private static View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null)
parent.removeView(view);
}
try {
view = inflater.inflate(R.layout.fragment_four, container, false);
resultView = (TextView) view.findViewById(R.id.result);
StrictMode.enableDefaults();
getData();
} catch (InflateException e) {
}
return view;
}
public void getData(){
String result = "";
InputStream isr = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://ieeehiit.host22.com/myfile.php"); //YOUR PHP SCRIPT ADDRESS
// HttpPost httppost = new HttpPost("http://172.23.193.32/elift-test/myfile.php"); //YOUR PHP SCRIPT ADDRESS
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
resultView.setText("Couldnt connect to database");
}///convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}//parse json data
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
s = s +"Name : "+json.getString("id")+" "+json.getString("username"); }
resultView.setText(s);
} catch (Exception e)
{ // TODO:处理异常
Log.e("log_tag", "Error Parsing Data "+e.toString());
}
}
}
一切正常,但 textView 中没有发生任何事情。我查看了 logcat 并注意到:
"2-09 21:06:05.155 13519-13519/com.example.nottinghamtouristapp E/log_tag﹕ Error Parsing Data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONArray"
我对 android 开发非常陌生,所以这个问题很可能是由于我缺乏碎片经验。如果我看起来愚蠢而傲慢地发帖寻求帮助,我深表歉意。我觉得已经用尽了所有想到的东西!
提前非常感谢您。
【问题讨论】:
-
错误说明了一切:来自服务器的“json”响应是 NOT json。它是 HTML。 json 响应不能以
<!DOCTYPE... 开头
标签: java android mysql json android-fragments