如何将radiobutton data recyclerview插入mysql数据库

wwodge7n  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(321)

我正在制作一个回收视图,每个项目包含3个单选按钮。所以你必须从每个项目中只选择一个单选按钮。我的问题是我不知道如何为每个单选按钮创建一个侦听器,我想把这个选项保存在我的mysql数据库中。下面是我的java类,它工作得很好:

public class GererVoteInvite extends AppCompatActivity {
    private ArrayList<VoteItem> itemArrayList;  //List items Array
    private MyAppAdapter myAppAdapter; //Array Adapter
    private RecyclerView recyclerView; //RecyclerView
    private RecyclerView.LayoutManager mLayoutManager;
    private boolean success = false; // boolean

    private static final String DB_URL = "jdbc:mysql://10.0.2.2/mvoting_db_1.0.0.0";
//    private static final String DB_URL = "jdbc:mysql://172.16.24.25/mvoting_db_1.0.0.0"; //"jdbc:mysql://DATABASE_IP/DATABASE_NAME";
    private static final String USER = "mootaz";
    private static final String PASS = "mootaz";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gerer_vote_invite);

        recyclerView = (RecyclerView) findViewById(R.id.recyclerView); //REcyclerview Declaration
        recyclerView.setHasFixedSize(true);
        // use a linear layout manager
        mLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(mLayoutManager);

        itemArrayList = new ArrayList<VoteItem>(); // Arraylist Initialization

        // Calling Async Task
        SyncData orderData = new SyncData();
        orderData.execute("");
    }

    // Async Task has three overrided methods,
    private class SyncData extends AsyncTask<String, String, String>
    {
        String msg = "Internet/DB_Credentials/Windows_FireWall_TurnOn Error, See Android Monitor in the bottom For details!";
        ProgressDialog progress;

        @Override
        protected void onPreExecute() //Starts the progress dailog
        {
            progress = ProgressDialog.show(GererVoteInvite.this, "Synchronising",
                    "RecyclerView Loading! Please Wait...", true);
        }

        @Override
        protected String doInBackground(String... strings)  // Connect to the database, write query and add items to array list
        {
            try
            {
                Class.forName("com.mysql.jdbc.Driver");

                Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); //Connection Object

                if (conn == null)
                {
                    success = false;
                }
                else {
                    // Change below query according to your own database.
                    String query = "SELECT lib_probleme , lib_solution_1 , lib_solution_2 , lib_solution_3  FROM reunion JOIN probleme JOIN solution WHERE reunion.id_reunion=probleme.id_reunion and probleme.id_probleme=solution.id_probleme ;";
                    Statement stmt = conn.createStatement();
                    java.sql.ResultSet rs = stmt.executeQuery(query);
                    if (rs != null) // if resultset not null, I add items to itemArraylist using class created
                    {
                        while (rs.next())
                        {
                            try {
                                itemArrayList.add(new VoteItem(rs.getString("lib_probleme"),rs.getString("lib_solution_1"),rs.getString("lib_solution_2"),rs.getString("lib_solution_3")));
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                        msg = "Found";
                        success = true;
                    } else {
                        msg = "No Data found!";
                        success = false;
                    }
                }
            } catch (Exception e)
            {
                e.printStackTrace();
                Writer writer = new StringWriter();
                e.printStackTrace(new PrintWriter(writer));
                msg = writer.toString();
                success = false;
            }
            return msg;
        }

        @Override
        protected void onPostExecute(String msg) // disimissing progress dialoge, showing error and setting up my gridview
        {
            progress.dismiss();
            Toast.makeText(GererVoteInvite.this, msg + "", Toast.LENGTH_LONG).show();
            if (success == false)
            {
            }
            else {
                try
                {
                    myAppAdapter = new MyAppAdapter(itemArrayList , GererVoteInvite.this);
                    recyclerView.setAdapter(myAppAdapter);
                } catch (Exception ex)
                {

                }

            }
        }
    }

    public class MyAppAdapter extends RecyclerView.Adapter<MyAppAdapter.ViewHolder> {
        private List<VoteItem> values;
        public Context context;

        public class ViewHolder extends RecyclerView.ViewHolder
        {

            public TextView txtProbleme;
            public RadioGroup group;
            public RadioButton txtSol1;
            public RadioButton txtSol2;
            public RadioButton txtSol3;
            public View layout;

            public ViewHolder(View v)
            {
                super(v);
                layout = v;
                group= (RadioGroup) v.findViewById(R.id.radio_group);
                txtProbleme = (TextView) v.findViewById(R.id.tv_probleme);
                txtSol1 = (RadioButton) v.findViewById(R.id.rb_1);
                txtSol2 = (RadioButton) v.findViewById(R.id.rb_2);
                txtSol3 = (RadioButton) v.findViewById(R.id.rb_3);

            }
        }

        // Constructor
        public MyAppAdapter(List<VoteItem> myDataset,Context context)
        {
            values = myDataset;
            this.context = context;
        }

        // Create new views (invoked by the layout manager) and inflates
        @Override
        public MyAppAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
        {
            // create a new view
            LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            View v = inflater.inflate(R.layout.vote_view, parent, false);
            ViewHolder vh = new ViewHolder(v);
            return vh;
        }

        // Binding items to the view
        private RadioButton lastCheckedRB = null;

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

            final VoteItem voteItem = values.get(position);
            holder.txtProbleme.setText(voteItem.getProbleme());
            holder.group.setTag(position);
            holder.txtSol1.setText(voteItem.getSol1());
            holder.txtSol2.setText(voteItem.getSol2());
            holder.txtSol3.setText(voteItem.getSol3());

        }

        // get item count returns the list item count
        @Override
        public int getItemCount() {
            return values.size();
        }

    }
}

请任何人帮我解决这个问题。

n3ipq98p

n3ipq98p1#

使…成为一个物体 VoteItem 在如下适配器中,向voteitem类添加一个属性:

public class VoteItem {

    public int radioButtonPosition;

    public int getRadioButtonPosition() {
        return radioButtonPosition;
    }

    public void setRadioButtonPosition(int radioButtonPosition) {
        this.radioButtonPosition = radioButtonPosition;
    }
}

//输入适配器
voteitem项目;
然后为它创建getter和setter方法:

public VoteItem getmVoteItem() {
        return mVoteItem;
    }

    public void setmVoteItem(VoteItem mVoteItem) {
        this.mVoteItem = mVoteItem;
    }

现在为您的radiogroup对象设置侦听器:

group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                switch (checkedId) {

                    case R.id.radioOne:
                        mVoteItem.setRadioButtonPosition(1);
                        setmVoteItem(mVoteItem);
                        break;
                   case R.id.radioTwo:
                        mVoteItem.setRadioButtonPosition(2);
                        setmVoteItem(mVoteItem);
                        break;
                   case R.id.radiothree:
                        mVoteItem.setRadioButtonPosition(3);
                        setmVoteItem(mVoteItem);
                        break;
                }
            }
        });

现在可以在活动中获取当前voteitem对象:

VoteItem mVoteItem;

if(adaper.getmVoteItem()==null){
//means no one radio item is selected
}else{
// selected latest radio item
mVoteItem =    adaper.getmVoteItem();
}

现在将数据保存在本地数据库中,如下所示:
-->制作一个方法保存到数据库类中的数据,如下所示(这只是一个示例,您可以根据需要编辑此方法):

public int addItem(VoteItem voteItem) {

        int rowId = 0;
        SQLiteDatabase database = null;
        try {
            database = dbHelper.getWritableDatabase();
            ContentValues values = new ContentValues();

            boolean exists = false;

            Cursor cursor = database.rawQuery(String.format("select * from " + "yourTableName" + " where " + "yourColumn" + "='" + voteItem.getCategoryName() + "'" + "COLLATE NOCASE"), null);
            exists = (cursor != null) && (cursor.getCount() > 0);

            if (exists) {
                rowId = -1;
            } else {
                values.put("yourColumn", "yourValue");

                database.insert("yourTableName", null, values);
            }

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

        } finally {
            if (database != null)
                database.close();
        }
        return rowId;
    }

-->在你的 setmVoteItem(VoteItem mVoteItem) 从数据库类方法调用上述方法以保存如下数据:

public void setmVoteItem(VoteItem mVoteItem) {
        this.mVoteItem = mVoteItem;
        dbHelper.addItem(mVoteItem);//declare dbHelper object in adaper 
                                    //class and initialise in constructor.
    }

相关问题