如何在数据库的地图上绘制标记

时间:2018-02-18 17:54:23

标签: java android string maps

我是Android开发的新手,也是StackOveflow的新手。对不起,如果我问一个重复的问题。 我正在制作一个应用程序来从MySQL数据库中获取位置坐标并在地图上绘制标记。 我可以将值提取到textView。

String answer = "-32.430412,-58.321323,#-32.430412,-58.321323,#-32.430412,-58.321323,#";

当以这种方式输入坐标时它完全有效,但是当从数据库中提取坐标时它不起作用。

String answer = json_string;

我无法找到问题的解决方案。应用程序以空指针异常关闭 这是我的MapsActivity.java

public void getCoords(View view) {
    new CoordsBackgroundTask().execute();

}

class CoordsBackgroundTask extends AsyncTask<Void, Void, String> {

    String json_url_coords;

    @Override
    protected void onPreExecute() {
        json_url_coords = "http://192.168.225.139/location_marker/just.php";
    }

    @Override
    protected String doInBackground(Void... voids) {
        try {
            URL url = new URL(json_url_coords);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuilder = new StringBuilder();
            while ((JSON_STRING = bufferedReader.readLine()) != null) {

                stringBuilder.append(JSON_STRING + "\n");
            }

            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return stringBuilder.toString().trim();


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {
        TextView textview = (TextView) findViewById(R.id.textviewMaps);
        textview.setText(result);
        json_string = result;

        Toast.makeText(getApplicationContext(), json_string, Toast.LENGTH_SHORT).show();
    }
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    setUpMap();
}

public void Gpsconnection() {
    gps = new GPSCord(MapsActivity.this);
    if (gps.canGetLocation()) {

        longitude = gps.getLongitude();
        latitude = gps.getLatitude();
        // Toast.makeText(getApplicationContext(),"Longitude:"+Double.toString(longitude)+"\nLatitude:"+Double.toString(latitude),Toast.LENGTH_SHORT).show();
    } else {

        gps.showSettingsAlert();
    }

}


private void setUpMap() {
    String answer = "-32.430412,-58.321323,#-32.430412,-58.321323,#-32.430412,-58.321323,#";
    //String answer = json_string;
    String[] parts = answer.split("#");

    for (String point : parts) {
        String[] pointData = point.split(",");
        Float lat = Float.parseFloat(pointData[0]);
        Float lng = Float.parseFloat(pointData[1]);

        mMap.addMarker(new MarkerOptions()
                .position(new LatLng(lat, lng))
                .title("Hello world"));


    }
}

我的PHP如下:

 <?php
$mysqli = new mysqli("localhost", "root", "password", "location_marker");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

$query = "SELECT markers.lat, markers.lng
FROM markers";

if ($result = $mysqli->query($query)) {

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
/*
echo $row['lat'];
echo ',';
echo $row['lng'];
echo ',';
echo '#';
*/

}
echo '-32.430412,-58.321323,#-32.430412,-58.321323,#-32.430412,-58.321323,#';

    /* free result set */
    $result->free();
}

/* close connection */
$mysqli->close();
?>

我甚至尝试了完全相同的结果来确认仍有异常。

Exception看起来像这样:

    02-19 02:40:42.246 28422-28441/com.hexapixel.hexa I/dalvikvm: Total arena pages for JIT: 21
02-19 02:40:44.786 28422-28422/com.hexapixel.hexa D/AndroidRuntime: Shutting down VM
02-19 02:40:44.786 28422-28422/com.hexapixel.hexa W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x430f2140)
02-19 02:40:44.796 28422-28422/com.hexapixel.hexa E/AndroidRuntime: FATAL EXCEPTION: main
                                                                    Process: com.hexapixel.hexa, PID: 28422
                                                                    java.lang.IllegalStateException: Could not execute method of the activity
                                                                        at android.view.View$1.onClick(View.java:3846)
                                                                        at android.view.View.performClick(View.java:4478)
                                                                        at android.view.View$PerformClick.run(View.java:18698)
                                                                        at android.os.Handler.handleCallback(Handler.java:733)
                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                        at android.os.Looper.loop(Looper.java:149)
                                                                        at android.app.ActivityThread.main(ActivityThread.java:5257)
                                                                        at java.lang.reflect.Method.invokeNative(Native Method)
                                                                        at java.lang.reflect.Method.invoke(Method.java:515)
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
                                                                        at dalvik.system.NativeStart.main(Native Method)
                                                                     Caused by: java.lang.reflect.InvocationTargetException
                                                                        at java.lang.reflect.Method.invokeNative(Native Method)
                                                                        at java.lang.reflect.Method.invoke(Method.java:515)
                                                                        at android.view.View$1.onClick(View.java:3841)
                                                                        at android.view.View.performClick(View.java:4478) 
                                                                        at android.view.View$PerformClick.run(View.java:18698) 
                                                                        at android.os.Handler.handleCallback(Handler.java:733) 
                                                                        at android.os.Handler.dispatchMessage(Handler.java:95) 
                                                                        at android.os.Looper.loop(Looper.java:149) 
                                                                        at android.app.ActivityThread.main(ActivityThread.java:5257) 
                                                                        at java.lang.reflect.Method.invokeNative(Native Method) 
                                                                        at java.lang.reflect.Method.invoke(Method.java:515) 
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609) 
                                                                        at dalvik.system.NativeStart.main(Native Method) 
                                                                     Caused by: java.lang.NullPointerException
                                                                        at com.hexapixel.hexa.MapsActivity.setUpMap(MapsActivity.java:193)
                                                                        at com.hexapixel.hexa.MapsActivity.getCoords(MapsActivity.java:62)
                                                                        at java.lang.reflect.Method.invokeNative(Native Method) 
                                                                        at java.lang.reflect.Method.invoke(Method.java:515) 
                                                                        at android.view.View$1.onClick(View.java:3841) 
                                                                        at android.view.View.performClick(View.java:4478) 
                                                                        at android.view.View$PerformClick.run(View.java:18698) 
                                                                        at android.os.Handler.handleCallback(Handler.java:733) 
                                                                        at android.os.Handler.dispatchMessage(Handler.java:95) 
                                                                        at android.os.Looper.loop(Looper.java:149) 
                                                                        at android.app.ActivityThread.main(ActivityThread.java:5257) 
                                                                        at java.lang.reflect.Method.invokeNative(Native Method) 
                                                                        at java.lang.reflect.Method.invoke(Method.java:515) 
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609) 
                                                                        at dalvik.system.NativeStart.main(Native Method) 

所以现在我在kitkat rom的应用程序中修复了问题,但为什么它现在崩溃在Lollipop rom上。任何人都可以自己提供链接来了解所有这些崩溃日志。

崩溃登录Lollipop rom:

    02-21 00:34:59.509 19445-19552/com.hexapixel.hexa I/art: DexFile_isDexOptNeeded failed to open oat file '/data/dalvik-cache/x86/data@data@com.google.android.gms@app_chimera@m@0000000d@GoogleCertificates_GmsCore_prodlmp_alldpi_release.apk@classes.dex' for file location '/data/data/com.google.android.gms/app_chimera/m/0000000d/GoogleCertificates_GmsCore_prodlmp_alldpi_release.apk': Failed to open oat filename for reading: No such file or directory
02-21 00:35:00.769 19445-19445/com.hexapixel.hexa D/AndroidRuntime: Shutting down VM
02-21 00:35:00.769 19445-19445/com.hexapixel.hexa E/AndroidRuntime: FATAL EXCEPTION: main
                                                                    Process: com.hexapixel.hexa, PID: 19445
                                                                    java.lang.IllegalStateException: Could not execute method of the activity
                                                                        at android.view.View$1.onClick(View.java:4007)
                                                                        at android.view.View.performClick(View.java:4756)
                                                                        at android.view.View$PerformClick.run(View.java:19761)
                                                                        at android.os.Handler.handleCallback(Handler.java:739)
                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                        at android.os.Looper.loop(Looper.java:135)
                                                                        at android.app.ActivityThread.main(ActivityThread.java:5253)
                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                        at java.lang.reflect.Method.invoke(Method.java:372)
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
                                                                     Caused by: java.lang.reflect.InvocationTargetException
                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                        at java.lang.reflect.Method.invoke(Method.java:372)
                                                                        at android.view.View$1.onClick(View.java:4002)
                                                                        at android.view.View.performClick(View.java:4756) 
                                                                        at android.view.View$PerformClick.run(View.java:19761) 
                                                                        at android.os.Handler.handleCallback(Handler.java:739) 
                                                                        at android.os.Handler.dispatchMessage(Handler.java:95) 
                                                                        at android.os.Looper.loop(Looper.java:135) 
                                                                        at android.app.ActivityThread.main(ActivityThread.java:5253) 
                                                                        at java.lang.reflect.Method.invoke(Native Method) 
                                                                        at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 
                                                                     Caused by: java.lang.ArrayIndexOutOfBoundsException: length=3; index=3
                                                                        at com.hexapixel.hexa.MapsActivity.setUpMap(MapsActivity.java:227)
                                                                        at com.hexapixel.hexa.MapsActivity.getCoords(MapsActivity.java:78)
                                                                        at java.lang.reflect.Method.invoke(Native Method) 
                                                                        at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                        at android.view.View$1.onClick(View.java:4002) 
                                                                        at android.view.View.performClick(View.java:4756) 
                                                                        at android.view.View$PerformClick.run(View.java:19761) 
                                                                        at android.os.Handler.handleCallback(Handler.java:739) 
                                                                        at android.os.Handler.dispatchMessage(Handler.java:95) 
                                                                        at android.os.Looper.loop(Looper.java:135) 
                                                                        at android.app.ActivityThread.main(ActivityThread.java:5253) 
                                                                        at java.lang.reflect.Method.invoke(Native Method) 
                                                                        at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 

应用SharedPreference之后的新程序,该程序在Kitkat中运行但在Lollipop和其他高级rom(奥利奥)中崩溃。

    public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,GoogleMap.OnInfoWindowClickListener {

    private GoogleMap mMap;
    private GPSCord gps;
    double longitude;
    double latitude;

    public String JSON_STRING;
    public String json_string;
    public static final String MY_PREFS_NAME = "MyPrefsFile";
    private static final String TAG = "Maps Activity check";




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_maps);
        Gpsconnection();
        Toast.makeText(getApplicationContext(), "yolla location traced \n Longitude:" + Double.toString(longitude) + "\nLatitude:" + Double.toString(latitude), Toast.LENGTH_SHORT).show();

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.


    }



    public void getCoords(View view) {
        new CoordsBackgroundTask().execute();

        setUpMap();
    }

    class CoordsBackgroundTask extends AsyncTask<Void, Void, String> {

        String json_url_coords;

        @Override
        protected void onPreExecute() {
            json_url_coords = "http://192.168.225.139/location_marker/just.php";
        }

        @Override
        protected String doInBackground(Void... voids) {
            try {
                URL url = new URL(json_url_coords);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder stringBuilder = new StringBuilder();
                while ((JSON_STRING = bufferedReader.readLine()) != null) {

                    stringBuilder.append(JSON_STRING + "\n");
                }

                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return stringBuilder.toString().trim();


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;

        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(String result) {
            TextView textview = (TextView) findViewById(R.id.textviewMaps);
            textview.setText(result);
            json_string = result;


            SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
            editor.putString("name", json_string);
            editor.commit();



        }

    }

@Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        //setUpMap();

        // marker information tab clicked...........

        googleMap.setOnInfoWindowClickListener(this);
        // Add a marker in Sydney and move the camera

        LatLng loc1 = new LatLng(latitude, longitude);
        mMap.addMarker(new MarkerOptions().position(loc1).title("My Current Location").snippet("").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
        float zoomLevel = 16; //This goes up to 21
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(loc1, zoomLevel));

    }

    public void Gpsconnection() {
        gps = new GPSCord(MapsActivity.this);
        if (gps.canGetLocation()) {

            longitude = gps.getLongitude();
            latitude = gps.getLatitude();
            // Toast.makeText(getApplicationContext(),"Longitude:"+Double.toString(longitude)+"\nLatitude:"+Double.toString(latitude),Toast.LENGTH_SHORT).show();
        } else {

            gps.showSettingsAlert();
        }

    }


    private void setUpMap() {

        SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
        String name = prefs.getString("name", "No name defined");
        Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();

        String answer = name;
        String[] parts = answer.split("#");

        for (String point : parts) {
            String[] pointData = point.split(",");
            Float lat = Float.parseFloat(pointData[0]);
            Float lng = Float.parseFloat(pointData[1]);
            String agencyName = pointData[2];
            String mainphoneNo = pointData[3];
            //String altphoneNo = pointData[4];

            mMap.addMarker(new MarkerOptions()
                    .position(new LatLng(lat, lng))
                    .title(agencyName)
                    .snippet(mainphoneNo));

        }


    }


    @Override
    public void onInfoWindowClick(Marker marker) {
        String uri = "tel:" + marker.getSnippet();
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse(uri));
        startActivity(intent);
    }

}

1 个答案:

答案 0 :(得分:1)

它实际上给你空值。网络调用发生在一个单独的线程中。如果它在同一个线程中,则数据将保留。但是在android中如果你在UI线程上进行网络调用那么你会得到一个&#34;应用程序没有响应&#34;对话。现在,要保留来自网络呼叫的数据,请使用SharedPreferences。这是存储数据然后稍后检索的最简单方法。您也可以尝试使用StringBuffer