2016-07-10 199 views
0

我想從asstes文件夾android中讀取json文件,但我無法讀取它,甚至我的日誌沒有得到顯示後讀線任何人都可以告訴我什麼是錯的? 這裏是我的代碼: 公共類MapsActivity擴展FragmentActivity實現OnMapReadyCallback {無法讀取資產文件夾中的.json文件android

 private GoogleMap mMap; 

     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_maps); 
      // Obtain the SupportMapFragment and get notified when the map is ready to be used. 
      SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
        .findFragmentById(R.id.map); 
      mapFragment.getMapAsync(this); 

      loadJSONFromAsset(); 
     } 

     public String loadJSONFromAsset() { 

      String json = null; 
      try { 

       Log.d("entry", "loadJSONFromAsset: "+json); 

       InputStream is = getAssets().open("data.json"); 

       int size = is.available(); 

       byte[] buffer = new byte[size]; 

       is.read(buffer); 

       is.close(); 

       json = new String(buffer, "UTF-8"); 

       Log.d("json", "loadJSONFromAsset: "+json); 


      } catch (IOException ex) { 
       Log.d("error", "loadJSONFromAsset: "+ex.toString()); 
       ex.printStackTrace(); 
       return null; 
      } 
      return json; 


     } 

    here is the log: 
    07-10 22:38:53.174 9783-9783/com.nodapp D/entry: loadJSONFromAsset: null 
                } 
    07-10 22:38:53.174 9783-9783/com.nodapp I/ViewRootImpl: CPU Rendering VSync enable = true 
    07-10 22:38:53.174 9783-9783/com.nodapp W/IInputConnectionWrapper: getExtractedText on inactive InputConnection 
    07-10 22:38:53.204 9783-9783/com.nodapp W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection 
    07-10 22:38:53.234 9783-9783/com.nodapp W/IInputConnectionWrapper: getSelectedText on inactive InputConnection 
    07-10 22:38:53.234 9783-9783/com.nodapp I/Timeline: Timeline: Activity_idle id: [email protected] time:24068058 
    07-10 22:38:53.314 9783-9783/com.nodapp W/IInputConnectionWrapper: getTextAfterCursor on inactive InputConnection 

回答

1

試試這個:

public String loadJSONFromAsset() { 

    String json = null; 
    try { 

     Log.d("entry", "loadJSONFromAsset: "+json); 

     InputStream is = getAssets().open("data.json"); 

     StringBuilder buf=new StringBuilder(); 
     BufferedReader in= 
     new BufferedReader(new InputStreamReader(is, "UTF-8")); 
     String str; 

     while ((str=in.readLine()) != null) { 
      buf.append(str); 
     } 

     in.close(); 

     json = buf.toString(); 

     Log.d("json", "loadJSONFromAsset: "+json); 

    } catch (IOException ex) { 
     Log.d("error", "loadJSONFromAsset: "+ex.toString()); 
     ex.printStackTrace(); 
     return null; 
    } 
    return json; 
}