在android中获得json结果

时间:2014-01-27 23:42:19

标签: android json

我正在尝试从我的Galaxy SII向我的计算机上的数据库做一个基本请求,该数据库有一个wamp设置。

应用程序在手机上崩溃并关闭。我认为它是在httpPost上进行的,因为在apache服务器的访问日志中没有显示任何内容。 (通过我的手机浏览器可以正常运行Web服务)。我在Eclipse中的logCat中获得了NullPointerExeptions。

查找信息一段时间后,我不知道我应该通过Android应用程序获取json结果。我认为下面的代码实际上就是你需要的,给予或采取一些小的改动。

有什么我可以改变我的代码或者我应该丢弃它并尝试不同的方法吗?

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String result = null;
    InputStream is = null;
    StringBuilder sb=null;

    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

  //http post
    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://10.1.1.11/food/food.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());
    }

    //convert response to string
    try{
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        sb = new StringBuilder();
        sb.append(reader.readLine() + "\n");
        String line="0";

        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());
    }

  //paring data
    int fd_id = 0;
    String fd_name = null;
    JSONArray jArray = new JSONArray();
    try{
    jArray = new JSONArray(result);
    JSONObject json_data=null;

    for(int i=0;i<jArray.length();i++){
            json_data = jArray.getJSONObject(i);
            fd_id=json_data.getInt("FOOD_ID");
            fd_name=json_data.getString("FOOD_NAME");
    }

    }catch(JSONException e1){
        Toast.makeText(getBaseContext(), "No Food Found", Toast.LENGTH_LONG).show();
    }catch (ParseException e1){
        e1.printStackTrace();
    }

    Toast.makeText(getBaseContext(), fd_name, Toast.LENGTH_LONG).show();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

2 个答案:

答案 0 :(得分:0)

您永远不应该从应用程序线程进行网络调用。您需要将网络调用放在Service,Thread或AsyncTask中。

答案 1 :(得分:0)

你应该像这样的asynctask进行网络通信:

class talkToServer extends AsyncTask<Void, Void, String>{


@Override
protected String doInBackground(Void... params) {
//http post
try{
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://10.1.1.11/food/food.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());
}

//convert response to string
try{
    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
    sb = new StringBuilder();
    sb.append(reader.readLine() + "\n");
    String line="0";

    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());
}

//paring data
int fd_id = 0;
String fd_name = null;
JSONArray jArray = new JSONArray();
try{
jArray = new JSONArray(result);
JSONObject json_data=null;

for(int i=0;i<jArray.length();i++){
        json_data = jArray.getJSONObject(i);
        fd_id=json_data.getInt("FOOD_ID");
        fd_name=json_data.getString("FOOD_NAME");
}

}catch(JSONException e1){
    Toast.makeText(getBaseContext(), "No Food Found", Toast.LENGTH_LONG).show();
}catch (ParseException e1){
    e1.printStackTrace();
}

return fd_name;

}

@Override
public void onPostExecute(String temp){

Toast.makeText(getBaseContext(), temp, Toast.LENGTH_LONG).show();

}
}