有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java应用程序说:不幸停止了。(关于从谷歌添加JsonObject)

在从加速计获取数据后,我试图将数据推送到服务器

因为我使用的是谷歌的JsonObject

这个物体似乎有问题。一旦我从中实例化一个对象,我的应用程序就会抛出一个错误:不幸的是appname已经停止

我的主要活动代码:

package com.example.accelerometerdemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;

import 安卓.app.Activity;
import 安卓.content.Context;
import 安卓.hardware.Sensor;
import 安卓.hardware.SensorEvent;
import 安卓.hardware.SensorEventListener;
import 安卓.hardware.SensorManager;
import 安卓.os.Bundle;
import 安卓.util.Log;
import 安卓.view.Menu;
import 安卓.widget.RelativeLayout;
import 安卓.widget.TextView;

import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;

public class MainActivity extends Activity implements SensorEventListener {

private static final String MSG_TAG_1 = "MainActivity";
private static final String MSG_TAG_2 = "place_holder";

private SensorManager mSensorManager;
private Sensor mAccelerometer;
TextView title,tv,tv1,tv2, test;
RelativeLayout layout;
int i = 0;

//For preparing file
String[] paramName = { "device_id", "timestamp", "sensor_type",
"sensor_value" };
String URLStr = "http://209.129.244.7/sensors";
java.util.Date date = new java.util.Date();

@Override
public final void onCreate(Bundle savedInstanceState)
 {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main); //refer layout file code below
   //get the sensor service
   mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
   //get the accelerometer sensor
   mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

   //If sensor not available
   if (mAccelerometer == null){
        System.out.println("no temperature sensor");
       }


   //get layout
   layout = (RelativeLayout)findViewById(R.id.relative);
    //get textviews
   title=(TextView)findViewById(R.id.name);
   tv=(TextView)findViewById(R.id.xval);
   tv1=(TextView)findViewById(R.id.yval);
   tv2=(TextView)findViewById(R.id.zval);
   test = (TextView)findViewById(R.id.testval);


     }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
  public final void onAccuracyChanged(Sensor sensor, int accuracy)
   {
     // Do something here if sensor accuracy changes.
   }

@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        i++;
        if (i < 5) {
            getAccelerometer(event);
        } else {
            onPause();
        }
    }

}
 public final void getAccelerometer(SensorEvent event)
   {
    // Many sensors return 3 values, one for each axis.
   float x = event.values[0];
   float y = event.values[1];
   float z = event.values[2];
   String t = "This is a test value";
   //display values using TextView
   title.setText(R.string.app_name);
   tv.setText("X axis" +"\t\t"+x);
   tv1.setText("Y axis" + "\t\t" +y);
   tv2.setText("Z axis" +"\t\t" +z);
   test.setText("Testing" +"\t\t" +event.values[2]);



   JsonObject jo = new JsonObject();



    try {
        //formatting the file
        jsonObject_x.put("sensor_value", 78);   

        jo.addProperty("device_id", "nexus_test_dev"); //Long type
        jo.addProperty("timestamp", date.getTime()); //Long type
        jo.addProperty("sensor_type", "Accelerometer_x");   //String type
        jo.addProperty("sensor_value", 78);                 //Double type

        //String[] paramName = { "device_id", "timestamp", "sensor_type", "sensor_value" };

        //{"device_id":"test", "timestamp": 1373566899100, "temp": 123}
    String[] paramVal = { "aeron_test_p", String.valueOf(date.getTime()),
                "temp", "121" };
        //Displaying readings in LOGCAT
        for(String s : paramVal){
            Log.d(MSG_TAG_1, s);
        }
        try {

            httpPostSensorReading(URLStr, jo.toString());

            Log.d(MSG_TAG_2, "Test");
        } catch (Exception e) {e.printStackTrace();
        }

    } catch (JsonIOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
       }






 public static String httpPostSensorReading(String urlStr, String jsonString) throws Exception {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "application/json");
        conn.setDoOutput(true);

        // Create the form content
        OutputStream out = conn.getOutputStream();
        Writer writer = new OutputStreamWriter(out, "UTF-8");

        writer.write(jsonString);

        writer.close();
        out.close();

        if (conn.getResponseCode() != 200) {
            throw new IOException(conn.getResponseMessage());
        }

        // Buffer the result into a string
        BufferedReader rd = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        rd.close();

        conn.disconnect();
        return sb.toString();
    }

@Override
protected void onResume()
{
super.onResume();
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause()
{
super.onPause();
mSensorManager.unregisterListener(this);
}

    }

当我加上这个的时候

 JsonObject jo = new JsonObject();

应用程序抛出错误“不幸的是appname hsa已停止”

JsonObject有一些问题。我使用了JSONObject,然后它工作得很好

谢谢


共 (1) 个答案