Android-dan mysql-serverga ma'lumotlarni qanday yuborish kerak?

Men androidning rivojlanishi uchun yangi odamman. Android Studio-dan foydalanayapman. Menda ochilgan ro'yxat nomlari mavjud bo'lgan ilovani qilmoqdaman. Har qanday nomni tanlashda ushbu nomdagi tegishli ID ilovada ko'rsatiladi. So'ngra, mavjud gps koordinatalarini qidirish va ularni ilovada ko'rsatishga mo'ljallangan tugma mavjud. Men shunga o'xshash savollarni izladim va ba'zi aloqalarni topdim (ularni oxirida e'lon qilaman), lekin ularni tushunolmadim. Quyida ilova ekrani tasvirlangan

android app screenshot

Mysql-dagi ikkita jadval bor; foydalanuvchilar va amallar ga qarang

foydalanuvchilar

mysql workbench screenshot listing fields 'Id' and 'Name'

Faoliyat

mysql workbench screenshot listing fields 'Id', 'UserId', 'Latitude', 'Longitude' and 'DateTime'

UserId , users jadvalidan Id faoliyat jadvalidagi xorijiy kalit hisoblanadi.

Ma'lumotlarni JSON sifatida qaytarish uchun quyidagi buyruq faylini yaratdim:

<?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'=>$row['Id'],
            'Name'=>$row['Name']
        )); 
      }//end while

    echo json_encode(array('users'=>$result));

    mysqli_close($con);
?>

Mening ilovalarimning kodida users sinf yaratdim

Foydalanuvchilar sinfi

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;
}}

JSON SINIFI

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;
}

MainActivity

 @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 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 result =
            LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient,
                    builder.build());

    result.setResultCallback(new ResultCallback() {

        @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 && 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
{

   /* @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();

       //Create an array to populate the spinner
        userList = new ArrayList();
       //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(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<?> 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<?> parent) {
                textViewResult.setText("");
            }
        });
    }


}
//////////////////////////////////////// End of getting JSON DATA //////////////////////////////////////////

Saqlash tugmachasini bosganimda quyidagi maydonlar Activity jadvaliga kiritiladi

  1. Id (Which is auto-increment)
  2. UserId (User ID from Users table based on the selected name)
  3. Latitude (Of current user)
  4. Longitude (Of current user)
  5. DateTime (Date time of the user)

Men User sinfini yaratganim kabi "faoliyat" sinfini yaratishim kerakmi?

Buning uchun menda bir narsa bor

  1. Ma'lumotlarni xml yoki txt faylga saqlayman, bundan keyin u JBga saqlanadi.
  2. Ma'lumotlarni json formatiga aylantirish va keyin uni JB
  3. ga saqlash kerak
  4. PHP skriptidagi so'rov yordamida bevosita JBga yozib oling

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 ( 1 , 2 ) and as described above I couldn't understand them :( .

Men unga yopishib oldim va nima qilishim kerakligini bilmayman. Har qanday yordam juda yuqori baholanadi.

2
javobimni tekshirib ko'ring. Agar yordam kerak bo'lsa, iltimos so'rang
qo'shib qo'ydi muallif Zaki Pathan, manba
@fisal Energiyadan foydalanishni tez-tez ishlatib turing.
qo'shib qo'ydi muallif Jason Bourne, manba
@fisal Energiyadan foydalanishni tez-tez ishlatib turing.
qo'shib qo'ydi muallif Jason Bourne, manba

7 javoblar

Api-ni yozishingiz kerak, u erda siz Android-dan ma'lumotlarni uzatib, Api-dagi ma'lumotlaringizni keltirib chiqarsiz va ma'lumotlar so'rovi yordamida ma'lumotlar bazasida saqlashingiz mumkin. Android tomonida kodni bajarishingiz kerak:

GetData (), PostData, DeleteData() uchun sinfim PutUtility. siz faqat paket nomini o'zgartirishingiz kerak

package fourever.amaze.mics;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;


public class PutUtility {

    private Map params = new HashMap<>();
    private static HttpURLConnection httpConnection;
    private static BufferedReader reader;
    private static String Content;
    private StringBuffer sb1;
    private StringBuffer response;

    public void setParams(Map params) {
        this.params = params;
    }

    public void setParam(String key, String value) {
        params.put(key, value);
    }

    public String getData(String Url) {


        StringBuilder sb = new StringBuilder();

        try {
           //Defined URL  where to send data

            URL url = new URL(Url);

            URLConnection conn = null;
            conn = url.openConnection();

           //Send POST data request
            httpConnection = (HttpURLConnection) conn;
            httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConnection.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(httpConnection.getInputStream()));
            String inputLine;
            response = new StringBuffer();



            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (Exception ex) { }
        }

        return response.toString();
    }


    public String postData(String Url) {


        StringBuilder sb = new StringBuilder();
        for (String key : params.keySet()) {
            String value = null;
            value = params.get(key);


            if (sb.length() > 0) {
                sb.append("&");
            }
            sb.append(key + "=" + value);
        }

        try {
           //Defined URL  where to send data

            URL url = new URL(Url);

            URLConnection conn = null;
            conn = url.openConnection();

           //Send POST data request
            httpConnection = (HttpURLConnection) conn;
            httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConnection.setRequestMethod("POST");
            httpConnection.setDoInput(true);
            httpConnection.setDoOutput(true);
            OutputStreamWriter wr = null;

            wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(sb.toString());
            wr.flush();

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(httpConnection.getInputStream()));
            String inputLine;
            response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {

                reader.close();
            } catch (Exception ex) {
            }
        }


        return response.toString();
    }


    public String putData(String Url) {


        StringBuilder sb = new StringBuilder();
        for (String key : params.keySet()) {
            String value = null;
            try {
                value = URLEncoder.encode(params.get(key), "UTF-8");
                if (value.contains("+"))
                    value = value.replace("+", "%20");

                //return sb.toString();


               //Get the server response

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

            if (sb.length() > 0) {
                sb.append("&");
            }
            sb.append(key + "=" + value);
        }

        try {
           //Defined URL  where to send data

            URL url = new URL(Url);

            URLConnection conn = null;
            conn = url.openConnection();

           //Send PUT data request
            httpConnection = (HttpURLConnection) conn;
            httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConnection.setRequestMethod("PUT");
            httpConnection.setDoInput(true);
            httpConnection.setDoOutput(false);
            OutputStreamWriter wr = null;

            wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(sb.toString());
            wr.flush();

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            ;
            String line = null;

           //Read Server Response
            while ((line = reader.readLine()) != null) {
               //Append server response in string
                sb1.append(line + " ");
            }

           //Append Server Response To Content String
            Content = sb.toString();


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {

                reader.close();
            } catch (Exception ex) {
            }
        }
       //Send PUT data request
        return Url;

    }


    public String deleteData(String Url) {


        StringBuilder sb = new StringBuilder();
        for (String key : params.keySet()) {

            try {
               //Defined URL  where to send data

                URL url = new URL(Url);

                URLConnection conn = null;
                conn = url.openConnection();

               //Send POST data request
                httpConnection = (HttpURLConnection) conn;
                httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                httpConnection.setRequestMethod("DELETE");
                httpConnection.connect();


                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                String line = null;

               //Read Server Response
                while ((line = reader.readLine()) != null) {
                   //Append server response in string
                    sb1.append(line + " ");
                }

               //Append Server Response To Content String
                Content = sb.toString();


            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {

                    reader.close();
                } catch (Exception ex) {
                }
            }



        }
        return Url;

    }

Va bu kabi sinfdan foydalaning. Bu sinf internetni avtomatik ravishda amalga oshiradi va sizga serverdan javob beradi:

    private class ServiceLogin extends AsyncTask {

            ProgressDialog mProgressDialog;
            private String res;

            @Override
            protected void onPreExecute() {
                mProgressDialog = ProgressDialog.show(LoginActivity.this,
                        "", "Please wait...");
            }

            @Override
            protected String doInBackground(String... params) {
                res = null;
                PutUtility put = new PutUtility();

                put.setParam("UserId", params[0].toString());
                put.setParam("Latitude", params[1].toString());
                put.setParam("Longitude", params[2].toString());
                put.setParam("DateTime", params[3].toString());

                try {
                    res = put.postData("INSERT URL of API HERE");
                    Log.v("res", res);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return res;

            }

            protected void onPostExecute(String res) {
                //"Here you get response from server in res"

            }
        }

Endi siz ushbu xizmatni tugmachasini bosib qo'ng'iroq qilishingiz mumkin va quyidagi ma'lumotlarni xizmatga qo'shishingiz mumkin:

new ServiceLogin().execute(pass four parameters here);

Umid qilamanki bu sizga yordam beradi

EDIT:

Bu ma'lumotlarni kiritish uchun oddiy PHP API

<?php include('connection.php');

$return_arr = array();

 $UserId=($_POST['UserId']);
 $Latitude=($_POST['Latitude']);
 $Longitude=($_POST['Longitude']);
$DateTime=($_POST['DateTime']);


        $user_register_sql1 = "INSERT INTO `activity`(`Id`,`UserId`, `Latitude`,`Longitude`,`DateTime`) values (NULL,'".$UserId."','".$Latitude."','".$Longitude."','".$DateTime."')"; 
             mysql_query($user_register_sql1);
             $row_array['errorcode1'] = 1; 

}
?>
5
qo'shib qo'ydi
Ba'zilar ba'zi ma'lumotlar serverga yuklangan yoki yo'qligini tekshirishimiz mumkin va biz SQLite ma'lumotlarini o'chirib tashlashimiz mumkin.
qo'shib qo'ydi muallif Panache, manba
Buni savolga qaraysizmi?
qo'shib qo'ydi muallif Moeez, manba
O'qituvchi uchun rahmat, u menga foydali bo'lib tuyuladi va men buni albatta sinab ko'raman. Agar PHP skriptini yuborishingiz mumkin bo'lsa, men uchun juda foydali bo'lar edi, chunki men skriptni qanday yozishni va nima qilishni bilaman, chunki userID user jadvali va keyin aktivite jadvaliga qo'ying :(
qo'shib qo'ydi muallif Moeez, manba
u erda javob berding
qo'shib qo'ydi muallif Moeez, manba
ma'lumotlar qo'yish va post ma'lumotlar o'rtasidagi farq nima?
qo'shib qo'ydi muallif Moeez, manba
qo'shib qo'ydi muallif Moeez, manba
Vau, qardosh champa kabi ishlaydi :)
qo'shib qo'ydi muallif Moeez, manba
Sizga javob yozishga yuborilgan javob @ faisal1208
qo'shib qo'ydi muallif Zaki Pathan, manba
Sizga yordam berishdan baxtiyor :) :) :)
qo'shib qo'ydi muallif Zaki Pathan, manba
@ faisal1208 Ma'lumotlar bazasida ishlayotganda mening PutUtility sinfingiz sizga kelajakda yordam beradi. Umid qilamanki bu sizga yordam beradi
qo'shib qo'ydi muallif Zaki Pathan, manba
Yangilangan javobni tekshirish @ faisal1208
qo'shib qo'ydi muallif Zaki Pathan, manba

Api-ni yozishingiz kerak, u erda siz Android-dan ma'lumotlarni uzatib, Api-dagi ma'lumotlaringizni keltirib chiqarsiz va ma'lumotlar so'rovi yordamida ma'lumotlar bazasida saqlashingiz mumkin. Android tomonida kodni bajarishingiz kerak:

GetData (), PostData, DeleteData() uchun sinfim PutUtility. siz faqat paket nomini o'zgartirishingiz kerak

package fourever.amaze.mics;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;


public class PutUtility {

    private Map params = new HashMap<>();
    private static HttpURLConnection httpConnection;
    private static BufferedReader reader;
    private static String Content;
    private StringBuffer sb1;
    private StringBuffer response;

    public void setParams(Map params) {
        this.params = params;
    }

    public void setParam(String key, String value) {
        params.put(key, value);
    }

    public String getData(String Url) {


        StringBuilder sb = new StringBuilder();

        try {
           //Defined URL  where to send data

            URL url = new URL(Url);

            URLConnection conn = null;
            conn = url.openConnection();

           //Send POST data request
            httpConnection = (HttpURLConnection) conn;
            httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConnection.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(httpConnection.getInputStream()));
            String inputLine;
            response = new StringBuffer();



            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (Exception ex) { }
        }

        return response.toString();
    }


    public String postData(String Url) {


        StringBuilder sb = new StringBuilder();
        for (String key : params.keySet()) {
            String value = null;
            value = params.get(key);


            if (sb.length() > 0) {
                sb.append("&");
            }
            sb.append(key + "=" + value);
        }

        try {
           //Defined URL  where to send data

            URL url = new URL(Url);

            URLConnection conn = null;
            conn = url.openConnection();

           //Send POST data request
            httpConnection = (HttpURLConnection) conn;
            httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConnection.setRequestMethod("POST");
            httpConnection.setDoInput(true);
            httpConnection.setDoOutput(true);
            OutputStreamWriter wr = null;

            wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(sb.toString());
            wr.flush();

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(httpConnection.getInputStream()));
            String inputLine;
            response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {

                reader.close();
            } catch (Exception ex) {
            }
        }


        return response.toString();
    }


    public String putData(String Url) {


        StringBuilder sb = new StringBuilder();
        for (String key : params.keySet()) {
            String value = null;
            try {
                value = URLEncoder.encode(params.get(key), "UTF-8");
                if (value.contains("+"))
                    value = value.replace("+", "%20");

                //return sb.toString();


               //Get the server response

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

            if (sb.length() > 0) {
                sb.append("&");
            }
            sb.append(key + "=" + value);
        }

        try {
           //Defined URL  where to send data

            URL url = new URL(Url);

            URLConnection conn = null;
            conn = url.openConnection();

           //Send PUT data request
            httpConnection = (HttpURLConnection) conn;
            httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConnection.setRequestMethod("PUT");
            httpConnection.setDoInput(true);
            httpConnection.setDoOutput(false);
            OutputStreamWriter wr = null;

            wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(sb.toString());
            wr.flush();

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            ;
            String line = null;

           //Read Server Response
            while ((line = reader.readLine()) != null) {
               //Append server response in string
                sb1.append(line + " ");
            }

           //Append Server Response To Content String
            Content = sb.toString();


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {

                reader.close();
            } catch (Exception ex) {
            }
        }
       //Send PUT data request
        return Url;

    }


    public String deleteData(String Url) {


        StringBuilder sb = new StringBuilder();
        for (String key : params.keySet()) {

            try {
               //Defined URL  where to send data

                URL url = new URL(Url);

                URLConnection conn = null;
                conn = url.openConnection();

               //Send POST data request
                httpConnection = (HttpURLConnection) conn;
                httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                httpConnection.setRequestMethod("DELETE");
                httpConnection.connect();


                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                String line = null;

               //Read Server Response
                while ((line = reader.readLine()) != null) {
                   //Append server response in string
                    sb1.append(line + " ");
                }

               //Append Server Response To Content String
                Content = sb.toString();


            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {

                    reader.close();
                } catch (Exception ex) {
                }
            }



        }
        return Url;

    }

Va bu kabi sinfdan foydalaning. Bu sinf internetni avtomatik ravishda amalga oshiradi va sizga serverdan javob beradi:

    private class ServiceLogin extends AsyncTask {

            ProgressDialog mProgressDialog;
            private String res;

            @Override
            protected void onPreExecute() {
                mProgressDialog = ProgressDialog.show(LoginActivity.this,
                        "", "Please wait...");
            }

            @Override
            protected String doInBackground(String... params) {
                res = null;
                PutUtility put = new PutUtility();

                put.setParam("UserId", params[0].toString());
                put.setParam("Latitude", params[1].toString());
                put.setParam("Longitude", params[2].toString());
                put.setParam("DateTime", params[3].toString());

                try {
                    res = put.postData("INSERT URL of API HERE");
                    Log.v("res", res);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return res;

            }

            protected void onPostExecute(String res) {
                //"Here you get response from server in res"

            }
        }

Endi siz ushbu xizmatni tugmachasini bosib qo'ng'iroq qilishingiz mumkin va quyidagi ma'lumotlarni xizmatga qo'shishingiz mumkin:

new ServiceLogin().execute(pass four parameters here);

Umid qilamanki bu sizga yordam beradi

EDIT:

Bu ma'lumotlarni kiritish uchun oddiy PHP API

<?php include('connection.php');

$return_arr = array();

 $UserId=($_POST['UserId']);
 $Latitude=($_POST['Latitude']);
 $Longitude=($_POST['Longitude']);
$DateTime=($_POST['DateTime']);


        $user_register_sql1 = "INSERT INTO `activity`(`Id`,`UserId`, `Latitude`,`Longitude`,`DateTime`) values (NULL,'".$UserId."','".$Latitude."','".$Longitude."','".$DateTime."')"; 
             mysql_query($user_register_sql1);
             $row_array['errorcode1'] = 1; 

}
?>
5
qo'shib qo'ydi
Ba'zilar ba'zi ma'lumotlar serverga yuklangan yoki yo'qligini tekshirishimiz mumkin va biz SQLite ma'lumotlarini o'chirib tashlashimiz mumkin.
qo'shib qo'ydi muallif Panache, manba
Vau, qardosh champa kabi ishlaydi :)
qo'shib qo'ydi muallif Moeez, manba
Buni savolga qaraysizmi?
qo'shib qo'ydi muallif Moeez, manba
qo'shib qo'ydi muallif Moeez, manba
O'qituvchi uchun rahmat, u menga foydali bo'lib tuyuladi va men buni albatta sinab ko'raman. Agar PHP skriptini yuborishingiz mumkin bo'lsa, men uchun juda foydali bo'lar edi, chunki men skriptni qanday yozishni va nima qilishni bilaman, chunki userID user jadvali va keyin aktivite jadvaliga qo'ying :(
qo'shib qo'ydi muallif Moeez, manba
u erda javob berding
qo'shib qo'ydi muallif Moeez, manba
ma'lumotlar qo'yish va post ma'lumotlar o'rtasidagi farq nima?
qo'shib qo'ydi muallif Moeez, manba
Sizga yordam berishdan baxtiyor :) :) :)
qo'shib qo'ydi muallif Zaki Pathan, manba
Sizga javob yozishga yuborilgan javob @ faisal1208
qo'shib qo'ydi muallif Zaki Pathan, manba
@ faisal1208 Ma'lumotlar bazasida ishlayotganda mening PutUtility sinfingiz sizga kelajakda yordam beradi. Umid qilamanki bu sizga yordam beradi
qo'shib qo'ydi muallif Zaki Pathan, manba
Yangilangan javobni tekshirish @ faisal1208
qo'shib qo'ydi muallif Zaki Pathan, manba

Server tomonida json so'rovini POST deb qabul qiladigan va Mysql ma'lumotlar bazasida ma'lumotlarni saqlaydigan api kerak. Android versiyasida talab qilish uchun Retrofit va Volley kabi Android kutubxonalarini olishingiz mumkin.

Retrofit ilovasidan foydalanish

Sizning poju deylik:

public class User {
    private String id;
    private String latitude;
    private String longitude;
public User(String id, String latitude,String longitude) {
    this.id = id;
    this.latitude = latitude;
    this.longitude = longitude
   }
}

Bizning so'nggi nuqta quyidagicha bo'ladi:

@POST("/users/new")
Call createUser(@Body User user);

Retrofit JSON ni o'zingiz qabul qilasiz. Sizda shunday bir narsa bo'lishi kerak:

User user = new User(123, "33.43", "34.34");
Call call = apiService.createuser(user);
call.enqueue(new Callback() {
  @Override
  public void onResponse(Call call, Response response) {

  }

  @Override
  public void onFailure(Call call, Throwable t) {

  }
4
qo'shib qo'ydi

Bu erda siz ma'lumotlarni yuborish uchun an'anaviy usullardan foydalanmoqdasiz Buning uchun quyidagi bosqichlarni bajaring.

1) build.gradle faylida buni qo'shing

useLibrary 'org.apache.http.legacy'

 compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'
    compile('org.apache.httpcomponents:httpmime:4.3') {
        exclude module: "httpclient"}

2) json ayrıştırıcı yaratish

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

@SuppressWarnings("deprecation")
public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

   //constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url, List params) {

       //Making HTTP request
        try {
            //Log.d("defaultHttpClient" ,"IN");
           //defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            //Log.d("url" ,url);
            HttpPost httpPost = new HttpPost(url);
            //Log.d("params" ,params.toString());
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            //Log.d("httpPost" , new UrlEncodedFormEntity(params).toString());
            HttpResponse httpResponse = httpClient.execute(httpPost);
            //Log.e("Entry", "1");
            HttpEntity httpEntity = httpResponse.getEntity();
            //Log.e("Entry", "2");
            is = httpEntity.getContent();
            //Log.e("Entry", "3");  
        } catch (UnsupportedEncodingException e) {
            //Log.e("UnsupportedEncodingException", "UnsupportedEncodingException");
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            //Log.e("ClientProtocolException", "ClientProtocolException");
            e.printStackTrace();
        } catch (IOException e) {
            //Log.e("IOException", "IOException");
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            //Log.e("Entry", "4");
            while ((line = reader.readLine()) != null) {
                //Log.e("line", line);
                sb.append(line + "\n");
            }
            //Log.e("Entry", "5");
            is.close();
            //Log.e("Entry", "6");
            json = sb.toString();
            //Log.e("JSON", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

       //try parse the string to a JSON object
        try {
            if(json.length()>0){
                jObj = new JSONObject(json);
            }else{
                jObj = new JSONObject();
            }
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

       //return JSON String
        return jObj;

    }
}

3) UserFunction deb nomlangan sinfda yaratiladi

    public class UserFunctions {
        private JSONParser jsonParser;
        Context ctx ;


       //constructor
        public UserFunctions(Context context){
            ctx = context;
            jsonParser = new JSONParser();
        }

   //create on function to send the value to server and get the json response back
    public JSONObject sendDataToSever(String val1, String val2,String val3){
        JSONObject json = null;
        try {
               //Building Parameters
                List params = new ArrayList();
                params.add(new BasicNameValuePair("val1", val1));
                params.add(new BasicNameValuePair("val2", val2));
                params.add(new BasicNameValuePair("val3", val3));
                json = jsonParser.getJSONFromUrl(Constants.BASE_URL, params);
           } catch (Exception e) {
               //TODO Auto-generated catch block
                e.printStackTrace();
            }
            return json;
    }
  }

4) sizda asosiy faoliyat klassi

// befor onCreate add 
UserFunctions uf;
ProgressDialog pDialog;
JSONObject DATA_JSON;

// onCreate usulida

uf = new UserFunctions(Mainactivity.this);

// Joylashtirilgandan so'ng, serverga ma'lumotlarni yuborish uchun AsyncTask-ni chaqirib oling.

Bu erda shunga o'xshash va shuning uchun sinf oxirida aasyncctask funksiyasini yozing

new LoadWebPageTask().execute(); //calling async task

5) LoadWebPageTask asnc vazifasi

maxsus sinf LoadWebPageTask kengaytiradi AsyncTask {

protected void onPreExecute() { 
            pDialog = new ProgressDialog(
                    Mainactivity.this);
            pDialog.setMessage("Please wait..");
            pDialog.setIndeterminate(true);
            pDialog.setCancelable(false);
            pDialog.show();
        }

       protected Void doInBackground(Void... unused) {
            runOnUiThread(new Runnable() {
                public void run() {
                    DATA_JSON = uf.sendDataToSever(val1, val2,val3);

                }
            }); 
            return (null);
        }

        protected void onPostExecute(Void unused) {
           //closing progress dialog
            pDialog.dismiss();
          //do your own logics here
        }
    }

This will send data to the server as post method you can process this as post method by using $_POST[];

Iltimos, shunday harakat qilib ko'ring. Bu sizga yordam berishi mumkin.

Server tomoni uchun

1) Ma'lumotlar bazasi sinfida yaratish

<?php
class Database{

   //specify your own database credentials
    private $host = "localhost";
    private $db_name = "db_name";
    private $username = "root";
    private $password = "password";



    public $conn;

   //get the database connection
    public function getConnection(){

        $this->conn = null;

        try{
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
        }catch(PDOException $exception){
            echo "Connection error: " . $exception->getMessage();
        }

        return $this->conn;
    }
}
?>

2) barcha JB funktsiyalarini bu erda umumiy deb nomlash uchun yana bir sinf yaratish

<?php
class Common{
   //database connection
    private $conn;  

   //getErrors
    public $error = array();

    public function __construct($db){
        $this->conn = $db;
    }

   //Save error to file
    function save_error($err){
        try {

            if(!is_dir("ERROR")){mkdir("ERROR");}

            $filename = "ERROR/".$this->getDate().".txt";

            if (!$handle = fopen($filename, 'a')) {echo "Cannot open file ($filename)"; return;}

           //Write $somecontent to our opened file.
            if (fwrite($handle, $err."\r\n") === FALSE) {echo "Cannot write to file ($filename)";return;}   

            fclose($handle);
        } catch (Exception $e) {
            echo 'Caught exception: ',  $e->getMessage(), "\n";
        }
    }

   //used for the 'created'
    function getTimestamp(){
        date_default_timezone_set('Asia/Calcutta');
        return  date('Y-m-d H:i:s');
    }

   //used for the 'created'
    function getDate(){
        date_default_timezone_set('Asia/Calcutta');
        return  date('Y-m-d');
    }

// create function to insert data into db

function syncLocalAppData($_tableName, $colName, $values){
        try{

            $query = " REPLACE INTO  ".$_tableName." (".$colName.") VALUES (".$values."); ";
            //echo $query;
            //exit;

            $stmt = $this->conn->prepare( $query );


            if($stmt->execute()){
                return true;
            }else{
                save_error("\r\nQRY : " . $stmt->queryString . " \r\n ERR CODE : " . $stmt->errorCode() . " \r\n ERR  : " .  json_encode($stmt->errorInfo()));
                 return false;
            }           

        } catch (Exception $e){
            save_error("\r\nOTHR : " . $e->getMessage());
            return false;
        }
    }
}

?>

3) post ma'lumotlarini userApi.php bilan ishlash uchun PHP faylida yaratilsin

<?php
$_errAry = array("status"=>400, "success"=>"false", "message"=>"Can't Service your request ","data"=>array());//error reprting json
$_sucAry = array("status"=>200, "success"=>"true", "message"=>"","data"=>array());//sccess rrespose json


nclude_once 'database.php';

// get database connection
$database = new Database();
$db = $database->getConnection();



// instantiate Common Objects
include_once 'objects/common.class.php';

$_tbl=""; $_cols="";  $_ord=""; 
$_whr="  ";


if(isset($_POST["val1"],$_POST["val2"],$_POST["val3"])){

$val1=$_POST["val1"];
$val2=$_POST["val2"];
$val3=$_POST["val3"];

$tableName="yourTableName";
$ColNameString="your coma separated coloumns name";
$ValueString="'".$val1."','".$val2."','".$val3."';
$_comm = new Common($db);
            $return=$_comm-> syncLocalAppData($tableName,$ColNameString,$ValueString);
if($return){
        $_op = $_sucAry;
        $_op["data"]=array("status"=>true),
        echo json_encode($_op);
        exit(0);
}else{
        $_op = $_sucAry;
        $_op["success"]= "false";
        $_op["message"]="cant process your request,
        echo json_encode($_op);exit(0);
}
}
1
qo'shib qo'ydi
O'qituvchi uchun rahmat, u menga foydali bo'lib tuyuladi va men buni albatta sinab ko'raman. Agar PHP skriptini yuborishingiz mumkin bo'lsa, men uchun juda foydali bo'lar edi, chunki men skript yozishni qanday amalga oshirishim va u bilan nima qilish kerak deb shubhalanaman :(
qo'shib qo'ydi muallif Moeez, manba
Buni albatta ishonch hosil qiling
qo'shib qo'ydi muallif Moeez, manba
foydalanuvchi identifikatori kodi kirish jadvaliga kiritilgan User
qo'shib qo'ydi muallif Moeez, manba
define ("HOST", "localhost"); belgilang ('JB', 'dastur'); define ('USER', 'root'); belgilang ('PASS', ''); $ con = mysqli_connect (HOST, USER, PASS, JB); agar (! $ con) {die ("Database Connection Error:". mysqli_connect_error ()); } else {// echo "Ulanish muvaffaqiyatli"; } Bu mening JB fayli
qo'shib qo'ydi muallif Moeez, manba
Sinf yaratish kerakmi? Kodni olish uchun require_once ('config.php') ishlatgan; $ Sql ​​= "SELECT * FROM foydalanuvchilar"; $ r = mysqli_query ($ con, $ sql); $ Natijada = array (); ($ string = mysqli_fetch_array ($ r)) {array_push ($ natija, array ('Id' => $ satr ['Id'], 'Nomi' => $ qator ['Nomi'])); } echo json_encode (array ('foydalanuvchilar' => $ natija));
qo'shib qo'ydi muallif Moeez, manba
qo'shib qo'ydi muallif Moeez, manba
Buni ham foydalanishingiz mumkin. MySQL aloqasi uchun PDO foydalanayapman. PDO istasangiz, men sizning yo'lingizni ta'qib qilishingiz mumkin bo'lgan Myshqli mening qadamlarimga amal qilishim mumkin.
qo'shib qo'ydi muallif Pranav MS, manba
iltimos, yangilangan javobni ko'rib chiqing. Va sizning talablaringiz bo'yicha narsalarni o'zgartiring.
qo'shib qo'ydi muallif Pranav MS, manba
OK bir necha daqiqa kutib turing, xuddi shunday yangilang. Endi siz buni Androidda qo'llashga harakat qilyapsiz.
qo'shib qo'ydi muallif Pranav MS, manba

Bu erda siz ma'lumotlarni yuborish uchun an'anaviy usullardan foydalanmoqdasiz Buning uchun quyidagi bosqichlarni bajaring.

1) build.gradle faylida buni qo'shing

useLibrary 'org.apache.http.legacy'

 compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'
    compile('org.apache.httpcomponents:httpmime:4.3') {
        exclude module: "httpclient"}

2) json ayrıştırıcı yaratish

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

@SuppressWarnings("deprecation")
public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

   //constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url, List params) {

       //Making HTTP request
        try {
            //Log.d("defaultHttpClient" ,"IN");
           //defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            //Log.d("url" ,url);
            HttpPost httpPost = new HttpPost(url);
            //Log.d("params" ,params.toString());
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            //Log.d("httpPost" , new UrlEncodedFormEntity(params).toString());
            HttpResponse httpResponse = httpClient.execute(httpPost);
            //Log.e("Entry", "1");
            HttpEntity httpEntity = httpResponse.getEntity();
            //Log.e("Entry", "2");
            is = httpEntity.getContent();
            //Log.e("Entry", "3");  
        } catch (UnsupportedEncodingException e) {
            //Log.e("UnsupportedEncodingException", "UnsupportedEncodingException");
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            //Log.e("ClientProtocolException", "ClientProtocolException");
            e.printStackTrace();
        } catch (IOException e) {
            //Log.e("IOException", "IOException");
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            //Log.e("Entry", "4");
            while ((line = reader.readLine()) != null) {
                //Log.e("line", line);
                sb.append(line + "\n");
            }
            //Log.e("Entry", "5");
            is.close();
            //Log.e("Entry", "6");
            json = sb.toString();
            //Log.e("JSON", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

       //try parse the string to a JSON object
        try {
            if(json.length()>0){
                jObj = new JSONObject(json);
            }else{
                jObj = new JSONObject();
            }
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

       //return JSON String
        return jObj;

    }
}

3) UserFunction deb nomlangan sinfda yaratiladi

    public class UserFunctions {
        private JSONParser jsonParser;
        Context ctx ;


       //constructor
        public UserFunctions(Context context){
            ctx = context;
            jsonParser = new JSONParser();
        }

   //create on function to send the value to server and get the json response back
    public JSONObject sendDataToSever(String val1, String val2,String val3){
        JSONObject json = null;
        try {
               //Building Parameters
                List params = new ArrayList();
                params.add(new BasicNameValuePair("val1", val1));
                params.add(new BasicNameValuePair("val2", val2));
                params.add(new BasicNameValuePair("val3", val3));
                json = jsonParser.getJSONFromUrl(Constants.BASE_URL, params);
           } catch (Exception e) {
               //TODO Auto-generated catch block
                e.printStackTrace();
            }
            return json;
    }
  }

4) sizda asosiy faoliyat klassi

// befor onCreate add 
UserFunctions uf;
ProgressDialog pDialog;
JSONObject DATA_JSON;

// onCreate usulida

uf = new UserFunctions(Mainactivity.this);

// Joylashtirilgandan so'ng, serverga ma'lumotlarni yuborish uchun AsyncTask-ni chaqirib oling.

Bu erda shunga o'xshash va shuning uchun sinf oxirida aasyncctask funksiyasini yozing

new LoadWebPageTask().execute(); //calling async task

5) LoadWebPageTask asnc vazifasi

maxsus sinf LoadWebPageTask kengaytiradi AsyncTask {

protected void onPreExecute() { 
            pDialog = new ProgressDialog(
                    Mainactivity.this);
            pDialog.setMessage("Please wait..");
            pDialog.setIndeterminate(true);
            pDialog.setCancelable(false);
            pDialog.show();
        }

       protected Void doInBackground(Void... unused) {
            runOnUiThread(new Runnable() {
                public void run() {
                    DATA_JSON = uf.sendDataToSever(val1, val2,val3);

                }
            }); 
            return (null);
        }

        protected void onPostExecute(Void unused) {
           //closing progress dialog
            pDialog.dismiss();
          //do your own logics here
        }
    }

This will send data to the server as post method you can process this as post method by using $_POST[];

Iltimos, shunday harakat qilib ko'ring. Bu sizga yordam berishi mumkin.

Server tomoni uchun

1) Ma'lumotlar bazasi sinfida yaratish

<?php
class Database{

   //specify your own database credentials
    private $host = "localhost";
    private $db_name = "db_name";
    private $username = "root";
    private $password = "password";



    public $conn;

   //get the database connection
    public function getConnection(){

        $this->conn = null;

        try{
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
        }catch(PDOException $exception){
            echo "Connection error: " . $exception->getMessage();
        }

        return $this->conn;
    }
}
?>

2) barcha JB funktsiyalarini bu erda umumiy deb nomlash uchun yana bir sinf yaratish

<?php
class Common{
   //database connection
    private $conn;  

   //getErrors
    public $error = array();

    public function __construct($db){
        $this->conn = $db;
    }

   //Save error to file
    function save_error($err){
        try {

            if(!is_dir("ERROR")){mkdir("ERROR");}

            $filename = "ERROR/".$this->getDate().".txt";

            if (!$handle = fopen($filename, 'a')) {echo "Cannot open file ($filename)"; return;}

           //Write $somecontent to our opened file.
            if (fwrite($handle, $err."\r\n") === FALSE) {echo "Cannot write to file ($filename)";return;}   

            fclose($handle);
        } catch (Exception $e) {
            echo 'Caught exception: ',  $e->getMessage(), "\n";
        }
    }

   //used for the 'created'
    function getTimestamp(){
        date_default_timezone_set('Asia/Calcutta');
        return  date('Y-m-d H:i:s');
    }

   //used for the 'created'
    function getDate(){
        date_default_timezone_set('Asia/Calcutta');
        return  date('Y-m-d');
    }

// create function to insert data into db

function syncLocalAppData($_tableName, $colName, $values){
        try{

            $query = " REPLACE INTO  ".$_tableName." (".$colName.") VALUES (".$values."); ";
            //echo $query;
            //exit;

            $stmt = $this->conn->prepare( $query );


            if($stmt->execute()){
                return true;
            }else{
                save_error("\r\nQRY : " . $stmt->queryString . " \r\n ERR CODE : " . $stmt->errorCode() . " \r\n ERR  : " .  json_encode($stmt->errorInfo()));
                 return false;
            }           

        } catch (Exception $e){
            save_error("\r\nOTHR : " . $e->getMessage());
            return false;
        }
    }
}

?>

3) post ma'lumotlarini userApi.php bilan ishlash uchun PHP faylida yaratilsin

<?php
$_errAry = array("status"=>400, "success"=>"false", "message"=>"Can't Service your request ","data"=>array());//error reprting json
$_sucAry = array("status"=>200, "success"=>"true", "message"=>"","data"=>array());//sccess rrespose json


nclude_once 'database.php';

// get database connection
$database = new Database();
$db = $database->getConnection();



// instantiate Common Objects
include_once 'objects/common.class.php';

$_tbl=""; $_cols="";  $_ord=""; 
$_whr="  ";


if(isset($_POST["val1"],$_POST["val2"],$_POST["val3"])){

$val1=$_POST["val1"];
$val2=$_POST["val2"];
$val3=$_POST["val3"];

$tableName="yourTableName";
$ColNameString="your coma separated coloumns name";
$ValueString="'".$val1."','".$val2."','".$val3."';
$_comm = new Common($db);
            $return=$_comm-> syncLocalAppData($tableName,$ColNameString,$ValueString);
if($return){
        $_op = $_sucAry;
        $_op["data"]=array("status"=>true),
        echo json_encode($_op);
        exit(0);
}else{
        $_op = $_sucAry;
        $_op["success"]= "false";
        $_op["message"]="cant process your request,
        echo json_encode($_op);exit(0);
}
}
1
qo'shib qo'ydi
foydalanuvchi identifikatori kodi kirish jadvaliga kiritilgan User
qo'shib qo'ydi muallif Moeez, manba
O'qituvchi uchun rahmat, u menga foydali bo'lib tuyuladi va men buni albatta sinab ko'raman. Agar PHP skriptini yuborishingiz mumkin bo'lsa, men uchun juda foydali bo'lar edi, chunki men skript yozishni qanday amalga oshirishim va u bilan nima qilish kerak deb shubhalanaman :(
qo'shib qo'ydi muallif Moeez, manba
Buni albatta ishonch hosil qiling
qo'shib qo'ydi muallif Moeez, manba
define ("HOST", "localhost"); belgilang ('JB', 'dastur'); define ('USER', 'root'); belgilang ('PASS', ''); $ con = mysqli_connect (HOST, USER, PASS, JB); agar (! $ con) {die ("Database Connection Error:". mysqli_connect_error ()); } else {// echo "Ulanish muvaffaqiyatli"; } Bu mening JB fayli
qo'shib qo'ydi muallif Moeez, manba
Sinf yaratish kerakmi? Kodni olish uchun require_once ('config.php') ishlatgan; $ Sql ​​= "SELECT * FROM foydalanuvchilar"; $ r = mysqli_query ($ con, $ sql); $ Natijada = array (); ($ string = mysqli_fetch_array ($ r)) {array_push ($ natija, array ('Id' => $ satr ['Id'], 'Nomi' => $ qator ['Nomi'])); } echo json_encode (array ('foydalanuvchilar' => $ natija));
qo'shib qo'ydi muallif Moeez, manba
qo'shib qo'ydi muallif Moeez, manba
iltimos, yangilangan javobni ko'rib chiqing. Va sizning talablaringiz bo'yicha narsalarni o'zgartiring.
qo'shib qo'ydi muallif Pranav MS, manba
Buni ham foydalanishingiz mumkin. MySQL aloqasi uchun PDO foydalanayapman. PDO istasangiz, men sizning yo'lingizni ta'qib qilishingiz mumkin bo'lgan Myshqli mening qadamlarimga amal qilishim mumkin.
qo'shib qo'ydi muallif Pranav MS, manba
OK bir necha daqiqa kutib turing, xuddi shunday yangilang. Endi siz buni Androidda qo'llashga harakat qilyapsiz.
qo'shib qo'ydi muallif Pranav MS, manba

Men foydalanuvchi sinfini yaratganimdek bir faoliyat sinfini yaratishim kerakmi?

Ha.

Eng oson echim, sizning faoliyat ob'ektingizni JSON obyektiga aylantirmoqda. Uni HTTP lib bilan so'rov orqali yuboring (OKHttp foydalanishni tavsiya qilaman http://square.github.io/okhttp/). Va nihoyat, spamni boshqaradigan php-script yozing, ob'ektni JSON-dan oling va ma'lumotlar bazasiga yozib qo'ying.

0
qo'shib qo'ydi

Men foydalanuvchi sinfini yaratganimdek bir faoliyat sinfini yaratishim kerakmi?

Ha.

Eng oson echim, sizning faoliyat ob'ektingizni JSON obyektiga aylantirmoqda. Uni HTTP lib bilan so'rov orqali yuboring (OKHttp foydalanishni tavsiya qilaman http://square.github.io/okhttp/). Va nihoyat, spamni boshqaradigan php-script yozing, ob'ektni JSON-dan oling va ma'lumotlar bazasiga yozib qo'ying.

0
qo'shib qo'ydi
Javascript UZB
Javascript UZB
99 ishtirokchilar

@js_uzb @vuejs_uz @react_uz @nodejs_uz @angular_uz @ngTashkent @yiiframework_uz @laravel_uz @linux_uzbek @python_uz @swift_uzb —————— @uzdevgroup @UzGeeksGroup ——— @UzDev_Jobs @jobs_uzb

PhP |BotsUz
PhP |BotsUz
93 ishtirokchilar

Phpni o'rganishni Hohlasangiz https://t.me/joinchat/AAAAAE-KRc5dd5tPMmGmWA A'zo bo'lin