2017-09-16 131 views
0

用戶必須通過點擊地圖來添加標記。我的目標是將名稱,類別,緯度和經度發送到SQL數據庫。
我跟着這個問題:How can you pass multiple primitive parameters to AsyncTask?,但我在這一行出現錯誤:AsyncTask執行錯誤

backgroundTask.execute(method,Name,Category,Latitude,Longitude); 

看到代碼:

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; 
Double Latitude, Longitude, Latitude_pass, Longitude_pass; 

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

@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) { 

      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); 

      Latitude_pass = latLng.latitude; 
      Longitude_pass = latLng.longitude; 
     } 
    }); 

} 

public void shopReg(View view) 
{ 
    Name = shop_name.getText().toString(); 
    Category = shop_category.getSelectedItem().toString(); 
    Latitude = Latitude_pass; 
    Longitude = Longitude_pass; 
    String method = "save"; 
    BackgroundTask backgroundTask = new BackgroundTask(this); 
    backgroundTask.execute(method,Name,Category,Latitude,Longitude); //here is the error. It asks me to create the method 'execute' but the guy in a tutorial I am watching doen't do this// 
    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> { 

String Name, Category; 
Double Latitude, Longitude; 

BackgroundTask(String method, String Name, String Category, Double Latitude, Double Longitude) { 
    this.Name = Name; 
    this.Category = Category; 
    this.Latitude = Latitude; 
    this.Longitude = Longitude; 
} //Trying to pass 2 types of variablew, string and double, because lat and long are double// 

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); 
      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(); 
} 
} 
+1

請添加錯誤 – cutiko

回答

3

查看鏈接的問題agai ñ。你錯過了「Params」類。

execute的參數傳遞給doInBackground,您的預期值僅爲String[]。然而,這並不完全錯誤所在

您的其他構造函數沒有被用來獲取2個字符串和2張雙人牀

你只使用的上下文一個

new BackgroundTask(this); 

教程我看着

我可以說是再次嘗試觀看,或找到另一個

我敢打賭,它僅調用execute("save");並具有這樣的事情

// add the context to this constructor also 
new BackgroundTask(this, Name, Category, Latitude, Longitude); 

或者,看的AsyncTask,你需要使用Double.parseDouble,你必須通過串

String Name = params[1]; 
    String Category = params[2]; 
    Double Latitude = Double.parseDouble(params[3]); 
    Double Longitude = Double.parseDouble(params[4]); 
+0

在鏈接中看到第3個答案(與63的投票)。我試圖申請的那一個。同時檢查_edited code_,我做了一些改變,如你所說。這次沒有出現紅色下劃線的錯誤,應用程序正在運行,但是當我點擊調用'shopReg'的按鈕**時,它會崩潰。 –

+0

我無法修復代碼中的所有運行時異常。閱讀日誌並瞭解如何修復它們。只有當你真的被卡住了,但實際上試圖瞭解錯誤日誌告訴你什麼 –

+0

而且我認爲這個答案可以修復你的初始帖子。編輯你的問題會使你在這裏收到的答案無效。建議採取的行動是接受一個答案,然後使用logcat消息將更正後的代碼重新發布爲[mcve] –

0

AsyncTask<String...的參數傳遞到execute方法都是字符串類型。你正在傳球,字符串和雙。

作爲一般性建議,按照駱駝案例慣例編寫變量。使用私人accesor。

你的AsyncTask應該


public class BackgroundTask extends AsyncTask { 

private String name, category; 
private double latitude, longitude; 

BackgroundTask(double latitude, double longitude) { 
    this.latitude = latitude; 
    this.longitude = longitude; 
} 
} 

現在你的構造函數初始化雙打和你現在做它從PARAMS得到的字符串。

相關問題