如何将资产文件夹中的JSON数据加载到Recyclerview和Cardview中

时间:2016-12-13 03:54:16

标签: java android android-recyclerview android-cardview

我被RecyclerView中的数据卡住了。我在资产文件夹中有一个像这样的json:

"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
            },
    .......

我想将这些数据加载到我的RecyclerViewCardView。我已阅读了很多教程,但没有关于我的案例。 RecyclerView的每个教程总是从互联网上加载json。这是我的代码:

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; }
}

这是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);
    }
}
}

这是我的活动:

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);
}

我的参考文献:https://www.codeproject.com/tips/631546/parse-json-data-in-android 编辑: 我的应用程序强制停止,我收到此错误

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) 

每个答案对我都很有帮助。提前致谢

3 个答案:

答案 0 :(得分:0)

试试这种方式..

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);
    }
}

并在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));

}

我希望这会有所帮助

答案 1 :(得分:0)

  

我已阅读了很多教程,但没有关于我的案例。 RecyclerView的每个教程总是从互联网上加载json

这就是事情 - 无论您是从文件中读取,还是从互联网上读取,都会获得String。您需要知道的是如何将资产文件转换为String以遵循任何这些教程。剩下的JSON解析应该完全相同。

你似乎已经有了这种方法,所以我不知道你为什么不使用它。

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

现在,查看您的Adapter类,您有两个不同的列表,并且您的构造函数不会初始化除null之外的任何内容。

private List<Item> items; // null

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

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

您需要将一些参数传递给适配器。

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

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

其他问题与您需要在中加载任何内容之前需要初始化列表的事实有关。

你的NullPointerException是你在开始循环之前从未向array分配任何内容的事实。

@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);

}

答案 2 :(得分:0)

已解决

我最后的活动:

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);
    }

}
}

感谢大家提供有用的答案并提出建议