2017-09-23 38 views
1

用戶必須通過點擊地圖來添加標記。我的目標是將名稱,類別,緯度和經度發送到SQL數據庫。我遵循這個教程:https://www.youtube.com/watch?v=cOsZHuu8Qog。該應用程序的作品,它甚至得到toast「註冊成功!」但數據庫仍爲空Android應用程序不會將數據保存到WAMP數據庫中

,也許我的應用程序和WampServer之間的通信有問題。我想知道連接網址是否正確。我在互聯網上發現,默認WAMP本地主機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

嗨,好像你在這裏有多個問題。 首先檢查移動應用程序和託管的WampServer是否位於同一網絡上。然後使用類似於Postman的工具來驗證您的註冊端點是否工作正常。澄清兩者後,我們嘗試解決移動應用程序問題。 –

+0

@Ruchira Randana我使用android Studio的默認模擬器。關於「郵差」工具,那是什麼?我從來沒有用過它。我在哪裏可以找到它? –

+0

郵差是和Chrome的附加組件。您可以使用它來測試您的Web服務。還有許多其他類似的工具,例如CURL。 https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en –

回答

1

假設後端(PHP)代碼僅僅是你提供什麼樣的在這個例子中,你從來沒有真正執行,節省了事情的任何代碼,所以難怪你的數據庫是空的。

現在你的代碼做什麼:

  • 準備在init.php
  • 連接準備通過將用戶的SQL查詢字符串表示提供的數據串在register.php哎喲,閱讀下面

缺少什麼:

  • 執行查詢真正做到對數據進行處理,即mysqli_query($conn, $sql_query);
  • 學習一下SQL injection
  • 實施的適當方式,以避免在PHP腳本SQL注入一個(即prepared statements
  • (可選但推薦)使用現代的PDO interface來訪問數據庫。

作爲一般性建議,您應該將複雜的代碼分解爲小的可測試部件,您可以驗證它們是否正常工作。

例如,您是否嘗試用實際值調用register.php而不是那些來自POST數據的數據,您很快就會發現它不保存任何內容,而不是查看IP,連接或Android代碼。你得到的評論是在這個方向 - 忘記你的Android應用程序,並嘗試驗證後端保存請求一旦進來。

+0

它的工作! mysqli_query($ conn,$ sql_query)'在'register.php'中。謝謝! –

相關問題