2016-08-11 8 views
1

以下は、assetsフォルダに保存されたJSONファイルを読み取るためのコードです。androidのJSONファイルを読み取ることができません

public class ReadJson extends Activity { 
public String loadJSONFromAsset() { 
    String json1 = null; 
    try { 

     InputStream is = getAssets().open("jsonfile1.json"); 
     int size = is.available(); 
     byte[] buffer = new byte[size]; 
     is.read(buffer); 
     is.close(); 
     json1 = new String(buffer, "UTF-8"); 
    } catch (IOException ex) { 
     ex.printStackTrace(); 
     return null; 
    } 
    return json1; 
} 
} 

アプリがクラッシュし、これを解決する方法

"Attempt to invoke virtual method 'android.content.res.AssetManager android.content.Context.getAssets()' on a null object reference" exception. 

を示して?

+0

パスが正しいことを確認してください。 –

+1

アクティビティの作成後にloadJSONを呼び出していることを確認してください。または、getApplicationContext.getAssets() – X3Btel

+0

これを参照してください:http://stackoverflow.com/questions/9544737/read-file-from-assets – DysaniazzZ

答えて

0

は、このコードを試してみてください。

BufferedReader reader = null; 
try { 
reader = new BufferedReader(
    new InputStreamReader(getAssets().open("jsonfile1.json"))); 

// do reading, usually loop until end of file reading 
String mLine; 
while ((mLine = reader.readLine()) != null) { 
    //process line 
    ... 
} 
} catch (IOException e) { 
//log the exception 
} finally { 
if (reader != null) { 
    try { 
     reader.close(); 
    } catch (IOException e) { 
     //log the exception 
    } 
} 
} 

は、あなたのファイルパスが

0

存在かないあなたは、以下のような何かをしようとしていることを確認してください。

try{ 
    StringBuilder buf=new StringBuilder(); 
    InputStream json = getAssets().open("jsonfile1.json"); 
    BufferedReader in = new BufferedReader(new InputStreamReader(json, "UTF-8")); 
    String str; 

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

    in.close(); 
} catch(Exception e){ 

} 

jsonfile1.jsonがアセットフォルダのファイルであることを確認してください。

0

いつloadJSONFromAsset()に電話しますか?あなたがアクティビティが作成される前にそれを呼び出すようです。以下を試してください:

public class ReadJson extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstaceState) { 
     super.onCreate(savedInstaceState); 
     loadJSONFromAsset(); // call after super.onCreate()!!!! 
     /// ... 
    } 

} 
関連する問題