我必须创建一个显示加速度计的应用程序 移动设备上的值并保存到学校的远程SQL数据库 项目,所以我试着去做。 我的逻辑是:获取传感器值,在Text View中显示它们并调用PHP文件将它们保存在数据库中。 尽管语法正确,但应用程序仍被强制执行 因某种原因关闭而不显示或做任何事情。 我真的很感激一些帮助。
我是新手,我无法理解日志猫在前3个错误中的含义:
Log Cat 06-04 01:35:20.417:W / dalvikvm(11760):threadid = 1:线程退出时未捕获异常(group = 0x41dba2a0) 06-04 01:35:20.447:E / AndroidRuntime(11760):致命异常:主要 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中)
答案 0 :(得分:2)
诀窍是阅读Exception。 NetworkOnMainThreadException意味着您无法在主线程中打开连接,为此您应该使用新的线程,在Android的情况下,指示使用AsyncTask进行简单请求。