将android连接到mysql数据库...应用程序已停止

时间:2015-09-04 21:20:43

标签: android mysql connect genymotion

我正在尝试连接我的Android应用。 " Genymotion模拟器"到localhost。我可以使用http://10.0.3.2在genymotion浏览器上访问mysql,但是当我运行应用程序时显示错误消息"不幸的是,应用已停止"。 我不知道发生了什么,有什么想法吗?

MainActivity.java

package com.example.coursetaxis;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject; 
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng; 
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends FragmentActivity {

GoogleMap mGoogleMap;

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

    // Getting reference to SupportMapFragment
    SupportMapFragment fragment = (SupportMapFragment)      getSupportFragmentManager()
            .findFragmentById(R.id.map);

    // Creating GoogleMap from SupportMapFragment
    mGoogleMap = fragment.getMap();

    // Enabling MyLocation button for the Google Map
    mGoogleMap.setMyLocationEnabled(true);

    // Setting OnClickEvent listener for the GoogleMap
    mGoogleMap.setOnMapClickListener(new OnMapClickListener() {
        @Override
        public void onMapClick(LatLng latlng) {
            addMarker(latlng);
            sendToServer(latlng);
        }
    });

    // Starting locations retrieve task
    new RetrieveTask().execute();
}

// Adding marker on the GoogleMaps
private void addMarker(LatLng latlng) {
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latlng);
    markerOptions.title(latlng.latitude + "," + latlng.longitude);
    mGoogleMap.addMarker(markerOptions);
}

// Invoking background thread to store the touched location in Remove MySQL server
private void sendToServer(LatLng latlng) {
    new SaveTask().execute(latlng);
}
// Background thread to save the location in remove MySQL server
private class SaveTask extends AsyncTask<LatLng, Void, Void> {
    @Override
    protected Void doInBackground(LatLng... params) {
        String lat = Double.toString(params[0].latitude);
        String lng = Double.toString(params[0].longitude);
        String strUrl = "http://10.0.3.2:5555/location_marker_mysql/save.php";
        URL url = null;
        try {
            url = new URL(strUrl);

            HttpURLConnection connection = (HttpURLConnection) url
                .openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
            connection.getOutputStream());

            outputStreamWriter.write("lat=" + lat + "&lng="+lng);
            outputStreamWriter.flush();
            outputStreamWriter.close();

            InputStream iStream = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new
            InputStreamReader(iStream));

            StringBuffer sb = new StringBuffer();

            String line = "";

            while( (line = reader.readLine()) != null){
                sb.append(line);
            }

            reader.close();
            iStream.close();

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

        return null;
    }
}

// Background task to retrieve locations from remote mysql server
private class RetrieveTask extends AsyncTask<Void, Void, String>{

    @Override
    protected String doInBackground(Void... params) {
        String strUrl = "http://10.0.3.2:5555/location_marker_mysql/retrieve.php";
        URL url = null;
        StringBuffer sb = new StringBuffer();
        try {
            url = new URL(strUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            InputStream iStream = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
            String line = "";
            while( (line = reader.readLine()) != null){
                sb.append(line);
            }

            reader.close();
            iStream.close();

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

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        new ParserTask().execute(result);
    }
}

// Background thread to parse the JSON data retrieved from MySQL server
private class ParserTask extends AsyncTask<String, Void, List<HashMap<String, String>>>{
    @Override
    protected List<HashMap<String,String>> doInBackground(String... params) {
        MarkerJSONParser markerParser = new MarkerJSONParser();
        JSONObject json = null;
        try {
            json = new JSONObject(params[0]);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        List<HashMap<String, String>> markersList = markerParser.parse(json);
        return markersList;
    }

    @Override
    protected void onPostExecute(List<HashMap<String, String>> result) {
        for(int i=0; i<result.size();i++){
            HashMap<String, String> marker = result.get(i);
            LatLng latlng = new LatLng(Double.parseDouble(marker.get("lat")), Double.parseDouble(marker.get("lng")));
            addMarker(latlng);
        }
    }
}

@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;
}
}

MarkerJSONParser.java

package com.example.coursetaxis;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MarkerJSONParser {

/** Receives a JSONObject and returns a list */
public List<HashMap<String,String>> parse(JSONObject jObject){

    JSONArray jMarkers = null;
   try {
        /** Retrieves all the elements in the 'markers' array */
        jMarkers = jObject.getJSONArray("chaufeur");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    /** Invoking getMarkers with the array of json object
    * where each json object represent a marker
    */
    return getMarkers(jMarkers);
}

private List<HashMap<String, String>> getMarkers(JSONArray jMarkers){
    int markersCount = jMarkers.length();
    List<HashMap<String, String>> markersList = new ArrayList<HashMap<String,String>>();
    HashMap<String, String> marker = null;

    /** Taking each marker, parses and adds to list object */
    for(int i=0; i<markersCount;i++){
        try {
            /** Call getMarker with marker JSON object to parse the marker */
            marker = getMarker((JSONObject)jMarkers.get(i));
            markersList.add(marker);
        }catch (JSONException e){
            e.printStackTrace();
        }
    }
    return markersList;
}

/** Parsing the Marker JSON object */
private HashMap<String, String> getMarker(JSONObject jMarker){

    HashMap<String, String> marker = new HashMap<String, String>();
    String lat = "-NA-";
    String lng ="-NA-";
    String place_name ="-NA-";

    try {
        // Extracting latitude, if available
        if(!jMarker.isNull("lat")){
            lat = jMarker.getString("lat");
        }

        // Extracting longitude, if available
        if(!jMarker.isNull("lng")){
            lng = jMarker.getString("lng");
        }
        if(!jMarker.isNull("place_name")){
            place_name = jMarker.getString("place_name");
        }
        marker.put("lat", lat);
        marker.put("lng", lng);
        marker.put("place_name",place_name);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return marker;
}
}

AndroidManifest.java

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.coursetaxis"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="18" />
<permission
    android:name="com.example.edf.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" />   
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- Required to show current location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature 
    android:glEsVersion="0x00020000"
    android:required="true"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.coursetaxis.MainActivity"
        android:label="@string/app_name"
        android:parentActivityName="com.example.coursetaxis.MainActivity" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <meta-data 
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="my_key"/>

     <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version"
    />
</application>

save.php

     <?php
    if(isset($_POST['lat']) && isset($_POST['lng'])){
     $lat = $_POST['lat'];
    $lng = $_POST['lng'];
    $place = $_POST['place_name'];
    $sql = "insert into markers values('',?,?,?)";
    $mysqli = new mysqli("localhost", "root", "", "my_db");
    $stmt = $mysqli->prepare($sql);

    $stmt->bind_param("ss",$lat,$lng,$place);
    $stmt->execute();
    $stmt->close();
    $mysqli->close();
  }else   echo"post est vide";
  ?>

0 个答案:

没有答案