-4

I have this 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"}
 ]

I want to set it to a listview so i create this layouts 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>

and 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>

So, with my json how can i put it in my RecyclerView ?

thanks in advance and sorry for my english.

Ok, i have change my script. change my doInBackground a bit to something and then i create model as you guys suggested

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

and i create an adapter

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

Here is my full activity

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

        }

    }

}

But when i run it. I get this error

E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #3 Process: id.co.rpgroup.boby.mstore, PID: 5311 java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:300) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) at java.util.concurrent.FutureTask.setException(FutureTask.java:222) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:841) Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6118) at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:881) at android.view.ViewGroup.invalidateChild(ViewGroup.java:4320) at android.view.View.invalidate(View.java:10935) at android.view.View.invalidate(View.java:10890) at android.widget.AbsListView.resetList(AbsListView.java:1937) at android.widget.ListView.resetList(ListView.java:521) at android.widget.ListView.setAdapter(ListView.java:462) at id.co.rpgroup.boby.mstore.Rijek$getListRijek.doInBackground(Rijek.java:143) at id.co.rpgroup.boby.mstore.Rijek$getListRijek.doInBackground(Rijek.java:65) at android.os.AsyncTask$2.call(AsyncTask.java:288) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)  at java.lang.Thread.run(Thread.java:841)

 

Jyoti JK
  • 2,141
  • 1
  • 17
  • 40
YVS1102
  • 2,658
  • 5
  • 34
  • 63

4 Answers4

0

Steps to store your data in Recyclerview(But you are not updated, So Listview):

  • First create a data model class to store the items.
  • Create an ArrayList and store your whole JsonArray in this List.
  • Create a Custom ArrayAdapter of type Data model
  • Call this adapter in your listview.

Note: Please use Recyclerview and not Listview for best result

Edited Answer:

  • First of all change your Asynctask to pass the ArrayList to the onPostExecute
  • Once you get dataModels in onPostExecute, init and set your listview like below:

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

Thanks Happy Coding!

Siraj Sumra
  • 934
  • 1
  • 11
  • 28
0

Create model class for Response, then use gson library to convert json to model class, then use CustomAdapter with response model .

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

}

Add gson to gradle

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

then use below line

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

Then create custom adapter with above list : reference

Rajan Kali
  • 12,627
  • 3
  • 25
  • 37
0

Your problem has nothing to do with ListViews or RecyclerViews or anything.

Check at this line in your logcat:

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

This means that you re trying to access the UI Thread from another thread. If you want to access your UIThread in Android (which means to modify visual things into your app), it is necessary to do in in the UIThread (as you re using an AsyncTask, it is necessary to do the modification with the (onPostExecute()) method.

For more info: https://developer.android.com/reference/android/os/AsyncTask.html#onPostExecute(Result)

zapotec
  • 2,628
  • 4
  • 31
  • 53
0

In your fragment add this line,

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

And remove this from your async task

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

And in postexecute() method, add this line,

     Rijekadapter adapter= new Rijekadapter(dataModels,yourcontext);
     LinearLayoutManager linearLayoutManager = new LinearLayoutManager(yourcontext);
     myListview.setLayoutManager(linearLayoutManager);
     myListview.setAdapter(mAdapter);   
Jyoti JK
  • 2,141
  • 1
  • 17
  • 40