如何将所选项目发送到服务器?

时间:2018-06-30 15:56:26

标签: android android-recyclerview recycler-adapter

我正在我的应用程序上获取所选复选框的值。我想将用户检查的项目发送到服务器。我将json对象转换为json数组,以便在服务器中接收它。我该怎么办?

适配器

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

Context context;
private List<Problems> mDataset;
private static final int TYPE_HEADER = 0;
private static final int TYPE_FOOTER = 1;
private static final int TYPE_ITEM = 2;
private ProblemListener setProblemListener;
CardView cv;

public void setProblemListener(ProblemListener problemListener){
    this.setProblemListener = problemListener;
}
public class ViewHolder extends RecyclerView.ViewHolder{
    public TextView tvProblems, tvPrice;
    public Button btnProblem;
    Button btnSubmitProblem;
    CheckBox cbProblems;

    public ViewHolder(View itemView) {
        super(itemView);
        tvProblems = (TextView) itemView.findViewById(R.id.tvProblems);
        tvPrice = (TextView) itemView.findViewById(R.id.tvPrice);
        btnSubmitProblem = (Button) itemView.findViewById(R.id.btnProblems);
        cbProblems = (CheckBox) itemView.findViewById(R.id.cbProblems);

       overrideFonts(context, tvProblems);
    }
}
private void overrideFonts(final Context context, final View v) {
    try {
        if (v instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) v;
            for (int i = 0; i < vg.getChildCount(); i++) {
                View child = vg.getChildAt(i);
                overrideFonts(context, child);
            }
        } else if (v instanceof TextView ) {
            ((TextView) v).setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/RobotoCondensedBold.ttf"));
        }
    } catch (Exception e) {
    }
}

public void add(List<Problems> itemList){
    mDataset = itemList;
    notifyDataSetChanged();
}

public void remove(Problems item){
    int position = mDataset.indexOf(item);
    mDataset.remove(position);
    notifyItemRemoved(position);
}

public MyAdapter(Context con, List<Problems> myDataset){
    mDataset = myDataset;
    this.context = con;
}
@Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {


    View itemView;
    if (viewType == TYPE_ITEM) {
        //Inflating recycle view item layout
        itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.problem_content, parent, false);
        return new ItemViewHolder(itemView);

    } else if (viewType == TYPE_HEADER) {
        //Inflating header view
        itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.problem_recycler_header, parent, false);
        return new HeaderViewHolder(itemView);
    } else if (viewType == TYPE_FOOTER) {
        //Inflating footer view
        itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.problem_recycler_footer, parent, false);
        return new FooterViewHolder(itemView);
    }
    throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
}

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

    try {
    if (holder instanceof HeaderViewHolder) {

        HeaderViewHolder headerHolder = (HeaderViewHolder) holder;
        headerHolder.tvHeader.setText("Please kindly ask the mechanic what the problem is and check them to continue");

    } else {
        if (holder instanceof FooterViewHolder) {

            final FooterViewHolder footerHolder = (FooterViewHolder) holder;
            footerHolder.btnSubmitProblem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                  //  footerHolder.cbProblems.setOnClickListener(null);
                   setProblemListener.onProblemSelected(v, mDataset, position);

                }
            });

        } else if (holder instanceof ItemViewHolder) {
            ItemViewHolder itemView = (ItemViewHolder) holder;

            //in some cases, it will prevent unwanted situations
            itemView.cbProblems.setOnCheckedChangeListener(null);

            //if true, your checkbox will be selected, else unselected
            itemView.cbProblems.setChecked(mDataset.get(position-1).isSelected());

            itemView.tvPrice.setText(mDataset.get(position - 1).getPrice());
            itemView.tvProblems.setText(mDataset.get(position - 1).getProblems());


            itemView.cbProblems.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                    if (buttonView.isPressed()){
                        mDataset.get(position - 1).setSelected(isChecked);
                        Toast.makeText(context, "postion " + position + "Boolean value " + Boolean.valueOf(isChecked), Toast.LENGTH_SHORT).show();;
                    }

                }
            });

        }
    }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
@Override
public int getItemCount() {
    return mDataset.size()+2;
}

public int getItemViewType(int position) {

    if (position == 0) {
        return TYPE_HEADER;
    } else if (position == mDataset.size() + 1) {
        return TYPE_FOOTER;
    }
    return TYPE_ITEM;
}

private class HeaderViewHolder extends MyAdapter.ViewHolder {
    TextView tvHeader;

    public HeaderViewHolder(View view) {
        super(view);
        tvHeader = (TextView) view.findViewById(R.id.tvHeader);
        overrideFonts(context, tvHeader);
    }
}

private class FooterViewHolder extends MyAdapter.ViewHolder {
    Button btnSubmitProblem;
    CheckBox cbProblems;


    public FooterViewHolder(View view) {
        super(view);
        btnSubmitProblem = (Button) view.findViewById(R.id.btnProblems);
        cbProblems = (CheckBox) itemView.findViewById(R.id.cbProblems);
    }
}

private class ItemViewHolder extends MyAdapter.ViewHolder {
    TextView tvProblems, tvPrice;

    public ItemViewHolder(View itemView) {
        super(itemView);
        tvProblems = (TextView) itemView.findViewById(R.id.tvProblems);
        tvPrice = (TextView) itemView.findViewById(R.id.tvPrice);
        cv = (CardView)itemView.findViewById(R.id.cards);

    }
}

private class CheckboxViewHolder extends MyAdapter.ViewHolder {
    public CheckboxViewHolder(View itemView) {
        super(itemView);
        cbProblems = (CheckBox) itemView.findViewById(R.id.cbProblems);

    }
}
public interface ProblemListener{
    void onProblemSelected(View view, List<Problems> problem, int position);
}

}

MainActivity

public class ProblemsActivity extends AppCompatActivity {

private String PROBLEM_URL = MYURL.url + "get-problems";

CardView cardView;
CheckBox breakCheckBox;
private ListView getListValue, listView;
SharedPreferences sharedPreferences;
Button btnSubmitProblems;
String problems;
List<Problems> listProblems = new ArrayList<>();
DividerItemDecoration mDividerItemDecoration;
Toolbar toolbar;
private double price = 0.0;
private RecyclerView mRecyclerView;
 MyAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
/**
 * ATTENTION: This was auto-generated to implement the App Indexing API.
 * See https://g.co/AppIndexing/AndroidStudio for more information.
 */


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_problems);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    toolbar.setTitleTextColor(Color.parseColor("#FFFFFF"));
    if (getSupportActionBar() != null){
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }
    mRecyclerView = (RecyclerView) findViewById(R.id.problem_recycle_view);
    mRecyclerView.setHasFixedSize(true);

    mLayoutManager = new LinearLayoutManager(ProblemsActivity.this, LinearLayoutManager.VERTICAL, false);
    mRecyclerView.setLayoutManager(mLayoutManager);


    mAdapter = new MyAdapter(ProblemsActivity.this, listProblems);

    RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
    StringRequest stringRequest = new StringRequest(Request.Method.GET, PROBLEM_URL, new com.android.volley.Response.Listener<String>() {

        @Override
        public void onResponse(String response)
        {
            mRecyclerView.setAdapter(mAdapter);
            JSONParse jsonParse = new JSONParse(response);
            jsonParse.parseJSON();
            listProblems = jsonParse.getProblems();
            mAdapter.add(listProblems);
            mAdapter.notifyDataSetChanged();
        }

    }, new com.android.volley.Response.ErrorListener() {

        @Override

        public void onErrorResponse(VolleyError error) {
            Log.i("Info", "Failed");
            error.printStackTrace();

        }

    });
    int socketTimeout = 30000;
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    stringRequest.setRetryPolicy(policy);
    requestQueue.add(stringRequest);

    mRecyclerView.addItemDecoration(new DividerItemDecoration(ProblemsActivity.this, LinearLayoutManager.HORIZONTAL));
    mAdapter.setProblemListener(new MyAdapter.ProblemListener() {
        @Override
        public void onProblemSelected(View view, List<Problems> problem, int position) {

           selectedProblems = new ArrayList<>();
            for(Problems item: problem)
            {
                if(item.isSelected())
                {
                    selectedProblems.add(item);
                }
            }

            Gson gson = new Gson();
            String selectedProblem = gson.toJson(selectedProblems);

            JSONParse jsonParse = new JSONParse(selectedProblem);
            jsonParse.parseJSON();
            finalSelectedProblems = jsonParse.getProblems();

            sendProblemsToServer(selectedProblems);
    });
}

public void sendProblemsToServer(List<Problems> selectedProblems){

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.logout){

        SharedPreferences preferences = getSharedPreferences("Mypref", 0);
        preferences.edit().clear().commit();
        Intent intent = new Intent(ProblemsActivity.this, HomeActivity.class); // Create an Intent
        startActivity(intent); // Move to Verification Activity
 Toast.LENGTH_SHORT).show();
    }else if (id == android.R.id.home){
        finish();
    }
    return super.onOptionsItemSelected(item);
}

 }

我不知道将json数组中的数据转换为json对象后如何将其发送到服务器。我只是停留在这个问题上,花了几个小时试图弄清楚。

enter image description here

0 个答案:

没有答案