[英]How to send data from android to mysql server?
I am newbie to the android development. 我是android开发的新手。 I am using Android Studio. 我正在使用Android Studio。 I am making an app in which there is a dropdown list of names. 我正在制作一个应用程序,其中有一个名称下拉列表。 On selecting any name, the corresponding ID
of that name is shown at the app. 在选择任何名称时,该应用程序将显示该名称的相应ID
。 Then there is a button which will search for the user's current gps coordinates and show them on the app. 然后有一个按钮,它将搜索用户当前的GPS坐标并在应用程序上显示它们。 I searched for similar questions and found some links (I will post them at the end) but I couldn't understand them. 我搜索了类似的问题并找到了一些链接(我会在最后发布)但我无法理解它们。 Below is the screenshot of the app 以下是该应用的屏幕截图
I have two tables in mysql; 我在mysql中有两个表; users
and activity
, as shown below users
和activity
,如下所示
Users 用户
Activity 活动
The UserId
is the foreign key in activity table ie the Id
from users
table will be inserted into it. UserId
是活动表中的外键,即users
表中的Id
将插入其中。
I have created following script to return the data as JSON: 我创建了以下脚本以将数据作为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);
?>
In my app code I have created a users
class 在我的应用代码中,我创建了一个users
类
Users Class 用户类
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 CLASS JSON CLASS
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 //////////////////////////////////////////
When I press the save button the following fields would be inserted into Activity
table 当我按下保存按钮时,以下字段将插入到Activity
表中
Id
(Which is auto-increment) Id
(自动增量) UserId
(User ID from Users table based on the selected name) UserId
(来自Users表的用户ID,基于所选名称) Latitude
(Of current user) Latitude
(当前用户) Longitude
(Of current user) Longitude
(当前用户) DateTime
(Date time of the user) DateTime
(用户的日期时间) Should I have to create an 'activity' class like I have created the User
class? 我是否应该像创建User
类一样创建一个“活动”类?
For this I have something in mind 为此,我有一些想法
xml
or txt
file first then it will be saved into the DB. 我会先将数据保存到xml
或txt
文件中,然后将其保存到数据库中。 json
format and then save it into DB 我应该将数据转换为json
格式,然后将其保存到DB中 php
script 使用我的php
脚本中的查询直接将其保存到数据库中 Which of these 3 is easiest to implement? 这3个中哪一个最容易实现? 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 :( . 这将是非常有益的,如果有人能提供给我的教程,虽然我看到很多人(的1 , 2 ),并如上所述我不明白他们:(。
I am stuck to it and don't know what I have to do. 我坚持不懈,不知道自己要做什么。 Any help would be highly appreciated. 任何帮助将受到高度赞赏。
You need to write Api where you can pass the data from android and and fetch that data in Api and store in database using insert query. 您需要编写Api,您可以从android传递数据,并使用插入查询在Api中获取数据并存储在数据库中。 On android side you have to do below code: 在android方面你必须做以下代码:
My class PutUtility for getData(), PostData, DeleteData(). 我的getData用于getData(),PostData,DeleteData()。 you just need to change package name 你只需要改变包名
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;
}
And use this class like this. 并像这样使用这个类。 this class Automatically do internet connection and give you response from server : 此类自动执行Internet连接并从服务器给您响应:
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"
}
}
Now you can call this service on button click and insert data in service like below: 现在,您可以通过按钮单击调用此服务并在服务中插入数据,如下所示:
new ServiceLogin().execute(pass four parameters here);
Hope this helps you 希望这对你有所帮助
EDIT: 编辑:
This is simple PHP Api for insert data 这是插入数据的简单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;
}
?>
You need an api in the server side which will accept json request as POST and it will save data in your Mysql database. 您需要服务器端的api,它将接受json请求作为POST,它将保存您的Mysql数据库中的数据。 You can take any android library like Retrofit and Volley to do request from android side. 你可以把任何像Retrofit和Volley这样的android库从android端做请求。
Using Retrofit 使用Retrofit
let's say your pojo is: 让我们说你的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
}
}
Our endpoint would look like the following: 我们的端点如下所示:
@POST("/users/new")
Call<User> createUser(@Body User user);
Retrofit will take care of JSON yourself. Retrofit将自己处理JSON。 You should have something like: 你应该有类似的东西:
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) {
}
Here you are using traditional methods to send data To do this way follow below steps. 在这里,您使用传统方法发送数据要执行此操作,请按照以下步骤操作。
1) in your build.gradle file add this 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) create json parser 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) create on class named as UserFunctions 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) in you main activityclass 4)在你的主要活动类中
// befor onCreate add
UserFunctions uf;
ProgressDialog pDialog;
JSONObject DATA_JSON;
// in onCreate method //在onCreate方法中
uf = new UserFunctions(Mainactivity.this);
// after getting the location lat and long call AsyncTask to send data to server. //获取位置lat后,长调用AsyncTask将数据发送到服务器。
// call asynctask like this here and write the aasyncctask functionality in the end of the class //在这里调用asynctask,并在类的末尾编写aasyncctask功能
new LoadWebPageTask().execute(); // calling async task
5) LoadWebPageTask asnc task 5)LoadWebPageTask asnc任务
private class LoadWebPageTask extends AsyncTask { 私有类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
}
}
This will send data to the server as post method you can process this as post method by using $_POST[];
这将以post方式将数据发送到服务器,您可以使用$_POST[];
将其作为post方法处理$_POST[];
Please try like this. 请尝试这样。 May this will help you. 愿这对你有所帮助。
For the server side 对于服务器端
1) create on Database class 1)在Database类上创建
<?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) create another class to write all DB functionalities here name as Common 2)创建另一个类来编写所有数据库功能,这里名称为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) create on php file to process the post data userApi.php 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);
}
}
Should i have to create a activity class same as i created user class? 我是否必须创建一个与创建用户类相同的活动类?
Yes. 是。
The easiest solution is convert your activity object into a JSON object. 最简单的解决方案是将您的活动对象转换为JSON对象。 Send it via a post request with your HTTP lib (I would recommend using OKHttp http://square.github.io/okhttp/ ). 通过HTTP lib发布请求发送(我建议使用OKHttp http://square.github.io/okhttp/ )。 And finally write a php script wich will handle the request, get the object from the JSON and save it into your database. 最后编写一个PHP脚本,它将处理请求,从JSON获取对象并将其保存到您的数据库中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.