0

我在尝试通过 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());
    }

}
}
4

1 回答 1

0

首先,确保您的应用请求INTERNET权限。更多关于这里。其次,您可以使用droidQuery库显着整理代码:

public void getMovie() {
    $.ajax(new AjaxOptions().url("http://website.com/myphp.php")
                            .type("POST")
                            .dataType("JSON")
                            .data("{ids: 1}")
                            .context(this)
                            .success(new Function() {
                                @Override
                                public void invoke($ droidQuery, Object... params) {
                                    JSONArray json = (JSONArray) params[0];
                                    Object[] datas = $.makeArray(json);
                                    for (Object data : datas) {
                                        JSONObject obj = (JSONObject) data;
                                        Map<String, ?> map = $.map(obj);
                                        Log.i("log_tag", map.toString());//will print all JSON Objects in a Key-Value format, such as "{1, 'text'}"
                                    }
                                }
                            })
                            .error(new Function() {
                                @Override
                                public void invoke($ droidQuery, Object... params) {
                                    String reason = (String) params[2];
                                    droidQuery.toast("Error in Ajax Request: " + reason, Toast.LENGTH_LONG);
                                }
                            }));
}

第三,如果您仍然遇到错误,请将您的调用包围getMovie()在一个try-catch块中,捕获 aThrowable而不是 a Exception

try {
    new getData().getMovie();
}
catch (Throwable t) {
    t.printStackTrace();
}
于 2013-07-15T18:51:56.940 回答