How to solve undefined getactivity in android application? - android

I have this piece of code I want to show this dummy data in a static list but I get error in extends fragment and also in get activity, how can I solve them? Do I need to change any part of it?
public class AgendaFragment extends Fragment{
private ArrayAdapter<String> magendaAdapter;
public AgendaFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String[] data = {
"Monday going to restaurant at 14",
"Monday going to restaurant at 1",
"Monday going to restaurant at 1",
};
List<String> weekForecast = new ArrayList<String>(Arrays.asList(data));
magendaAdapter =
new ArrayAdapter<String>(
getActivity(), // The current context (this activity)
R.layout.list_item_agenda, // The name of the layout ID.
R.id.list_item_agenda_textview, // The ID of the textview to populate.
weekForecast);
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// Get a reference to the ListView, and attach this adapter to it.
ListView listView = (ListView) rootView.findViewById(R.id.listview_agenda);
listView.setAdapter(magendaAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
String forecast = magendaAdapter.getItem(position);
Toast.makeText(getActivity(), forecast, Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
}

Add
import android.app.Fragment;
at the beginning of your code file.
(or android.support.v4.app.Fragment if you are using Android support library)

Related

OnItemClickListener and OnClickListener not working for ListView using BaseAdapter

Here is my code which is not working
I'm getting data from server using `AsyncTask` and set data to the `listview` using `baseadapter` but using `convertview.setonclicklistner` working in adapter class and below code contains in `Fragmentclass(import android.support.v4.app.Fragment;)` so I think it is not problematic
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view= inflater.inflate(R.layout.fragment_restaurants, container, false);
restaurant_list = (ListView)view.findViewById(R.id.restatrant_lv);
no_restaturants=(TextView)view.findViewById(R.id.no_restaturants);
// listening to single list item on click
restaurant_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.e("temp","temppppp");
}
});
//set layout slide listener
rowItems = new ArrayList<>();
history_list = new ArrayList<HashMap<String, String>>();
list_adapter = new ViewAdapter(getActivity(),rowItems);
restaurant_list.setAdapter(list_adapter);
}
What is the solution for this ?
add id to your parent layout for custom_list_item.xml
holder.parentLayout.setOnClickListener(new OnClickItem(position));
private class OnClickItem implements View.OnClickListener{
private int mPostion;
public OnClickItem(int position){
mPostion = position;
}
#Override
public void onClick(View v) {
YourActivity yourActivity = (YourActivity) mContext;
yourActivity.onItemClicked(mPostion);
}
}
android:descendantFocusability="blocksDescendants"
If any ListView contains focusable or clickable view then OnItemClickListener won't work. In that case we need to use this.
Try to set your setOnClickListener after setting the adapter:
Like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view= inflater.inflate(R.layout.fragment_restaurants, container, false);
restaurant_list = (ListView)view.findViewById(R.id.restatrant_lv);
no_restaturants=(TextView)view.findViewById(R.id.no_restaturants);
//set layout slide listener
rowItems = new ArrayList<>();
history_list = new ArrayList<HashMap<String, String>>();
list_adapter = new ViewAdapter(getActivity(),rowItems);
restaurant_list.setAdapter(list_adapter);
// listening to single list item on click
restaurant_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.e("temp","temppppp");
}
});
}

How to display detailed view activity inside Fragment on image button click

I am moving my code from Activity to use it under Fragment view. The grid has multiple images which gets successfully displayed inside the fragment.I am trying to display detailed view based on the image clicked. But I am unable to get to do this, tried different ways but resulting one or other error.Earlier I used to have setContentView which does not seem to work when used for Fragment. I am already inflating the Fragment under OnCreateView method but not sure how load with the detailed view upon the image click.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
int iconSize=getResources().getDimensionPixelSize(android.R.dimen.app_icon_size);
CustomGrid adapter = new CustomGrid(view.getContext(), iconSize);
GridView gridview = (GridView) view.findViewById(R.id.grid);
gridview.setAdapter(adapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(view.getContext(), "You Clicked at " +web[+ position], Toast.LENGTH_SHORT).show();
//setContentView(R.layout.list_item_main);
mListView = (ListView) view.findViewById(R.id.item_list_view);
Item.getRecipesFromDB(OneFragment.this, DBReference);
}
});
return view;
}
#Override
public void newDataReceived(ArrayList<Item> itemList) {
ItemAdapter adapter = new ItemAdapter(mListView.getContext(), itemList);
mListView.setAdapter(adapter);
}
Open a new Fragment when a gridView is clicked and then pass the position from the bundle parameters. Then in NewFragment show the listview and the data from database.
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
NextFragment nextFrag= new NextFragment();
Bundle bundle = new Bundle();
bundle.putInt("POSITION",position);
this.getFragmentManager().beginTransaction()
.replace(R.id.Layout_container, nextFrag,TAG_FRAGMENT)
.addToBackStack(null)
.commit();
}
});
In the NextFragment get the reference of listView and then update the data from database using proper adapter.

Sending Data from One fragment to another

I have 2 fragment hosted on an activity with a frame layout, I want to implement fragment communication.I have tried some of the codes, but my requirements are not met. Thanks in advance.!
First fragment: It contains a list .
public class ListWithSearch extends Fragment{
String[] cityName;
String[] cityFact;
int[] cityPic;
ListView list;
ListViewAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.city_list_fragment, container,
false);
// Generate sample data
cityName = new String[] { "Delhi", "Chandigarh", "Mumbai", "Bangalore", "Chennai" };
cityFact = new String[] { "China", "India", "United States",
"Indonesia", "Brazil" };
cityPic = new int[] { R.drawable.ic_launcher, R.drawable.ic_launcher,
R.drawable.ic_launcher, R.drawable.ic_launcher,
R.drawable.ic_launcher };
list = (ListView) rootView.findViewById(R.id.listView);
adapter = new ListViewAdapter(getActivity(), cityName,cityPic);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//To implement
}
});
return rootView;
}
}
Second Fragment: That will be inflated on item click of the list in the first fragment.
public class ResultFragment extends Fragment {
TextView resCityName;
TextView resFact;
ImageView resPic;
String[] cityName;
String[] cityFact;
int[] cityPic;
int position;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
}
Requirements:
1. ImageView in second fragment to have the same image of the item image in the list.
2. TextViews in second fragment to have data from the list item itself.
In other words, the second fragment is details of the item clicked in the list.
Add the below code to ListWithSearch fragment:
OnListItemSelectListener mCallback;
// Your MainActivity must implement this interface so that ResultFragment can use it
public interface OnListItemSelectListener {
public void onItemSelected(int position, int imageId);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnListItemSelectListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnListItemSelectListener");
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Send the event to the host activity
// You can pass the image id to below method. Modify the code as required.
mCallback.onItemSelected(position, imageId);
}
Google provide a great tutorial for this situation here
There plenty of ways to achieve this but take a look on EventBus, it might simplify the job

Best way to fill a list with an adapter in a fragment

I developed an app which fills a list. It works fine in the way I did it but I'm not conviced that I solved the problem in a recommended way. I read that you should override onActivityCreated in a Fragment and fill the list there instead of doing this in onCreateView. onCreateView should only be used to inflate static views. Is this true? If yes, how should these two methods look like in the end?
This is my Fragment class:
public class FragmentMain extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
List<MyItem> items = createListItems();
ListView listView = (ListView) view.findViewById(R.id.list);
MyListAdapter adapter = new MyListAdapter(view.getContext(), items);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(view.getContext(),
"Clicked " + position, Toast.LENGTH_LONG)
.show();
}
});
return view;
}
.
.
.
}
My MainActivity just adds the fragment:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentMain fm = new FragmentMain();
getFragmentManager().beginTransaction()
.add(R.id.fragment_main_container, fm).commit();
}
.
.
.
}
That is true to a certain extend only because onCreateView happens on the UI thread and you don't want anything slowing that down otherwise your UI will be slow and choppy. For example, in your fragment class you have a call to a method "createListItems()". I don't know how many items you're making but if it's a lot it could slow down your UI (especially if youre accessing a database and querying objects and so on). So you could do it in onActivityCreated but you could also use an AsyncTask. So your code would become something like this:
public class LoadListObjectsTask extend AsyncTask<Void, List<MyItem>, Void> {
private MyListAdapter myListAdapter;
private Context mContext;
public LoadListObjectsTask(Context context) {
this.mContext = context;
}
#Override
public void doInBackground(Void...params) {
//create your list objects here instead of on UI thread. This will run on a separate thread.
myListAdapter = new MyListAdapter(mContext, items);
return items; //return list of MyItems
}
//This is called when doInBackground is done. THIS WILL RUN ON THE UI THREAD So don't do
//anything slow here
#Override
public void onPostExecute(List<MyItem>...params //don't really need the list here//) {
listView.setAdapter(myListAdapter);
}
}
then in your fragment
public class FragmentMain extends Fragment {
private ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
List<MyItem> items = new ArrayList<MyItem>();
listView = (ListView) view.findViewById(R.id.list);
//new code
new LoadListObjectsTask(getActivity()).execute();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(view.getContext(),
"Clicked " + position, Toast.LENGTH_LONG)
.show();
}
});
return view;
}
public void onResume()... {
//also add the task here so your content is reloaded on resume..
new LoadListObjectsTask(getActivity()).execute();
}
.
.
.
}
If you don't want to do this just make your List of MyItems a private field and move
List<MyItem> items = createListItems();
to onActivityCreated().
Hope that helps!

setOnItemClickListener event doesn't work in Fragment

I am trying to get onItemClick on ListItems to work from a fragment. Here is my code:
public class MyBudgetPageMenuFragment extends Fragment {
private Context context;
private ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.my_budget_listview,
container, false);
ListView listView = (ListView) myFragmentView
.findViewById(android.R.id.list);
context = this.getActivity().getApplicationContext();
String[] values = new String[4];
ListAdapter adapter = new ListAdapter(context, values);
listView.setAdapter(adapter);
listView.setOnItemClickListener( new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
selectItem(position);
}
});
return myFragmentView;
}
private void selectItem(int position) {
FragmentManager fragmentManager = getFragmentManager();
Fragment fragment;
switch (position) {
case 0:
fragment = new MyBudgetPageFragments();
fragmentManager.beginTransaction()
.replace(R.id.listFragment, fragment).commit();
break;
default:
String message1 = Integer.toString(position);
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setMessage("Position: " + message1);
alertDialog.show();
break;
}
}
}
But every time when I select an item, it isn't doing anything or throwing any exceptions. It seems that the event doesn't get registered. I debuged the code and it doesn't enter my event.
Can someoane tell me what I'm doing wrong?
Note that the ListView blocks clicks of an item that contains at least one focusable
descendant but it doesn’t make the content focus-reachable calling
setItemsCanFocus(true). One workaround is by disabling focusability of descendants, using
android:descendantFocusability="blocksDescendants"
in the layout defining your list item. (First learned of this myself from http://cyrilmottier.com/2011/11/23/listview-tips-tricks-4-add-several-clickable-areas/) Does your layout contain buttons? If so, you'd fall into this case.
Just go the simple way.
In your Adapter class, between getView method, initialize View v = convertView; then
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "test "+ list.get(position).getS_name(), Toast.LENGTH_SHORT).show();
}
});

Categories

Resources