如何将我的json结果设置为RecyclerView?

时间:2018-02-15 09:26:18

标签: android listview

我有这个json。

 [
   {"RijekCode":"RK-K-SM3-035013","DrDocumentNo":"DRDOC-EH-K-SM3-14","DoDocumentNo":"DOSM-EG-GBAR1-2179","CreatedDate":"2018-02-15 09:50:10.857","CreatedBy":"1602762","Status":2,"ApprovedBy":"1602762","ApproveDate":"2018-02-15 09:57:38.720","CustomerCode":"K-SM3"},
   {"RijekCode":"RK-K-SM3-080101","DrDocumentNo":"DRDOC-EG-K-SM3-54","DoDocumentNo":"DOIM-EE-GM000-1471","CreatedDate":"2018-02-15 14:00:59.270","CreatedBy":"1602762","Status":0,"ApprovedBy":null,"ApproveDate":null,"CustomerCode":"K-SM3"}
 ]

我想将其设置为listview,所以我创建了这个布局 rijekmain.xml

   <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v7.widget.RecyclerView
         android:id="@+id/myListview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

rijekitem.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

        <EditText
            android:id="@+id/rijekno"
            android:layout_width="wrap_content"
            android:text="1"
            android:layout_marginLeft="10sp"
            android:layout_height="wrap_content" />

        <EditText
            android:id="@+id/drno"
            android:layout_width="wrap_content"
            android:text="2"
            android:layout_marginLeft="30sp"
            android:layout_height="wrap_content" />

        <EditText
            android:id="@+id/dono"
            android:layout_width="wrap_content"
            android:text="2"
            android:layout_marginLeft="30sp"
            android:layout_height="wrap_content" />


</LinearLayout>

所以,有了我的json,我怎么能把它放在我的RecyclerView中?

提前致谢并抱歉我的英语。

好的,我已经更改了我的脚本。把我的doInBackground改成了一些东西 然后我按你们的建议创建模型

public class RijekModel {

String DoDocumentNo,RijekCode,DrDocumentNo;


    public RijekModel(String RijekCode, String DrDocumentNo, String DoDocumentNo) {
        this.RijekCode=RijekCode;
        this.DrDocumentNo=DrDocumentNo;
        this.DoDocumentNo=DoDocumentNo;
    }

    public String getRijekCode() {
        return RijekCode;
    }

    public void setRijekCode(String rijekCode) {
        this.RijekCode = rijekCode;
    }

    public String getDrDocumentNo() {
        return DrDocumentNo;
    }

    public void setDrDocumentNo(String drDocumentNo) {
        this.DrDocumentNo = drDocumentNo;
    }

    public String getDoDocumentNo() {
        return DoDocumentNo;
    }

    public void setDoDocumentNo(String doDocumentNo) {
        this.DoDocumentNo = doDocumentNo;
    }
}

我创建了一个适配器

public class Rijekadapter  extends ArrayAdapter<RijekModel> {
    private ArrayList<RijekModel> dataSet;
    Context mContext;

    // View lookup cache
    private static class ViewHolder {
        TextView txtRK;
        TextView txtDO;
        TextView txtDR;

    }
    public Rijekadapter(ArrayList<RijekModel> data, Context context) {
        super(context, R.layout.rijekitem, data);
        this.dataSet = data;
        this.mContext=context;

    }
    private int lastPosition = -1;

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        RijekModel dataModel = getItem(position);
        // Check if an existing view is being reused, otherwise inflate the view
        ViewHolder viewHolder; // view lookup cache stored in tag

        final View result;

        if (convertView == null) {

            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(R.layout.rijekitem, parent, false);
            viewHolder.txtRK = (TextView) convertView.findViewById(R.id.rijekno);
            viewHolder.txtDO = (TextView) convertView.findViewById(R.id.drno);
            viewHolder.txtDR = (TextView) convertView.findViewById(R.id.dono);

            result=convertView;

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
            result=convertView;
        }

        viewHolder.txtRK.setText(dataModel.getRijekCode());
        viewHolder.txtDO.setText(dataModel.getDoDocumentNo());
        viewHolder.txtDR.setText(dataModel.getDrDocumentNo());

        return convertView;
    }
}

这是我的完整活动

public class Rijek extends Fragment {

    ArrayList<HashMap<String, String>> RijekLists;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        startASycnc();
        return inflater.inflate(R.layout.rijekmain, container, false);
    }

    public void startASycnc() {
        SessionHandler ses = new SessionHandler();
        String Nip = new SessionHandler().getNip(getContext());

        new getListRijek().execute(Nip);
    }

    @Override
    public Context getContext() {
        return super.getContext();
    }

    public class getListRijek extends AsyncTask<String,String,String>{
        Context ctx = getContext();

        HttpURLConnection conn;
        URL url = null;
        String result = "";

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected String doInBackground(String... params) {
            try {
                url = new URL("http://192.168.3.223:84/storelf/api/Getrijek");
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }

            try {
                // Setup HttpURLConnection class to send and receive data from php and mysql
                conn = (HttpURLConnection)url.openConnection();
                conn.setConnectTimeout(100);
                conn.setRequestMethod("POST");
                // setDoInput and setDoOutput method depict handling of both send and receive
                conn.setDoInput(true);
                conn.setDoOutput(true);
                // Append parameters to URL
                Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("user_login", params[0]);
                String query = builder.build().getEncodedQuery();
                // Open connection for sending data
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(query);
                writer.flush();
                writer.close();
                os.close();
                conn.connect();

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                return "exception";
            }
            try {
                int response_code = conn.getResponseCode();
                if (response_code == HttpURLConnection.HTTP_OK) {
                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        result += line;
                    }

                    try {


                        ArrayList<RijekModel> dataModels;
                        ListView theList =(ListView)getActivity().findViewById(R.id.myListview);

                        dataModels= new ArrayList<>();
                        Log.d("TAG", "jsonArray "+ result);

                        JSONArray jsonArray = new JSONArray(result);
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject c = jsonArray.getJSONObject(i);
                                String DrDocumentNo = c.getString("DrDocumentNo");
                                String DoDocumentNo = c.getString("DoDocumentNo");
                                String RijekCode = c.getString("RijekCode");

                                dataModels.add(new RijekModel(RijekCode, DoDocumentNo, DrDocumentNo));
                            }
                        Rijekadapter adapter= new Rijekadapter(dataModels,getContext());

                        theList.setAdapter(adapter);
                        }

                    catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                } else {
                  Log.e("ERROR", "ERR --> " +response_code);
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                conn.disconnect();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

        }

    }

}

但是当我跑的时候。我收到此错误

  

E / AndroidRuntime:致命异常:AsyncTask#3                                                                            处理:id.co.rpgroup.boby.mstore,PID:5311                                                                            java.lang.RuntimeException:执行时发生错误   doInBackground()                                                                                在android.os.AsyncTask $ 3.done(AsyncTask.java:300)                                                                                在   java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)                                                                                at java.util.concurrent.FutureTask.setException(FutureTask.java:222)                                                                                在java.util.concurrent.FutureTask.run(FutureTask.java:242)                                                                                在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:231)                                                                                在   java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)                                                                                在   java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:587)                                                                                在java.lang.Thread.run(Thread.java:841)                                                                             引起:android.view.ViewRootImpl $ CalledFromWrongThreadException:   只有创建视图层次结构的原始线程才能触及它   观点。                                                                                在android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6118)                                                                                在   android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:881)                                                                                在android.view.ViewGroup.invalidateChild(ViewGroup.java:4320)                                                                                在android.view.View.invalidate(View.java:10935)                                                                                在android.view.View.invalidate(View.java:10890)                                                                                在android.widget.AbsListView.resetList(AbsListView.java:1937)                                                                                在android.widget.ListView.resetList(ListView.java:521)                                                                                在android.widget.ListView.setAdapter(ListView.java:462)                                                                                在   id.co.rpgroup.boby.mstore.Rijek $ getListRijek.doInBackground(Rijek.java:143)                                                                                在   id.co.rpgroup.boby.mstore.Rijek $ getListRijek.doInBackground(Rijek.java:65)                                                                                在android.os.AsyncTask $ 2.call(AsyncTask.java:288)                                                                                在java.util.concurrent.FutureTask.run(FutureTask.java:237)                                                                                在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:231)                                                                                在   java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)                                                                                在   java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:587)                                                                                在java.lang.Thread.run(Thread.java:841)

4 个答案:

答案 0 :(得分:0)

在Recyclerview中存储您的数据的步骤(但您没有更新,所以Listview):

  • 首先创建一个数据模型类来存储项目。
  • 创建一个ArrayList并将整个JsonArray存储在此List中。
  • 创建数据模型类型的自定义ArrayAdapter
  • 在列表视图中调用此适配器。

注意:请使用Recyclerview而非Listview以获得最佳结果

编辑答案:

  • 首先更改您的Asynctask以将ArrayList传递给onPostExecute
  • 在onPostExecute中获取dataModel后,初始化并设置列表视图,如下所示:

    ListView yourListView = (ListView) findViewById(R.id.yourListView);
    Rijekadapter customAdapter = new Rijekadapter(List<RijekModel>,this);
    yourListView .setAdapter(customAdapter);
    

由于 快乐的编码!

答案 1 :(得分:0)

Response创建模型类,然后使用gson库将json转换为模型类,然后将CustomAdapter与响应模型一起使用。

<强> Response.java

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Response {

@SerializedName("RijekCode")
@Expose
private String rijekCode;
@SerializedName("DrDocumentNo")
@Expose
private String drDocumentNo;
@SerializedName("DoDocumentNo")
@Expose
private String doDocumentNo;
@SerializedName("CreatedDate")
@Expose
private String createdDate;
@SerializedName("CreatedBy")
@Expose
private String createdBy;
@SerializedName("Status")
@Expose
private int status;
@SerializedName("ApprovedBy")
@Expose
private String approvedBy;
@SerializedName("ApproveDate")
@Expose
private String approveDate;
@SerializedName("CustomerCode")
@Expose
private String customerCode;

public String getRijekCode() {
return rijekCode;
}

public void setRijekCode(String rijekCode) {
this.rijekCode = rijekCode;
}

public String getDrDocumentNo() {
return drDocumentNo;
}

public void setDrDocumentNo(String drDocumentNo) {
this.drDocumentNo = drDocumentNo;
}

public String getDoDocumentNo() {
return doDocumentNo;
}

public void setDoDocumentNo(String doDocumentNo) {
this.doDocumentNo = doDocumentNo;
}

public String getCreatedDate() {
return createdDate;
}

public void setCreatedDate(String createdDate) {
this.createdDate = createdDate;
}

public String getCreatedBy() {
return createdBy;
}

public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}

public int getStatus() {
return status;
}

public void setStatus(int status) {
this.status = status;
}

public String getApprovedBy() {
return approvedBy;
}

public void setApprovedBy(String approvedBy) {
this.approvedBy = approvedBy;
}

public String getApproveDate() {
return approveDate;
}

public void setApproveDate(String approveDate) {
this.approveDate = approveDate;
}

public String getCustomerCode() {
return customerCode;
}

public void setCustomerCode(String customerCode) {
this.customerCode = customerCode;
}

}

gson添加到gradle

compile 'com.google.code.gson:gson:2.8.2'

然后使用下面的行

Lis<Response> resultList = gson.fromJson(result, new TypeToken<List<Response>>(){}.getType());

然后使用上面的列表创建自定义适配器:reference

答案 2 :(得分:0)

您的问题与ListViews或RecyclerViews无关。

检查logcat中的这一行:

  

android.view.ViewRootImpl $ CalledFromWrongThreadException:只有   创建视图层次结构的原始线程可以触及其视图。

这意味着您尝试从另一个线程访问UI线程。 如果你想在Android中访问你的UIThread(这意味着将视觉内容修改为你的app),就必须在UIThread中进行操作(当你使用AsyncTask时,有必要使用(onPostExecute)进行修改( ))方法。

欲了解更多信息: https://developer.android.com/reference/android/os/AsyncTask.html#onPostExecute(Result)

答案 3 :(得分:0)

在你的片段中添加这一行,

 View v=inflater.inflate(R.layout.rijekmain, container, false);
 myListview=(RecyclerView)v.findViewById(R.id.myListview);
 startASycnc();
 return v;

从异步任务中删除它

Rijekadapter adapter= new Rijekadapter(dataModels,getContext());
theList.setAdapter(adapter);

在postexecute()方法中,添加此行

     Rijekadapter adapter= new Rijekadapter(dataModels,yourcontext);
     LinearLayoutManager linearLayoutManager = new LinearLayoutManager(yourcontext);
     myListview.setLayoutManager(linearLayoutManager);
     myListview.setAdapter(mAdapter);