0

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.

3
  • 1
    Too much code. Do you really expect anyone to go through all this? Commented Jul 30, 2016 at 9:53
  • No go directly to Submit method at bottom the code. Commented Jul 30, 2016 at 9:56
  • yes i will solve it. Thank you Commented Aug 1, 2016 at 6:57

1 Answer 1

3

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.!!

Sign up to request clarification or add additional context in comments.

5 Comments

How i can use that. Their is nothing to displayed on that page. please provide a exact link
Hello @user6657179, check it now.!!
It was good but i want the simplest one..i has too big process to create and send. Thank You i will use it letter if simplest solution is not found .
null pointer error is gone now the error is Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
Hello @user6657179, Debug your code and get JSON String. I think yous json is not valid. Please paste your json into this link : pro.jsonlint.com. and check is valid or not..!!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.