How to insert selected multiple checkbox values into different rows to mysql database in android and php

孤人 提交于 2019-12-11 05:49:56

问题


Here i am accessing contacts from the phone and displaying in custom listview. Now i have to insert the selected checkbox values to different rows to mysql database.Here i can able to insert single checkbox value to the database..if i selected more than one value, the data will be stored in the single row..What modifications i have to make to insert the single data to each row..?i am using php file to store data to the database.

DisplayContact.java

public class DisplayContact extends Activity implements OnItemClickListener{

    //ArrayList to store name and phone number
    List<String> name1 = new ArrayList<String>();
    List<String> phno1 = new ArrayList<String>();
    MyAdapter ma ;
    Button select;

    private String vault;

    public static final String kvault = "vault_no";
    public static final String kname = "name";
    public static final String kphone = "phone";

    public static final String SHARED_PREF_NAME = "myloginapp";


    public static final String CONTACTNAME_SHARED_PREF = "name";
    public static final String PHONE_SHARED_PREF = "phone";

    //We will use this to store the boolean in sharedpreference to track user is loggedin or not
    public static final String LOGGEDIN_SHARED_PREF = "loggedin";

    public static final String UPLOAD_URL = "http://oursite.com/contacts.php";

    Cursor phones;

    private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActionBar().setDisplayShowTitleEnabled(false);
        setContentView(R.layout.display);

        SharedPreferences sharedPreferences = getSharedPreferences(ProfileLogin.SHARED_PREF_NAME, MODE_PRIVATE);

        vault = sharedPreferences.getString(ProfileLogin.EMAIL_SHARED_PREF,"Not Available");

        getAllContacts(this.getContentResolver());
        ListView lv= (ListView) findViewById(R.id.lv);
        ma = new MyAdapter();
        lv.setAdapter(ma);
        lv.setOnItemClickListener(this);
        lv.setItemsCanFocus(false);
        lv.setTextFilterEnabled(true);
        // adding
        select = (Button) findViewById(R.id.button1);
        select.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View v) {
                StringBuilder checkedcontacts= new StringBuilder();
                StringBuilder name2 = new StringBuilder();
                StringBuilder phone2 = new StringBuilder();
                for(int i = 0; i < name1.size(); i++)

                {
                    if(ma.mCheckStates.get(i)==true)
                    {
                        checkedcontacts.append(name1.get(i).toString());
                        checkedcontacts.append(phno1.get(i).toString());
                        checkedcontacts.append("\n");

                         name2.append(name1.get(i).toString());
                         phone2.append(phno1.get(i).toString());
                    }
                    else
                    {

                    }
                }
                SharedPreferences sharedPreferences = DisplayContact.this.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);

                //Creating editor to store values to shared preferences
                SharedPreferences.Editor editor = sharedPreferences.edit();

                //Adding values to editor
                editor.putBoolean(LOGGEDIN_SHARED_PREF, true);
                editor.putString(CONTACTNAME_SHARED_PREF, name2.toString());
                editor.putString(PHONE_SHARED_PREF, phone2.toString());

                //Saving values to editor
                editor.commit();

                Toast.makeText(DisplayContact.this, name2.toString() + " , " + phone2.toString() + " Added to Database", Toast.LENGTH_LONG).show();
                uploadImage();
            }
        });

    }

    public void uploadImage(){

        SharedPreferences sharedPreferences = getSharedPreferences(DisplayContact.SHARED_PREF_NAME, MODE_PRIVATE);

        final String name = sharedPreferences.getString(DisplayContact.CONTACTNAME_SHARED_PREF, "Not Available");
        final String phone = sharedPreferences.getString(DisplayContact.PHONE_SHARED_PREF, "Not Available");

        final String vault_no = vault;

        class UploadImage extends AsyncTask<Void,Void,String> {
            ProgressDialog loading;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(DisplayContact.this,"Please wait...","uploading",false,false);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                if(s.equalsIgnoreCase("Successfully Saved")){
                    //Intent intent = new Intent(CollegeDetails.this,Work.class);
                    Toast.makeText(DisplayContact.this, s, Toast.LENGTH_SHORT).show();
                    // startActivity(intent);
                }else{
                    Toast.makeText(DisplayContact.this,s,Toast.LENGTH_SHORT).show();

                }
            }

            @Override
            protected String doInBackground(Void... params) {
                RequestHandler rh = new RequestHandler();
                //RegisterUserClass rh = new RegisterUserClass();
                HashMap<String,String> param = new HashMap<String,String>();

                param.put(kvault,vault_no);
                param.put(kname,name);
                param.put(kphone,phone);

                String result = rh.sendPostRequest(UPLOAD_URL, param);
                return result;
            }
        }
        UploadImage u = new UploadImage();
        u.execute();
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub
        ma.toggle(arg2);
    }

    public  void getAllContacts(ContentResolver cr) {

        int result = ContextCompat.checkSelfPermission(DisplayContact.this, Manifest.permission.READ_CONTACTS);
        if (result == PackageManager.PERMISSION_GRANTED){

            phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
            contactsdisplay();

        } else {

            requestForLocationPermission();
        }
    }

    private void requestForLocationPermission()
    {

        if (ActivityCompat.shouldShowRequestPermissionRationale(DisplayContact.this, Manifest.permission.READ_CONTACTS))
        {
        }
        else {

            ActivityCompat.requestPermissions(DisplayContact.this, new String[]{Manifest.permission.READ_CONTACTS}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
    {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_READ_CONTACTS:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                {
                    getAllContacts(DisplayContact.this.getContentResolver());
                    contactsdisplay();
                }
                break;
        }
    }

    public  void contactsdisplay() {


        while (phones.moveToNext())
        {
            String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            System.out.println(".................."+name+ "" +phoneNumber);
            name1.add(name);
            phno1.add(phoneNumber);
        }

        phones.close();
    }

    class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
    {  private SparseBooleanArray mCheckStates;
        LayoutInflater mInflater;
        TextView tv1,tv;
        CheckBox cb;
        MyAdapter()
        {
            mCheckStates = new SparseBooleanArray(name1.size());
            mInflater = (LayoutInflater)DisplayContact.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return name1.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub

            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            View vi=convertView;
            if(convertView==null)
                vi = mInflater.inflate(R.layout.row, null);
            tv= (TextView) vi.findViewById(R.id.contact_name);
            tv1= (TextView) vi.findViewById(R.id.phone_number);
            cb = (CheckBox) vi.findViewById(R.id.checkBox_id);
            tv.setText("Name :"+ name1.get(position));
            tv1.setText("Phone No :"+ phno1.get(position));
            cb.setTag(position);
            cb.setChecked(mCheckStates.get(position, false));
            cb.setOnCheckedChangeListener(this);

            return vi;
        }
        public boolean isChecked(int position) {
            return mCheckStates.get(position, false);
        }

        public void setChecked(int position, boolean isChecked) {
            mCheckStates.put(position, isChecked);
        }

        public void toggle(int position) {
            setChecked(position, !isChecked(position));
        }
        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                                     boolean isChecked) {
            // TODO Auto-generated method stub

            mCheckStates.put((Integer) buttonView.getTag(), isChecked);
        }
    }
}

contacts.php

<?php
    session_start();
    define('HOST','hostname');
    define('USER','username');
    define('PASS','password');
    define('DB','dbname');

    $response = array();

$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');

if(!mysqli_connect_errno()){

    $error_flag = false;

$contacts = json_decode($_POST['contacts'], true);
foreach($contacts as $contact){
  //echo $contact['name'];


            // create a new user profile
        $sql = "INSERT INTO contacts (vault_no , name, phone, update_at,created_at)
        VALUES ('".$contact['vault_no']."', '".$contact['name']."',  '".$contact['phone']."', NOW(), NOW())";
            if(mysqli_query($con,$sql)){

                echo "Successfully Saved";

            }else{
                $response["error"] = true;
                $response["error_msg"] = "INSERT operation failed";
                echo json_encode($response);
            }
}

}else{
    $response["error"] = true;
    $response["error_msg"] = "Database connection failed";
    echo json_encode($response);
}

?>


回答1:


You need to start using JSON to hold your data:

Build it:

JSONArray contacts = new JSONArray();
for(int i = 0; i < name1.size(); i++)
{
    JSONObject contact = new JSONObject();
    contact.put(kname, name1.get(i).toString());
    contact.put(kphone, phno1.get(i).toString());
    contact.put(kvault,vault_no);
    contacts.put(contact);
}

Then pass it to your hashmap as a parameter:

HashMap<String,String> param = new HashMap<String,String>();
param.put(kcontacts,contacts.toString());
return rh.sendPostRequest(UPLOAD_URL, param);

Finally in PHP decode that:

$contacts = json_decode($_POST['contacts'], true);
foreach($contacts as $contact){
    echo $contact['name'];
}



回答2:


use Foreah post of check box values.

       $vault_no1= $this->input->post("vault_no");
       foreach($vault_no1 as $key=>$val){
            $arra[] = $val;
        }


        $name= $this->input->post("name");
       foreach($name as $key=>$val){
            $arre[] = $val;
        }


        $phone= $this->input->post("phone");
       foreach($phone as $key=>$val){
            $arrv[] = $val;
        }

        $length = count($arra);
        for ($i = 0; $i < $length; $i++) {
          echo "vault_no".$arra[$i]." Name:".$arre[$i]." phone:".$arrv[$i];   //Sample print for you
          //Use your Insert query here with aboe arrays value
        }


来源:https://stackoverflow.com/questions/37893418/how-to-insert-selected-multiple-checkbox-values-into-different-rows-to-mysql-dat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!