【问题标题】:Send recycler view data into a json将回收站视图数据发送到 json
【发布时间】:2018-12-01 05:09:57
【问题描述】:

Attendance Screen

我正在为学生出勤创建一个应用程序我从服务器获取数据作为学生详细信息,现在我想获取收音机出席(绿色)或缺席(红色)的值,我该怎么做。 对不起我的英语

这是 JSON 格式,我将作为出勤详细信息发送回服务器

{
"Date": "",
"ClassRSN": "",
"SectionRSN": "",
"SessionRSN": "",
"Studentdetails": [
    {
        "AdmissionID": "",
        "Attendance": ""
    }
]}

我无法迭代每个值

recyclerView 类

public class StudentDetailsAdapter extends RecyclerView.Adapter<StudentDetailsAdapter.ViewHolder> {
private Context context;
Integer attendance;


ArrayList<HashMap<String, String>> StudentDetailList;

public StudentDetailsAdapter(Context context, ArrayList<HashMap<String, String>> Studetails) {
    this.context = context;
    StudentDetailList = Studetails;
    Log.e("MD", "" + Studetails);
}


@Override
public StudentDetailsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(context).inflate(R.layout.single_row_student_details, parent, false);
    return new StudentDetailsAdapter.ViewHolder(itemView);

}

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

    if (position % 2 == 1) {
        holder.itemView.setBackgroundColor(Color.parseColor("#FFFFFF"));

    } else {
        holder.itemView.setBackgroundColor(Color.parseColor("#FFFAF8FD"));

    }

    holder.tvrollno.setText(StudentDetailList.get(position).get("stu_no"));
    holder.tvname.setText(StudentDetailList.get(position).get("stu_name"));

    if (holder.rdBtnPresent.isChecked()) {
        attendance = 1;
    } else {
        attendance = 0;
    }
    try {
        // Creating JSONObject from String
        JSONObject jsonObjMain = new JSONObject(ConstantClass.myjsonstring);
        Log.e("jsonObjMain", "jsonObjMain" + jsonObjMain);
        jsonObjMain.put("Date", "30-11-2018");
        jsonObjMain.put("ClassRSN", "1");
        jsonObjMain.put("SectionRSN", "1");
        jsonObjMain.put("SessionRSN", "13");


        JSONArray quesans = new JSONArray(jsonObjMain.getString("Studentdetails"));
        for (int i = 0; i < StudentDetailList.size(); i++) {
            JSONObject studata = quesans.getJSONObject(i);
            studata.put("AdmissionID", StudentDetailList.get(position).get("stu_no"));
            studata.put("Attendance",StudentDetailList.get(position).attendance);

        }


    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}


@Override
public int getItemCount() {

    return StudentDetailList.size();

}

public class ViewHolder extends RecyclerView.ViewHolder {
    TextView tvrollno, tvname;
    RadioButton rdBtnPresent, rdBtnAbsent;

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

        tvrollno = (TextView) itemView.findViewById(R.id.tv_rollno);
        tvname = (TextView) itemView.findViewById(R.id.tv_name);
        rdBtnPresent = (RadioButton) itemView.findViewById(R.id.attendance_present);
        rdBtnAbsent = (RadioButton) itemView.findViewById(R.id.attendance_absent);


    }
}}

主活动

public class Attendance extends AppCompatActivity {
ArrayList<HashMap<String, String>> StudentList = new ArrayList<>();
Calendar myCalendar1;
RecyclerView rdrecyclerView;
DatePickerDialog.OnDateSetListener date1;
EditText etAttDAte;
Spinner classpinner, sectionspinner;
List<SpinnerBean> block;
Button btnGo;
ArrayList<HashMap<String, String>> StudentDetailsList = new ArrayList<>();
LinearLayout LL_studeatils;

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

    SetIDs();
    SpinnerData();


    InVokeDatePicker();
    getSystemDate();
}

public void InVokeDatePicker() {
    myCalendar1 = Calendar.getInstance();

    date1 = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            // TODO Auto-generated method stub
            myCalendar1.set(Calendar.YEAR, year);
            myCalendar1.set(Calendar.MONTH, monthOfYear);
            myCalendar1.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            updateLabel1();
        }

    };


    etAttDAte.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            new DatePickerDialog(Attendance.this, date1, myCalendar1
                    .get(Calendar.YEAR), myCalendar1.get(Calendar.MONTH),
                    myCalendar1.get(Calendar.DAY_OF_MONTH)).show();
        }
    });

}

private void updateLabel1() {
    String myFormat = "dd/MM/yyyy"; //In which you need put here
    SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);

    etAttDAte.setText(sdf.format(myCalendar1.getTime()));

}

public void getSystemDate() {
    Date c = Calendar.getInstance().getTime();
    System.out.println("Current time => " + c);

    SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
    String formattedDate = df.format(c);
    etAttDAte.setText(formattedDate);
}

public void SpinnerData() {
    final List<SpinnerBean> dist = UtilityClass.getAllDistrict(Attendance.this);
    classpinner.setAdapter(new StateListAdapter(Attendance.this, dist));

    classpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            SpinnerBean bean = (SpinnerBean) adapterView.getItemAtPosition(i);
            //Toast.makeText(getApplicationContext(), dist.get(i).getId(), Toast.LENGTH_LONG).show();
            ConstantClass.GetClass = dist.get(i).getId();
            block = UtilityClass.getDistricWiseBlock(Attendance.this, dist.get(i).getId());
            sectionspinner.setAdapter(new StateListAdapter(Attendance.this, block));
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {
            // DO Nothing here
        }
    });
    sectionspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            SpinnerBean bean = (SpinnerBean) adapterView.getItemAtPosition(i);

            //  Toast.makeText(getApplicationContext(), block.get(i).getId(), Toast.LENGTH_LONG).show();
            ConstantClass.GetSection = block.get(i).getId();

        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {
            // DO Nothing here
        }
    });
}

public void SetIDs() {
    rdrecyclerView = (RecyclerView) findViewById(R.id.recView);
    etAttDAte = (EditText) findViewById(R.id.attendance_date);
    classpinner = (Spinner) findViewById(R.id.spinner_class);
    sectionspinner = (Spinner) findViewById(R.id.spinner_section);
    btnGo = (Button) findViewById(R.id.btn_go);
    LL_studeatils = (LinearLayout) findViewById(R.id.LL_studetailsView);

    btnGo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            StudentDetailsList.clear();
            LL_studeatils.setVisibility(View.VISIBLE);
            new SendPostRequest().execute();
        }
    });
}

class SendPostRequest extends AsyncTask<String, Void, String> {

    protected void onPreExecute() {
    }

    protected String doInBackground(String... arg0) {

        try {

            java.net.URL url = new URL("http://mindfacttech.com/api/SchoolERPAPITemp/BL/StudentManager.php"); // here is your URL path
            Log.e("url", "" + url);

            JSONObject postDataParams = new JSONObject();
            postDataParams.put("ClassRSN", ConstantClass.GetClass);
            postDataParams.put("SectionRSN", ConstantClass.GetSection);
            postDataParams.put("studentlist", "yes");
            Log.e("postDataParams", "" + postDataParams);


            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();

            int responseCode = conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {

                BufferedReader in = new BufferedReader(new
                        InputStreamReader(
                        conn.getInputStream()));

                StringBuffer sb = new StringBuffer("");
                String line = "";

                while ((line = in.readLine()) != null) {

                    sb.append(line);
                    break;
                }

                in.close();
                return sb.toString();

            } else {
                return new String("false : " + responseCode);
            }
        } catch (Exception e) {
            return new String("Exception: " + e.getMessage());
        }

    }

    @Override
    protected void onPostExecute(String result) {
        Log.e("result", "" + result);
        try {
            JSONObject jo = new JSONObject(result);
            Log.e("ConstantClass.resJSon", "" + jo);
            JSONArray jsonArray = new JSONArray(jo.getString("Students"));
            for (int i = 0; i < jsonArray.length(); i++) {

                HashMap<String, String> reqedetails = new HashMap<>();

                reqedetails.put("stu_no", jsonArray.getJSONObject(i).getString("AdmissionNo"));
                reqedetails.put("stu_name", jsonArray.getJSONObject(i).getString("Name"));
                String s1 = jsonArray.getJSONObject(i).getString("AdmissionNo");
                Log.e("s1", "" + s1);
                StudentDetailsList.add(reqedetails);
                Log.e("StudentDetailsList.....", "" + StudentDetailsList);
            }


            rdrecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL,
                    false));
            rdrecyclerView.setItemAnimator(new DefaultItemAnimator());
            rdrecyclerView.setAdapter(new StudentDetailsAdapter(getApplicationContext(), StudentDetailsList));
        } catch (JSONException e) {
            e.printStackTrace();


        }

    }

    public String getPostDataString(JSONObject params) throws Exception {

        StringBuilder result = new StringBuilder();
        boolean first = true;

        Iterator<String> itr = params.keys();

        while (itr.hasNext()) {

            String key = itr.next();
            Object value = params.get(key);

            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(key, "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(value.toString(), "UTF-8"));

        }
        return result.toString();
    }
}
public void getjsondata() {
    // Reading json file from assets folder
    StringBuffer sb = new StringBuffer();
    BufferedReader br = null;
    try {
        br = new BufferedReader(new InputStreamReader(getAssets().open(
                "Student.json")));
        String temp;
        while ((temp = br.readLine()) != null)
            sb.append(temp);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //                br.close(); // stop reading
    }
    ConstantClass.myjsonstring = sb.toString();}}

【问题讨论】:

  • 分享你的代码
  • @vikrantarankalle 请发现我编辑了我的问题
  • 点击单选按钮更新 ArrayList> StudentDetailList,然后使用 gson 库和反射将 ArrayList> StudentDetailList 转换为 json
  • 你能改一下吗@akshay
  • @PrateekGupta 使用 Radio 组代替单选按钮并在其上添加事件侦听器并根据事件更改您的数组列表数据

标签: android json android-recyclerview


【解决方案1】:

希望这会有所帮助。

在这里做一些改变。

//make jsonarray called "Studentdetails" and put it into your main json object.
JSONArray quesans = new JSONArray(jsonObjMain.getString("Studentdetails")); //  not requred
for (int i = 0; i < StudentDetailList.size(); i++) {
        JSONObject studata = new JSONOject();
        studata.put("AdmissionID", StudentDetailList.get(position).get("stu_no"));
        studata.put("Attendance",StudentDetailList.get(position).attendance);
        jsonObjMain.accumulate("Studentdetails" , studata);   // add this
    }

【讨论】:

  • 如何使用他们的 AdmissionID 获取每个学生的出勤率
  • 你能告诉我你为获得学生的出勤率做了什么吗?我的意思是你为学生上课或静态数组或在运行时接受输入。
  • 我从 API 获得了学生的详细信息并希望获得每个学生的出勤率
【解决方案2】:

您正在 onBindView 中制作 Json 对象??! ,每个滚动都会添加/重写到 json 数据。我猜你的应用程序会滞后。这样做 使用 getter 和 setter 创建一个具有所有学生属性的模型类。制作该模型类的arraylist。在回收站视图中显示它。用户标记出勤后,只需使用适配器中的方法将数组列表返回到包含 recyclerview 的活动。然后使用 gson 库从 arraylist 中为 u 制作 json 数据。

【讨论】:

  • 当然!你有例子吗
  • 很难找到一个拥有一切的例子。使用在线工具jsonschema2pojo.org 制作您的Student 模型。制作一个学生的 ArrayList 并使用 recyclerview 显示。在您的内部 ViewHolder 适配器类中设置一个 onclick 侦听器,您可以为每个学生设置 student.setAttendance(true/false)。使用简单的 return 语句获取 Student 的列表/数组列表。使用 gson 将 arraylist 更改为 json 以发布Gson gson = new Gson(); String post_this = gson.toJson(studentarraylist);
  • 我无法获得确切的代码,你能帮我看看吗
  • 这需要时间。无论如何你最终都会学会它。现在初始化另一个 hashmap,Hashmap&lt;Integer,Integer&gt; attendanceMap 用于适配器中的 rollnumber 和出席。在 onclick put (rollnumber,attendance) 中使用hackernoon.com/… 在recyclerview 上设置onclick 并在适配器public Hashmap&lt;Int,Int&gt; getAttendancemap(){ return attendanceMap; } 中创建一个方法,确保单选按钮具有默认状态,例如absent 或检查学生人数以防止部分数据.
猜你喜欢
  • 2018-08-01
  • 1970-01-01
  • 2020-12-22
  • 1970-01-01
  • 1970-01-01
  • 2020-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多