2

I'm confused about how to parse local Json. I tried alot, but I can't find a solution.
I want to populate an ArrayList which contains just a simple title - I want to add that tite from JSON to a RecylerView.

{
    "hollywood": [{
        "_id": "58d3264f93f24d2bc87bebf5",
        "title": "sagar rana",
        "image": "encrypted-tbn1.gstatic.com/...",
        "genre": "hollywood",
        "description": "This for only demo purpose",
        "release": 2010,
        "download": "No download",
        "youtube": "youtube.com/embed/C-5EOd8xavw...",
        "__v ": 0,
        "upload ": "2017-03-23T01:35:11.182Z"
    }]
}

MainActivty.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

import static android.R.attr.data;

public class MainActivity extends AppCompatActivity {
    RecyclerView recyclerView;
    MyAdapter recycleradapter;
    private ArrayList<Moviedemo> mArrayList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try {
            JSONObject obj = new JSONObject(loadJSONFromAsset());
            JSONArray m_jArry = obj.getJSONArray("hollywood");
            ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
            HashMap<String, String> m_li;

            for (int i = 0; i < m_jArry.length(); i++) {
                JSONObject jo_inside = m_jArry.getJSONObject(i);
                Log.d("Details-->", jo_inside.getString("hollywood"));
                String formula_value = jo_inside.getString("hollywood");
                String url_value = jo_inside.getString("url");

                //Add your values in your `ArrayList` as below:
                m_li = new HashMap<String, String>();
                m_li.put("formule", formula_value);
                m_li.put("url", url_value);

                formList.add(m_li);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        recycleradapter = new MyAdapter(mArrayList);
        recyclerView.setAdapter(recycleradapter);

        recyclerViewstart();
        loadJSONFromAsset();


    }

    private String loadJSONFromAsset() {
        String json = null;
        try {

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

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

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


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;


    }

    private void recyclerViewstart() {
        recyclerView=(RecyclerView)findViewById(R.id.recylce);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

    }
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Bhupinder Singh
  • 409
  • 5
  • 6
  • { "hollywood": [ { "_id": "58d3264f93f24d2bc87bebf5", "title": "sagar rana", "image": "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRGIS3UlHSRvHFV6fm8kOS5HsXI3BIY8oO1HgxHpmu2dYO6ci3-9A", "genre": "hollywood", "description": "This for only demo purpose", "release": "2010", "download": "No download", "youtube": "https://www.youtube.com/embed/C-5EOd8xavw", "__v": 0, "upload": "2017-03-23T01:35:11.182Z" } ] – Bhupinder Singh Mar 22 '17 at 15:55
  • You can use Gson for parsing the json – Sanjeet Mar 22 '17 at 15:56
  • @BhupinderSingh add it the post not as comment – Atef Hares Mar 22 '17 at 15:56
  • i am new to json – Bhupinder Singh Mar 22 '17 at 15:58
  • JSON isn't that difficult, so where exactly is the problem with this code? – OneCricketeer Mar 22 '17 at 16:06

4 Answers4

2

So this is your adapter.

recycleradapter = new MyAdapter(mArrayList);
recyclerView.setAdapter(recycleradapter);

You never initialized mArrayList... so do that first

mArrayList = new ArrayList<Moviedemo>();

Then, you'll want to add to that list after to determine what you want to parse in the JSON.

You have shown you know how to get an array and a string already.

I want to add title from json to recyler view

Just the title? As a string? Then why does the adapter hold a whole Moviedemo object?

// Set the adapter
recycleradapter = new MyAdapter(mArrayList);
recyclerView.setAdapter(recycleradapter);

// Open and parse file
try {
    JSONObject obj = new JSONObject(loadJSONFromAsset());
    JSONArray m_jArry = obj.getJSONArray("hollywood");

    for (int i = 0; i < m_jArry.length(); i++) {
        // Start an object
        Moviedemo movie = new Moviedemo();

        // Parse the JSON
        JSONObject jo_inside = m_jArry.getJSONObject(i);
        String title = jo_inside.getString("title");

        // Build the object
        movie.setTitle(title);

        // Add the object to the list
        mArrayList.add(movie);
    }

} catch (JSONException e) {
    e.printStacktrace();
}

// Update adapter
recycleradapter.notifyDataSetChanged();
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0

As have been shown here, this should do it:

StringBuilder buf = new StringBuilder();
InputStream json = getAssets().open("book/contents.json");
BufferedReader in =
    new BufferedReader(new InputStreamReader(json, "UTF-8"));
String str;

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

in.close();

and the you could do something like this to parse it:

JSONObject object = new JSONObject(jsonString);

using the org.jsonlibrary which can be found here

Community
  • 1
  • 1
Catman155
  • 155
  • 1
  • 9
0

Try this simple method

    private JSONObject getAssetJSON() {
        String inFile = "fileName.json";
        JSONObject assetJson = null;
        try {
            InputStream stream = context.getAssets().open(inFile);
            int size = stream.available();
            byte[] buffer = new byte[size];
            stream.read(buffer);
            stream.close();
            String assetString = new String(buffer);
            assetJson = new JSONObject(assetString);
        } catch (IOException e) {
            // Handle IO exceptions here
        } catch (JSONException e) {
            // Handle JSON exceptions here
        }
       return assetJson;
   }
albeee
  • 1,452
  • 1
  • 12
  • 20
0

Dealing with JSON is a most important step for any Android Application. As of my suggestion try learning about GSON Library.

These are some helpful links where you can have a better understanding of it. 1 . this , 2. this

Akshay Nandwana
  • 1,260
  • 11
  • 18