If I have a listview inside a fragment, it has a custom layout, an array adapter, a fragment class and an array class.
If I want to open a link when clicking a list contained in the listview, how and where do I put the code?
I have tried the following code that I put in the fragment class, but when I try to click on the available list, my application force closes. Is my code wrong?
list_fish_easy.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent linkEasy = new Intent(Intent.ACTION_VIEW, Uri.parse(String.valueOf(arrayListeasy)));
startActivity(linkEasy);
}
});
What I want is that I can open the link contained in the arraylist like the following
public class Fish extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fish_layout, container, false);
ListView list_fish_easy = (ListView) view.findViewById(R.id.list_fish_easy);
final ArrayList<Animal> arrayListeasy= new ArrayList<>();
arrayListeasy.add(new Animal("Contoh Nama 1", "Easy", "Ominvore", "7.5", "30 C", "http://images.google.com/images?um=1&hl=en&safe=active&nfpr=1&q=cabomba_aquatica"));
arrayListeasy.add(new Animal("Contoh Nama 2", "Moderate", "Ominvore", "7.5", "30 C", "http://images.google.com/images?um=1&hl=en&safe=active&nfpr=1&q=cabomba_aquatica"));
arrayListeasy.add(new Animal("Contoh Nama 3", "Difficult", "Ominvore", "7.5", "30 C", "http://images.google.com/images?um=1&hl=en&safe=active&nfpr=1&q=cabomba_aquatica"));
final AnimalAdapter animalAdaptereasy = new AnimalAdapter(getContext(), R.layout.list_fish, arrayListeasy);
list_fish_easy.setAdapter(animalAdaptereasy);
list_fish_easy.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent linkEasy = new Intent(Intent.ACTION_VIEW, Uri.parse(String.valueOf(arrayListeasy)));
if(linkEasy.resolveActivity(requireContext().getPackageManager()) != null) {
startActivity(linkEasy);
}
}
});
return view;
}
}
I am very new to creating Android programs. Please help
You are trying to open url from whole arraylist
Intent linkEasy = new Intent(Intent.ACTION_VIEW, Uri.parse(String.valueOf(arrayListeasy)));
Uri.parse(String.valueOf(arrayListeasy)
You should get exact field with url from you arraylist
It will be something like
Uri.parse(String.valueOf(arrayListeasy.get(position).getYourUrlProperty());
whole code
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent linkEasy = new Intent(Intent.ACTION_VIEW, Uri.parse(String.valueOf(arrayListeasy.get(position).getYourUrlProperty());
if(linkEasy.resolveActivity(requireContext().getPackageManager()) != null) {
startActivity(linkEasy);
}
}
And also you can get rid of String.valueOf( logic
android.content.ActivityNotFoundException: No Activity found to handle Intent
Before staring activities of Implicit intents, you need to check whether the device has some component that can handle this intent or not (this is typically browsers in your case), otherwise you will get this exception.
To do that you can use intent.resolveActivity().
Intent linkEasy = new Intent(Intent.ACTION_VIEW, Uri.parse(String.valueOf(arrayListeasy)));
if(intent.resolveActivity(requireContext().getPackageManager()) != null) {
startActivity(linkEasy);
}
Related
I have an ListView which I have populate with a dynamic ArrayList and I used an OnItemClickListener to make it does something when i click on them (Code bellow).
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,txtOnlyList);
returnSaveNotesList.setAdapter(arrayAdapter);
AdapterView.OnItemClickListener noteClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> txtOnlyList, View view, int position, long id) {
if(position == 0 ) {
Intent intent = new Intent(ReadFromFile1.this, SaveAndRstoreNote.class);
intent.putExtra("firstNote","1 .txt");
startActivity(intent);
}
}
};
returnSaveNotesList.setOnItemClickListener(noteClickListener);
Now comes the tricky part, I want, somehow to be able to read what is actually written lets say on the position [0], the actual String. Is there any way to achieve that?
public void onItemClick(AdapterView<?> txtOnlyList, View view, int position, long id) {
if (position == 0) {
String yourString = txtOnlyList.get(position);// use this
Intent intent = new Intent(ReadFromFile1.this, SaveAndRstoreNote.class);
intent.putExtra("firstNote", "1 .txt");
startActivity(intent);
}
}
Your ArrayAdapter<String> has a getItem() method that returns the String for a given position.
I have used the getItemAtPosition(position).
Here is the entire code:
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,txtOnlyList);
returnSaveNotesList.setAdapter(arrayAdapter);
AdapterView.OnItemClickListener noteClickListener = new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> txtOnlyList, View view, int position, long id) {
if(position == 0 ){
Intent intent = new Intent(ReadFromFile1.this, SaveAndRstoreNote.class);
String stringFromArray=txtOnlyList.getItemAtPosition(position).toString(); // I added this
intent.putExtra("firstNote","1 .txt");
startActivity(intent);
}
}
};
returnSaveNotesList.setOnItemClickListener(noteClickListener);
The View type parameter being passed in your OnItemClick function is the list item's view at that position.
AdapterView.OnItemClickListener noteClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> txtOnlyList, View view, int position, long id) {
TextView tv = (TextView) view.findViewById(R.id.tv);
String text = tv.getText().toString(); //The required text is available in this variable
}
}
I have a listview and want to set an onClickListener on each item in this fragment but it's not working.I also wanted to set a contextMenu on the listview and that's not working either.
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
purchasedItemsView = inflater.inflate(R.layout.purchased_items_fragment , container, false);
db = new StoreDataBase(getActivity() , Consts.StoreDB.DB_NAME , Consts.StoreDB.DB_VERSION);
storeArrayList = new ArrayList<>();
listView = (ListView) purchasedItemsView.findViewById(R.id.storeListView);
adapter = new StoreListViewAdapter(getContext() , R.layout.store_item_row , storeArrayList);
listView.setAdapter(adapter);
adapter .notifyDataSetChanged();
registerForContextMenu(listView);
sendData(purchasedItemsView);
return purchasedItemsView;
}
private void sendData(View view){
Bundle bundle = getArguments();
if (bundle != null) {
final String[] names = bundle.getStringArray(Constc.Data.names);
listView = (ListView) view.findViewById(R.id.storeListView);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("Data" , "clicked");
}
});
}else{
}
}
Don't reinitialize listview after you have done it once in onCreateView(). Therefore, remove this line from sendData() method:
// remove this
listView = (ListView) view.findViewById(R.id.storeListView);
Then you need to move this part of code outside of if statement or inside of onCreateView() method.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("Data" , "clicked");
}
});
Point 1:
Seems your array list is empty, so fill some data
storeArrayList = new ArrayList<>();
//-------------------------------------
Bundle bundle = getArguments();
if (bundle != null) {
final String[] names = bundle.getStringArray(Constc.Data.names);
if(names != null && names.length() > 0) {
storeArrayList.addAll(names);
}
}
//-------------------------------------
listView = (ListView) purchasedItemsView.findViewById(R.id.storeListView);
adapter = new StoreListViewAdapter(getContext() , R.layout.store_item_row , storeArrayList);
listView.setAdapter(adapter);
Point 2: You don't need "notifyDataSetChanged();" right after you set the adapter.
//adapter .notifyDataSetChanged();
Point 3:
Use long click listener for showing context menu
listView.setOnItemLongClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("Data" , "long press clicked");
//show dialog or context menu dialog.
}
});
Point 4:
comment the sendData method and use the onclick directly
//sendData(purchasedItemsView);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("Data" , "clicked");
}
});
Hope this helps.
Vote Up - If you like it.
I'm Using Fabric kit of twitter to my android app , and I have a listview of tweets but whene I try to click on a tweet (item) to open a new activity ( that's shows the details of the tweet) but whene I click to the item , an app chooser apear automatically
It seems that the twitter-api already set an onItemClickListener so I'm asking if someone had already use Fabric kit I need help
ListView tweetLV = (ListView) root.findViewById(R.id.list_tweets);
adapter = new TweetViewAdapter<CompactTweetView>(getActivity());
tweetLV.setAdapter(adapter);
tweetLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String hashtag = adapter.getItem(i);
Intent intent = new Intent(getActivity(), DetailActivity.class)
.putExtra(Intent.EXTRA_TEXT, hashtag);
startActivity(intent);
}
});
As I suggest on this question you can try to create a custom adapter that overrides the default onClick behavior of tweet:
class CustomTweetTimelineListAdapter extends TweetTimelineListAdapter {
public CustomTweetTimelineListAdapter(Context context, Timeline<Tweet> timeline) {
super(context, timeline);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
//disable subviews to avoid links are clickable
if(view instanceof ViewGroup){
disableViewAndSubViews((ViewGroup) view);
}
//enable root view and attach custom listener
view.setEnabled(true);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO: implement your custom behavior when clicks
}
});
return view;
}
// see full example to find helper method disableViewAndSubViews
}
Full code example here
Hope it helps.
So I have two fragments linking to layout files which display ListViews. The ListViews are defined in the xml and have entries from a string array. I want to click on items in the ListView and open new activities. There are 8 items in one ListView and 9 in the other. In the onItemClick code, how do I create intents to start activities based on the item clicked? I will create 1 class per item as its own activity. How can I start the activities in the classes via intents inside the onItemClick methods of this code?
class CommunityFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.community_fragment, container, false);
ListView lv = (ListView) view.findViewById(R.id.communityListView);
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3){
// TODO Auto-generated method stub
}
});
return view;
}
}
class ResourcesFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.resources_fragment, container, false);
ListView lv = (ListView) view.findViewById(R.id.resourcesListView);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
});
return view;
}
}
Implement your OnItemClickListener() like below
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity(), nextactivity.class);
startActivity(intent);
}
});
Make switch statement for each items click and open activities accordingly as below:
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
int itm=arg0.getItemAtPosition(arg2);
switch (itm) {
case 0:
Toast.makeText(m_context, "Position Zero", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), FirstActivity.class);
startActivity(intent);
break;
case 1:
Intent intent1 = new Intent(getActivity(), SecondActivity.class);
startActivity(intent1);
break;
case 2:
//..............................
}
});
on Item Click you will get Position based on position you can start fragment
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG)
.show();
switch(position) {
case CONST_FRAGMENT_1 :
//Start fragment 1
...
...
}
}
});
one Generic solution can be ..
Create an array of items that hold class name of activity you want to open ..
like ..
Class[] activityArray = new Class[numberOfItemsInListView];
activityArray[0] = Activity1.class;
//add all activities like that..............
now on ListView onItemCLick :
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long arg3) {
Intent intent = new Intent(CommunityFragment.this.getActivity(), activityArray[postion]);
CommunityFragment.this.getActivity.startActivity(intent);
}
});
Use this to start next intent in your onItemClickListener:
Intent intent = new Intent(getActivity(), nextactivity.class);
startActivity(intent);
I think following code help you.
public class PdfListViewFragment extends Fragment {
ListView listView;
Activity rootView;
Activity context;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//returning our layout file
//change R.layout.yourlayoutfilename for each of your fragments
View rootView = inflater.inflate(R.layout.pdf_list_view, container, false);
context = getActivity();
// Get ListView object from xml
listView = (ListView) rootView.findViewById(R.id.list);
// Defined Array values to show in ListView
String[] values = new String[]{"Android List View",
"Adapter implementation",
"Simple List View In Android",
"Create List View Android",
"Android Example",
"List View Source Code",
"List View Array Adapter",
"Android Example List View"
};
// Define a new Adapter
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
// ListView Item Click Listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == 0) {
Intent myIntent = new Intent(view.getContext(), ListItemActivity1.class);
startActivityForResult(myIntent, 0);
}
if (position == 1) {
Intent myIntent = new Intent(view.getContext(), ListItemActivity2.class);
startActivityForResult(myIntent, 0);
}
if (position == 2) {
Intent myIntent = new Intent(view.getContext(), ListItemActivity1.class);
startActivityForResult(myIntent, 0);
}
if (position == 3) {
Intent myIntent = new Intent(view.getContext(), ListItemActivity2.class);
startActivityForResult(myIntent, 0);
}
if (position == 4) {
Intent myIntent = new Intent(view.getContext(), ListItemActivity1.class);
startActivityForResult(myIntent, 0);
}
if (position == 5) {
Intent myIntent = new Intent(view.getContext(), ListItemActivity2.class);
startActivityForResult(myIntent, 0);
}
if (position == 6) {
Intent myIntent = new Intent(view.getContext(), ListItemActivity1.class);
startActivityForResult(myIntent, 0);
}
if (position == 7) {
Intent myIntent = new Intent(view.getContext(), ListItemActivity2.class);
startActivityForResult(myIntent, 0);
}
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText(context.getApplicationContext(), "Position :" + itemPosition + " ListItem : " + itemValue, Toast.LENGTH_LONG).show();
}
});
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("XYZ");
}
}
If you use an adapter to display the items in a list, it is important to differentiate the following:
The ID of the list AdapterView#getId() is different than the ID of the items in the list ArrayAdapter<String>#getId(), because the view of the list contains the views of the elements.
Suppose an example where you are going to launch activities with user roles. You will have to do the transformation for your particular case.
public class SignInFragment extends Fragment implements AdapterView.OnItemClickListener {
//TODO: Declare constants (GUEST, HOST, EMPLOYEE...)
private ArrayAdapter<String> userRolesAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_sign_in, container, false);
// ListView Instance
ListView userRolesList = root.findViewById(R.id.user_roles_list);
String[] userRoles = {
GUEST,
HOST,
EMPLOYEE
};
// Initialize the adapter
userRolesAdapter = new ArrayAdapter<>(
getActivity(),
android.R.layout.simple_list_item_1,
userRoles
);
// Link to the list with the adapter. This reference starts the process of filling the list.
userRolesList.setAdapter(userRolesAdapter);
// Events
userRolesList.setOnItemClickListener(this);
return root;
}
/**
* #param adapterView: View using the adapter from the list
* #param view: View of the item that has been pressed
* #param i: Refers to the position of the item that the adapter handles
*/
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (adapterView.getId() == R.id.user_roles_list) {
// Obtain the item pressed on the adapter with the entry position
String currentUserRol = userRolesAdapter.getItem(i);
assert currentUserRol != null;
switch (currentUserRol) {
case GUEST:
startActivity(Host.class);
break;
case HOST:
startActivity(Host.class);
break;
case EMPLOYEE:
startActivity(Employee.class);
break;
default:
Log.d("Error", "The activity passed as an argument to startActivity() does not exist");
break;
}
}
}
/**
* PRECONDITION: The class given as an argument exists.
*/
public void startActivity(Class<?> cls) {
Intent intent = new Intent(getActivity(), cls);
startActivity(intent);
}
}
Best :)
I have created one listview of some names,what i need is when i will click selected row it will go to that page only,on click on different row it will move to the same class but different content.I think it will move by question id.could anybody help me how to pass the question id Or any other method to do this..
here is my code..
private OnItemClickListener mlist = new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
}
};
You can try something like this -
private OnItemClickListener mlist = new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
if(Some condition)
{
Intent i= new Intent(YourActivity.this,ActivityOne.class);
// To pass data
i.putExtra("SomeId", someValue);
startActivity(i);
}
else if(Some other condition)
{
Intent i= new Intent(YourActivity.this,SecondActivityTwo.class);
startActivity(i);
}
else
{
// Do something else--
}
}
};
And in the other activity -
String identifier = getIntent().getExtras().getString("SomeId");
Here I've given an example assuming you have user list and clicking on item you want to show user profile...
In List_Act activity...
public View getView(int position, View convertView, ViewGroup parent)
{
convertView = mInflater.inflate(R.layout.rowitem,parent,false);
convertView.setTag(UserId);
}
private OnItemClickListener mlist = new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Intent i=new Intent(List_Act.this, Profile_Act.class);
int UserId = ((View)v.getParent()).getTag();
i.putExtra("UserId", UserId); //Setting variable you want to pass to another activity
startActivity(i);
}
};
in Profile_Act activity in onCreate()
String UserId = getIntent().getExtras().getString("UserId"); //retrieving value in another activity
now you'll have UserId variable set and you can use it...