Home > other >  How to open URL from ListView inside fragment?
How to open URL from ListView inside fragment?

Time:10-15

Wanna make to open website when I click it from ListView. I made it with some youtube videos. Mixed up those youtube videos and of course, It's not working. What should fix or add more code? I put my every codes to understand it. Need you guys help a lot.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Teams">

    <ListView
        android:id="@ id/listView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="16dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@ id/teamImage"
        android:src="@mipmap/ic_launcher"
        android:layout_width="60dp"
        android:layout_height="60dp"/>

    <TextView
        android:id="@ id/teamName"
        android:layout_toRightOf="@id/teamImage"
        android:layout_marginLeft="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@style/TextAppearance.AppCompat.Title"
        android:text="Name"/>

    <TextView
        android:id="@ id/teamDivision"
        android:layout_toRightOf="@id/teamImage"
        android:layout_marginLeft="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/teamName"
        style="@style/TextAppearance.AppCompat.SearchResult.Subtitle"
        android:text="Division"/>

</RelativeLayout>

Two upper codes are for layout.

package com.example.gridiron;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link Settings#newInstance} factory method to
 * create an instance of this fragment.
 */
public class Teams extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public Teams() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment Settings.
     */
    // TODO: Rename and change types and number of parameters
    public static Teams newInstance(String param1, String param2) {
        Teams fragment = new Teams();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_teams, container, false);

        ListView listView = (ListView) view.findViewById(R.id.listView);

        ArrayList<TeamsList> arrayList = new ArrayList<>();
        arrayList.add(new TeamsList(R.drawable.arizona, "Arizona Cardinals", "NFC West", "https://namu.wiki/w/애리조나 카디널스"));
        arrayList.add(new TeamsList(R.drawable.atlanta, "Atlanta Falcons", "NFC South", "https://namu.wiki/w/애틀랜타 팰컨스"));
        arrayList.add(new TeamsList(R.drawable.baltimore, "Baltimore Ravens", "AFC North", "https://namu.wiki/w/볼티모어 레이븐스"));
        arrayList.add(new TeamsList(R.drawable.buffalo, "Buffalo Bills", "AFC East", "https://namu.wiki/w/버팔로 빌스"));
        arrayList.add(new TeamsList(R.drawable.carolina, "Carolina Panthers", "NFC South", "https://namu.wiki/w/캐롤라이나 팬서스"));
        arrayList.add(new TeamsList(R.drawable.chicago, "Chicago Bears", "NFC North", "https://namu.wiki/w/시카고 베어스"));
        arrayList.add(new TeamsList(R.drawable.cincinnati, "Cincinnati Bengals", "AFC North", "https://namu.wiki/w/신시내티 벵골스"));
        arrayList.add(new TeamsList(R.drawable.cleveland, "Cleveland Browns", "AFC North", "https://namu.wiki/w/클리블랜드 브라운스"));
        arrayList.add(new TeamsList(R.drawable.dallas, "Dallas Cowboys", "NFC East", "https://namu.wiki/w/댈러스 카우보이스"));
        arrayList.add(new TeamsList(R.drawable.denver, "Denver Broncos", "AFC West", "https://namu.wiki/w/덴버 브롱코스"));
        arrayList.add(new TeamsList(R.drawable.detroit, "Detroit Lions", "NFC North", "https://namu.wiki/w/디트로이트 라이언스"));
        arrayList.add(new TeamsList(R.drawable.greenbay, "Green Bay Packers", "NFC North", "https://namu.wiki/w/그린베이 패커스"));
        arrayList.add(new TeamsList(R.drawable.houston, "Houston Texans", "AFC South", "https://namu.wiki/w/휴스턴 텍산스"));
        arrayList.add(new TeamsList(R.drawable.indianapolis, "Indianapolis Colts", "AFC South", "https://namu.wiki/w/인디애나폴리스 콜츠"));
        arrayList.add(new TeamsList(R.drawable.jacksonville, "Jacksonville Jaguars", "AFC South", "https://namu.wiki/w/잭슨빌 재규어스"));
        arrayList.add(new TeamsList(R.drawable.kansascity, "Kansas City Chiefs", "AFC West", "https://namu.wiki/w/캔자스시티 치프스"));
        arrayList.add(new TeamsList(R.drawable.lasvegas, "Las Vegas Raiders", "AFC West", "https://namu.wiki/w/라스베이거스 레이더스"));
        arrayList.add(new TeamsList(R.drawable.losangeleschargers, "Los Angeles Chargers", "AFC West", "https://namu.wiki/w/로스앤젤레스 차저스"));
        arrayList.add(new TeamsList(R.drawable.losangelesrams, "Los Angeles Rams", "NFC West", "https://namu.wiki/w/로스앤젤레스 램스"));
        arrayList.add(new TeamsList(R.drawable.miami, "Miami Dolphins", "AFC East", "https://namu.wiki/w/마이애미 돌핀스"));
        arrayList.add(new TeamsList(R.drawable.minnesota, "Minnesota Vikings", "NFC North", "https://namu.wiki/w/미네소타 바이킹스"));
        arrayList.add(new TeamsList(R.drawable.newengland, "New England Patriots", "AFC East", "https://namu.wiki/w/뉴잉글랜드 패트리어츠"));
        arrayList.add(new TeamsList(R.drawable.neworleans, "New Orleans Saints", "NFC South", "https://namu.wiki/w/뉴올리언스 세인츠"));
        arrayList.add(new TeamsList(R.drawable.newyorkgiants, "New York Giants", "NFC East", "https://namu.wiki/w/뉴욕 자이언츠"));
        arrayList.add(new TeamsList(R.drawable.newyorkjets, "New York Jets", "AFC East", "https://namu.wiki/w/뉴욕 제츠"));
        arrayList.add(new TeamsList(R.drawable.philadelphia, "Philadelphia Eagles", "NFC East", "https://namu.wiki/w/필라델피아 이글스"));
        arrayList.add(new TeamsList(R.drawable.pittsburgh, "Pittsburgh Steelers", "AFC North", "https://namu.wiki/w/피츠버그 스틸러스"));
        arrayList.add(new TeamsList(R.drawable.sanfrancisco, "San Francisco 49ers", "NFC West", "https://namu.wiki/w/샌프란시스코 포티나이너스"));
        arrayList.add(new TeamsList(R.drawable.seattle, "Seattle Seahawks", "NFC West", "https://namu.wiki/w/시애틀 시호크스"));
        arrayList.add(new TeamsList(R.drawable.tampabay, "Tampa Bay Buccaneers", "NFC South", "https://namu.wiki/w/탬파베이 버커니어스"));
        arrayList.add(new TeamsList(R.drawable.tennessee, "Tennessee Titans", "AFC South", "https://namu.wiki/w/테네시 타이탄스"));
        arrayList.add(new TeamsList(R.drawable.washington, "Washington Football Team", "NFC East", "https://namu.wiki/w/워싱턴 풋볼팀"));

        TeamsListAdapter teamsListAdapter = new TeamsListAdapter(getActivity(), R.layout.list_row, arrayList);

        listView.setAdapter(teamsListAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.valueOf(arrayList)));

                if(intent.resolveActivity(requireContext().getPackageManager()) != null){
                    startActivity(intent);
                }
            }
        });

        return view;
    }
}
package com.example.gridiron;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.ArrayList;

public class TeamsListAdapter extends ArrayAdapter<TeamsList> {

    private Context mContext;
    private int mResource;

    public TeamsListAdapter(@NonNull Context context, int resource, @NonNull ArrayList<TeamsList> objects) {
        super(context, resource, objects);
        this.mContext = context;
        this.mResource = resource;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        LayoutInflater layoutInflater = LayoutInflater.from(mContext);

        convertView = layoutInflater.inflate(mResource, parent, false);

        ImageView teamImage = convertView.findViewById(R.id.teamImage);
        teamImage.setImageResource(getItem(position).getTeamImage());

        TextView teamName = convertView.findViewById(R.id.teamName);
        teamName.setText(getItem(position).getTeamName());

        TextView teamDivision = convertView.findViewById(R.id.teamDivision);
        teamDivision.setText(getItem(position).getTeamDivision());

        return convertView;
    }
}
package com.example.gridiron;

public class TeamsList {
    int TeamImage;
    String TeamName;
    String TeamDivision;
    String TeamURL;

    public TeamsList(int teamImage, String teamName, String teamDivision, String teamURL) {
        TeamImage = teamImage;
        TeamName = teamName;
        TeamDivision = teamDivision;
        TeamURL = teamURL;
    }

    public int getTeamImage() {
        return TeamImage;
    }

    public void setTeamImage(int teamImage) {
        TeamImage = teamImage;
    }

    public String getTeamName() {
        return TeamName;
    }

    public void setTeamName(String teamName) {
        TeamName = teamName;
    }

    public String getTeamDivision() {
        return TeamDivision;
    }

    public void setTeamDivision(String teamDivision) {
        TeamDivision = teamDivision;
    }

    public String getTeamURL() {
        return TeamURL;
    }

    public void setTeamURL(String teamURL) {
        TeamURL = teamURL;
    }
}

And last 3 codes are for class. It's really hard to make it. Please, Help me!

CodePudding user response:

Currently according to your code above when you click on a ListView item you are trying to open a url using the below Intent which is failing to construct a url from an ArrayList:

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.valueOf(arrayList)));

You should get the clicked item url first to be able to construct a valid url like below:

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.valueOf(arrayList.get(position).getTeamURL())));

An example of a sample url link based on your code redirecting to the specific url will be like below:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.valueOf("https://namu.wiki/w/인디애나폴리스 콜츠")));
        
        if(intent.resolveActivity(requireContext().getPackageManager()) != null){
            getActivity().startActivity(intent);
        }
    }
});
  • Related