user6657179
user6657179

Reputation: 17

How to send String Array data to Server using php in android

I have a String array which contains value string array = {6,37,38,837,7,...} and I have also used some string values.

I want to send that all string values and string array to my database which is located at server side. When I am click on submit button the data will stored in table.

On the PHP side I want to read this array as it is,other thing i will do at background means PHP side. See my below code then you will get it what I am says.

Here is my code:

public class  Hotels extends Activity {
// Declare Variables
JSONArray jsonarray = null;
private static final String TAG_ID = "id";
public static final String TAG_NAME = "name";
public static final String TAG_LOCATION = "location";
public static final String TAG_DESC = "description";
String f_date, l_date;
ArrayList<String> ne = new ArrayList<String>();
public Set<String> interestList = new HashSet<String>();
public Set<String> interestlist = new HashSet<String>();
//public String[] hotel_id = new String[0];

ProgressDialog loading;
ListView list;
Button booknow;
private ArrayList<Product> itemlist;
Product product;
static String Array = "MyHotels";
View view;
CheckBox click;
String hotel = "http://app.goholidays.info/getHotelData.php";
String booking = "http://app.goholidays.info/insertIntoBooking.php";
SharedPreferences sp;
SharedPreferences.Editor editor;


@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_item_layout);
    product = new Product();
    itemlist = new ArrayList<Product>();
    new ReadJSON().execute();
    click = (CheckBox) findViewById(R.id.mycheckbox);
    booknow = (Button) findViewById(R.id.bookhotel);
    product = new Product();
    list = (ListView) findViewById(R.id.myimagelist);

    Calendar c = Calendar.getInstance();
    System.out.println("Current time => " + c.getTime());
    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
    sp = PreferenceManager.getDefaultSharedPreferences(Hotels.this);
    editor = sp.edit();

    final String user_id = sp.getString("id", TAG_ID);
    final String start_date = sp.getString("start_date", f_date);
    final String end_date = sp.getString("end_date", l_date);
    final String chk_status = df.format(c.getTime());

    booknow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String[] hotel_id = new String[ne.size()]; //here is my string array{1,2,2,3,4,...} i want send it to server as it is.
            hotel_id = ne.toArray(hotel_id);

            for(int i = 0; i < hotel_id.length ; i++){
                Log.d("string is",(String)hotel_id[i]);
            }

            new BackTask().execute();
        }
    });
}

..........

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

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

        @Override
        protected String doInBackground(String... params) {

List<NameValuePair> param = new ArrayList<NameValuePair>();
            param.add(new BasicNameValuePair("start_date", start_date));
            param.add(new BasicNameValuePair("end_date", end_date));
            param.add(new BasicNameValuePair("chk_status", chk_status));
            for(String value: hotel_id){
                param.add(new BasicNameValuePair("hotel_id[]",value));
            }
            param.add(new BasicNameValuePair("user_id", user_id));

            JSONObject json = jsonParser.makeHttpRequest(booking, "POST", param);

            Log.d("Create Response", json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully book a hotels
                    Intent i = new Intent(getApplicationContext(), HomePage.class);
                    startActivity(i);

                    // closing this screen
                    finish();
                } else {
                    // failed to book hotels
                    Log.d("failed to book hotel", json.toString());

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

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if(result != null){
                Toast.makeText(getApplicationContext(), "Book Success", Toast.LENGTH_SHORT).show();
            }
        }

    }
    BackTask lg = new BackTask();
    //here the array is converted in to string
    lg.execute(start_date, end_date, chk_status, String.valueOf(hotel_id), user_id);
}
}

see my logcat

JSON Parser: Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

Here is my php code

<?php   

require "db_connect.php";

$response = array();

// check for required fields
if (isset($_POST['start_date']) && isset($_POST['end_date']) &&     isset($_POST['user_id']) && isset($_POST['hotel_id']) && isset($_POST['chk_status'])) {

$start_date= $_POST["start_date"];
$end_date= $_POST["end_date"];
$user_id= $_POST["user_id"];
$hotel_id= $_POST["hotel_id"];
$chk_status= $_POST["chk_status"];

$result= mysqli_query("insert into tb_booking(start_date,end_date,user_id,hotel_id,chk_status) values ('$start_date','$end_date','$user_id','$hotel_id','$chk_status')");

if ($result) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "Hotel book successfully.";

    // echoing JSON response
    echo json_encode($response);
} else {
    // failed to insert row
    $response["success"] = 0;
    $response["message"] = "Oops! An error occurred.Please select hotels";

    // echoing JSON response
    echo json_encode($response);
}
}else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
}    
?>

Please help me solve this problem.

Upvotes: 0

Views: 1930

Answers (1)

Mitesh Vanaliya
Mitesh Vanaliya

Reputation: 2591

You can use Retrofit api for service call.

Retrofit is a REST Client for Android and Java by Square. It makes it relatively easy to retrieve and upload JSON (or other structured data) via a REST based webservice. In Retrofit you configure which converter is used for the data serialization

For more information:

http://www.androidhive.info/2016/05/android-working-with-retrofit-http-library

Retrofit handle automatically array,string json and etc.

Try it.!!

Upvotes: 3

Related Questions