问题
I created MAGNETIC_FIELD sensor. this code giving x y z event values, ArithmeticAvg and SQRTx^2+y^2+z^2 i have to upload database these values. how can i upload database these values with json or something else. here my code
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
SensingTextView tv = new SensingTextView(this);
SensorManager sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sm.registerListener(tv,
sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
SensorManager.SENSOR_DELAY_UI);
setContentView(tv);
}
public class SensingTextView extends TextView implements SensorEventListener {
public SensingTextView(Context context) {
super(context);
}
@Override
public void onSensorChanged(SensorEvent event) {
String newstr = String.format("x: %f\ny:%f\nz:%f\n\nSQRTx^2+y^2+z^2: %f\n\nArithmeticAvg: %f",
new Object[] { event.values[0],event.values[1],event.values[2],Math.sqrt(((event.values[0] * event.values[0])
+ (event.values[1] * event.values[1]) + (event.values[2] * event.values [2]))),
((event.values[0] + event.values[1] + event.values[2])/3)
} );
setText(newstr);
}
回答1:
If you want to upload your values to mySql database here is the steps :
1 - create table on the server with the fields needed.
2 - write php or any server side code to get the values from client
3 - implement the code in android
JOSNParser.java
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
in upload code in activity like this - assumed you have a button to send data.
public class MainActivity extends Activity {
ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
Button sendData;
JSONObject json;
private static String url_create_user = "http://localhost/android_connect/getData.php";
private static final String TAG_SUCCESS = "success";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendData = (Button)findViewById(R.id.send);
sendData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new CreateNewUser().execute();
}
});
class CreateNewUser extends AsyncTask<String, String,String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Uploading data...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... arg0) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
//get here your valuse like String values = "your data"
params.add(new BasicNameValuePair("values", values));
json = jsonParser.makeHttpRequest(url_create_user, "POST", params);
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
//write something in log file
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
if(json != null){
Toast.makeText(getApplicationContext(), "The data has been sent successfully!", Toast.LENGTH_LONG).show();
}
else
Toast.makeText(getApplicationContext(), "Failed to send data!", Toast.LENGTH_LONG).show();
}
}
}
This line :
private static String url_create_user = "http://localhost/android_connect/getData.php";
means : yourserver/foldername(in which the file)/php file to get the data
getData.php
<?php
//connect to server
$con = mysql_connect(db_name, user_name, password) or die(mysql_error());
// Selecing database
$db = mysql_select_db(db_name) or die(mysql_error());
// check for required fields
if (isset($_POST['values']) ) {
$_values = $_POST['values'];
// mysql inserting a new row
$result = mysql_query("INSERT INTO table_name(data) VALUES('$_values')");
db.close();
?>
来源:https://stackoverflow.com/questions/27655786/android-values-upload-database-with-json