2016-03-13 3 views
0

Я пишу одно приложение для отображения текущего адреса пользователя на основе широты и долготы, но я получаю одну ошибку в этом коде в строке Toast.makeText(this, "No address found try again", Toast.LENGTH_SHORT).show(); Говорят, что makeText в типе типа не применим для аргументов. Я не могу устранить эту ошибку. Любая помощь ?? Я пытаюсь показать адрес пользователя в TextView, но я не уверен, что я делаю это хорошо, или может возникнуть некоторая ошибка времени выполнения в будущем. Вот мой основной код деятельности Java:maketext не применим для аргументов

import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.GoogleApiAvailability; 
import com.google.android.gms.common.api.GoogleApiClient; 
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; 
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; 
import com.google.android.gms.location.LocationServices; 
import android.app.Activity; 
import android.app.Dialog; 
import android.app.DialogFragment; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.content.IntentSender.SendIntentException; 
import android.location.Geocoder; 
import android.location.Location; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.ResultReceiver; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemSelectedListener; 
import android.widget.ArrayAdapter; 
import android.widget.Spinner; 
import android.widget.TextView; 
import android.widget.Toast; 
public class MainActivity extends Activity implements OnItemSelectedListener, ConnectionCallbacks, OnConnectionFailedListener{ 
    private static final int REQUEST_RESOLVE_ERROR = 1001; 
    private static final String DIALOG_ERROR = "dialog_error"; 
    private static final String STATE_RESOLVING_ERROR = "resolving_error"; 
    GoogleApiClient mGoogleApiClient; 
    protected Location mLastLocation; 
    private boolean mResolvingError=false; 
    private AddressResultReceiver mResultReceiver; 
    // Request code to use when launching the resolution activity 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     Spinner spinner = (Spinner) findViewById(R.id.shop_category); 
     // Create an ArrayAdapter using the string array and a default spinner layout 
     ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, 
       R.array.shop_category, android.R.layout.simple_spinner_item); 
     // Specify the layout to use when the list of choices appears 
     adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
     // Apply the adapter to the spinner 
     spinner.setAdapter(adapter); 
     spinner.setOnItemSelectedListener(this); 
     if (mGoogleApiClient == null) { 
      mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
     } 
     mResolvingError = savedInstanceState != null 
       && savedInstanceState.getBoolean(STATE_RESOLVING_ERROR, false); 
    } 
    @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; 
    } 
    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 
     if (id == R.id.action_settings) { 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 
    @Override 
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 
     // TODO Auto-generated method stub 
     TextView mytext = (TextView) view; 
     Toast.makeText(this,"You selected "+mytext.getText(),Toast.LENGTH_SHORT).show();  
    } 
    @Override 
    public void onNothingSelected(AdapterView<?> parent) { 
     // TODO Auto-generated method stub  
    } 
    protected void startIntentService() { 
     Intent intent = new Intent(this, FetchAddressIntentService.class); 
     intent.putExtra(Constants.RECEIVER, mResultReceiver); 
     intent.putExtra(Constants.LOCATION_DATA_EXTRA, mLastLocation); 
     startService(intent); 
    } 
    @Override 
    public void onConnected(Bundle arg0) { 
     boolean mAddressRequested=false; 
     // TODO Auto-generated method stub 
     TextView myLatitude = (TextView)findViewById(R.id.lat_value); 
     TextView myLongitude = (TextView)findViewById(R.id.lang_value); 
     mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
       mGoogleApiClient); 
     if (mLastLocation != null) { 
      myLatitude.setText(String.valueOf(mLastLocation.getLatitude())); 
      myLongitude.setText(String.valueOf(mLastLocation.getLongitude())); 
     if (!Geocoder.isPresent()) { 
       Toast.makeText(this, R.string.no_geocoder_available, 
         Toast.LENGTH_LONG).show(); 
       return; 
      } 
     else{ 
      mAddressRequested=true; 
      if (mAddressRequested) { 
       startIntentService(); 
      } 
     } 
     } 
    } 
    @Override 
    public void onConnectionSuspended(int arg0) { 
     // TODO Auto-generated method stub 
    } 
    @Override 
    public void onConnectionFailed(ConnectionResult result) { 
     // TODO Auto-generated method stub 
     if (mResolvingError) { 
      Toast.makeText(this, "Resolving errors", Toast.LENGTH_SHORT).show(); 
      return; 
     } else if (result.hasResolution()) { 
      try { 
       mResolvingError = true; 
       result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR); 
      } catch (SendIntentException e) { 
       // There was an error with the resolution intent. Try again. 
       mGoogleApiClient.connect(); 
      } 
     } else { 
      // Show dialog using GoogleApiAvailability.getErrorDialog() 
      showErrorDialog(result.getErrorCode()); 
      mResolvingError = true; 
     } 
    } 
    private void showErrorDialog(int errorCode) { 
     // Create a fragment for the error dialog 
     ErrorDialogFragment dialogFragment = new ErrorDialogFragment(); 
     // Pass the error that should be displayed 
     Bundle args = new Bundle(); 
     args.putInt(DIALOG_ERROR, errorCode); 
     dialogFragment.setArguments(args); 
     dialogFragment.show(getFragmentManager(), "errordialog"); 
    } 
    public void onDialogDismissed() { 
     mResolvingError = false; 
    } 
    public static class ErrorDialogFragment extends DialogFragment { 
     public ErrorDialogFragment() { } 

     @Override 
     public Dialog onCreateDialog(Bundle savedInstanceState) { 
      // Get the error code and retrieve the appropriate dialog 
      int errorCode = this.getArguments().getInt(DIALOG_ERROR); 
      return GoogleApiAvailability.getInstance().getErrorDialog(
        this.getActivity(), errorCode, REQUEST_RESOLVE_ERROR); 
     } 

     @Override 
     public void onDismiss(DialogInterface dialog) { 
      ((MainActivity) getActivity()).onDialogDismissed(); 
     } 
    } 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     if (requestCode == REQUEST_RESOLVE_ERROR) { 
      mResolvingError = false; 
      if (resultCode == RESULT_OK) { 
       if (!mGoogleApiClient.isConnecting() && 
         !mGoogleApiClient.isConnected()) { 
        mGoogleApiClient.connect(); 
       } 
      } 
      } 
     } 
    protected void onSaveInstanceState(Bundle outState) { 
     super.onSaveInstanceState(outState); 
     outState.putBoolean(STATE_RESOLVING_ERROR, mResolvingError); 
    } 
    protected void onStart() { 
     mGoogleApiClient.connect(); 
     super.onStart(); 
    } 

    protected void onStop() { 
     mGoogleApiClient.disconnect(); 
     super.onStop(); 
    } 
    class AddressResultReceiver extends ResultReceiver { 
     public AddressResultReceiver(Handler handler) { 
      super(handler); 
     } 
     @Override 
     protected void onReceiveResult(int resultCode, Bundle resultData) { 
      // Display the address string 
      // or an error message sent from the intent service. 
      String mAddressOutput = resultData.getString(Constants.RESULT_DATA_KEY); 

      // Show a toast message if an address was found. 
      if (resultCode == Constants.SUCCESS_RESULT) { 
       TextView myaddress=(TextView) findViewById(R.id.myaddress); 
       myaddress.setText(mAddressOutput); 
      } 
      else{ 
       Toast.makeText(this, "No address found try again", Toast.LENGTH_SHORT).show(); 
      } 
     } 
    } 
} 

Спасибо заранее.

ответ

1

Замените this на MainActivity.this в качестве первого параметра для вашего звонка makeText(). this - это экземпляр вашего внутреннего класса AddressResultReceiver. Это не ваша деятельность, и makeText() нуждается в Context, как Activity.

0

Использовать getApplicationContext() вместо this. Использование:

Toast.makeText(getApplicationContext(), "message", Toast.LENGTH_SHORT).show(); 

this относится к AddressResultReceiver, которая не является подклассом Context.

Toast.makeText()Context.

Смежные вопросы