0

I have a string array and I need to pass the array data to a php file. The accepted data(php) should be stored inside the database. I have a file where I have multiple check boxes. After selecting some check boxes I want to pass the selected data to php. am unable to get where am doing mistake.

Here is my code..

First File :callplanactivity.java

         public class CallplanActivity extends Activity implements
            OnItemSelectedListener {

        ListView lv;

        Context context;

        Spinner city;

        ImageButton done;

        ProgressDialog pDialog;

        private ArrayList<City> cityList;

        JSONParser jParser = new JSONParser();

        JSONArray doctors_info;

        ListView listview;
        ListViewAdapter adapter, adaper2;

        String cityselected,username;

        ArrayList<Doclist> doclists;

        List<String> cities = new ArrayList<String>();

        private String URL_CITY = "http://10.0.2.2/android_login_api/select_city.php";
        private String URL_DOCTORS = "http://10.0.2.2/android_login_api/select_doctors.php";

        private static final String TAG_DOCDETAILS = "doctors_details";
        static final String TAG_DOC_NAME = "doc_name";
        static final String TAG_DOC_QUALI = "qualification";

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

            Intent i=getIntent();
            username=i.getStringExtra("username");
        //  Log.d("callplan", username);

            doclists = new ArrayList<Doclist>();
            city = (Spinner) findViewById(R.id.city_spinner);
            listview = (ListView) findViewById(R.id.listview);

            done = (ImageButton) findViewById(R.id.done);

            adapter = new ListViewAdapter(CallplanActivity.this, doclists);

            listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

            cityList = new ArrayList<City>();

            city.setOnItemSelectedListener(this);

            new GetCity().execute();

            done.setOnClickListener(new OnClickListener() {

                @SuppressWarnings("null")
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    // StringBuffer responseText = new StringBuffer();
                    ArrayList<Doclist> doclistarray = adapter.doclist;
                    String[] outputStrArr = new String[doclistarray.size()];
                    //String[] outputStrArr = null;
                    //String[] outputStrArr2= new String[doclistarray.size()];
                    for (int i = 0; i < doclistarray.size(); i++) {

                        Doclist dc = doclistarray.get(i);

                        if (dc.isSelected()) {

                        //  Log.d("dc", "" + dc.docname);

                            outputStrArr[i] = dc.docname;

                            Log.d("sagar", "" + outputStrArr[i]);

                            Intent intent=new Intent(CallplanActivity.this,CallplanEnd.class);
                            intent.putExtra("selectedItems", outputStrArr);
                            startActivity(intent);
                        }
                        else {
                        //  Log.d("sagar not selected", "" + outputStrArr[i]);

                        }

                    }

                }

            });
        }

        private void populateSpinner() {

            // txtCategory.setText("");

            for (int i = 0; i < cityList.size(); i++) {
                cities.add(cityList.get(i).getName());
            }

            // Creating adapter for spinner
            ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, cities);

            // Drop down layout style - list view with radio button
            spinnerAdapter
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

            // attaching data adapter to spinner
            city.setAdapter(spinnerAdapter);

        }

        private class GetCity extends AsyncTask<Void, Void, Void> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(CallplanActivity.this);
                pDialog.setMessage("Fetching cities..");
                pDialog.setCancelable(false);
                pDialog.show();

            }

            @Override
            protected Void doInBackground(Void... arg0) {
                ServiceHandler jsonParser = new ServiceHandler();
                String json = jsonParser.makeServiceCall(URL_CITY,
                        ServiceHandler.GET);

                Log.e("Response: ", "> " + json);

                if (json != null) {
                    try {
                        JSONObject jsonObj = new JSONObject(json);
                        if (jsonObj != null) {
                            JSONArray categories = jsonObj
                                    .getJSONArray("doctors_details");

                            for (int i = 0; i < categories.length(); i++) {
                                JSONObject catObj = (JSONObject) categories.get(i);
                                City cat = new City(catObj.getString("city"));
                                cityList.add(cat);
                            }
                        }

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

                } else {
                    Log.e("JSON Data", "Didn't receive any data from server!");
                }

                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                if (pDialog.isShowing())
                    pDialog.dismiss();
                populateSpinner();
            }

        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.callplan, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
            if (id == R.id.action_settings) {
                return true;
            }

            return super.onOptionsItemSelected(item);
        }

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position,
                long id) {
            // TODO Auto-generated method stub

            // new GetCategories().execute();
            Spinner city1 = (Spinner) parent;

            if (city1.getId() == R.id.city_spinner) {

                cityselected = cities.get(position);

                Toast.makeText(getApplicationContext(), cityselected,
                        Toast.LENGTH_LONG).show();

                new GetDoctorsDetails().execute();

            } else {
                Toast.makeText(getApplicationContext(),
                        "Please Select City from Dropdown Box", Toast.LENGTH_LONG)
                        .show();
            }
        }

        class GetDoctorsDetails extends AsyncTask<String, String, JSONObject> {

            JSONObject jsonObject;

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

            }

            @Override
            protected JSONObject doInBackground(String... params) {
                // TODO Auto-generated method stub

                String city_name = cityselected.toString();
                List<NameValuePair> params1 = new ArrayList<NameValuePair>();
                params1.add(new BasicNameValuePair("city", city_name));

                jsonObject = jParser.makeHttpRequest(URL_DOCTORS, "POST", params1);

                Log.e("Response: ", "> " + jsonObject.toString());
                return jsonObject;

            }

            @Override
            protected void onPostExecute(JSONObject json) {

                adapter.doclist.clear();
                pDialog.dismiss();
                if (json != null) {
                    try {
                        doctors_info = json.getJSONArray(TAG_DOCDETAILS);

                        Log.e("Response: ", "> " + doctors_info.toString());

                        for (int i = 0; i < doctors_info.length(); i++) {
                            JSONObject c = doctors_info.getJSONObject(i);

                            Doclist dl = new Doclist();

                            String doc_name = c.getString(TAG_DOC_NAME);
                            String qualification = c.getString(TAG_DOC_QUALI);

                            dl.setdocname(doc_name);
                            dl.setquali(qualification);

                            doclists.add(dl);

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

                    listview.setAdapter(adapter);

                    adapter.notifyDataSetChanged();
                }

            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // TODO Auto-generated method stub

        }
        }

After selecting some values from checkboxes the data is passed to another file.

Second File:callplanend.java

        public class CallplanEnd extends Activity {

        String[] str,str1;

        ServiceHandler servicehandler;

        JSONParser jsonparser;

        String username;
        private String url_callplanends = "http://10.0.2.2/android_login_api/callplanends.php";

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);

            Intent intt = getIntent();
            username = intt.getStringExtra("username");
            // Log.d("detailing", username);

            Bundle b = getIntent().getExtras();
            String[] resultArr = b.getStringArray("selectedItems");

            for (int i = 0; i < resultArr.length; i++) {
                if (resultArr[i] != null) {

                    str = resultArr;

                    Log.d("sagar#######", "" + str[i]);
                    Toast.makeText(getApplicationContext(), ""+str, Toast.LENGTH_LONG).show();

                }
                else {

                //  str1[i]=resultArr[i];

                }
            }

            new detailparser().execute();
        }

        public class detailparser extends
                AsyncTask<String, Void, ArrayList<String>> {

            @Override
            protected ArrayList<String> doInBackground(String... params) {
                // TODO Auto-generated method stub
                 JSONObject jobject=new JSONObject();
                String[] docs = str;
                String id = "1";
                String user_id = "2";
                String username = "sagar";

                Log.d("size",""+docs.length);

                List<NameValuePair> dc = new ArrayList<NameValuePair>();

                for (int k = 0; k < docs.length; k++) {

                    if (docs[k] != null) {

                    //  Log.d("size==--==",""+docs.length);
                    //  Log.d("size==",""+dc.size());

                        Log.d("id", "" + id);
                        Log.d("user_id", "" + user_id);
                        Log.d("username", "" + username);
                        Log.d("docs name", "" + docs[k]);


                        dc.add(new BasicNameValuePair("docslist[]", docs[k]));
                        dc.add(new BasicNameValuePair("id", id));
                        dc.add(new BasicNameValuePair("user_id", user_id));
                        dc.add(new BasicNameValuePair("username", username));

                        try {

                            JSONObject json = jsonparser.makeHttpRequest(
                                    url_callplanends, "POST", dc);

                            Log.d("Json-data", json.toString());

                            try {
                                int success = json.getInt("success");
                                if (success == 1) {
                                    /*
                                     * Intent i = new Intent(getApplicationContext(),
                                     * MaindisplayActivity.class); startActivity(i);
                                     */
                                    // finish();

                                    /*Log.d("id", "" + id);
                                    Log.d("user_id", "" + user_id);
                                    Log.d("username", "" + username);
                                    Log.d("docs", "" + docs[k]);*/

                                    Log.d("success", json.toString());

                                } else {

                                    Log.d("failed", "upload failed");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }catch(NullPointerException e){

                            e.printStackTrace();

                        }



                    }
                    else {
                        Log.d("null", "null"+k);
                    }

                }

                return null;
            }

        }
        }

and this is my php code to accept the array value from android.. the selected values should be passed to this php file and they must be stored inside the database.

        <?php
     $response = array();

     if (isset($_POST['id']) && 
     isset($_POST['user_id'])  &&
     isset($_POST['username'])
     &&  isset ($_POST['docslist'])
     ) {

     $id=$_POST['id'];
     $user_id=$_POST['user_id'];
     $username=$_POST['username'];
     $docslist = $_POST['docslist'];

     $docarray=json_decode($docslist);

     require_once 'include/DB_Connect.php';
     $db = new DB_Connect();


     $query=    mysql_query("INSERT INTO selected_docs(id,user_id,username,docname) VALUES('$id','$user_id','$username','$docarray')");
          if ($result) {
             // successfully inserted into database
             $response["success"] = 1;
             $response["message"]="successfully inserted data";
     // echoing JSON response
             echo json_encode($response);
         } else {
           //   failed to insert row
             $response["success"] = 0;
             $response["message"]="Insertion failed ";
          //   echoing JSON response
             echo json_encode($response);
         }
     }
     else {
      $response["success"] = 0;
      $response["message"]="Connection Failure";
        // echoing JSON response
         echo json_encode($response);
     }

    ?>
3
  • Just paste the post method code don't copy paste full class code.
    – Pankaj
    Aug 6, 2015 at 6:14
  • ok. just wanted to clear the question and code Aug 6, 2015 at 6:26
  • unable to find solution. can anyone suggest something Aug 8, 2015 at 6:40

2 Answers 2

0

I don't know about php but in android you can use a loop to add the values of the array one by one or use a solution like in this link:
Passing String array to PHP as POST

0

Instead of sending the array and decoding that array in php, i converted the array to string and passed that value to php.

Here is the changes that i did with my code..

 dc.add(new BasicNameValuePair("docslist[]", docs.ArraytoString));

just changed this line and converted the Array to string and sent.

Now it works fine and the sent data is inserted into database.

1
  • Is docs a String[] ? If so, then what is a docs.ArraytoString? There's no such field in arrays. Should that be Arrays.toString(docs) ? Sep 24, 2017 at 19:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.