Ошибка возврата в Google Maps: не найдена активность для обработки намерения - PullRequest
0 голосов
/ 15 января 2020

У меня есть метод navigate:

    public void navigate(String coordinates){

        Uri intentUri = Uri.parse("geo"+coordinates);
        Intent mapIntent = new Intent(Intent.ACTION_VIEW);
        mapIntent.setData(intentUri);
        mapIntent.setPackage("com.google.android.apps.maps");
        getContext().startActivity(mapIntent);
    }

, который вызывается, когда я нажимаю TextView:

        TextView location = (TextView) listItemView.findViewById(R.id.location);
        location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                navigate(currentAttraction.getLocation());
            }
        });

Однако, когда приложение работает, и я нажмите на TextView, приложение crashes and I get this error:

2020-01-15 21:29:20.164 17438-17438/com.example.android.explorecapetown E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.android.explorecapetown, PID: 17438
    android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=geo-33.920864,18.418210 pkg=com.google.android.apps.maps }
        at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2051)
        at android.app.Instrumentation.execStartActivity(Instrumentation.java:1709)
        at android.app.Activity.startActivityForResult(Activity.java:5192)
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
        at android.app.Activity.startActivityForResult(Activity.java:5150)
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663)
        at android.app.Activity.startActivity(Activity.java:5521)
        at android.app.Activity.startActivity(Activity.java:5489)
        at com.example.android.explorecapetown.AttractionAdapter.navigate(AttractionAdapter.java:72)
        at com.example.android.explorecapetown.AttractionAdapter$1.onClick(AttractionAdapter.java:46)
        at android.view.View.performClick(View.java:7125)
        at android.view.View.performClickInternal(View.java:7102)
        at android.view.View.access$3500(View.java:801)
        at android.view.View$PerformClick.run(View.java:27336)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

Устройство имеет Google Maps.

Я очень новичок в использовании намерений Карты, поэтому я надеялся, что кто-то сможет дайте мне представление о том, что я делаю неправильно.

PS

Обратите внимание, что это происходит в классе адаптера:

public class AttractionAdapter extends ArrayAdapter<Attraction> {


    public AttractionAdapter(Context context, ArrayList<Attraction> attractions) {
        super(context, 0, attractions);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View listItemView = convertView;
        if (listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_item, parent, false);
        }

        final Attraction currentAttraction = getItem(position);

        ImageView imageView = (ImageView) listItemView.findViewById(R.id.attraction_image);
        imageView.setImageResource(currentAttraction.getImageResourceId());

        TextView attractionName = (TextView) listItemView.findViewById(R.id.attraction_name);
        attractionName.setText(currentAttraction.getName());

        TextView location = (TextView) listItemView.findViewById(R.id.location);
        location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                navigate(currentAttraction.getLocation());
            }
        });

        // Find the ImageView in the list_item.xml layout with the ID image.
        TextView contact = (TextView) listItemView.findViewById(R.id.contact);
        // Check if an image is provided for this word or not
        if (currentAttraction.hasContact()) {
            // If an image is available, display the provided image based on the resource ID
            contact.setText(currentAttraction.getContact());
            // Make sure the view is visible
            contact.setVisibility(View.VISIBLE);
        } else {
            // Otherwise hide the ImageView (set visibility to GONE)
            contact.setVisibility(View.GONE);
        }

        return listItemView;
    }

    public void navigate(String coordinates){

        Uri intentUri = Uri.parse("geo"+coordinates);
        Intent mapIntent = new Intent(Intent.ACTION_VIEW);
        mapIntent.setData(intentUri);
        mapIntent.setPackage("com.google.android.apps.maps");
        getContext().startActivity(mapIntent);
    }
}

Ответы [ 3 ]

0 голосов
/ 15 января 2020

publi c void navigate (Контекст контекста, строковые координаты) {

    Uri intentUri = Uri.parse("geo:"+coordinates);
    Intent mapIntent = new Intent(Intent.ACTION_VIEW);
    mapIntent.setData(intentUri);
    mapIntent.setPackage("com.google.android.apps.maps");
    context.startActivity(mapIntent);
}

navigate (getContext, currentAttraction.getLocation ());

0 голосов
/ 15 января 2020

Всегда безопасно проверить, есть ли какое-либо действие для обработки намерения или нет, прежде чем запускать какое-либо неявное намерение.

Внимание : Возможно, что пользователь не будет есть любые приложения, которые обрабатывают неявное намерение, которое вы отправляете в startActivity (). Либо приложение может быть недоступно из-за ограничений профиля или настроек, установленных администратором. Если это произойдет, вызов не удастся, и ваше приложение вылетает. Чтобы убедиться, что действие получит намерение, вызовите resolActivity () для объекта Intent. Если результат не нулевой, есть хотя бы одно приложение, которое может обработать намерение, и безопасно вызывать startActivity (). Если результат нулевой, не используйте намерение

//Uri intentUri = Uri.parse("geo:37.7749,-122.4194");

Uri intentUri = Uri.parse("geo:"+coordinates);
Intent mapIntent = new Intent(Intent.ACTION_VIEW);
mapIntent.setData(intentUri);
mapIntent.setPackage("com.google.android.apps.maps");

if (mapIntent.resolveActivity(context.getPackageManager()) != null) {
    context.startActivity(mapIntent);
} else {
    //Show info
}

Проверьте официальную документацию здесь

0 голосов
/ 15 января 2020

Вы забыли двоеточие после geo:

Uri intentUri = Uri.parse("geo:"+coordinates);

Это должно быть причиной, по которой он не находит никаких связанных действий.

Формат для использования geo: намерения для отображения карты в указанное местоположение и уровень масштабирования:

geo:latitude,longitude?z=zoom

И масштабирование необязательно.

Документы можно найти здесь: https://developers.google.com/maps/documentation/urls/android-intents

Вот причина крэ sh. И, в качестве дополнения, вы должны проверить, есть ли какие-либо действия для обработки намерения. Поскольку на других устройствах не может быть установлено приложение карт.

...