简体   繁体   中英

Recyclerview+JSON+Fragment+Android

I'm trying to pass an Arraylist with Objects obtained from a JSON, and pass to another fragment in Android Studio.

Here is the class that i want to receive the array

   @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_car, container, false);

        new AsyncTaskParseJson().execute();



        mRecyclerView = (RecyclerView) view.findViewById(R.id.rv_list);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.addOnItemTouchListener(new RecyclerViewTouchListener( getActivity(), mRecyclerView, this ));

        LinearLayoutManager llm = new LinearLayoutManager(getActivity());
        llm.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(llm);

        CarAdapter adapter = new CarAdapter(getActivity(), mList);
        mRecyclerView.setAdapter( adapter );

        return view;
    }

That is my class that is creating the array:

   public class AsyncTaskParseJson extends AsyncTask<String, String, String> {

        final String TAG = "AsyncTaskParseJson.java";
        String yourJsonStringUrl = "http://marciowelben.servidorturbo.net/getjson.php";
        JSONArray dataJsonArr = null;

        @Override
        protected void onPreExecute() {}

        @Override
        protected String doInBackground(String... arg0) {

            try {
                JsonParser jParser = new JsonParser();
                JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
                dataJsonArr = json.getJSONArray("emp_info");
                for (int i = 0; i < dataJsonArr.length(); i++) {

                    JSONObject c = dataJsonArr.getJSONObject(i);

                    // Storing each json item in variable
                    String firstname = c.getString("employee name");
                    String lastname = c.getString("employee no");

                    Car d = new Car(firstname, lastname, R.mipmap.ic_launcher );
                    listAux.add(d);
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
            mList = listAux;
            return null;
        }
    }

So i just want to populate my Recyclerview with this array.

Since you are adding the adapter first before waiting for the data to return you will have to call notifyDataSetChanged() for the adapter to redraw the list after it is done parsing. Another way of accomplishing this is waiting for the result to come back and then set the adapter. See below

public class MainActivity extends AppCompatActivity {
 private static final String TAG = "RecyclerViewExample";

    private List<FeedItem> feedItemList = new ArrayList<FeedItem>();

    private RecyclerView mRecyclerView;

    private MyRecyclerAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        /* Initialize recyclerview */
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        /*Downloading data from below url*/
        final String url = "http://javatechig.com/api/get_category_posts/?dev=1&slug=android";
        new AsyncHttpTask().execute(url);
    }

    public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {

        @Override
        protected void onPreExecute() {
            setProgressBarIndeterminateVisibility(true);
        }

        @Override
        protected Integer doInBackground(String... params) {
            InputStream inputStream = null;
            Integer result = 0;
            HttpURLConnection urlConnection = null;

            try {
                /* forming th java.net.URL object */
                URL url = new URL(params[0]);

                urlConnection = (HttpURLConnection) url.openConnection();

                /* for Get request */
                urlConnection.setRequestMethod("GET");

                int statusCode = urlConnection.getResponseCode();

                /* 200 represents HTTP OK */
                if (statusCode ==  200) {

                    BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = r.readLine()) != null) {
                        response.append(line);
                    }

                    parseResult(response.toString());
                    result = 1; // Successful
                }else{
                    result = 0; //"Failed to fetch data!";
                }

            } catch (Exception e) {
                Log.d(TAG, e.getLocalizedMessage());
            }

            return result; //"Failed to fetch data!";
        }

        @Override
        protected void onPostExecute(Integer result) {

            setProgressBarIndeterminateVisibility(false);

            /* Download complete. Lets update UI */
            if (result == 1) {
                adapter = new MyRecyclerAdapter(MainActivity.this, feedItemList);
                mRecyclerView.setAdapter(adapter);
            } else {
                Log.e(TAG, "Failed to fetch data!");
            }
        }
    }

    private void parseResult(String result) {
        try {
            JSONObject response = new JSONObject(result);
            JSONArray posts = response.optJSONArray("posts");

            /*Initialize array if null*/
            if (null == feedItemList) {
                feedItemList = new ArrayList<FeedItem>();
            }

            for (int i = 0; i < posts.length(); i++) {
                JSONObject post = posts.optJSONObject(i);

                FeedItem item = new FeedItem();
                item.setTitle(post.optString("title"));
                item.setThumbnail(post.optString("thumbnail"));
                feedItemList.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
1.Design Recycleview in layout
  <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingTop="10dp"
        android:layout_weight="1"
        />
2.add dependency in gradle.build
 compile 'com.android.support:recyclerview-v7:23.1.1'

3.Write the code in Activity

public class DoctorInformationActivity extends AppCompatActivity {

    String URL="YOUR URL";

    JSONArray Cities=null;

    ArrayList<DocotorInformation> doctorList =new ArrayList<DocotorInformation>();
    Sqlitedatabase sql;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.doctor_information_listview);
        sql=new Sqlitedatabase(getApplicationContext());
        ConnectivityManager connectivityManager
                = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        if(activeNetworkInfo != null && activeNetworkInfo.isConnected())
        {
            Toast.makeText(getApplicationContext()," connect",Toast.LENGTH_LONG).show();
            new JSONAsyncTask().execute();
        }
        else
        {
            ArrayList<DocotorInformation> listdata=sql.getAllContacts();
            doctorList=listdata;
            RecyclerView  recyclerView = (RecyclerView) findViewById(R.id.recycler_view);


            DoctorAdapter mAdapter = new DoctorAdapter(getApplicationContext(), doctorList);
            recyclerView.setAdapter(mAdapter);
            recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

            Toast.makeText(getApplicationContext(),"Not connect",Toast.LENGTH_LONG).show();
        }


    }

    private class JSONAsyncTask extends AsyncTask<String, Void, JSONArray> {

        private ProgressDialog dialog = new ProgressDialog(DoctorInformationActivity.this);

        @Override
        protected void onPreExecute() {
            this.dialog.setMessage("Please wait");
            this.dialog.show();
        }

        @Override
        protected JSONArray doInBackground(String... urls) {
            try {

                //------------------>>
                HttpGet httppost = new HttpGet(URL);
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = httpclient.execute(httppost);

                // StatusLine stat = response.getStatusLine();
                int status = response.getStatusLine().getStatusCode();

                if (status == 200) {
                    HttpEntity entity = response.getEntity();
                    String data = EntityUtils.toString(entity);


                    JSONObject jsono = new JSONObject(data);
                    Cities = jsono.getJSONArray("SearchDoctorsData");
                    return Cities;
                }


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

                e.printStackTrace();
            }
            return Cities;
        }

        protected void onPostExecute(JSONArray result) {
            dialog.dismiss();
            System.out.println(result);

            for (int i = 0; i < result.length(); i++) {
                JSONObject c = null;
                try {
                    DocotorInformation doc=new DocotorInformation();
                    c = result.getJSONObject(i);
                    doc.setName(c.getString("DoctorName"));
                    doc.setNumber(c.getString("Mobile"));
                    doctorList.add(doc);

                    sql.insertData(doc);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            RecyclerView  recyclerView = (RecyclerView) findViewById(R.id.recycler_view);


        DoctorAdapter mAdapter = new DoctorAdapter(getApplicationContext(), doctorList);
        recyclerView.setAdapter(mAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));


    }
}
}


public class DoctorAdapter extends RecyclerView.Adapter<DoctorAdapter.ViewHolder> {
private ArrayList<DocotorInformation> countries;
Context con;
public DoctorAdapter(Context c ,ArrayList<DocotorInformation> countries) {
    this.con=c;
        this.countries = countries;
        }

@Override
public DoctorAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.doctor_textviews, viewGroup, false);
        return new ViewHolder(view);
        }

@Override
public void onBindViewHolder(DoctorAdapter.ViewHolder viewHolder, int i) {
    viewHolder.name.setText(countries.get(i).getName());
        viewHolder.number.setText(countries.get(i).getNumber());
        }

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

public class ViewHolder extends RecyclerView.ViewHolder{
    private TextView name,number;
    public ViewHolder(View view) {
        super(view);

        name = (TextView)view.findViewById(R.id.name);
        number = (TextView)view.findViewById(R.id.numebr);
    }
}

}

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