1

I'm using below code to populate my Main Activity with Fragment containing Listview. I'm following a tutorial from http://wptrafficanalyzer.in/blog/android-itemclicklistener-for-a-listview-with-images-and-text/.

I would like to know, how to use intent to open a separate activity / Fragment when each item clicked on Listview.

For example, wWhen first item is clicked, it will open A Fragment and when second item is clicked, it will open B Fragment.

package com.nepalpolice.cdp;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * Created by Sagar on 2017/09/23.
 */


public class club extends Fragment  {
    // Array of strings storing country names
    String[] countries = new String[]{
            "India",
            "Pakistan",
            "Sri Lanka",
            "China",
            "Bangladesh",
            "Nepal",
            "Afghanistan",
            "North Korea",
            "South Korea",
            "Japan"
    };

    // Array of integers points to images stored in /res/drawable-ldpi/
    int[] flags = new int[]{
            R.drawable.eka,
            R.drawable.kat,
            R.drawable.rat,
            R.drawable.set,
            R.drawable.ann,
            R.drawable.kar,
            R.drawable.suk,
            R.drawable.sap,
            R.drawable.him,
            R.drawable.gor
    };

    // Array of strings to store currencies
    String[] currency = new String[]{
            "Indian Rupee",
            "Pakistani Rupee",
            "Sri Lankan Rupee",
            "Renminbi",
            "Bangladeshi Taka",
            "Nepalese Rupee",
            "Afghani",
            "North Korean Won",
            "South Korean Won",
            "Japanese Yen"
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_club, container, false);
// Each row in the list stores country name, currency and flag
        List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();

        for (int i = 0; i < 10; i++) {
            HashMap<String, String> hm = new HashMap<String, String>();
            hm.put("txt", "Country : " + countries[i]);
            hm.put("cur", "Currency : " + currency[i]);
            hm.put("flag", Integer.toString(flags[i]));
            aList.add(hm);
        }

        // Keys used in Hashmap
        String[] from = {"flag", "txt", "cur"};

        // Ids of views in listview_layout
        int[] to = {R.id.flag, R.id.txt, R.id.cur};

        // Instantiating an adapter to store each items
        // R.layout.listview_layout defines the layout of each item
        SimpleAdapter adapter = new SimpleAdapter(getActivity(), aList, R.layout.listview_layout, from, to);

        // Getting a reference to listview of main.xml layout file
        ListView listView = (ListView) view.findViewById(R.id.listview);

        // Setting the adapter to the listView
        listView.setAdapter(adapter);
        return view;
    }

    // Item Click Listener for the listview
    AdapterView.OnItemClickListener itemClickListener = new

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

                    if(position == 1/*or any other position*/){
                        Fragment fragment = new notices();
                        FragmentManager fragmentManager = getFragmentManager();
                        fragmentManager.beginTransaction().replace(R.id.fragment_frame, fragment).addToBackStack(null).commit();
                    }
                    else if(position == 2){


                    } // etc...

                }
            };
}

enter image description here

BlueYeti81
  • 67
  • 10
  • Possible duplicate of [How to create listview onItemclicklistener](https://stackoverflow.com/questions/10295226/how-to-create-listview-onitemclicklistener) – Jaydip Kalkani Mar 15 '18 at 15:15
  • @JaydipKalkani no it is not , here i want to open a separate individual fragment for each item from listview when clicked. – BlueYeti81 Mar 15 '18 at 15:15
  • `Intent` is not involved in Fragment transaction. Just set click on list item and follow https://stackoverflow.com/questions/8163104/android-replace-the-current-fragment-with-another-fragment. – ADM Mar 15 '18 at 15:16
  • You can implement whatever you want once you implement onclicklistener for listview. Inside onclicklistener you can pass condition as per your requirement. – Jaydip Kalkani Mar 15 '18 at 15:18
  • @JaydipKalkani I'm totally new to android. So for now I can get the position of each item when clicked..but I would like to use switch and Case for each item which will open a new activity/fragment for each individual item.....if there is other way to do so ...please guide me through this...I'm banging my head around 2 hours for same. – BlueYeti81 Mar 15 '18 at 15:18
  • then first of all i have to see which kind of list you are displaying to the user and also which fragments you have for that list items. so, update your question. – Jaydip Kalkani Mar 15 '18 at 15:22
  • @JaydipKalkani here is the tutorial I'm following http://wptrafficanalyzer.in/blog/android-itemclicklistener-for-a-listview-with-images-and-text/ Hope it'll help you to understand my question in brief. – BlueYeti81 Mar 15 '18 at 15:26
  • Yes, as i can see there is onclicklistener implemented for listview items. You only have to change remove toast sentence in onclicklistener and put your logic there instead of this. You want to open different fragment item clicks then first create one master activity having fragment container and then change fragment in this according to items position which is clicked. If you don't know concept of fragment and how to open it then refer [this](https://developer.android.com/reference/android/app/Fragment.html) – Jaydip Kalkani Mar 15 '18 at 15:32
  • and if you need more help then you can reach to me at my fb ac [Jaydip Kalkani](https://www.facebook.com/kalkani.jaydip.1). i will be happy to help you.we should do more conversation on stack bcz it will disturb others also and it will also hide meaningfull comments. – Jaydip Kalkani Mar 15 '18 at 15:34
  • It was nice of you. Could be more better if you would post your solution on how to achieve the same. Anyway have a great day. I will be happy to have some nice conversation with you. – BlueYeti81 Mar 15 '18 at 15:39

2 Answers2

1

Inside onItemClick just make an if or switch to call your activity

// Item Click Listener for the listview
AdapterView.OnItemClickListener itemClickListener = new 

AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
           Intent intent;

           if(position == 1/*or any other position*/){
               intent = new Intent(YourActivity.this,OtherActivity1.class); // YourActivity is the activity containing this code, if this line causes problems, use context value here
           }
           else if(position == 2){
               intent = new Intent(YourActivity.this,OtherActivity2.class);
           } // etc...

           // create intent to activity and call it


           startActivity(intent);
        }
    };

or if you want to start the same activity with different parameters(which I usually do with listView), try this: (I strongly recommend you this one if your list is long, and all your activities are going to be similar)

// Item Click Listener for the listview
AdapterView.OnItemClickListener itemClickListener = new 

AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
           Intent intent;

           intent = new Intent(YourActivity.this,SomeActivity.class);

           intent.putExtra("some_key",((TextView)container).getText.toString()); // if your container is not TextView, for example custom layout, you'll need to change this line a bit to fit your needs

           // instead of calling different activities, all one activity
           // but with different parameters. 

           startActivity(intent);
        }
    };

EDIT

You wrote "i am totally new to android". I want to give you advice about this then.
When you have a list view, and you want to perform action when user clicks some item, and action is a bit different for each item (such as list of countries, and click will view information about that country, all actions are simmilar, to view the information),
then use one activity, and just call them with other parameters (Intent's extras).
If you make separate activity for every list item(if your list is long), it would be as bad as creating SQL table for each user(do you know SQL?).

Hope it helps. Tell me if you have any problems with code, or if something is unclear for you.

EDIT 2

If you have problem with 'new Intent(YourActivity.this/here/,[...])

Try to pass a context variable to your fragment and use it instead of YourActivity.this

//in you Activity class

final Activity a_this = this;

then you need to pass a_this to your fragment, and use it instead of YourActivity.this:

intent = new Intent(a_this, SomeActivity.class);

If your fragment is nested in your activity, there will be no problem with passing a_this to fragment.

J K
  • 632
  • 7
  • 24
  • I upvoted your answer but it will be more helpfull if you describe code to change fragments on bases of selected item position. – Jaydip Kalkani Mar 15 '18 at 15:36
  • Dear JK, I have updated my question with answers you provided but still it does nothing when clicked on first item from listview. When I add implements OnClicklistener, It throws error with that class must be declared abstract. How do I solve it. ** I'm implementing the solution inside fragment not in activity. – BlueYeti81 Mar 15 '18 at 16:03
  • still no help...listview is inside my fragments.....and with your solution ( which I've edited and added in my question" doesn't do anything when clicked. – BlueYeti81 Mar 15 '18 at 16:18
  • first of all try by putting toast there and make sure onclicklistener is working or not and then proceed furthur @BlueYeti81 – Jaydip Kalkani Mar 15 '18 at 16:19
  • @BlueYeti81 There was nothing about fragment in tutorial you followed. What are you using this fragment for? Can you please post it's code? – J K Mar 15 '18 at 16:20
  • @JK I have mainactivity where I'm adding 4-5 fragments inside container. I'm using above fragment to open another fragment when clicked. So when first Item is clicked i.e India then it will open fragment called India and when second Item clicked Pakistan it will open fragment pakistan and so on....hope I make myself clear. And above I have posted the whole code of fragment which I have modified to use for fragment as on give tutorial it is for mainactivity. I don't which code you are asking for?? – BlueYeti81 Mar 15 '18 at 16:24
  • @BlueYeti81 `Fragment fragment = new notices();` `notices`? And I mean what do you except when list item is clicked. You said to open a fragment, but I mean what you are excepting to see on screen. You want to display some more information about the country when clicked, or something like this? – J K Mar 15 '18 at 16:30
  • @JaydipKalkani, yes jaydip I did as you have suggested for me to..but it also don't display the Toast either....the final code I have edited and posted in my question..can you please help me here?? – BlueYeti81 Mar 15 '18 at 16:30
  • @JK, I am sorry for misunderstanding...I have a fragment named notices. So when India is clicked I would like to open fragment called notices where It contains Textview and few Images. – BlueYeti81 Mar 15 '18 at 16:32
  • when you clicked the item it shows what? It's showing any error? app is crashing? or nothing happens? If nothing happens then try to debug your app and determine problem is in which line. @BlueYeti81 – Jaydip Kalkani Mar 15 '18 at 16:35
  • @JaydipKalkani neither the app crash or shows any error.....I think problem is on implementing on Onclicklistener....can't we use switch and case instead of solution provided by JK......I think that may solves the problem??? Similar approach is here https://www.android-examples.com/open-new-activity-on-clicking-child-element-in-expandablelistview/ and yes I want the same approach to open new fragment/activity when each item is clicked from listview items. – BlueYeti81 Mar 15 '18 at 16:37
  • @BlueYeti81 Ok... Couldn't you do it by activity instead of fragment? Can you post a screenshot of what you want to do? (You can draw it in Paint or something... just to let us know what you are exactly excepting to see, because I am not sure if I understand you correctly, and if I am, it could be made much easier by activity instead of fragment) – J K Mar 15 '18 at 16:37
  • @BlueYeti81 In reply to your last comment. If it's not working by if, it won't work by switch. – J K Mar 15 '18 at 16:38
  • yes, JK is right and in addition there is no other way then OnItemClickListener to detect click on list item so you have to implement OnItemClickListener.@BlueYeti81 – Jaydip Kalkani Mar 15 '18 at 16:40
  • @JK Similar approach is here android-examples.com/… and yes I want the same approach to open new fragment/activity when each item is clicked from listview items from above. let me edit my question and I hope it would make it more clear. – BlueYeti81 Mar 15 '18 at 16:40
  • you should give a try to [this](https://stackoverflow.com/a/10295659/7804719) and at starting i suggest you to put just a toast inside listener and if it work then go ahead and implement your logic. @BlueYeti81 – Jaydip Kalkani Mar 15 '18 at 16:42
  • @BlueYeti81 I'm pretty sure that my code is correct, because it's copied from working app that is doing the same as you want to do. Can you use an activity instead of `notices` fragment? – J K Mar 15 '18 at 16:44
  • @JK I have added image of what I exactly want to get, hope it'll helps – BlueYeti81 Mar 15 '18 at 16:49
  • @JaydipKalkan I have added image of what I exactly want to get, hope it'll helps – BlueYeti81 Mar 15 '18 at 16:49
  • @BlueYeti81 Ok, I think you can use Activity (instead of fragment) to do this. It would be much easier. I've made a very similar app that is working and is using activity, not fragment. I'm not saying it's impossible with fragment, just giving a suggestion that using activity would be easier in this case – J K Mar 15 '18 at 16:52
  • I understood what exactly you want but i think you are making any mistake in implementing onitemclicklistener. i am not saying that JK gives wrong solution but i think there is a possibility of mistake from your side @BlueYeti81 so, please double check your code and even if it doesn't work then try [this](https://stackoverflow.com/a/10295659/7804719). It's different method to implement same thing. May be it will help you. – Jaydip Kalkani Mar 15 '18 at 16:52
  • @JK Yes, you are right but it also can be achieved by fragment also. I think there is no need to use activity instead of fragment. i think there is another mistake in implementing click listener. – Jaydip Kalkani Mar 15 '18 at 16:54
  • @JaydipKalkani, I thought solution was too easy..but I'm getting sense that it is not...well till now nothing has worked....I'll create a new thread..instead...anyway thanks. – BlueYeti81 Mar 15 '18 at 16:59
  • @BlueYeti81 to decite use fragment or activity see this: https://developer.android.com/guide/components/fragments.html#Design – J K Mar 15 '18 at 17:00
0

Here is the working solution,

I added

 listView.setOnItemClickListener(itemClickListener);

above return view;

The complete code is

package com.nepalpolice.cdp;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * Created by Sagar on 2017/09/23.
 */


public class club extends Fragment  {
    // Array of strings storing country names
    String[] countries = new String[]{
            "India",
            "Pakistan",
            "Sri Lanka",
            "China",
            "Bangladesh",
            "Nepal",
            "Afghanistan",
            "North Korea",
            "South Korea",
            "Japan"
    };

    // Array of integers points to images stored in /res/drawable-ldpi/
    int[] flags = new int[]{
            R.drawable.eka,
            R.drawable.kat,
            R.drawable.rat,
            R.drawable.set,
            R.drawable.ann,
            R.drawable.kar,
            R.drawable.suk,
            R.drawable.sap,
            R.drawable.him,
            R.drawable.gor
    };

    // Array of strings to store currencies
    String[] currency = new String[]{
            "Indian Rupee",
            "Pakistani Rupee",
            "Sri Lankan Rupee",
            "Renminbi",
            "Bangladeshi Taka",
            "Nepalese Rupee",
            "Afghani",
            "North Korean Won",
            "South Korean Won",
            "Japanese Yen"
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_club, container, false);
// Each row in the list stores country name, currency and flag
        List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();

        for (int i = 0; i < 10; i++) {
            HashMap<String, String> hm = new HashMap<String, String>();
            hm.put("txt", "Country : " + countries[i]);
            hm.put("cur", "Currency : " + currency[i]);
            hm.put("flag", Integer.toString(flags[i]));
            aList.add(hm);
        }

        // Keys used in Hashmap
        String[] from = {"flag", "txt", "cur"};

        // Ids of views in listview_layout
        int[] to = {R.id.flag, R.id.txt, R.id.cur};

        // Instantiating an adapter to store each items
        // R.layout.listview_layout defines the layout of each item
        SimpleAdapter adapter = new SimpleAdapter(getActivity(), aList, R.layout.listview_layout, from, to);
        // Getting a reference to listview of main.xml layout file
        ListView listView = (ListView) view.findViewById(R.id.listview);
        // Setting the adapter to the listView
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(itemClickListener);
        return view;
    }

// Setting the adapter to the listView


    // Item Click Listener for the listview
    OnItemClickListener itemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
            // Getting the Container Layout of the ListView
            if(position == 1/*or any other position*/){
                Fragment fragment = new notices();
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction().replace(R.id.fragment_frame, fragment).addToBackStack(null).commit();
            }
            else if(position == 2){


            } // etc...
        }
    };
}
BlueYeti81
  • 67
  • 10