-7

I want to parse text and image from a json on file in asset folder to my listview. Please explain clearly because I am biginner in android. Give me complete codes of all files. Thank you a lot.

Tabish Hussain
  • 852
  • 5
  • 13

2 Answers2

0

Just open the file from the assets folder like this

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

    while ((str=in.readLine()) != null) {
      buf.append(str);
    }
    }
    catch (IOException e1) {
        e1.printStackTrace();
    }
    result1 = buf.toString();

result1 will have the complete json from your file

then use this library called Gson to parse the json ...

Here is the tutorial for it Json parsing through Gson

Tabish Hussain
  • 852
  • 5
  • 13
0

Maybe code can help you.

public class MainActivity extends Activity {


private ListView listView;

private void log(String msg) {
    Log.d("DNB", this.getClass().getName() + ">>" + msg);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    this.listView = new ListView(this);


    String jsonData = loadJsonFromAsset();
    String[] items = parseJson(jsonData);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);

    listView.setAdapter(adapter);
    setContentView(listView);
    log("json from asset: " + jsonData);

}

private String[] parseJson(String jsonData) {

    String[] items = new String[0];
    if (jsonData != null) {
        try {
            JSONArray jsonArray = new JSONArray(jsonData);
            if (jsonArray != null) {
                items = new String[jsonArray.length()];
                for (int i = 0; i < items.length; i++) {
                    items[i] = jsonArray.get(i).toString();
                }
            }
        } catch (JSONException e) {
            log("err--" + e.toString());
        }
    }


    return items;
}


private String loadJsonFromAsset() {
    InputStream stream;
    try {
        stream = getBaseContext().getAssets().open("json_list.txt");
        if (stream != null) {
            int size = stream.available();
            byte[] buffer = new byte[size];
            stream.read(buffer);
            stream.close();

            if (buffer != null) {
                return new String(buffer);
            }
        }
    } catch (IOException e1) {
        log("err--" + e1.toString());
    }
    return "";
}

And json file at assets

["item line 1","item line 2","item line 3"]
Dungnbhut
  • 176
  • 5