0

i get stuck in my data in RecyclerView. I have a json in asset folder like this :

"tTisch": {
        "t-tisch": [
            {
                "tischnr": 1,
                "departement": 1,
                "normalbeleg": 0,
                "kellner-nr": 0,
                "bezeich": "TABLE 01",
                "roomcharge": false,
                "betriebsnr": 0
            },
            {
                "tischnr": 2,
                "departement": 1,
                "normalbeleg": 0,
                "kellner-nr": 0,
                "bezeich": "TABLE 02",
                "roomcharge": false,
                "betriebsnr": 0
            },
            {
                "tischnr": 3,
                "departement": 1,
                "normalbeleg": 0,
                "kellner-nr": 0,
                "bezeich": "TABLE 03",
                "roomcharge": false,
                "betriebsnr": 0
            },
    .......

I want to load this data into my RecyclerView and CardView. I have read many tutorials but there is none regarding my case. Every tutorial for RecyclerView always loads json from internet. This is my codes :

Item.java

public class Item {
private String txt_no_table;
private String txt_pax;
private String txt_time;
private String txt_guestname;
private String txt_bill;

Item(String txt_no_table, String txt_pax, String txt_time, String txt_guestname, String txt_bill) {
    this.txt_no_table = txt_no_table;
    this.txt_pax = txt_pax;
    this.txt_time = txt_time;
    this.txt_guestname = txt_guestname;
    this.txt_bill = txt_bill;
}

public String getTxt_no_table() {
    return txt_no_table;
}

public String getTxt_pax() {
    return txt_pax;
}

public String getTxt_time() {
    return txt_time;
}

public String getTxt_guestname() {
    return txt_guestname;
}

public String getTxt_bill() { return txt_bill; }
}

This is Adapter.java :

public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
@SuppressWarnings("unused")
private static final String TAG = Adapter.class.getSimpleName();

private List<Item> items;

Context context;
List<Item> item;

public Adapter() {
    super();
    this.item = item;
    this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.table_item_occupied, parent, false);
    return new ViewHolder(v);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    final Item item = items.get(position);

    holder.txt_no_table.setText(item.getTxt_no_table());
    holder.txt_pax.setText(item.getTxt_pax());
    holder.txt_time.setText(item.getTxt_time());
    holder.txt_guestname.setText(item.getTxt_guestname());
    holder.txt_bill.setText(item.getTxt_bill());
}

@Override
public int getItemCount() {
    return items.size();
}

public static class ViewHolder extends RecyclerView.ViewHolder {
    TextView txt_no_table;
    TextView txt_pax;
    TextView txt_time;
    TextView txt_guestname;
    TextView txt_bill;

    public ViewHolder(View itemView) {
        super(itemView);

        txt_no_table= (TextView) itemView.findViewById(R.id.txt_no_table);
        txt_pax = (TextView) itemView.findViewById(R.id.txt_pax);
        txt_time = (TextView) itemView.findViewById(R.id.txt_time);
        txt_guestname = (TextView) itemView.findViewById(R.id.txt_guestname);
        txt_bill = (TextView) itemView.findViewById(R.id.txt_bill);
    }
}
}

This is my Activity :

public class TableActivity extends AppCompatActivity {
@SuppressWarnings("unused")

private static final String TAG = TableActivity.class.getSimpleName();
List<Item> items;
RecyclerView recyclerView;
RecyclerView.Adapter recyclerViewadapter;
JSONArray array;

public static String AssetJSONFile (String filename, Context context) throws IOException {
    AssetManager manager = context.getAssets();
    InputStream file = manager.open(filename);
    byte[] formArray = new byte[file.available()];
    file.read(formArray);
    file.close();

    return new String(formArray);
}

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_table);

    try {
        loadJSONFromAsset();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    recyclerView = (RecyclerView) findViewById(R.id.table_rv);
    items = new ArrayList<>();
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new GridLayoutManager(this, 6));
    //recyclerView.setLayoutManager(new LinearLayoutManager(this));

}

public void loadJSONFromAsset() throws IOException, JSONException {
    JSONObject json = null;
    Item items2 = new Item();
    InputStream is = getAssets().open("tableplan.json");
    int size = is.available();
    byte[] buffer = new byte[size];
    is.read(buffer);
    is.close();

    for (int i = 0; i<array.length(); i++) {
        try {
            json = array.getJSONObject(i);
            items2.set_txt_no_table(json.getString("bezeich"));
            items2.set_txt_pax(json.getString("normalbeleg"));
            items2.set_txt_time(json.getString("betriebsnr"));
            items2.set_txt_guestname(json.getString("betriebsnr"));
            items2.set_txt_bill(json.getString("betriebsnr"));

        } catch (JSONException e) {
            e.printStackTrace();
        }
        items.add(items2);
    }
    recyclerViewadapter = new Adapter(items);
    recyclerView.setAdapter(recyclerViewadapter);
}

My referencec : https://www.codeproject.com/tips/631546/parse-json-data-in-android EDITED: my app force stop and i get this error

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.development_laptop.vhp_restotemp, PID: 7897
              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.development_laptop.vhp_restotemp/com.example.development_laptop.vhp_restotemp.TableActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                  at android.app.ActivityThread.-wrap11(ActivityThread.java)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:148)
                  at android.app.ActivityThread.main(ActivityThread.java:5417)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference
                  at com.example.development_laptop.vhp_restotemp.TableActivity.loadJSONFromAsset(TableActivity.java:79)
                  at com.example.development_laptop.vhp_restotemp.TableActivity.onCreate(TableActivity.java:54)
                  at android.app.Activity.performCreate(Activity.java:6237)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                  at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                  at android.os.Handler.dispatchMessage(Handler.java:102) 
                  at android.os.Looper.loop(Looper.java:148) 
                  at android.app.ActivityThread.main(ActivityThread.java:5417) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

Every answer is very helpful for me. Thanks in advance

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
mario margo
  • 71
  • 2
  • 14

3 Answers3

0

Try this way..

public void loadJSONFromAsset() throws IOException, JSONException {
    String json = null;
    InputStream is = activity.getAssets().open("tableplan.json");
    int size = is.available();
    byte[] buffer = new byte[size];
    is.read(buffer);
    is.close();
    json = new String(buffer, "UTF-8");
    JSONObject obj = new JSONObject(json);
    JSONArray m_jArry = obj.getJSONArray("t-tisch");
    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("formule"));
        String getTxt_no_table = jo_inside.getString("bezeich");
        String getTxt_pax = jo_inside.getString("normalbeleg");
        String getTxt_time = jo_inside.getString("kellner-nr");
        String getTxt_guestname = jo_inside.getString("betriebsnr");
        String getTxt_bill = jo_inside.getString("kellner-nr");

        m_li = new HashMap<String, String>();
        m_li.put("bezeich", getTxt_no_table);
        m_li.put("normalbeleg", getTxt_pax);
        m_li.put("kellner-nr", getTxt_time);
        m_li.put("betriebsnr", getTxt_guestname);
        m_li.put("kellner-nr", getTxt_bill);

        formList.add(m_li);
    }
}

and call this method inside onCreate().

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_table);

    try {
        loadJSONFromAsset();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.table_rv);
    item1 = new ArrayList<>();
    recyclerView.setAdapter(new Adapter());
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new GridLayoutManager(this, 6));
    //recyclerView.setLayoutManager(new LinearLayoutManager(this));

}

I Hope this will help

V-rund Puro-hit
  • 5,518
  • 9
  • 31
  • 50
0

I have read many tutorials but there is none regarding my case. Every tutorial for RecyclerView always loads json from internet

Here's the thing - Whether you read from a file, or from the internet, you get a String. All you need to know is how to get an asset file into a String to follow any of those tutorials. The remaining JSON parsing should be the exact same.

And you seem to have that method already, so I do not know why you aren't using it.

public static String AssetJSONFile (String filename, Context context) throws IOException {

Now, looking at your Adapter class, you have two different lists and your constuctor isn't initializing anything but null.

private List<Item> items; // null

Context context; // null
List<Item> item; // null

public Adapter() {
    super();
    this.item = item;  // null
    this.context = context; // null
}

You need to pass in some parameters to the adapter.

private List<Item> items; // Only one list

public Adapter(Context ctx, List<Item> items) {
    super();
    this.items = items; 
    this.context = ctx;
}

And the rest of the issues are related to the fact that you need probably need the list initialized before you load anything into it.

Your NullPointerException is the fact that you never assigned anything to array before you started looping over it.

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

    recyclerView = (RecyclerView) findViewById(R.id.table_rv);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new GridLayoutManager(this, 6));

    String jsonString = null;
    try {
        jsonString = AssetJSONFile("tableplan.json", TableActivity.this);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    List<Item> items = new ArrayList<Item>();
    if (jsonString != null) {
        JSONObject jsonObj = new JSONObject(jsonString);

        // TODO: parse data into 'new Item()' objects
        // items.add(item);
    }

    Adapter adapter = new Adapter(TableActivity.this, items);
    recyclerView.setAdapter(adapter);

}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0

SOLVED

My final Activity :

public class TableActivity extends AppCompatActivity {
@SuppressWarnings("unused")

private static final String TAG = TableActivity.class.getSimpleName();
List<Item> items;
RecyclerView recyclerView;


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_table);



    recyclerView = (RecyclerView) findViewById(R.id.table_rv);
    items = new ArrayList<>();
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new GridLayoutManager(this, 6));
    //recyclerView.setLayoutManager(new LinearLayoutManager(this));

    writeJSON();

}

public void writeJSON() {
    try {
        JSONObject json = new JSONObject(loadJSONFromAsset());
        JSONArray tablelist = json.getJSONObject("response")
                .getJSONObject("tTisch").getJSONArray("t-tisch");

        for (int i = 0; i < tablelist.length(); i++) {
            Item items2 = new Item();
            JSONObject AllTable = tablelist.getJSONObject(i);

            items2.set_txt_no_table(AllTable.getString("bezeich"));
            items2.set_txt_pax(AllTable.getString("normalbeleg"));
            items2.set_txt_time(AllTable.getString("betriebsnr"));
            items2.set_txt_guestname(AllTable.getString("betriebsnr"));
            items.add(items2);
        }

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

    Adapter adapter = new Adapter(TableActivity.this, items);
    recyclerView.setAdapter(adapter);
}

public String loadJSONFromAsset() {
    StringBuilder stringBuilder = new StringBuilder();
    try {
        InputStream is = getAssets().open("tableplan.json");
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(is));

        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        }

        bufferedReader.close();

        Log.d("X","Response Ready:"+stringBuilder.toString());

        return stringBuilder.toString();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.deptes:
            if (item.isChecked()) item.setChecked(false);
            else item.setChecked(true);

            return true;

        case R.id.deptes2:
            if (item.isChecked()) item.setChecked(false);
            else item.setChecked(true);

            return true;

        case R.id.deptes3:
            if (item.isChecked()) item.setChecked(false);
            else item.setChecked(true);

            return true;

        default:

            return super.onOptionsItemSelected(item);
    }

}
}

Thanks everyone for helpful answer and suggest

mario margo
  • 71
  • 2
  • 14