I am getting Null Pointer Exception in GridView Android - java

I am getting null pointer exception in fragment using Gridview.
My code is
public class HomeFragment extends Fragment {
GridView grid;
String[] web = { "Bata", "Service", "puma", "Hush" };
int[] imageId = { R.drawable.shoesmall, R.drawable.shoe1, R.drawable.shoe3,
R.drawable.shoe4 };
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
// ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_home, container);
CustomGrid adapter = new CustomGrid(getActivity().getApplicationContext(), web, imageId);
grid = (GridView) getView().findViewById(R.id.gridview);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity().getApplicationContext(),
"You Clicked at " + web[+position], Toast.LENGTH_SHORT)
.show();
}
});
return rootView;
}
}
Can anyone guide why it is happing? I don't use fragments commonly.

your getView() is null,because view not yet created,So change
grid = (GridView) getView().findViewById(R.id.gridview);
to
grid = (GridView) rootView.findViewById(R.id.gridview);

Related

Android Passing String from fragment to fragment

I have two fragments ListNav and SwipeNav in Navigation Drawer. ListNav shows list view of data from String array. SwipeNav shows data as swipe views of the same data from string array.
I am using single fragment for viewpager swipe views multiple tabs.
My problem is :
When I click on B in List View, it shows A in SwipeNav,
When I click on C in List View, it shows A in SwipeNav,
When I click on D in List View, it shows A in SwipeNav,
When I click on E in List View, it shows A in SwipeNav,
I want to get result:
If I click on B in List View, it will show B in SwipeNav,
If I click on C in List View, it will show C in SwipeNav,
If I click on D in List View, it will show D in SwipeNav
String Array:
<string-array name="tab_titles">
<item>A</item>
<item>B</item>
<item>C</item>
<item>D</item>
<item>E</item>
<item>F</item>
<item>G</item>
<item>H</item>
<item>I</item>
........
</string-array>
I ListNav I use below to replace to SwipeNav with OnItemClickListener:
ListNav:
public class ListNav extends Fragment {
#Nullable
#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
return inflater.inflate(R.layout.nav_lis_layout, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
FragmentManager fm=getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment12, new ListNavAdapter());
ft.commit();
ListNavAdapter:
public class ListNavAdapter extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.nav_list_layout, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.tab_titles, android.R.layout.simple_list_item_1);
setListAdapter(adapter);
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String[] tabTitlesArray = getContext().getResources().getStringArray(R.array.tab_titles);
Bundle bundle = new Bundle();
bundle.putString("tab_titles", tabTitlesArray[i].toString());
SwipeNav fragobj = new SwipeNav();
fragobj.setArguments(bundle);
FragmentManager fm=getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(((ViewGroup)(getView().getParent())).getId(), fragobj);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
});
}
In SwipeNav:
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
if (getArguments() != null && !getArguments().isEmpty()) {
Bundle bundle = this.getArguments();
String myInt = bundle.getString("tab_titles");
}
return inflater.inflate(R.layout.nav_swipe, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
myPagerAdapter = new MyPagerAdapter(getChildFragmentManager(),getContext());
viewPager = (ViewPager) view.findViewById(R.id.pager);
viewPager.setAdapter(myPagerAdapter);
}
This is MyPagerAdapter:
public class MyPagerAdapter extends FragmentStatePagerAdapter {
private Context context;
private String[] tabTitlesArray = null;
public MyPagerAdapter(FragmentManager fm, Context context) {
super(fm);
tabTitlesArray = context.getResources().getStringArray(R.array.tab_titles);
this.context= context;
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new AFragment();
Bundle args = new Bundle();
args.putString(AFragment.ARG_OBJECT, tabTitlesArray[i]);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return tabTitlesArray.length;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
Single fragment for tabbed activity AFragment:
public class AFragment extends Fragment {
public static final String ARG_OBJECT = "object";
public AFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated
// properly.
View rootView = inflater.inflate(R.layout.fragment_a, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(R.id.text1)).setText(args.getString(ARG_OBJECT));
return rootView;
}
nav_lis_layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment12"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
nav_list_layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
I searched all answers in Stackoverflow. But fail to solve my problem why particular item click not showing same item to the next fragment.
I need your help plz.
you should not put into string commas
"tabTitlesArray[i]"
try with
""+tabTitlesArray[i]
When I click on B in List View, it shows A in SwipeNav,
The problem is because you are sending the same object but with different keys.
What you have to do is, in your onClick get the position of your adapter and put it to your bundle
bundle.putString("tab_titles", tabTitlesArray[i].toString());
Then you get the value using String myString = bundle.getString("tab_titles");
And then when you create the adapter, you can send the String via parameter and put the text in your adapter, anyways the code is a mess... It's very hard to understand.
In your SwipeNav, after you setup the ViewPager, you have not use viewPager.setCurrentItem() to change to your desired page. Since setCurrentItem() needs an integer argument, so the clicked position in the list needs to pass from ListNavAdapter to SwipeNav.
ListNavAdapter.java:
public class ListNavAdapter extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.nav_list_layout, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.tab_titles, android.R.layout.simple_list_item_1);
setListAdapter(adapter);
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//Toast.makeText(getActivity(), "Item: " + (i +1), Toast.LENGTH_SHORT).show();
String[] tabTitlesArray = getContext().getResources().getStringArray(R.array.tab_titles);
Bundle bundle = new Bundle();
bundle.putString("tab_titles", tabTitlesArray[i].toString());
bundle.putInt("tab_int", i); //Added
// set Fragmentclass Arguments
SwipeNav fragobj = new SwipeNav();
fragobj.setArguments(bundle);
FragmentManager fm=getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(((ViewGroup)(getView().getParent())).getId(), fragobj);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
//Fragment f=getFragmentManager().findFragmentById(R.id.fragment12);
// if(f==null){
// getFragmentManager().beginTransaction().replace(((ViewGroup)(getView().getParent())).getId(), new SwipeNav()).commit();
// }
}
});
}
// Toast.makeText(getActivity(), "Item: " + (position +1), Toast.LENGTH_SHORT).show();
// Create new fragment and transaction
}
SwipeNav.java:
public class SwipeNav extends Fragment {
private MyPagerAdapter myPagerAdapter;
private ViewPager viewPager;
private int tab_int; //Added
#Nullable
#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
//String passingString = getArguments().getString("TAG");
if (getArguments() != null && !getArguments().isEmpty()) {
Bundle bundle = this.getArguments();
String myInt = bundle.getString("tab_titles");
tab_int = bundle.getInt("tab_int"); //Added
return inflater.inflate(R.layout.nav_swipe, container, false);
} else {
return inflater.inflate(R.layout.nav_swipe, container, false);
}
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
myPagerAdapter = new MyPagerAdapter(getChildFragmentManager(),getContext());
viewPager = (ViewPager) view.findViewById(R.id.pager);
//viewPager.setId( R.id.pager );
viewPager.setAdapter(myPagerAdapter);
viewPager.setCurrentItem(tab_int); //Added
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("Satyanusaran Bengali");
}
}
Hope that helps!

Trying to call a function in a Fragment from a different class

I need to call a function in my portfolioActivity Fragment which comes from the class portfolioListAdapter.
It says my parameters are incorrect.
This function works just fine when I'm not using a Fragment, but as I am linking my Fragment to a navigation drawer, it is necessary to keep it this way.
Here is my Fragment:
public class portfolioActivity extends Fragment {
ListView portfolioList;
String[] stockTicker={"AAPL", "GOOG", "MSFT"};
double[] stockPrice={138.96, 830.63, 64.01};
int[] shares={5, 2, 10};
double[] percentChange={0.59, 0.55, 1.43};
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.portfolio_layout, container, false);
portfolioList = (ListView) getView().findViewById(R.id.portfolioListView);
//ADAPTER
ListAdapter adapter = new portfolioListAdapter(this, stockTicker, stockPrice, shares, percentChange);
portfolioList.setAdapter(adapter);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Portfolio");
}
}
The error comes when I try to call portfolioListAdapter().
It says there is a problem with the "this" parameter.
Here is my other class:
public class portfolioListAdapter extends ArrayAdapter<String> {
//DECLARATIONS
String[] stockTicker={};
double[] stockPrice={};
int[] shares={};
double[] percentChange={};
Context c;
LayoutInflater inflater;
public portfolioListAdapter(Context context, String[] stockTicker,
double[] stockPrice, int[] shares, double[] percentChange) {
super(context, R.layout.portfolio_row_model, stockTicker);
this.c=context;
this.stockTicker=stockTicker;
this.stockPrice=stockPrice;
this.shares=shares;
this.percentChange=percentChange;
}
public class ViewHolder
{
TextView stockTicker;
TextView stockPrice;
TextView shares;
TextView totalValue;
TextView percentChange;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null)
{
inflater=(LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.portfolio_row_model, null);
}
// OUR VIEWHOLDER OBJECT
final ViewHolder holder = new ViewHolder();
//INITIALIZE VIEWS
holder.stockTicker= (TextView) convertView.findViewById(R.id.list_portfolio_ticker);
holder.stockPrice= (TextView) convertView.findViewById(R.id.list_portfolio_price);
holder.shares= (TextView) convertView.findViewById(R.id.list_portfolio_shares);
holder.totalValue= (TextView) convertView.findViewById(R.id.list_portfolio_value);
holder.percentChange= (TextView) convertView.findViewById(R.id.list_portfolio_change);
//ASSIGN VIEWS
holder.stockTicker.setText(stockTicker[position]);
holder.stockPrice.setText(String.valueOf("$"+stockPrice[position]));
holder.shares.setText(String.valueOf(shares[position]));
holder.totalValue.setText(String.valueOf("$"+(stockPrice[position]*shares[position])));
holder.percentChange.setText(String.valueOf(percentChange[position]+"%"));
//return super.getView(position, convertView, parent);
return convertView;
}
}
You can't put code after return.
And your parameters are wrong. this is a Fragment, not a Context, you need to use getActivity() or (preferably) onAttach there.
private ListView portfolioList;
private PortfolioListAdapter adapter;
#Override
public void onAttach(Context context) {
super.onAttach(activity);
( (Activity) context).setTitle("Portfolio");
adapter = new PortfolioListAdapter(context, stockTicker, stockPrice, shares, percentChange);
portfolioList.setAdapter(adapter);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.portfolio_layout, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
portfolioList = (ListView) view.findViewById(R.id.portfolioListView);
}
Note: You also are not using the ViewHolder correctly.
Might want to read back over how to do that (or use a RecyclerView)
1) Can't put code after return.
2) Constructor for adapter is expecting a "Context" object. What you are passing is a fragment object(this)
Add this code fragment
private Context mContext;
#Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = context;
}
And in call to adapter pass mContext instead of this.

Error when show data to recycler view in fragment

I have an problem when show data in fragment. I send data from another activity to fragment and show it but it's show. Here is my code.
Function in activity:
public void sendResultRoundtripDomestic(ArrayList<ItemSearch> listOutbound, ArrayList<ItemSearch> listInbound) {
listItemOutbound = ListItem.createSearchOnewayDomesticResult(listOutbound);
outboundFragment = new OutboundFragment(listItemOutbound, 0);
listItemInbound = ListItem.createSearchOnewayDomesticResult(listInbound);
inboundFragment = new InboundFragment(listItemInbound, 1);
setupViewPager(viewPager);
}
And here is my fragment I want to show
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rv = inflater.inflate(R.layout.fragment_outbound, container, false);
rvResultOutbound = (RecyclerView) rv.findViewById(R.id.roundtrip_outbound);
adapterOutbound = new OnewayAdapter(rv.getContext(), list);
rvResultOutbound.setAdapter(adapterOutbound);
rvResultOutbound.setLayoutManager(new LinearLayoutManager(rv.getContext(), LinearLayoutManager.VERTICAL, false));
return rv;
}
public OutboundFragment(ArrayList<ListItem> list, int position) {
this.list = list;
this.position = position;
}
Can you help me fix this?

IllegalArgumentException: No view found for id for fragment

This exception is being thrown:
Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f0e006b (com.example.simplegamer003.sunshine.app:id/container) for fragment MainActivityFragment{37dff01 #1 id=0x7f0e006b FFTAG}
Code causing the exception:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
mForecastAdapter = new ForecastAdapter(getActivity(), null, 0);
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_forecast);
listView.setAdapter(mForecastAdapter);
// We'll call our MainActivity
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// CursorAdapter returns a cursor at the correct position for getItem(), or null
// if it cannot seek to that position.
Cursor cursor = (Cursor) adapterView.getItemAtPosition(position);
if (cursor != null) {
String locationSetting = Utility.getPreferredLocation(getActivity());
Intent intent = new Intent(getActivity(), DetailActivity.class)
.setData(WeatherContract.WeatherEntry.buildWeatherLocationWithDate(
locationSetting, cursor.getLong(COL_WEATHER_DATE)
));
startActivity(intent);
}
}
});
return rootView;
}
try this : View rootView = inflater.inflate(R.layout.fragment_main, null, false);instead of View rootView = inflater.inflate(R.layout.fragment_main, container, false); I think container is null. hope it helps you

setBackgroundResource on ImageView return null

I'm using ListFragment in my android project. I decided to make a listView, each listview item consist of music frequency imageView. I will try to animate the imageView of music frequency. Each listView has a button called play, once the play is clicked, the music frequency start to animate.
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragmentmusiclist, container, false);
lv = (ListView) v.findViewById(R.id.list);
mp = new MediaPlayer();
mp = null;
Song s1 = new Song("Love Story",(float) 2.5, onMusicPlayListener);
Song s2 = new Song("Sad Story",(float) 1.0, onMusicPlayListener);
Song s3 = new Song("Breakup Story",(float) 3.5, onMusicPlayListener);
songs = new ArrayList<Song>();
songs.add(s1);
songs.add(s2);
songs.add(s3);
adapter = new MusicListAdapter(getActivity(),songs);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
OnClickListener onMusicPlayListener = new OnClickListener() {
#Override
public void onClick(View v) {
final int position = getListView().getPositionForView((LinearLayout)v.getParent());
animMusicFreq = (ImageView) v.findViewById(R.id.music_anim);
animMusicFreq.setBackgroundResource(R.anim.anim_music);
animMusicFreq.post(new Runnable() {
#Override
public void run() {
AnimationDrawable frameAnimation =
(AnimationDrawable) animMusicFreq.getBackground();
frameAnimation.start();
}
});
You are inflating your view inside onCreateView, but you don't pass it to the system. Instead you tell it to inflate its own (you return super). It doesn't make any sense.
You should return your v view like so:
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragmentmusiclist, container, false);
// ...
return v;
}

Categories

Resources