我在尝试通过 JSON 连接到 PHP 文件以访问 android 中的 MySQL 时遇到问题。我一生都无法弄清楚为什么这会导致我的应用程序崩溃。有任何想法吗?
它抛出以下错误:
AndroidRuntime
FATAL EXCEPTION: main
我正在尝试从我的主要活动中调用它:
new getData().getMovie();
这称为:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.*;
import org.json.*;
import android.util.Log;
import android.widget.Toast;
public class getData extends FullscreenActivity{
public void getMovie() {
String result = "";
String rID="1";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("ids",rID));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://website.com/myphp.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
}catch(Exception e){
Toast.makeText(this, "Error in http connection "+e.toString(), Toast.LENGTH_LONG).show();
//Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
InputStream is = null;
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){
Toast.makeText(this, "Error converting result "+e.toString(), Toast.LENGTH_LONG).show();
//Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getString("id")+
", 1: "+json_data.getString("1")+
", 2: "+json_data.getString("2")+
", 3: "+json_data.getString("3")+
", 4: "+json_data.getString("4")+
", 5: "+json_data.getString("5")
);
}
} catch (JSONException e) {
Toast.makeText(this, "Error parsing data "+e.toString(), Toast.LENGTH_LONG).show();
//Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}