Android Null指针向数据库发送经度和纬度时出现异常

时间:2015-12-28 04:27:32

标签: php android android-layout android-intent android-activity

我正在制作简单的Android应用程序来存储纬度和经度mysql数据库。我创建了一个本地database.databse有3个字段id自动递增,两个字段lat2(float)和lng2(float)来存储来自机器人。

这是我的logcat错误

  12-28 16:45:04.470: D/gralloc_goldfish(1400): Emulator without GPU emulation detected.
12-28 16:45:11.190: D/AndroidRuntime(1400): Shutting down VM
12-28 16:45:11.190: W/dalvikvm(1400): threadid=1: thread exiting with uncaught exception (group=0xb3a71ba8)
12-28 16:45:11.320: E/AndroidRuntime(1400): FATAL EXCEPTION: main
12-28 16:45:11.320: E/AndroidRuntime(1400): Process: com.example.test, PID: 1400
12-28 16:45:11.320: E/AndroidRuntime(1400): java.lang.NullPointerException
12-28 16:45:11.320: E/AndroidRuntime(1400):     at com.example.test.MainActivity$1.onClick(MainActivity.java:51)
12-28 16:45:11.320: E/AndroidRuntime(1400):     at android.view.View.performClick(View.java:4438)
12-28 16:45:11.320: E/AndroidRuntime(1400):     at android.view.View$PerformClick.run(View.java:18422)
12-28 16:45:11.320: E/AndroidRuntime(1400):     at android.os.Handler.handleCallback(Handler.java:733)
12-28 16:45:11.320: E/AndroidRuntime(1400):     at android.os.Handler.dispatchMessage(Handler.java:95)
12-28 16:45:11.320: E/AndroidRuntime(1400):     at android.os.Looper.loop(Looper.java:136)
12-28 16:45:11.320: E/AndroidRuntime(1400):     at android.app.ActivityThread.main(ActivityThread.java:5001)
12-28 16:45:11.320: E/AndroidRuntime(1400):     at java.lang.reflect.Method.invokeNative(Native Method)
12-28 16:45:11.320: E/AndroidRuntime(1400):     at java.lang.reflect.Method.invoke(Method.java:515)
12-28 16:45:11.320: E/AndroidRuntime(1400):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
12-28 16:45:11.320: E/AndroidRuntime(1400):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
12-28 16:45:11.320: E/AndroidRuntime(1400):     at dalvik.system.NativeStart.main(Native Method)
12-28 16:45:17.380: I/Process(1400): Sending signal. PID: 1400 SIG: 9

这是我的主要活动

    package com.example.test;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {


    private float lat;
    private float lng;
    private String lat2;
    private String lng2;
    MainActivity gps;
    private String line;
    Button btninsert;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);


          btninsert = (Button) findViewById(R.id.button1);
          btninsert.setOnClickListener(new View.OnClickListener() {

          @Override
                public void onClick(View v) {

                    // TODO Auto-generated method stub
                    if(gps.canGetLocation()){   
                     lat = (float) gps.getLatitude();
                     lng = (float) gps.getLongitude();
                     lat2= String.valueOf(lat);
                     lng2= String.valueOf(lng);




        Toast.makeText(getApplicationContext(), "Success insert - \nLat: " + lat2 + "\nLong: " + lng2, Toast.LENGTH_LONG).show();   
                }else{
                    // can't get location
                    // GPS or Network is not enabled
                    // Ask user to enable GPS/network in settings
                    gps.showSettingsAlert();
                }
                }});
        }


        protected void showSettingsAlert() {
        // TODO Auto-generated method stub

    }


        protected float getLatitude() {
        // TODO Auto-generated method stub
        return 0;
    }
        protected float getLongitude() {
            // TODO Auto-generated method stub
            return 0;
        }


        protected boolean canGetLocation() {
        // TODO Auto-generated method stub
        return false;
    }


        public void insert(String result, String lat2,String lng2) {
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

            nameValuePairs.add(new BasicNameValuePair("lat2", lat2));
            nameValuePairs.add(new BasicNameValuePair("lng2", lng2));

            InputStream is = null;
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://192.168.1.31/insert_android.php");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
                Log.e("pass 1", "connection success ");
            } catch (Exception e) {
                Log.e("Fail 1", e.toString());
                Toast.makeText(getApplicationContext(), "Invalid IP Address",
                        Toast.LENGTH_LONG).show();
            }

            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
                Log.e("pass 2", "connection success ");
            } catch (Exception e) {
                Log.e("Fail 2", e.toString());
            }

            try {
                JSONObject json_data = new JSONObject(result);
                lng2 = (json_data.getString("code"));

                if (lng2 == null) {
                    Toast.makeText(getBaseContext(), "Inserted Successfully",
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getBaseContext(), "Sorry, Try Again",
                            Toast.LENGTH_LONG).show();
                }
            } catch (Exception e) {
                Log.e("Fail 3", e.toString());
            }
        }

}

这是我的php脚本

<?php

$hostname = 'localhost';
$username = 'root';
$password = '';

$conn =  mysql_connect($hostname,$username,$password) or die('Blah');

if ($conn) {

mysql_select_db("test", $conn);

// extract your data
if (isset($_POST['lat']) && isset($_POST['lng']) ){


$lat2 = $_POST['lat'];
$lng2 = $_POST['lng'];



        $query2 = "INSERT INTO markers_awal VALUES('','$lat2','$lng2')";

    if (mysql_query($query2, $conn))
    echo "data inserted";
    else {
        echo "Oh dear " . mysql_error();


    }
    }
}
    ?>

4 个答案:

答案 0 :(得分:2)

老兄,你有一个名为gps的对象,其MainActivity实际上与你所处的活动相同。

所以有两个问题,

  • 您根本不需要gps个对象。只需拨打canGetLocation,不要gps.canGetLocation
  • 其次,如果您真的想要保留那个奇怪的gps对象,那么您必须为其分配一个值,在您的情况下为gps = this;

这肯定会解决您的NullPointerException

我希望这会有所帮助。

答案 1 :(得分:1)

你正在使用gps类,所以在哪里初始化gps? 如果你没有初始化gps然后初始化它。我还观察到在setContentView方法之前代码中没有超级构造函数。把它放到你的代码中。

super.onCreate(savedInstanceState);

答案 2 :(得分:0)

将您的浮点值转换为String使用方法

String lat2 = String.valueOf(lat);
String lng2 = String.valueOf(lng);

请确保这些值具有一定价值。使用日志或Toast消息进行检查。

答案 3 :(得分:0)

您在第51行收到错误。这实际上是您的onclick方法。每次返回假值时,你能检查 canGetLocation() 方法吗?根据你的logcat,你也得到一个空指针异常。将所有数据放在onclick方法中的try catch块中。