Android应用程序不会将数据保存在WAMP数据库中

时间:2017-09-23 17:52:00

标签: java php android mysql wamp

用户必须通过点击地图添加标记。我的目标是将名称,类别,纬度和经度发送到SQL数据库。我遵循了本教程:https://www.youtube.com/watch?v=cOsZHuu8Qog。该应用有效,它甚至可以toast "注册成功!" 但数据库仍为空

,也许我的应用和WampServer之间的通信有问题。我想知道连接URL是否正确。我在互联网上发现 默认WAMP localhost IP 是10.0.2.2,或者它可以与我的PC的本地IP一起使用。他们俩都没有工作。

参见代码:

AddShopActivity.java

public class AddShopActivity extends MainScreen implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {

Spinner spinner;
ArrayAdapter<CharSequence> adapter;


GoogleMap mGoogleMap;
GoogleApiClient mGoogleApiClient;

String Name, Category, Latitude, Longitude;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_shop);
    initMap();
    spinner = (Spinner) findViewById(R.id.spinner);
    adapter = ArrayAdapter.createFromResource(this, R.array.eidoskatastimatos, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
}

private void initMap() {
    MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapFragment);
    mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mGoogleMap = googleMap;
    mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
    mGoogleApiClient.connect();
}

LocationRequest mLocationsRequest;

@Override
public void onConnected(Bundle bundle) {
    mLocationsRequest = LocationRequest.create();
    mLocationsRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationsRequest.setInterval(5000);
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }

     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationsRequest, this);


    mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng latLng) {

            EditText shop_name = (EditText)findViewById(R.id.editName);
            Spinner shop_category = (Spinner)findViewById(R.id.spinner);

            MarkerOptions marker = new MarkerOptions()
                                       .position(new LatLng(latLng.latitude, latLng.longitude))
                                       .draggable(true)
                                       .title(shop_name.getText().toString())
                                       .snippet(shop_category.getSelectedItem().toString());


            CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng, 16);
            mGoogleMap.animateCamera(update);

            mGoogleMap.clear();
            mGoogleMap.addMarker(marker);

            Name = shop_name.getText().toString();
            Category = shop_category.getSelectedItem().toString();
            Latitude = String.valueOf(latLng.latitude);
            Longitude = String.valueOf(latLng.longitude);
        }
    });

}

public void shopReg(View view)
{
    String method = "save";
    BackgroundTask backgroundTask = new BackgroundTask(this);
    backgroundTask.execute(method, Name, Category, Latitude, Longitude);
    finish();
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

@Override
public void onLocationChanged(Location location) {
    if (location == null){
        Toast.makeText(this, "Can't get current location", Toast.LENGTH_LONG).show();
    } else {
        LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
        CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, 16);
        mGoogleMap.animateCamera(update);
    }

}
}

BackgroundTask.java

public class BackgroundTask extends AsyncTask<String,Void,String> {


Context ctx;

BackgroundTask(Context ctx)
{
    this.ctx = ctx;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected String doInBackground(String... params) {
    String reg_url = "http://10.0.2.2/shop/register.php";
    String method = params[0];
    if(method.equals("save"))
    {
        String Name = params[1];
        String Category = params[2];
        String Latitude = params[3];
        String Longitude = params[4];
        try {
            URL url = new URL(reg_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream OS = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
    String data = URLEncoder.encode("Name", "UTF-8") +"="+URLEncoder.encode(Name,"UTF-8")+"&"+
            URLEncoder.encode("Category", "UTF-8") +"="+URLEncoder.encode(Category,"UTF-8")+"&"+
            URLEncoder.encode("Latitude", "UTF-8") +"="+URLEncoder.encode(Latitude,"UTF-8")+"&"+
            URLEncoder.encode("Longitude", "UTF-8") +"="+URLEncoder.encode(Longitude,"UTF-8");
            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            OS.close();
            InputStream IS = httpURLConnection.getInputStream();
            IS.close();
            return "Το κατάστημα προστέθηκε!";
        } 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) {
    Toast.makeText(ctx,result,Toast.LENGTH_LONG).show();
}
}

的init.php

<?php
$db_name="shops";
$mysql_user="root";
$mysql_pass="";
$server_name="localhost";

$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$db_name);

?>

register.php

<?php
require"init.php";

$shop_name=$_POST["Name"];
$shop_category=$_POST["Category"];
$shop_latitude=$_POST["Latitude"];
$shop_longitude=$_POST["Longitude"];

$sql_query="insert into shop_info values('$shop_name','$shop_category','$shop_latitude','$shop_longidude');";

?>

1 个答案:

答案 0 :(得分:1)

假设后端(php)代码正是您在此示例中提供的代码,您实际上从未执行任何保存任何内容的代码,因此难怪您的数据库是空的。

您的代码现在做了什么:

  • init.php
  • 中准备连接
  • 通过在register.php中的字符串中插入用户提供的数据来准备SQL查询的字符串表示形式( ouch,请阅读以下

缺少什么:

  • 执行查询以实际对数据执行某些操作,即mysqli_query($conn, $sql_query);
  • 了解SQL injection
  • 在PHP脚本中实现避免SQL注入的正确方法之一(即prepared statements
  • (可选但建议使用)使用现代PDO interface访问数据库。

作为一般性建议,您应该将复杂的代码分解为可以验证它们工作的小型可测试部分。

例如,如果您尝试使用实际值调用register.php而不是来自POST数据的数据,您很快就会看到它不会保存任何内容,而不是查看IP,连接或者你的android代码。你得到的评论就是那个方向 - 忘记你的Android应用程序并尝试验证后端是否会在请求后保存请求。