title: How to send data from android to mysql server?
body: <p>I am newbie to the android development. I am using Android Studio. I am making an app in which there is a dropdown list of names. On selecting any name, the corresponding <code>ID</code> of that name is shown at the app. Then there is a button which will search for the user's current gps coordinates and show them on the app. I searched for similar questions and found some links (I will post them at the end) but I couldn't understand them. Below is the screenshot of the app </p>
  
  <p><a href="https://i.stack.imgur.com/I4oZN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/I4oZN.png" alt="android app screenshot"></a></p>
  
  <p>I have two tables in mysql; <code>users</code> and <code>activity</code>, as shown below </p>
  
  <p><strong>Users</strong></p>
  
  <p><a href="https://i.stack.imgur.com/IuC9h.png" rel="noreferrer"><img src="https://i.stack.imgur.com/IuC9h.png" alt="mysql workbench screenshot listing fields &#39;Id&#39; and &#39;Name&#39;"></a></p>
  
  <p><strong>Activity</strong></p>
  
  <p><a href="https://i.stack.imgur.com/MHCKI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MHCKI.png" alt="mysql workbench screenshot listing fields &#39;Id&#39;, &#39;UserId&#39;, &#39;Latitude&#39;, &#39;Longitude&#39; and &#39;DateTime&#39;"></a></p>
  
  <p>The <code>UserId</code> is the foreign key in activity table i.e. the <code>Id</code> from <code>users</code> table will be inserted into it.</p>
  
  <p>I have created following script to return the data as JSON:</p>
  
  <pre><code>&lt;?php
      require_once ('config.php');
  
      $sql = "SELECT * FROM users";  
      $r = mysqli_query($con,$sql); 
      $result = array();
  
      while($row = mysqli_fetch_array($r)){
          array_push($result,array(
              'Id'=&gt;$row['Id'],
              'Name'=&gt;$row['Name']
          )); 
        }//end while
  
      echo json_encode(array('users'=&gt;$result));
  
      mysqli_close($con);
  ?&gt;
  </code></pre>
  
  <p>In my app code I have created a <code>users</code> class </p>
  
  <p><strong>Users Class</strong></p>
  
  <pre><code>public class Users {
  
  private String Id;
  private String Name;
  
  public String getId() {
      return Id;
  }
  
  public void setId(String id) {
      this.Id = id;
  }
  
  public String getName() {
      return Name;
  }
  
  public void setName(String name) {
      this.Name = name;
  }}
  </code></pre>
  
  <p><strong>JSON CLASS</strong></p>
  
  <pre><code>public class JSONfunctions {
  
  
  public static JSONObject getJSONfromURL(String url)
  {
  
      String json = "";
      JSONObject jsonObject = null;
      try
      {
          HttpClient httpClientt = new DefaultHttpClient();
          HttpGet httpGet = new HttpGet(url);
          HttpResponse httpResponse = httpClientt.execute(httpGet);
          BufferedReader br = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
          StringBuffer sb = new StringBuffer();
          String line = "";
          while ((line = br.readLine()) != null) {
              sb.append(line);
          }
  
          json = sb.toString();
      } catch (ClientProtocolException e) {
          e.printStackTrace();
      } catch (IOException e) {
          e.printStackTrace();
      }
  
      try
      {
          jsonObject = new JSONObject(json);
      } catch (JSONException e) {
          e.printStackTrace();
      }
  
      return jsonObject;
  }
  </code></pre>
  
  <p><strong>MainActivity</strong></p>
  
  <pre><code> @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
  
      _latitude = (TextView)findViewById(R.id.latitude);
      _longitude = (TextView)findViewById(R.id.longitude);
      btn_get_coordinates = (Button)findViewById(R.id.button);
  
  
  
  
      final PermissionListener permissionlistener = new PermissionListener() {
          @Override
          public void onPermissionGranted() {
              //Toast.makeText(MainActivity.this, "Permission Granted", Toast.LENGTH_SHORT).show();
  
              buildGoogleApiClient();
              //checkLocation(); //check whether location service is enable or not in your  phone
          }
  
          @Override
          public void onPermissionDenied(ArrayList&lt;String&gt; deniedPermissions) {
              Toast.makeText(MainActivity.this, "Permission Denied\n" + deniedPermissions.toString(), Toast.LENGTH_SHORT).show();
          }
      };
  
      btn_get_coordinates.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
  
  
              new TedPermission(MainActivity.this)
                      .setPermissionListener(permissionlistener)
                      .setRationaleMessage("This app needs Permission to find your location")
                      .setPermissions(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                      .check();
  
  
          }
      });
  
      // Download JSON file AsyncTask
      new DownloadJSON().execute();
  }
  
  /////////////////////////////////////// Start of Location Services ///////////////////////////////////////////////////////
  
  protected synchronized  void buildGoogleApiClient() {
  
      mGoogleApiClient = new GoogleApiClient.Builder(this)
              .addConnectionCallbacks(this)
              .addOnConnectionFailedListener(this)
              .addApi(LocationServices.API)
              .build();
  
      if (mGoogleApiClient != null) {
          mGoogleApiClient.connect();
      } else
          Toast.makeText(this, "Not Connected!", Toast.LENGTH_SHORT).show();
  
  }
  
  
  /*Ending the updates for the location service*/
  @Override
  protected void onStop() {
      mGoogleApiClient.disconnect();
      super.onStop();
  }
  
  @Override
  public void onConnected(@Nullable Bundle bundle) {
      settingRequest();
  }
  
  @Override
  public void onConnectionSuspended(int i) {
      Toast.makeText(this, "Connection Suspended!", Toast.LENGTH_SHORT).show();
  }
  
  @Override
  public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
      Toast.makeText(this, "Connection Failed!", Toast.LENGTH_SHORT).show();
      if (connectionResult.hasResolution()) {
          try {
              // Start an Activity that tries to resolve the error
              connectionResult.startResolutionForResult(this, 90000);
          } catch (IntentSender.SendIntentException e) {
              e.printStackTrace();
          }
      } else {
          Log.i("Current Location", "Location services connection failed with code " + connectionResult.getErrorCode());
      }
  }
  
  
  /*Method to get the enable location settings dialog*/
  public void settingRequest() {
      mLocationRequest = new LocationRequest();
      mLocationRequest.setInterval(10000);    // 10 seconds, in milliseconds
      mLocationRequest.setFastestInterval(1000);   // 1 second, in milliseconds
      mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
  
      LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
              .addLocationRequest(mLocationRequest);
  
      PendingResult&lt;LocationSettingsResult&gt; result =
              LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient,
                      builder.build());
  
      result.setResultCallback(new ResultCallback&lt;LocationSettingsResult&gt;() {
  
          @Override
          public void onResult(@NonNull LocationSettingsResult result) {
              final Status status = result.getStatus();
              final LocationSettingsStates state = result.getLocationSettingsStates();
              switch (status.getStatusCode()) {
                  case LocationSettingsStatusCodes.SUCCESS:
                      // All location settings are satisfied. The client can
                      // initialize location requests here.
                      getLocation();
                      break;
                  case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                      // Location settings are not satisfied, but this can be fixed
                      // by showing the user a dialog.
                      try {
                          // Show the dialog by calling startResolutionForResult(),
                          // and check the result in onActivityResult().
                          status.startResolutionForResult(MainActivity.this, 1000);
                      } catch (IntentSender.SendIntentException e) {
                          // Ignore the error.
                      }
                      break;
                  case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                      // Location settings are not satisfied. However, we have no way
                      // to fix the settings so we won't show the dialog.
                      break;
              }
          }
  
      });
  }
  
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
      switch (requestCode) {
          case 1000:
              switch (resultCode) {
                  case Activity.RESULT_OK:
                      // All required changes were successfully made
                      getLocation();
                      break;
                  case Activity.RESULT_CANCELED:
                      // The user was asked to change settings, but chose not to
                      Toast.makeText(this, "Location Service not Enabled", Toast.LENGTH_SHORT).show();
                      break;
                  default:
                      break;
              }
              break;
      }
  }
  
  
  public void getLocation() {
      if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &amp;&amp; ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
          // TODO: Consider calling
          //    ActivityCompat#requestPermissions
          // here to request the missing permissions, and then overriding
          //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
          //                                          int[] grantResults)
          // to handle the case where the user grants the permission. See the documentation
          // for ActivityCompat#requestPermissions for more details.
          return;
      } else {
          /*Getting the location after aquiring location service*/
          mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                  mGoogleApiClient);
  
          if (mLastLocation != null) {
             // _progressBar.setVisibility(View.INVISIBLE);
              _latitude.setText("Latitude: " + String.valueOf(mLastLocation.getLatitude()));
              _longitude.setText("Longitude: " + String.valueOf(mLastLocation.getLongitude()));
          } else {
              /*if there is no last known location. Which means the device has no data for the loction currently.
              * So we will get the current location.
              * For this we'll implement Location Listener and override onLocationChanged*/
              Log.i("Current Location", "No data for location found");
  
              if (!mGoogleApiClient.isConnected())
                  mGoogleApiClient.connect();
  
              LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, MainActivity.this);
          }
      }
  }
  
  
  
  @Override
  public void onLocationChanged(Location location) {
  
      mLastLocation = location;
      _progressBar.setVisibility(View.INVISIBLE);
      _latitude.setText("Latitude: " + String.valueOf(mLastLocation.getLatitude()));
      _longitude.setText("Longitude: " + String.valueOf(mLastLocation.getLongitude()));
  
  }
  
  //////////////////////////////////////////// End of Location services ///////////////////////////////////////////////
  
  
  ////////////////////////////////////////// Start of getting JSON DATA ///////////////////////////////////////////////
  
  // Download JSON file AsyncTask
  private class DownloadJSON extends AsyncTask&lt;Void, Void, Void&gt;
  {
  
     /* @Override
      protected void onPreExecute() {
          super.onPreExecute();
          progressDialog = new ProgressDialog(MainActivity.this);
          progressDialog.setMessage("Fetching Users....!");
          progressDialog.setCancelable(false);
          progressDialog.show();
  
      }*/
  
      @Override
      protected Void doInBackground(Void... params) {
  
          // Locate the Users Class
          users = new ArrayList&lt;Users&gt;();
  
          // Create an array to populate the spinner
          userList = new ArrayList&lt;String&gt;();
          // http://10.0.2.2:8000/MobileApp/index.php
          //http://10.0.2.2:8000/app/web/users/
          //http://192.168.100.8:8000/app/web/users/
          // JSON file URL address
          jsonObject = JSONfunctions.getJSONfromURL("http://192.168.100.15:8000/MobileApp/GET_DATA.php");
  
          try
          {
              JSONObject jobj = new JSONObject(jsonObject.toString());
              // Locate the NodeList name
              jsonArray = jobj.getJSONArray("users");
  
              for(int i=0; i&lt;jsonArray.length(); i++)
              {
                  jsonObject = jsonArray.getJSONObject(i);
  
                  Users user = new Users();
  
                  user.setId(jsonObject.optString("Id"));
                  user.setName(jsonObject.optString("Name"));
                  users.add(user);
  
                  userList.add(jsonObject.optString("Name"));
  
              }
          } catch (JSONException e) {
              Log.e("Error", e.getMessage());
              e.printStackTrace();
          }
  
  
          return null;
      }
  
      @Override
      protected void onPostExecute(Void args)
      {
          // Locate the spinner in activity_main.xml
          Spinner spinner = (Spinner)findViewById(R.id.spinner);
  
          // Spinner adapter
          spinner.setAdapter(new ArrayAdapter&lt;String&gt;(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, userList));
  
          // Spinner on item click listener
  
          spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
              @Override
              public void onItemSelected(AdapterView&lt;?&gt; parent, View view, int position, long id) {
  
                  textViewResult = (TextView)findViewById(R.id.textView);
  
                  // Set the text followed by the position
  
                  textViewResult.setText("Hi " + users.get(position).getName() + " your ID is " + users.get(position).getId());
  
              }
  
              @Override
              public void onNothingSelected(AdapterView&lt;?&gt; parent) {
                  textViewResult.setText("");
              }
          });
      }
  
  
  }
  //////////////////////////////////////// End of getting JSON DATA //////////////////////////////////////////
  </code></pre>
  
  <p>When I press the save button the following fields would be inserted into <code>Activity</code> table</p>
  
  <ol>
  <li><code>Id</code> (Which is auto-increment)</li>
  <li><code>UserId</code> (User ID from Users table based on the selected name)</li>
  <li><code>Latitude</code> (Of current user)</li>
  <li><code>Longitude</code> (Of current user)</li>
  <li><code>DateTime</code> (Date time of the user)</li>
  </ol>
  
  <p>Should I have to create an 'activity' class like I have created the <code>User</code> class?</p>
  
  <p>For this I have something in mind</p>
  
  <ol>
  <li>I would save the data into <code>xml</code> or <code>txt</code> file first then it will be saved into the DB.</li>
  <li>I should convert the data into <code>json</code> format and then save it into DB</li>
  <li>Directly save it into the DB by using a query in my <code>php</code> script</li>
  </ol>
  
  <p>Which of these 3 is easiest to implement? It would be very helpful if anyone could provide me a tutorial, though I saw many of them ( <a href="https://stackoverflow.com/a/32200552/6854117">1</a> , <a href="http://androidexample.com/How_To_Make_HTTP_POST_Request_To_Server_-_Android_Example/index.php?view=article_discription&amp;aid=64" rel="noreferrer">2</a> ) and as described above I couldn't understand them :( . </p>
  
  <p>I am stuck to it and don't know what I have to do. Any help would be highly appreciated.</p>