0

it is list of student selected by me it is list of student already selected when i scroll list in my custom list view when i am running application then radio buttons at bottom are already checked when i am checking upper radio button .how can i set radio button so that its state never change on scrolling list .

Here is my code for studentlist.java

public class studentlist extends AppCompatActivity  {


    private static final String TAG_RESULTS="result";
    private static final String TAG_ID = "id";
    private static final String TAG_ClassDet = "classdetails";
    private static final String TAG_YEAR = "yearof";
    private static final String TAG_BRANCH ="branchof";
    private static final String TAG_SECTION ="sectionof";

    private static String KEY_SUCCESS = "success";
    private static String KEY_ERROR = "error";


    private  ArrayList<HashMap<String, String>> studentattendence,studentstatus;
    ListView listView;
    ArrayAdapter<Model> adapter;
    List<Model> list = new ArrayList<Model>();
    public ArrayList<HashMap<String, String>> personList;
    private static final String KEY_STUDENT = "student";
    private RadioGroup radioGroup;
    private RadioButton radiobtn;
public Button ok;
    private RadioButton radioButton;
    HashMap<String, String> contact,contactstatus;
    private String convertjson;
    private String statusofattendence;


    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.liststudent);




        listView = (ListView) findViewById(R.id.my_list);
studentattendence=new ArrayList<HashMap<String, String>>();
studentstatus=new ArrayList<HashMap<String, String>>();
        personList = new ArrayList<HashMap<String, String>>();
        Intent getstud = getIntent();
        personList = (ArrayList<HashMap<String, String>>) getstud.getSerializableExtra(KEY_STUDENT);
ok= (Button) findViewById(R.id.ok);

  Toast.makeText(getApplicationContext(), pioGroup.ersonList.get(0).get("enrolment") + "" + personList.get(1).get("enrolment") + "" + personList.get(2).get("enrolment"), Toast.LENGTH_LONG).show();


        adapter = new MyAdapter(this, getModel(personList));
        listView.setAdapter(adapter);

         radioGroup = (RadioGroup) findViewById(R.id.radio);
                          listView.childDrawableStateChanged(radioGroup);






        ////ok button click get status of each radio button and store in hashmap
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int child=listView.getChildCount();
                ArrayList<String> radio=new ArrayList<>();
                View[] vy = new View[1];

                Log.d("child", String.valueOf(child));
for(int i=0;i<child;i++) {
 //   RadioGroup rd = (RadioGroup) listView.getChildAt(i);


   View rgg=listView.getChildAt(i);
    Log.d("radioview",String.valueOf(rgg));
    radioGroup = (RadioGroup) rgg.findViewById(R.id.radio);
   Log.d("radiogroup", String.valueOf(radioGroup));
    int selectedId=radioGroup.getCheckedRadioButtonId();

    radioButton = (RadioButton) rgg.findViewById(selectedId);
    TextView tv= (TextView) rgg.findViewById(R.id.label);
    Log.d("radiobutton and id", selectedId + "" + radioButton);

String status= radioButton.getText().toString();
    Log.d("hello",status);

    String enrol=tv.getText().toString();
    contact = new HashMap<String, String>();
    contact.put("enrollmentnum",enrol);
    Log.d("enum",enrol);
    studentattendence.add(contact);
contactstatus = new HashMap<String, String>();
    contactstatus.put("status",status);
    Log.d("ststuss",status);
    studentstatus.add(contactstatus);

}

///here converting arraylist in to json string
                convertjson = new Gson().toJson(studentattendence);
                statusofattendence=new Gson().toJson(studentstatus);
    Toast.makeText(getApplicationContext(),""+convertjson+""+statusofattendence,Toast.LENGTH_LONG).show();
                NetAsync(v, convertjson,statusofattendence);
            }
        });

    }


    private List<Model> getModel(ArrayList<HashMap<String, String>> personList) {
        for (int i = 0; i < personList.size(); i++) {
            String enrolment = personList.get(i).get("enrolment");
            list.add(new Model(enrolment));

        }

        return list;
    }
    ////now we will send taked attendence to webservice
    private class NetCheck extends AsyncTask<String,String,Boolean>
    {
public final String convertjson,statusofattendence;
        private ProgressDialog nDialog;

        public NetCheck(String convertjson,String statusofattendence) {
            this.convertjson=convertjson;
            this.statusofattendence=statusofattendence;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            nDialog = new ProgressDialog(studentlist.this);
            nDialog.setMessage("Loading..");
            nDialog.setTitle("Checking Network");
            nDialog.setIndeterminate(false);
            nDialog.setCancelable(true);
            nDialog.show();
        }

        @Override
        protected Boolean doInBackground(String... args) {



/**
 * Gets current device state and checks for working internet connection by trying Google.
 **/
            /*
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if (netInfo != null && netInfo.isConnected()) {
                try {
                    URL url = new URL("http://www.google.com");
                    HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                    urlc.setConnectTimeout(3000);
                    urlc.connect();
                    if (urlc.getResponseCode() == 200) {
                        return true;
                    }
                } catch (MalformedURLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }*/
            // return false;
            return true;
        }

        @Override
        protected void onPostExecute(Boolean th) {

            if (th == true) {
                nDialog.dismiss();
                new ProcessRegister().execute();
            } else {
                nDialog.dismiss();

            }
        }
    }

    private class ProcessRegister extends AsyncTask<String, String, JSONObject> {


        private ProgressDialog pDialog;

        String forgotpassword;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pDialog = new ProgressDialog(studentlist.this);
            pDialog.setTitle("Contacting Servers");
            pDialog.setMessage("Getting Data ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected JSONObject doInBackground(String... args) {

TeacherFunctions userFunction = new TeacherFunctions();
            Log.d("convertjson",convertjson);
                        Log.d("convertjson",statusofattendence);
            JSONObject json = userFunction.addAttendence(convertjson,statusofattendence);

            return json;
        }


        @Override
        protected void onPostExecute(JSONObject json) {
            /**
             * Checks if the Password Change Process is sucesss
             **/
            try {
                if (json.getString(KEY_SUCCESS) != null) {

                    String res = json.getString(KEY_SUCCESS);
                    String red = json.getString(KEY_ERROR);


                    if(Integer.parseInt(res) == 1){
                        pDialog.dismiss();

                        Toast.makeText(getApplicationContext(),"students Attendence Uploaded successfully"+json.getString("user"),Toast.LENGTH_LONG).show();


                    }
                    else if (Integer.parseInt(red) == 2)
                    {    pDialog.dismiss();
                    }
                    else {
                        pDialog.dismiss();

                    }




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

                pDialog.dismiss();

                Toast.makeText(getApplicationContext()," not Uploaded successfully"+e,Toast.LENGTH_LONG).show();

            }
        }}
    public void NetAsync(View view, String convertjson,String statusofattendence){
        new NetCheck(convertjson,statusofattendence).execute();
    }
}

Code for model.java

public class Model {

    private String name;
    private boolean selected;

    public Model(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public boolean isSelected() {
        return selected;
    }

    public void setSelected(boolean selected) {
        this.selected = selected;
    }
} 

code for MyAdapter.java

public class MyAdapter extends ArrayAdapter<Model> {

    private final List<Model> list;
    private final Activity context;
    boolean checkAll_flag = false;
    boolean checkItem_flag = false;

    public MyAdapter(Activity context, List<Model> list) {
        super(context, R.layout.row, list);
        this.context = context;
        this.list = list;
    }

    static class ViewHolder {
        protected TextView text;
        protected RadioButton radiobox;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder viewHolder = null;
        if (convertView == null) {
            LayoutInflater inflator = context.getLayoutInflater();
            convertView = inflator.inflate(R.layout.row, null);
            viewHolder = new ViewHolder();
            viewHolder.text = (TextView) convertView.findViewById(R.id.label);
            viewHolder.radiobox = (RadioButton) convertView.findViewById(R.id.radio1);
            viewHolder.radiobox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    int getPosition = (Integer) buttonView.getTag();  // Here we get the position that we have set for the checkbox using setTag.
                    list.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
                }
            });
            convertView.setTag(viewHolder);
            convertView.setTag(R.id.label, viewHolder.text);
            convertView.setTag(R.id.radio1, viewHolder.radiobox);
            } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        viewHolder.radiobox.setTag(position); // This line is important.

        viewHolder.text.setText(list.get(position).getName());
        viewHolder.radiobox.setChecked(list.get(position).isSelected());

        return convertView;
    }
}
Shubham Sharma
  • 2,763
  • 5
  • 31
  • 46
  • Could you please edit your post into a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve)? – yennsarah Apr 25 '16 at 12:57
  • Possible duplicate of [checkbox unchecked when i scroll listview in android](http://stackoverflow.com/questions/10895763/checkbox-unchecked-when-i-scroll-listview-in-android) – yennsarah Apr 25 '16 at 12:58

3 Answers3

1

You are using setOnCheckedChangeListener() on viewHolder.radiobox. it is very bad code for that, because each time convertView getting null to view then setOnCheckedChangeListener() also called. And it set your modal data to next position. If you want to check it just put Log in onCheckedChange or try to put breakpoint in it. just try this :

@Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder viewHolder = null;
        if (convertView == null) {
            LayoutInflater inflator = context.getLayoutInflater();
            convertView = inflator.inflate(R.layout.row, null);
            viewHolder = new ViewHolder();
            viewHolder.text = (TextView) convertView.findViewById(R.id.label);
            viewHolder.radiobox = (RadioButton) convertView.findViewById(R.id.radio1);

            convertView.setTag(viewHolder);
            convertView.setTag(R.id.label, viewHolder.text);
            convertView.setTag(R.id.radio1, viewHolder.radiobox);
            } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

 viewHolder.radiobox.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) 
{
     if(viewHolder.radiobox.isChecked())
{
viewHolder.radiobox.setChecked(false);
}
else
{
viewHolder.radiobox.setChecked(true);
}               
                    list.get(getPosition).setChecked( viewHolder.radiobox.isChecked()); // Set the value of checkbox to maintain its state.
                }
            });

        viewHolder.text.setText(list.get(position).getName());
        viewHolder.radiobox.setChecked(list.get(position).isChecked());

        return convertView;
    }

hope it will help you.

Mangesh Sambare
  • 594
  • 3
  • 23
  • No it is not helping me , problem is comming when i am selecting upper radio button and then i am scrolling list then below elements are by defaultly selected , i had attached images with name firslychecked.png and alreadysel.png please see – Shubham Sharma Apr 25 '16 at 15:18
  • just remove `convertView.setTag(R.id.label, viewHolder.text);` `convertView.setTag(R.id.radio1, viewHolder.radiobox);` this two lines and then try. – Mangesh Sambare Apr 26 '16 at 04:38
0
enter code here
 getListView().setOnScrollListener(this);***

enter code here

public void onScroll(AbsListView view, int firstCell, int cellCount, int itemCount) {

   RadioButton rb1 = (RadioButton) findViewById(R.id.option1);
rb1.setChecked(flase);
}

public void onScrollStateChanged(AbsListView view, int scrollState) {        
}
Ghasem
  • 14,455
  • 21
  • 138
  • 171
-1

Actually everything was not working properly and then i had moved to listview with 4 button in place of radio button.

Shubham Sharma
  • 2,763
  • 5
  • 31
  • 46