安卓值上传数据库使用JSON [英] android values upload database with json

查看:205
本文介绍了安卓值上传数据库使用JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建MAGNETIC_FIELD传感器。这code给x和yž事件值,ArithmeticAvg和SQRTx ^ 2 + Y ^ 2 + Z ^ 2
我要上传数据库中的这些值。如何上传数据库,这些值与JSON或别的东西。在这里我的code

 公共类MainActivity扩展ActionBarActivity {@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.activity_main);
    SensingTextView电视=新SensingTextView(本);
    的SensorManager SM =(的SensorManager)getSystemService(Context.SENSOR_SERVICE);
    sm.registerListener(电视,
            sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD)
            SensorManager.SENSOR_DELAY_UI);
    的setContentView(电视);}
公共类SensingTextView扩展TextView的实现SensorEventListener {
    公共SensingTextView(上下文的背景下){
        超级(上下文);
    }    @覆盖
    公共无效onSensorChanged(SensorEvent事件){        字符串=中newstr的String.format(X:%F \\ NY:%F \\新西兰:%F \\ n \\ nSQRTx ^ 2 + Y ^ 2 + Z ^ 2%F \\ n \\ nArithmeticAvg:%F
                新对象[] {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);    }


解决方案

如果你想你的价值观上传到 MYSQL 此数据库的步骤:

1 - 有需要的领域在服务器上创建表

2 - 编写PHP或任何服务器端code从客户端获得的值

3 - 实现了code的android

JOSNParser.java

 进口java.io.BufferedReader中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口java.io.UnsupportedEncodingException;
进口的java.util.List;进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.NameValuePair;
进口org.apache.http.client.ClientProtocolException;
进口org.apache.http.client.entity.UrlEn codedFormEntity;
进口org.apache.http.client.methods.HttpGet;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.client.utils.URLEn codedUtils;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.json.JSONException;
进口org.json.JSONObject;进口android.util.Log;公共类JSONParser {    静态InputStream为= NULL;
    静态的JSONObject jObj = NULL;
    静态JSON字符串=;    //构造
    公共JSONParser(){    }    //函数得到JSON的网址
    //通过HTTP POST或GET mehtod
    公众的JSONObject makeHtt prequest(URL字符串,字符串的方法,
            清单<&的NameValuePair GT; PARAMS){        //使HTTP请求
        尝试{            //检查请求的方法
            如果(方法==POST){
                //请求方法是POST
                // defaultHttpClient
                DefaultHttpClient的HttpClient =新DefaultHttpClient();
                HttpPost httpPost =新HttpPost(URL);
                httpPost.setEntity(新UrlEn codedFormEntity(PARAMS));                HTT presponse HTT presponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = HTT presponse.getEntity();
                是= httpEntity.getContent();            }否则如果(方法==GET){
                //请求方法是GET
                DefaultHttpClient的HttpClient =新DefaultHttpClient();
                字符串中的paramString = URLEn codedUtils.format(参数,可以UTF-8);
                网址+ =? +中的paramString;
                HTTPGET HTTPGET =新HTTPGET(URL);                HTT presponse HTT presponse = httpClient.execute(HTTPGET);
                HttpEntity httpEntity = HTT presponse.getEntity();
                是= httpEntity.getContent();
            }        }赶上(UnsupportedEncodingException五){
            e.printStackTrace();
        }赶上(ClientProtocolException E){
            e.printStackTrace();
        }赶上(IOException异常五){
            e.printStackTrace();
        }        尝试{
            读者的BufferedReader =新的BufferedReader(新的InputStreamReader(
                    是,ISO-8859-1),8);
            StringBuilder的SB =新的StringBuilder();
            串线= NULL;
            而((行= reader.readLine())!= NULL){
                sb.append(行+\\ n);
            }
            is.close();
            JSON = sb.toString();
        }赶上(例外五){
            Log.e(缓冲区错误,错误转换结果+ e.toString());
        }        //尝试分析字符串到一个JSON对象
        尝试{
            jObj =新的JSONObject(JSON);
        }赶上(JSONException E){
            Log.e(JSON解析器,错误分析数据+ e.toString());
        }        //返回JSON字符串
        返回jObj;    }
}

在这样的活动上载code - 假设你有一个按钮发送数据

 公共类MainActivity延伸活动{
    ProgressDialog pDialog;    JSONParser jsonParser =新JSONParser();
    按钮送出数据;
    JSON的JSONObject;私人静态字符串url_create_user =HTTP://localhost/android_connect/getData.php私有静态最后弦乐TAG_SUCCESS =成功;
@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);    送出数据=(按钮)findViewById(R.id.send);    sendData.setOnClickListener(新View.OnClickListener(){        @覆盖
        公共无效的onClick(视图v){
                新CreateNewUser()执行();        }
    });
类CreateNewUser扩展的AsyncTask<字符串,字符串,字符串> {
    @覆盖
    在preExecute保护无效(){
        super.on preExecute();
        pDialog =新ProgressDialog(MainActivity.this);
        pDialog.setMessage(上传数据...);
        pDialog.setIndeterminate(假);
        pDialog.setCancelable(真);
        pDialog.show();
    }
    @覆盖
    保护字符串doInBackground(字符串...为arg0){        //大厦参数
        清单<&的NameValuePair GT; PARAMS =新的ArrayList<&的NameValuePair GT;();        //到达这里您valuse像字符串值=数据        params.add(新BasicNameValuePair(价值,价值));        JSON = jsonParser.makeHtt prequest(url_create_user,POST,则params);        尝试{
            INT成功= json.getInt(TAG_SUCCESS);            如果(成功== 1){
                   //写入日志文件的东西            }其他{            }
        }赶上(JSONException E){
            e.printStackTrace();
        }
        返回null;
    }
    保护无效onPostExecute(字符串FILE_URL){
        //辞退做一次对话
        pDialog.dismiss();
        如果(JSON!= NULL){
            Toast.makeText(getApplicationContext()的数据已经发送成功!,Toast.LENGTH_LONG).show();
        }
        其他
            Toast.makeText(getApplicationContext()!发送失败的数据,Toast.LENGTH_LONG).show();
    }
}

}

这行:

 私有静态字符串url_create_user =HTTP://localhost/android_connect/getData.php

表示:yourserver / FOLDERNAME(其中文件)/ PHP文件来获取数据

访问getdata.php

 < PHP
//连接到服务器$ CON = mysql_connect(DB_NAME,USER_NAME,密码)或死亡(mysql_error());        // Selecing数据库
$ DB = mysql_select_db(DB_NAME)或死亡(mysql_error());
//检查必填字段
如果(使用isset($ _ POST ['值'])){    $ _values​​ = $ _ POST ['值'];
    // MySQL的插入新行
    $结果= mysql_query(INSERT INTO TABLE_NAME(数据)VALUES('$ _值')); db.close();?>

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

    }

解决方案

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

?>

这篇关于安卓值上传数据库使用JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆