-1

我必须创建一个在移动设备上显示加速度计值的应用程序,并将其保存到学校项目的远程 SQL 数据库中,所以我尝试制作它。我的逻辑是:获取传感器值,在文本视图中显示它们并调用 PHP 文件将它们保存在数据库中。尽管语法是正确的,但由于某种原因,应用程序被迫关闭而不显示或执行任何操作。我真的很感激一些帮助。

我是新手,我不明白日志猫在前 3 个错误中的含义:

日志 Cat 06-04 01:35:20.417: W/dalvikvm(11760): threadid=1: 线程退出但未捕获异常 (group=0x41dba2a0) 06-04 01:35:20.447: E/AndroidRuntime(11760): FATAL EXCEPTION : 主要 06-04 01:35:20.447: E/AndroidRuntime(11760): android.os.NetworkOnMainThreadException

我的 MainActivity.java

    package com.example.try1;

    import java.util.ArrayList;
    import java.util.List;
    import org.apache.http.NameValuePair;
    import org.apache.http.message.BasicNameValuePair;
    import org.json.JSONObject;
    import android.app.Activity;
    import android.content.Intent;
    import android.hardware.Sensor;
    import android.hardware.SensorEvent;
    import android.hardware.SensorEventListener;
    import android.hardware.SensorManager;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.TextView;

    public class MainActivity extends Activity implements SensorEventListener {

private static String url_create_product =                 "http://192.168.2.11/android_connect/create_accel_data.php";
 JSONParser jsonParser = new JSONParser();

public void selfDestruct(View view) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

}


    private SensorManager sensorManager;

    TextView xCoor; // declare X axis object
    TextView yCoor; // declare Y axis object
    TextView zCoor; // declare Z axis object

    @Override
    public void onCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

xCoor=(TextView)findViewById(R.id.xcoor); // create X axis object
yCoor=(TextView)findViewById(R.id.ycoor); // create Y axis object
zCoor=(TextView)findViewById(R.id.zcoor); // create Z axis object

sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
// add listener. The listener will be HelloAndroid (this) class
sensorManager.registerListener(this,
        sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
        SensorManager.SENSOR_DELAY_NORMAL);

/*  More sensor speeds (taken from api docs)
    SENSOR_DELAY_FASTEST get sensor data as fast as possible
    SENSOR_DELAY_GAME   rate suitable for games
    SENSOR_DELAY_NORMAL rate (default) suitable for screen       orientation changes
*/
    }

    public void onAccuracyChanged(Sensor sensor,int accuracy){

    }

    public void onSensorChanged(SensorEvent event){

// check sensor type
if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){

    // assign directions
    float x=event.values[0];
    float y=event.values[1];
    float z=event.values[2];

    xCoor.setText("X: "+x);
    yCoor.setText("Y: "+y);
    zCoor.setText("Z: "+z);

 // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("x", Float.toString(x)));
    params.add(new BasicNameValuePair("y", Float.toString(y)));
    params.add(new BasicNameValuePair("z", Float.toString(z)));

    // getting JSON Object
    // Note that create product url accepts POST method
    JSONObject json = jsonParser.makeHttpRequest(url_create_product,
            "POST", params);

    Log.d("Create Response", json.toString());
        }
    }
    }

我的 JSONParser.java 类

    package com.example.try1;

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

}
}

我的布局 activity_main.xml :

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:gravity="center"
        android:paddingTop="20dip"
        android:text="pinakas_dedomenwn"
        android:textSize="16sp"
        android:textStyle="bold" />

<TableLayout
    android:id="@+id/tableLayout1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="56dp"
    android:paddingTop="10dip"
    android:stretchColumns="*" >

    <TableRow>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14dp"
            android:gravity="center"
            android:text="X-Axis"
            android:textSize="14sp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Y-Axis"
            android:textSize="14sp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Z-Axis"
            android:textSize="14sp" />
    </TableRow>



    <TableRow>


<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/xcoor"
     android:gravity="center"/>
     <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/ycoor"
    android:gravity="center"/>
    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/zcoor"
    android:gravity="center"/>
    </TableRow>

</TableLayout>

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="44dp"
    android:onClick="selfDestruct"
    android:text="@string/exit" />

    </RelativeLayout>

我的 db_connect_accel.php

  <?php

  /**
   * A class file to connect to database
   */
  class DB_CONNECT {

// constructor
function __construct() {
    // connecting to database
    $this->connect();
}

// destructor
function __destruct() {
    // closing db connection
    $this->close();
}

/**
 * Function to connect with database
 */
function connect() {
    // import database connection variables
    require_once __DIR__ . '/db_config_accel.php';

    // Connecting to mysql database
    $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());

    // Selecing database
    $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());

    // returing connection cursor
    return $con;
}

/**
 * Function to close db connection
 */
function close() {
    // closing db connection
    mysql_close();
}

  }

  ?>

我的 db_config_accel.php

     <?php

/*
 * All database connection variables
 */

define('DB_USER', "george1"); // db user
define('DB_PASSWORD', "george1"); // db password (mention your db password here)
define('DB_DATABASE', "db_accelerometer"); // database name
define('DB_SERVER', "localhost"); // db server
?>

最后是我的 create_accel_data.php,它应该调用其他两个 .php,以便连接到数据库并保存值。

   <?php

/*
 * Following code will create a new product row
 * All product details are read from HTTP Post Request
 */

// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['x']) && isset($_POST['y']) && isset($_POST['z'])) {

$x = $_POST['x'];
$y = $_POST['y'];
$z = $_POST['z'];

// include db connect class
require_once __DIR__ . '/db_connect_accel.php';

// connecting to db
$db = new DB_CONNECT();

// mysql inserting a new row
$result = mysql_query("INSERT INTO accel_data(x, y, z) VALUES('$x', '$y', '$z')");

// check if row inserted or not
if ($result) {
    // successfully inserted into database
    $response["success"] = 1;

} else {
    // failed to insert row
    $response["success"] = 0;

}
} else {
// required field is missing
$response["success"] = 0;

}
?>

谁能看到出了什么问题?(我怀疑问题出在 MainActivity 中)

4

1 回答 1

2

诀窍是阅读异常。NetworkOnMainThreadException 意味着您无法在主线程中打开连接,为此您应该使用新线程,在 Android 的情况下,指示使用 AsyncTask 进行简单请求。

于 2013-06-04T00:39:21.523 回答