简体   繁体   中英

Json paring with Recycler view

Here I am trying to display the name and price of the test. and I'm taking a recycler view to do the same using the JET Parsing GET method. But I'm not getting anything in my business and showing myself black there. here is my code please help me find the solution.

Model class

        public class TestListsModel {

        public String test_price;

        public String testlist_id;

        public String test_name;
    }

This is my Adapter:

public class AdapterTestList  extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private Context context;
        private LayoutInflater inflater;
        List<TestListsModel> data= Collections.emptyList();
        TestListsModel current;
        int currentPos=0;

        // create constructor to innitilize context and data sent from MainActivity
        public AdapterTestList(Context context, List<TestListsModel> data){
            this.context=context;
            inflater= LayoutInflater.from(context);
            this.data=data;
        }

        // Inflate the layout when viewholder created
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view=inflater.inflate(R.layout.test_list_row, parent,false);
            MyHolder holder=new MyHolder(view);
            return holder;
        }

        // Bind data
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

            // Get current position of item in recyclerview to bind data and assign values from list
            MyHolder myHolder= (MyHolder) holder;
            TestListsModel current=data.get(position);
            myHolder.testName.setText(current.test_name);
            myHolder.testPrice.setText( current.test_price);


            // load image into imageview using glide
           /* Glide.with(context).load("http://192.168.1.7/test/images/" + current.fishImage)
                    .placeholder(R.drawable.ic_img_error)
                    .error(R.drawable.ic_img_error)
                    .into(myHolder.ivFish);*/

        }

        // return total item from List
        @Override
        public int getItemCount() {
            return data.size();
        }


        class MyHolder extends RecyclerView.ViewHolder{

            TextView testName;
            TextView testPrice;

            // create constructor to get widget reference
            public MyHolder(View itemView) {
                super(itemView);

                testName = (TextView) itemView.findViewById(R.id.test_name);
                testPrice = (TextView) itemView.findViewById(R.id.price_name);

            }

        }

    }

This is my Activity Class:

public class HealthServicesActivity extends AppCompatActivity implements View.OnClickListener {

            SharePreferenceManager<LoginModel> sharePreferenceManager;

            // CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
            public static final int CONNECTION_TIMEOUT = 10000;
            public static final int READ_TIMEOUT = 15000;
            private RecyclerView testListRecylerView;
            private AdapterTestList mAdapter;

         @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_health_services);
                ButterKnife.bind(this);

                sharePreferenceManager = new SharePreferenceManager<>(getApplicationContext());

                dayTimeDisplay();

                new AsyncLogin().execute();
            }

 private class AsyncLogin extends AsyncTask<String, String, String> {
        //ProgressDialog pdLoading = new ProgressDialog(getApplicationContext());
        HttpURLConnection conn;
        URL url = null;

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

            //this method will be running on UI thread
          /*  pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();*/

        }

        @Override
        protected String doInBackground(String... params) {
            try {

                String url_test="http://192.168.1.80/aoplnew/api/users/gettestlist/"+sharePreferenceManager.getUserLoginData(LoginModel.class).getResult().getCenterId();
                // Enter URL address where your json file resides
                // Even you can make call to php file which returns json data
                //url = new URL("http://192.168.1.7/test/example.json");
                url = new URL(url_test);

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return e.toString();
            }
            try {

                // Setup HttpURLConnection class to send and receive data from php and mysql
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("GET");

                // setDoOutput to true as we recieve data from json file
                conn.setDoOutput(true);

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                return e1.toString();
            }

            try {

                int response_code = conn.getResponseCode();

                // Check if successful connection made
                if (response_code == HttpURLConnection.HTTP_OK) {

                    // Read data sent from server
                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                    // Pass data to onPostExecute method
                    return (result.toString());

                } else {

                    return ("[]");
                }

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


        }

        @Override
        protected void onPostExecute(String result) {

            //this method will be running on UI thread

            //pdLoading.dismiss();
            List<TestListsModel> data=new ArrayList<>();

            //pdLoading.dismiss();
            try {

                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList as class objects
                for(int i=0;i<jArray.length();i++){
                    JSONObject json_data = jArray.getJSONObject(i);
                    TestListsModel testData = new TestListsModel();
                    testData.testlist_id= json_data.getString("testlist_id");
                    testData.test_name= json_data.getString("test_name");
                    testData.test_price= json_data.getString("test_price");

                    data.add(testData);
                }

                // Setup and Handover data to recyclerview
                testListRecylerView = (RecyclerView)findViewById(R.id.test_list_recycler_view);
                mAdapter = new AdapterTestList(HealthServicesActivity.this, data);
                testListRecylerView.setAdapter(mAdapter);
                testListRecylerView.setLayoutManager(new LinearLayoutManager(HealthServicesActivity.this));

            } catch (JSONException e) {
                Toast.makeText(HealthServicesActivity.this, e.toString(), Toast.LENGTH_LONG).show();
            }

        }

    }
}

Thanks in advance for any answer!

You need to set the setLayoutManager before the setting the adapter like below. In your code, you have setAdapter() before the setLayoutManager therefore your adapter not set properly.

Refer this for the further explanation https://developer.android.com/guide/topics/ui/layout/recyclerview

    testListRecylerView = (RecyclerView)findViewById(R.id.test_list_recycler_view);


    mAdapter =  new AdapterTestList(HealthServicesActivity.this, data);
    /**
     * SET THE LAYOUT MANAGER BEFORE SETTING THE ADAPTER
     */

    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(HealthServicesActivity.this);
    testListRecylerView.setLayoutManager(mLayoutManager);
    testListRecylerView.setItemAnimator(new DefaultItemAnimator());

     /**
      * AND THAN SET THE ADAPTER 
      */

    testListRecylerView.setAdapter(mAdapter);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM