【问题标题】:How to send data from android to mysql server?如何将数据从android发送到mysql服务器?
【发布时间】:2017-07-12 04:03:53
【问题描述】:

我是 android 开发的新手。我正在使用安卓工作室。我正在制作一个应用程序,其中有一个名称下拉列表。选择任何名称时,该名称对应的ID 会显示在应用程序中。然后有一个按钮,它将搜索用户当前的 gps 坐标并在应用程序上显示它们。我搜索了类似的问题并找到了一些链接(我将在最后发布它们)但我无法理解它们。以下是应用截图

我在mysql中有两个表; usersactivity,如下图

用户

活动

UserId 是活动表中的外键,即将来自users 表的Id 插入其中。

我创建了以下脚本以 JSON 格式返回数据:

<?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);
?>

在我的应用代码中,我创建了一个users

用户类

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 类

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

    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {

        @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<Void, Void, Void>
{

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

        // Create an array to populate the spinner
        userList = new ArrayList<String>();
        // 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<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<String>(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 //////////////////////////////////////////

当我按下保存按钮时,以下字段将被插入到Activity 表中

  1. Id(自动递增)
  2. UserId(基于所选名称的用户表中的用户 ID)
  3. Latitude(当前用户)
  4. Longitude(当前用户)
  5. DateTime(用户的日期时间)

我应该像创建User 类一样创建一个“活动”类吗?

对此我有一些想法

  1. 我会先将数据保存到xmltxt 文件中,然后再将其保存到数据库中。
  2. 我应该将数据转换成json格式,然后保存到数据库中
  3. 在我的php 脚本中使用查询直接将其保存到数据库中

这 3 个中哪一个最容易实现?如果有人可以为我提供教程,那将非常有帮助,尽管我看到了很多(12),如上所述,我无法理解它们:(。

我坚持下去,不知道我必须做什么。任何帮助将不胜感激。

【问题讨论】:

  • 请检查我的答案。如果需要任何帮助,请随时询问
  • @faisal 使用改造,现在主要使用。

标签: php android mysql json http-post


【解决方案1】:

我应该创建一个与我创建用户类相同的活动类吗?

是的。

最简单的解决方案是将您的活动对象转换为 JSON 对象。 使用您的 HTTP 库通过 post 请求发送它(我建议使用 OKHttp http://square.github.io/okhttp/)。最后编写一个 php 脚本来处理请求,从 JSON 中获取对象并将其保存到您的数据库中。

【讨论】:

    【解决方案2】:

    您需要编写 Api,您可以在其中传递来自 android 的数据,并在 Api 中获取该数据并使用插入查询存储在数据库中。在 android 端,您必须执行以下代码:

    我的类 PutUtility 用于 getData()、PostData、DeleteData()。你只需要更改包名

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

    并像这样使用这个类。此类自动进行互联网连接并给您来自服务器的响应:

        private class ServiceLogin extends AsyncTask<String, Void, String> {
    
                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"
    
                }
            }
    

    现在您可以在单击按钮时调用此服务并在服务中插入数据,如下所示:

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

    希望对你有帮助

    编辑:

    这是用于插入数据的简单 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; 
    
    }
    ?>
    

    【讨论】:

    • @faisal1208 我的 PutUtility 课程可以在您将来处理数据库时为您提供帮助。希望对你有帮助
    • 感谢您的教程,它似乎很有帮助,我一定会尝试的。另外,如果您可以发布php 脚本,这对我很有帮助,因为我对如何编写脚本以及在其中做什么感到困惑,因为我必须从user 表中获取userID,然后输入它进入acitivity 表:(
    • 在聊天回复中向您发送消息@faisal1208
    • 发给你回复
    • put datapost data有什么区别
    【解决方案3】:

    您需要在服务器端有一个 api,它将接受 json 请求作为 POST,并将数据保存在您的 Mysql 数据库中。您可以使用任何 android 库(如 Retrofit 和 Volley)从 android 端发出请求。

    使用改造

    假设你的 pojo 是:

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

    我们的端点如下所示:

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

    Retrofit 会自己处理 JSON。你应该有类似的东西:

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

    【讨论】:

      【解决方案4】:

      这里您使用的是传统方法发送数据 要做到这一点,请按照以下步骤操作。

      1) 在你的 build.gradle 文件中添加这个

      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解析器

      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<NameValuePair> 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) 在名为 UserFunctions 的类上创建

          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<NameValuePair> params = new ArrayList<NameValuePair>();
                      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) 在你的主要活动类中

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

      //在onCreate方法中

      uf = new UserFunctions(Mainactivity.this);
      

      //获取位置lat和long后调用AsyncTask向服务器发送数据。

      //这里这样调用asynctask,在类的最后写aasyncctask功能

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

      5) LoadWebPageTask asnc 任务

      私有类 LoadWebPageTask 扩展 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
              }
          }
      

      这会将数据作为 post 方法发送到服务器,您可以使用 $_POST[]; 将其作为 post 方法处理

      请像这样尝试。希望这会对你有所帮助。

      对于服务器端

      1) 在数据库类上创建

      <?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) 创建另一个类以将所有 DB 功能在这里命名为 Common

      <?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) 在 php 文件上创建处理 post 数据 userApi.php

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

      【讨论】:

      • 感谢您的教程,它似乎很有帮助,我一定会尝试的。另外,如果您可以发布php 脚本,这对我很有帮助,因为我对如何编写脚本以及在其中做什么感到困惑:(
      • 好的,等几分钟,我会更新相同的。现在你尝试在 android 上应用它。
      • 确定这样做
      • user id 是来自User 表的ID,它将被插入到activity 表中
      • 请看我更新的答案。并根据您的要求更改内容。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-13
      • 2021-03-20
      • 2012-07-19
      • 2015-08-21
      相关资源
      最近更新 更多