简体   繁体   中英

How to update data to recylerview on click

I am developing an app, wherein I get JSON data and I am displaying it in the recylcer view. Now on click to the recycler view, on the basis of the item clicked I need to fetch the JSON data from the server and display it in the same recycler view. Its kind of recursive function. I am unable to find anything.

In the MainActivity , I have created an inner class for doing network task

new LauncherLoadThread(rootView).execute(appUsername, appPassword, loadURL,   path);

class LauncherLoadThread extends AsyncTask<String, Integer, String[]> {

    private View rootView;

    public LauncherLoadThread(View rootView) {
        this.rootView = rootView;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onPostExecute(String[] strings) {
        super.onPostExecute(strings);
        progressBar.setVisibility(View.GONE);
        if (strings != null) {
            if (strings[0].contentEquals("200")) {
                try {
                    String data = strings[1];
                    Log.d("Data", data);
                    JSONArray allData = new JSONArray(data);

                    for (int i = 0; i < allData.length(); i++) {
                        JSONObject jsonObject = allData.getJSONObject(i);
                        String id = jsonObject.getString("id");
                        String name = jsonObject.getString("name");
                        String path = jsonObject.getString("path");
                        String leaf = jsonObject.getString("leaf");
                        Log.d("Loaded Data: ", "Id: " + id + ". name: " + name + ". Path: " + path);
                        LauncherModel launcherModel=new LauncherModel(id,name,leaf,path);
                        launcherModelList.add(launcherModel);
                    }

                    adapter=new LauncherAdapter(launcherModelList,getContext());
                    launcherRecyclerView.setAdapter(adapter);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Snackbar snackbar = Snackbar.make(rootView, strings[0] + " Something broke down.", Snackbar.LENGTH_LONG);
                View snackBarView = snackbar.getView();
                TextView tv = (TextView) snackBarView.findViewById(android.support.design.R.id.snackbar_text);
                snackbar.show();
            }
        } else {
            Snackbar snackbar = Snackbar.make(rootView, "Oops something went wrong.", Snackbar.LENGTH_LONG);
            View snackBarView = snackbar.getView();
            TextView tv = (TextView) snackBarView.findViewById(android.support.design.R.id.snackbar_text);
            snackbar.show();
        }
    }

    @Override
    protected String[] doInBackground(String... strings) {
        String username = strings[0];
        String password = strings[1];
        String url = strings[2];
        String path=strings[3];
        String processURL="";
        if(path.equals("")) {
            processURL=url+"?path=Library";
        }else {
            processURL=url+"?path=" + path;
        }
        Log.d("doInBackURL", url);

        String credential = Credentials.basic(username, password);
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .get()

                .addHeader("authorization", credential)
                .addHeader("content-type", "application/json")

                .build();

        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String body = response.body().string();

                Log.d("Body--->",body);
                String code = response.code() + "";
                Log.d("Code--->",code);
                String[] output = {code, body};
                return output;
            } else {
                String body = "Error: 404";
                String code = response.code() + "";
                String[] output = {code, body};
                return output;
            }

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

}

Here is my adapter onClickMethod :

public void onBindViewHolder(LauncherViewHolder holder, int position) {
    LauncherModel launcherModel = listItem.get(position);
    .......
    .......
    .......
    .......
    .......
    .......

    holder.launcherItemRelativeLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });
}

Here you have many options depending on architecture you using. Basically, you can create interface like MyCustomItemClickListener :

interface MyCustomItemClickListener {
    void onClick();
}

Than you extend MyCustomItemClickListener by Activity related to RecyclerView and override its method:

@Override
public void onClick(){
    // basically, here goes the logic you want on click
}

As I assume you already have ViewHolder in Adapter , the simple option would be to pass Activity as custom Listener in your `Adapter. Than, if we choose this option, it should work like this:

//adapter's inner
class SomeClassViewHolder(val view: View) extends RecyclerView.ViewHolder(view) {
    //here can be view initializing, like
    txtHeader = (TextView) view.findViewById(R.id.audio_subtitle);

    void bind(int position){
        // all view binding logic goes here, for example:
        txtHeader.setText("someText");

        // AND here is also your listener working:
        view.setOnClickListener{
            listener.onItemClick(item)
        }
    }
}

//and then in adapter
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        holder.bind(values.get(position));
}

The only trick here is to pass the view(Activity or Fragment) as listener to custom Adapter and it should work.

Edit : For sure, with this approach you can simply reload data from activity with your own logic, like make another async request.

您可以简单地调用Adapter类的notifyDataSetChanged()函数。

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