2017-05-10 18 views
0

我在使用此代碼時遇到問題。變量結果應該從服務器的響應中填充,但由於某種原因,它會一直返回一個空字符串。讀取服務器發送的數據時出現空字符串

這是整個代碼:這裏

public class FragmentRally extends Fragment { 

public FragmentRally() { 
    // Required empty public constructor 
} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    View rootView = inflater.inflate(R.layout.fragment_fragment_rally, container, false); 


    new AsyncFetch().execute(); 


    return rootView; 
} 


// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds 
public static final int CONNECTION_TIMEOUT = 10000; 
public static final int READ_TIMEOUT = 15000; 
private RecyclerView vistaRallye; 
private AdapterRallye adaptadorRallye; 

private class AsyncFetch extends AsyncTask<String, String, String> { 
    ProgressDialog pdLoading = new ProgressDialog(getActivity()); 
    HttpURLConnection conn; 
    URL url = null; 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 

     //this method will be running on UI thread 
     pdLoading.setMessage("\tCarregant..."); 
     pdLoading.setCancelable(false); 
     pdLoading.show(); 

    } 

    @Override 
    protected String doInBackground(String... params) { 
     try { 

      // Enter URL address where your json file resides 
      // Even you can make call to php file which returns json data 
      url = new URL("http://www.rallyecat.esy.es/Obtenir_events.php"); 

     } catch (MalformedURLException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
      return e.toString(); 
     } 
     try { 

      // Setup HttpURLConnection class to send and receive data from php and mysql 
      conn = (HttpURLConnection) url.openConnection(); 
      conn.setReadTimeout(READ_TIMEOUT); 
      conn.setConnectTimeout(CONNECTION_TIMEOUT); 
      conn.setRequestMethod("GET"); 

      // setDoOutput to true as we recieve data from json file 
      conn.setDoOutput(true); 

     } catch (IOException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
      return e1.toString(); 
     } 

     try { 

      int response_code = conn.getResponseCode(); 

      // Check if successful connection made 
      if (response_code == HttpURLConnection.HTTP_OK) { 

       // Read data sent from server 
       InputStream input = conn.getInputStream(); 
       BufferedReader reader = new BufferedReader(new InputStreamReader(input)); 
       StringBuilder result = new StringBuilder(); 
       String line; 

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

       // Pass data to onPostExecute method 
       return (result.toString()); 

      } else { 

       return ("No hi ha connexió a internet."); 
      } 

     } catch (IOException e) { 
      e.printStackTrace(); 
      return e.toString(); 
     } finally { 
      conn.disconnect(); 
     } 


    } 

    @Override 
    protected void onPostExecute(String result) { 

     //this method will be running on UI thread 

     pdLoading.dismiss(); 
     List<DataRallye> data = new ArrayList<>(); 

     pdLoading.dismiss(); 
     try { 
      JSONArray jArray = new JSONArray(result); 

      // Extract data from json and store into ArrayList as class objects 
      for (int i = 0; i < jArray.length(); i++) { 
       JSONObject json_data = jArray.getJSONObject(i); 
       DataRallye dadesrallye = new DataRallye(); 
       dadesrallye.RallyeNom = json_data.getString("nom"); 
       dadesrallye.RallyeTipus = json_data.getString("tipus"); 
       dadesrallye.RallyeDataI = json_data.getString("datai"); 
       dadesrallye.RallyeDataF = json_data.getString("dataf"); 
       dadesrallye.RallyeCiutat = json_data.getString("ciutat"); 
       dadesrallye.RallyeOrganitzacio = json_data.getString("organitzacio"); 
       dadesrallye.RallyeFoto = json_data.getString("foto"); 
       data.add(dadesrallye); 
      } 

      // Setup and Handover data to recyclerview 
      vistaRallye = (RecyclerView) getView().findViewById(R.id.llistarallyes); 
      adaptadorRallye = new AdapterRallye(getActivity(), data); 
      vistaRallye.setAdapter(adaptadorRallye); 
      vistaRallye.setLayoutManager(new LinearLayoutManager(getActivity())); 

     } catch (JSONException e) { 
      Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show(); 
     } 

    } 

} 

}

的問題出現:

// Read data sent from server 
       InputStream input = conn.getInputStream(); 
       BufferedReader reader = new BufferedReader(new InputStreamReader(input)); 
       StringBuilder result = new StringBuilder(); 
       String line; 

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

       // Pass data to onPostExecute method 
       return (result.toString()); 

這個變量,結果是這裏經過,在那裏我做了JSON解析。但因爲它是空的,它直接進入catch異常:

@Override 
    protected void onPostExecute(String result) { 

     //this method will be running on UI thread 

     pdLoading.dismiss(); 
     List<DataRallye> data = new ArrayList<>(); 

     pdLoading.dismiss(); 
     try { 
      JSONArray jArray = new JSONArray(result); 

      // Extract data from json and store into ArrayList as class objects 
      for (int i = 0; i < jArray.length(); i++) { 
       JSONObject json_data = jArray.getJSONObject(i); 
       DataRallye dadesrallye = new DataRallye(); 
       dadesrallye.RallyeNom = json_data.getString("nom"); 
       dadesrallye.RallyeTipus = json_data.getString("tipus"); 
       dadesrallye.RallyeDataI = json_data.getString("datai"); 
       dadesrallye.RallyeDataF = json_data.getString("dataf"); 
       dadesrallye.RallyeCiutat = json_data.getString("ciutat"); 
       dadesrallye.RallyeOrganitzacio = json_data.getString("organitzacio"); 
       dadesrallye.RallyeFoto = json_data.getString("foto"); 
       data.add(dadesrallye); 
      } 

      // Setup and Handover data to recyclerview 
      vistaRallye = (RecyclerView) getView().findViewById(R.id.llistarallyes); 
      adaptadorRallye = new AdapterRallye(getActivity(), data); 
      vistaRallye.setAdapter(adaptadorRallye); 
      vistaRallye.setLayoutManager(new LinearLayoutManager(getActivity())); 

     } catch (JSONException e) { 
      Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show(); 
     } 

這裏是從我們的網站上的PHP文件生成的JSON:

[{"id_rally":"1","nom":"45e rallye costa brava","tipus":"velocitat i regularitat","datai":"2017-06-20","dataf":"2017-06-22","ciutat":"Girona","organitzacio":"rallyclassics ","foto":"brava.png"},{"id_rally":"2","nom":"26e rallye igualada","tipus":"velocitat","datai":"2017-08-13","dataf":"2017-08-16","ciutat":"Igualada","organitzacio":"ecb org","foto":"igualada.png"}] 
+0

'conn.setDoOutput(true);'。刪除該行。 – greenapps

+0

'result.append(line);'這應該是'result.append(line)+「\ n」;' – greenapps

+0

@greenapps解決了我的問題!萬分感謝!這條線是幹什麼的?謝謝! –

回答

1
conn.setDoOutput(true);. 

刪除了這一行。因爲您不會將數據寫入輸出流。

result.append(line); 

這應該是

result.append(line) + "\n"; 
0

對於 'GET' 連接設置

conn.setDoOutput(false); 

setDoOutput(真)用於POST和PUT請求。

相關問題