使用ServiceHandler和AsyncTask从localhost获取JSON文件

时间:2014-03-30 05:12:18

标签: android json android-asynctask

我在www文件夹中添加了questions.json文件,我正在尝试检索它。 问题响应总是返回null我猜这个例外是httpClient.execute(httpGet);,但不确定

@SuppressLint("NewApi")
public class QuestionListFragment extends android.app.ListFragment 
{
    private ProgressDialog pDialog;
    // url to make request
        private static String url = "http://localhost/questions.json";

        // JSON Node names
        private static final String TAG_QUESTIONS = "Questions";
        private static final String TAG_ID = "Question_Id";
        private static final String TAG_BODY = "QuestionBody";
        private static final String TAG_TITLE = "QuestionTitle";
        private static final String TAG_NAME = "Asker_Name";
        private static final String TAG_TIME = "Created At";
        private static final String TAG_ANSWERS = "Answers";
        private static final String TAG_ANSWER = "answer";
        private static final String TAG_A_NAME = "Name";
        private static final String TAG_RATING = "Rating";


        // questions JSONArray
        JSONArray questions = null;
        ListView lv;
        Context c;
        JSONObject obj ;
        ArrayList<HashMap<String, String>> questionsList = new ArrayList<HashMap<String, String>>();

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

        View view = inflater.inflate(ask.code.R.layout.questions_list_frag, container, false);


         new GetQuestions().execute();

         return view;
    }

    private class GetQuestions extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }
        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try{
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    questions = jsonObj.getJSONArray(TAG_QUESTIONS);



                        // looping through All Questions
                        for(int i = 0; i < questions.length(); i++){
                            JSONObject c = questions.getJSONObject(i);


                            String id = c.getString(TAG_ID);
                            String title = c.getString(TAG_TITLE);
                            String body = c.getString(TAG_BODY);
                            String name = c.getString(TAG_NAME);
                            String time = c.getString(TAG_TIME);


                            JSONObject answers = c.getJSONObject(TAG_ANSWERS);
                            String answer = answers.getString(TAG_ANSWER);
                            String a_name = answers.getString(TAG_A_NAME);
                            String a_rating = answers.getString(TAG_RATING);

                            // creating new HashMap
                            HashMap<String, String> map = new HashMap<String, String>();

                            // adding each child node to HashMap key => value
                            map.put(TAG_ID, id);
                            map.put(TAG_NAME, name);
                            map.put(TAG_TITLE, title);
                            map.put(TAG_BODY, body);

                            // adding HashList to ArrayList
                            questionsList.add(map);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    getActivity(), 
                    questionsList, 
                    ask.code.R.layout.question_item,
                    new String[] {
                        TAG_NAME,
                        TAG_TITLE,
                        TAG_TIME},
                    new int[] {
                        ask.code.R.id.asker_name,
                        ask.code.R.id.question_title,
                        ask.code.R.id.question_rating});


            setListAdapter(adapter);



                }



    }


    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub

        super.onListItemClick(l, v, position, id);  

    }






        // TODO Auto-generated method stub







}

的ServiceHandler

public class ServiceHandler {

static String response = null;
public final static int GET = 1;
public final static int POST = 2;

public ServiceHandler() {

}

/**
 * Making service call
 * @url - url to make request
 * @method - http request method
 * */
public String makeServiceCall(String url, int method) {
    return this.makeServiceCall(url, method, null);
}

/**
 * Making service call
 * @url - url to make request
 * @method - http request method
 * @params - http request params
 * */
public String makeServiceCall(String url, int method,
        List<NameValuePair> params) {
    try {
        // http client
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        // Checking http request method type
        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);
            // adding post params
            if (params != null) {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            }

            httpResponse = httpClient.execute(httpPost);

        } else if (method == GET) {
            // appending params to url
            if (params != null) {
                String paramString = URLEncodedUtils
                        .format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);

            httpResponse = httpClient.execute(httpGet);

        }
        httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity);

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

    return response;

}

}

questions.json

{
    "Questions": [
        {
            "CreatedAt": "2013-07-31T09: 57: 34.618Z",
            "Asker_Name": "Cloyd",
            "QuestionTitle": "temporadoloremquevoluptatemestquisquamundevoluptatemsuntearum\nsitfugaducimusnequeomnisin\npariaturminusdebitisquaeratrerumnamvelitveritatisrem",
            "QuestionBody": "voluptatemtemporadignissimosanimivelitdelectusconsequaturcumquedeserunt\nillumaperiamquisminimaeumremveniam\nutnumquamdoloremconsequaturvoluptatemofficiaveniam\nutarchitectoiddelenitiuteiuscumpossimus\ndolorumprovidentmollitianullarerum\n\r\tquiainarchitectodebitislaboreerror\nvoluptatibussitquaeratdoloreassumendadoloremdoloresconsectetur\nsedetevenietsaepeconsequaturvelarchitecto\n\r\tdolorumvoluptatemquaevoluptatebeatae\ndoloremqueutofficiisquibusdamiustopariaturiureautdolorem\nidquialiquideosvelet",
            "Question_Id": 0,
            "Answers": {
                "Answer": "temporakdjd",
                "Name": "saleem",
                "Rating": "10"
            }
        },
        {
            "CreatedAt": "1997-08-05T20: 13: 37.888Z",
            "Asker_Name": "Alexander",
            "QuestionTitle": "fugaetnequequoettemporibus\natvoluptatumessesit\nnullaadipisciquaeducimus",
            "QuestionBody": "quiainciduntetquoserror\ncumqueetautsitidexcepturiaccusantiumpariaturconsequatur\nlaudantiummaioressedillomagniexplicabo\nindolorprovidentvoluptasearumdelenitidelectusmollitia\n\r\tsapienteinnemo\nexpeditaautinnon\nprovidentabveniamut\n\r\tenimducimussuntrerumnamsed\nsaepepraesentiumaliquamverolaborumdeseruntidex\nautsedvelittemporibusexplicaboveniamvoluptatemin\nisteetutnobisprovidentasperiores\nexpeditaitaqueullam",
            "Question_Id": 1,
            "Answers": {
                "Answer": "temporakdjd",
                "Name": "saleem",
                "Rating": "10"
            }
        },
        {
            "CreatedAt": "1990-02-16T06: 37: 46.327Z",
            "Asker_Name": "Kade",
            "QuestionTitle": "nisidelectusasperioresveletidtempore\nrationeautautet\neaquenisiestrerumodioasperiorescupiditate",
            "QuestionBody": "exrepellendusliberoeosautemetdictaautemsed\nabconsequaturetsitvoluptatemassumendavelitsint\nautconsequaturveniamodioquodoloremdolorem\neligendirerumexplicaboquiquiadolorem\n\r\tminusvoluptatemnamvelcupiditateaperiamsedrerumearum\nautrepudiandaeeavelsitreprehenderiteterrorfugiat\nsedeaquidemveritatisiure\n\r\tdoloremqueidsuntatquiacorruptimolestiaeexpeditavoluptate\nnontemporevelitestrepellendus\nessequaeinsit\nporronihilfacereautnecessitatibusquosunt\natlaborumatemporaullam",
            "Question_Id": 2,
            "Answers": {
                "Answer": "temporakdjd",
                "Name": "saleem",
                "Rating": "10"
            }
        },
        {
            "CreatedAt": "1987-02-28T20: 39: 36.422Z",
            "Asker_Name": "Madaline",
            "QuestionTitle": "omnisnesciuntexcepturieligendirerumquam\netmolestiasfugiatremvoluptasvelitautet\nsedoccaecatidelectuseoset",
            "QuestionBody": "inciduntquosbeataevoluptasidcommodideseruntexvero\netitaquemollitialaborumnemosedvoluptatibusperferendisdoloremque\nestsuscipitnonveniamutquaeaperiam\nveroetquiaautillo\nasperioressimiliquetempora\n\r\tvoluptatemaccusantiumconsequunturetconsequaturrepellataut\naspernaturnesciunteavoluptasnatusmaxime\nmaioresatconsequaturnequereiciendis\nadipiscienimrationeipsummagnamveniamsed\n\r\treiciendisutundequi\naperiamcorporisnesciuntid\nculpaetreprehenderittemporibusofficiaplaceataccusantiumcum\nquassitmaioresdelectusesse\nconsequaturtotamdolor",
            "Question_Id": 3,
            "Answers": {
                "Answer": "temporakdjd",
                "Name": "saleem",
                "Rating": "10"
            }
        },
        {
            "CreatedAt": "1991-11-22T12: 50: 21.965Z",
            "Asker_Name": "Lizzie",
            "QuestionTitle": "quiaremnatus\nnatusofficiisquamomnisquifuga\nquiasitavoluptatem",
            "QuestionBody": "quisvoluptasquilaborumsednostrumfugaea\nipsumquaeratveritatis\nporrouterrorex\nauteiusexplicabononfugaadutvoluptatumnihil\nabnoninarchitectocommodiminusquasanimi\n\r\tenimdebitisbeataemollitiadoloresiureiustoquia\ncommodiquiapossimusatemporibus\nidutnobisvoluptatumfugaaccusamusharum\netdictaquiamollitiaaccusamuspossimusvoluptatibusautalias\nautemdoloremnamaliquam\n\r\tsitdeseruntautestexcepturiquasi\nquibusdamevenietexcepturiducimusquosdicta\nearumsitenimautquisquamaliquam\nmagnamnesciuntinciduntvelitarchitectoomnis\nomnisminimaerrorfuga",
            "Question_Id": 4,
            "Answers": {
                "Answer": "temporakdjd",
                "Name": "saleem",
                "Rating": "10"
            }
        },
        {
            "CreatedAt": "1987-05-09T15: 46: 08.048Z",
            "Asker_Name": "Colleen",
            "QuestionTitle": "rerumetaccusamussedabdolorenonest\nestperspiciatisquisedsintmolestiaeautcorporisomnis\nperferendisvelenim",
            "QuestionBody": "iustomolestiasrerummollitiafacilisatquecumque\neumquaeatqueaspernaturadoloresestomnis\ndolornihilexcepturinecessitatibus\n\r\tidveniamevenietquifugiat\nreprehenderiterrornumquamautetquiquiarerum\ndolorummaximequasicorporismodiin\neosnostrumutsapientedoloremque\nquaeratconsequunturveniamperferendisautnisidoloresnonest\n\r\tquisuscipitadconsequaturrepellatvoluptatemmollitia\nquidemverocum\nmodidelenitivoluptasadipisciodio",
            "Question_Id": 5,
            "Answers": {
                "Answer": "temporakdjd",
                "Name": "saleem",
                "Rating": "10"
            }
        },
        {
            "CreatedAt": "2002-05-04T05: 31: 45.704Z",
            "Asker_Name": "Carlotta",
            "QuestionTitle": "impeditquodillumconsequunturlabore\nsitundeblanditiisitaqueiustoutcorporisut\ndeseruntquasquam",
            "QuestionBody": "illumevenietdolor\ndoloribusdistinctiorerumvoluptatumquibusdamest\ndoloremquevoluptassitautemeos\nexcepturiquieasuntverodictaatque\n\r\tisteullamut\nanimivoluptasautdoloresoccaecatiuttenetur\neaimpeditautaquispossimusperspiciatisestaccusantium\nutconsequaturminimabeataemolestiae\ndoloresdolorethic\n\r\tquisquamquidempariaturassumendalaborumveritatisquasdolore\ncommodiquaedebitisipsafugitcorporissitharumquam\nvoluptasbeataeeaetetutaperiam\naiurenihilnamnonaut\ndoloresprovidenthicetveroautmagnimaximelabore",
            "Question_Id": 6,
            "Answers": {
                "Answer": "temporakdjd",
                "Name": "saleem",
                "Rating": "10"
            }
        }
    ]
}

4 个答案:

答案 0 :(得分:1)

如果您使用的是模拟器,那么您必须编写10.0.2.2来代替localhost。 如果您使用的是设备,则必须连接到同一网络,并且必须将localhost替换为您的计算机IP地址。

我希望这会有所帮助

答案 1 :(得分:1)

您正尝试通过将localhost指定为托管服务的系统的地址来连接到服务器。 Android模拟器在虚拟机(QEMU)内运行。因此,localhost将是模拟器自己的环回地址,而不是系统的地址。

因此,您可以转到Windows中的CommandPrompt获取系统的IP地址,或者只使用http://10.0.2.2:8080/...而不是localhost

<强> private static String url = "http://10.0.2.2:8080/questions.json";

答案 2 :(得分:0)

public String makeServiceCall(String url, int method,
                              List<NameValuePair> params) {

    StringBuilder result = new StringBuilder();

    try {
        //URL urlObj = new URL(url);
        URL urlObj = new URL(url.replace(" ","%20"));
        urlConnection = (HttpURLConnection) urlObj.openConnection();
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));

        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

    }catch( Exception e) {
        e.printStackTrace();
    }
    finally {
        urlConnection.disconnect();
    }


    return result.toString();
}

答案 3 :(得分:0)

这可能会有所帮助:

public class ServiceHandler {

static String response = null;
public final static int GET = 1;
public final static int POST = 2;
HttpURLConnection urlConnection;
public ServiceHandler() {

}
public String makeServiceCall(String url, int method) {
    return this.makeServiceCall(url, method, null);
}
public String makeServiceCall(String url, int method,
                              List<NameValuePair> params) {
    StringBuilder result = new StringBuilder();


    try {
        //URL urlObj = new URL(url);
        URL urlObj = new URL(url.replace(" ","%20"));
        urlConnection = (HttpURLConnection) urlObj.openConnection();
        InputStream in = new       BufferedInputStream(urlConnection.getInputStream());

        BufferedReader reader = new BufferedReader(new    InputStreamReader(in));

        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

    }catch( Exception e) {
        e.printStackTrace();
    }
    finally {
        urlConnection.disconnect();
    }


    return result.toString();
   }
   }