代码不使用 httpclient.execute 填充 json 变量

The code do not fill json variable using httpclient.execute

我的代码有问题。我在这段代码中尝试了很多东西,但没有解决。最后描述了错误。该代码没有语法错误,但是当我 运行 代码时,该应用程序无法运行。所以我调试并注意到 jsonResult 为空。

当我在一个新的应用程序中编写时,只有 main activity,该应用程序运行良好。

SelectActivityAnswer.java

package com.example.test;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
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.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;





public  class SelectAnswerActivity extends Fragment  {
     final static String ARG_POSITION_ANSWER = "position";
     private String jsonResult;
     private String url = "http://myip/employee_details.php";
     private ListView listView;


     public SelectAnswerActivity() {
         // Empty constructor required for fragment subclasses


     }



    //@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        //SimpleAdapter simpleAdapter = new SimpleAdapter(this, null, 0, null, null);
        View rootView = inflater.inflate(R.layout.activity_select_answer, container, false);

        accessWebService();


    //  selectListAns = (ListView) rootView.findViewById(R.id.ans_list);
         // novo code abaixo
      //  ListAdapterAns adapterAns = new ListAdapterAns(this,toppings);
     //   selectListAns.setAdapter(adapterAns);
     //   selectListAns.setOnItemClickListener(new AnsItemClickListener());

        //View rootView = inflater.inflate(R.layout.activity_select_answer, container, false);
        //int i = getArguments().getInt(ARG_PLANET_NUMBER);
        //String planet = getResources().getStringArray(R.array.planets_array)[i];

        //int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
                    //    "drawable", getActivity().getPackageName());
       // ((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
      //  getActivity().setTitle(planet);
        return rootView;
    }

 // Async Task to access the web
    private class JsonReadTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(params[0]);
            try {
                HttpResponse response = httpclient.execute(httppost);
                jsonResult = inputStreamToString(
                        response.getEntity().getContent()).toString();
            }

            catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }



        private StringBuilder inputStreamToString(InputStream is) {
            String rLine = "";
            StringBuilder answer = new StringBuilder();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));

            try {
                while ((rLine = rd.readLine()) != null) {
                    answer.append(rLine);
                }
            }

            catch (IOException e) {
                // e.printStackTrace();
                //Toast.makeText(getApplicationContext(),
                //      "Error..." + e.toString(), Toast.LENGTH_LONG).show();
            }
            return answer;
        }

        @Override
        protected void onPostExecute(String result) {
            ListDrwaer();
        }
    }// end async task

    public void accessWebService() {
        JsonReadTask task = new JsonReadTask();
        // passes values for the urls string array
        task.execute(new String[] { url });
    }

    // build hash set for list view
    public void ListDrwaer() {
        List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();

        try {
            JSONObject jsonResponse = new JSONObject(jsonResult);
            JSONArray jsonMainNode = jsonResponse.optJSONArray("emp_info");

            for (int i = 0; i < jsonMainNode.length(); i++) {
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                String name = jsonChildNode.optString("employee name");
                String number = jsonChildNode.optString("employee no");
                String outPut = name + "-" + number;
                employeeList.add(createEmployee("employees", outPut));
            }
        } catch (JSONException e) {
            //Toast.makeText(getApplicationContext(), "Error" + e.toString(),
            //      Toast.LENGTH_SHORT).show();
        }

        SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
                R.id.content_list_ans,
                new String[] { "employees" }, new int[] { android.R.id.text1 });
        listView.setAdapter(simpleAdapter);
        //Toast.makeText(getApplication(), "c", Toast.LENGTH_SHORT).show();

    }

    private HashMap<String, String> createEmployee(String name, String number) {
        HashMap<String, String> employeeNameNo = new HashMap<String, String>();
        employeeNameNo.put(name, number);
        return employeeNameNo;
    }

}

在此块代码中:

 // Async Task to access the web
    private class JsonReadTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(params[0]);
            try {
                HttpResponse response = httpclient.execute(httppost);
                jsonResult = inputStreamToString(
                        response.getEntity().getContent()).toString();
            }

            catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

我不知道为什么,但是当行是 运行ning 时:

HttpResponse response = httpclient.execute(httppost);

代码跳转到行:

} catch (IOException e) {
  e.printStackTrace();

尝试改变

jsonResult = inputStreamToString(
                    response.getEntity().getContent()).toString();

BufferedReader reader=new BufferedReader(new InputStreamReader(response.getEntity().getContent(),"UTF-08"));
jsonResult = reader.readLine();

还要检查是否已将互联网权限添加到 manifest.XML

<uses-permission android:name="android.permission.INTERNET" />