将RecyclerView适配器类中的JSON数组传递给活动类

时间:2017-08-31 11:54:57

标签: android json android-recyclerview

我有一个RecyclerView,我正在创建一个JSON数组,其中包含在onClick方法中单击的元素ID。我能够生成JSON数组,但是我将这个JSON数组传递给我的Activity时遇到了麻烦。

我创建了一个界面:

public interface ClientDataTransfer {
public void getValues(JSONArray jsonArray);
}

并修改了适配器构造函数,如下所示:

public ClientListAdapter(List<ClientListData> clientListData, Context context, ClientDataTransfer clientDataTransfer) {
    super();

    this.clientListData = clientListData;
    this.context = context;
    this.clientDataTransfer = clientDataTransfer;
}

在我的Activity类中,我正在设置适配器,如下所示:

recyclerViewAdapter = new ClientListAdapter(clientListData, this, this);
            recyclerView.setAdapter(recyclerViewAdapter);

我在Activity类中实现了Interface并继承了该方法,但是我在Activity类中获取JSON数组时遇到了麻烦。

我在onBindViewHolder中的setOnClickListener方法中创建了JSON数组。

这是我的适配器类:

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

private Context context;
private List<ClientListData> clientListData;
public JSONArray clientArray = new JSONArray();
public ClientDataTransfer clientDataTransfer;


public ClientListAdapter(List<ClientListData> clientListData, Context context, ClientDataTransfer clientDataTransfer) {
    super();

    this.clientListData = clientListData;
    this.context = context;
    this.clientDataTransfer = clientDataTransfer;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.client_list_item, parent, false);
    ViewHolder viewHolder = new ViewHolder(view);

    return viewHolder;
}

@Override
public void onBindViewHolder(final ClientListAdapter.ViewHolder holder, final int position) {

    final ClientListData clientListDataModel = clientListData.get(position);
    holder.clientList.setText(clientListDataModel.getClientName());

    holder.itemView.setBackgroundColor(clientListDataModel.isSelected() ? Color.GRAY : Color.WHITE);
    holder.clientList.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            clientListDataModel.setSelected(!clientListDataModel.isSelected());

            try {
                JSONObject clientObject = new JSONObject();
                if(clientListDataModel.isSelected()) {
                    holder.itemView.setBackgroundColor(Color.GRAY);
                    clientObject.put("id", clientListData.get(position).getClientId());
                    clientArray.put(clientObject);
                } else if(!clientListDataModel.isSelected()) {

                    holder.itemView.setBackgroundColor(Color.WHITE);

                    for (int i = 0; i < clientArray.length(); i++) {
                        clientObject = clientArray.getJSONObject(i);
                        if (clientObject.getString("id").equals(clientListDataModel.getClientId())) {
                            clientArray=removeFromJsonArray(clientArray,i);
                            break;
                        }
                    }
                }
                //clientArray.put(clientObject);

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

            clientDataTransfer.getValues(clientArray);
            Log.e("client id array", ""+clientArray);
        }
    });
}

@Override
public int getItemCount() {
    return clientListData == null ? 0:clientListData.size();
}

class ViewHolder extends RecyclerView.ViewHolder {

    public TextView clientList;

    public ViewHolder(View itemView) {
        super(itemView);

        clientList = (TextView) itemView.findViewById(R.id.tv_client_list);

    }
}

private JSONArray removeFromJsonArray(JSONArray array,int position) {
    JSONArray newArray = new JSONArray();
    for (int i=0;i<array.length();i++)
    {
        //Excluding the item at position
        if (i != position)
        {
            try {
                newArray.put(array.get(i));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    return newArray;
}
}

holder.clientList.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            clientListDataModel.setSelected(!clientListDataModel.isSelected());

            try {
                JSONObject clientObject = new JSONObject();
                if(clientListDataModel.isSelected()) {
                    holder.itemView.setBackgroundColor(Color.GRAY);
                    clientObject.put("id", clientListData.get(position).getClientId());
                    clientArray.put(clientObject);
                } else if(!clientListDataModel.isSelected()) {

                    holder.itemView.setBackgroundColor(Color.WHITE);

                    for (int i = 0; i < clientArray.length(); i++) {
                        clientObject = clientArray.getJSONObject(i);
                        if (clientObject.getString("id").equals(clientListDataModel.getClientId())) {
                            clientArray=removeFromJsonArray(clientArray,i);
                            break;
                        }
                    }
                }
                //clientArray.put(clientObject);

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

            clientDataTransfer.getValues(clientArray);
            Log.e("client id array", ""+clientArray);
        }
    }); 

这是我正在实现适配器的Activity类:

public class ClientListActivity extends AppCompatActivity implements View.OnClickListener, ClientDataTransfer {

private String groupId;
private String clientId;
private String clientName;
private RecyclerView recyclerView;
private List<ClientListData> clientListData;
private RecyclerView.LayoutManager recyclerViewLayoutManager;
private RecyclerView.Adapter recyclerViewAdapter;
private JSONArray clientArrayList = new JSONArray();
ClientDataTransfer clientDataTransferx;

private Toolbar toolbar;
private FloatingActionButton share;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_client_list);

    recyclerView = (RecyclerView) findViewById(R.id.rv_client_list);
    toolbar = (Toolbar) findViewById(R.id.client_list_toolbar);
    share = (FloatingActionButton) findViewById(R.id.floating_action_button);
    share.setOnClickListener(this);

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Window window = getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(ContextCompat.getColor(this, R.color.colorSecondary));
    }

    setSupportActionBar(toolbar);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);

    clientListData = new ArrayList<>();
    recyclerViewLayoutManager = new LinearLayoutManager(this);
    recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setLayoutManager(recyclerViewLayoutManager);

    if(getIntent() != null) {

        Bundle bundle = getIntent().getExtras();
        try {
            JSONObject jsonClientListObject = new JSONObject(getIntent().getStringExtra("clientList"));
            JSONArray clientArray = jsonClientListObject.optJSONArray("activeClients");

            for(int i = 0 ; i < clientArray.length(); i++) {
                ClientListData clientListData = new ClientListData();
                clientListData.setClientId(clientArray.getJSONObject(i).getString("id"));
                clientListData.setClientName(clientArray.getJSONObject(i).getString("name"));

                clientId = clientListData.getClientId();
                clientName = clientListData.getClientName();
            }
            groupId = bundle.getString("groupId");

            for(int i=0; i<clientArray.length(); i++) {
                ClientListData clientListDataModel = new ClientListData();
                JSONObject jsonObject = null;
                jsonObject = clientArray.getJSONObject(i);
                clientListDataModel.setClientName(jsonObject.getString("name"));
                clientListDataModel.setClientId(jsonObject.getString("id"));
                clientListData.add(clientListDataModel);
            }

            recyclerViewAdapter = new ClientListAdapter(clientListData, this, this);
            recyclerView.setAdapter(recyclerViewAdapter);

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

/*@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.select_all, menu);

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

        case R.id.select_all:

            break;
    }

    return super.onOptionsItemSelected(item);
}*/

@Override
public void getValues(JSONArray jsonArray) {

}

@Override
public void onClick(View v) {
    switch (v.getId()) {

        case R.id.floating_action_button:
            clientDataTransferx = new ClientDataTransfer() {
                @Override
                public void getValues(JSONArray jsonArray) {
                    clientDataTransferx.getValues(clientArrayList);
                }
            };
            break;
    }
}

}

1 个答案:

答案 0 :(得分:1)

将json对象传递为String 当你必须阅读使用时: -

JJSONObject obj = new JSONObject(Stringhere);
JSONArray jsonArray = obj.getJSONArray("results");
ArrayList < objectClass > somearray= new ArrayList < objectClass > ();
for (int i = 0; i < jsonArray.length(); i++) 
{
  Movie objectClass = new objectClass();
  JSONObject json_data = jsonArray.getJSONObject(i);
  somearray.setImageUrl(json_data.getString("key1"));
  somearray.setTitle(json_data.getString("key2"));
  somearray.setPlot(json_data.getString("key3"));
}