2014-03-30 59 views
1

我已經將一個questions.json文件添加到www文件夾,並試圖檢索它。 問題是響應始終返回null我猜的例外是在httpClient.execute(httpGet);,不知道雖然使用ServiceHandler和AsyncTask從本地主機獲取JSON文件

@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" 
      } 
     } 
    ] 
} 

回答

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";

1

如果您使用的是仿真器,那麼您必須寫10.0.2.2來代替localhost。 如果你正在使用你的設備,那麼你必須連接到同一網絡,並且必須用你的計算機ip地址替換localhost。

我希望這將有助於

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

你能解釋一下你的代碼,請! –

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

這看起來像下面的soumit的無法解釋的代碼轉儲的副本。請發佈實際上對問題的答案的原始答案。 – laalto

相關問題