Nullpoint Exception on image gallery - imageview

I'm creating an image gallery application in Android but I gives me a null point exception at run-time. Please help me to correct it. Here is my code
I use Gallery and ImageSwitcher for XML design
I here when user click the gallery images move in animation on ImageSwitcher
public class MainActivity extends Activity implements ViewFactory,OnItemSelectedListener{
private ImageSwitcher mswitcher;
private Integer[] mThimId={R.drawable.fba,R.drawable.fbb,R.drawable.fbc,R.drawable.fbd,R.drawable.fbe,R.drawable.fbf,R.drawable.fbg,R.drawable.fbh,R.drawable.fbi,R.drawable.fbj};
private Integer[] mImageId={R.drawable.fba,R.drawable.fbb,R.drawable.fbc,R.drawable.fbd,R.drawable.fbe,R.drawable.fbf,R.drawable.fbg,R.drawable.fbh,R.drawable.fbi,R.drawable.fbj};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mswitcher=(ImageSwitcher)findViewById(R.id.imageSwitcher1);
mswitcher.setFactory(this);
mswitcher.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));
mswitcher.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
Gallery g=(Gallery) findViewById(R.id.gallery1);
g.setAdapter(new ImageAdapter(this));
g.setOnItemSelectedListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
mswitcher.setImageResource(mImageId[arg2]);
}
public class ImageAdapter extends BaseAdapter {
private Context mcontext;
public ImageAdapter(Context c) {
// TODO Auto-generated constructor stub
mcontext=c;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mThimId.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView i = new ImageView(mcontext);
i.setImageResource(mThimId[position]);
i.setAdjustViewBounds(true);
i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
return null;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
#Override
public View makeView() {
// TODO Auto-generated method stub
ImageView i = new ImageView(this);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
return null;
}
}
Here is my XML file code
<Gallery
android:id="#+id/gallery1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="48dp"
android:layout_marginTop="36dp" />
<ImageSwitcher
android:id="#+id/imageSwitcher1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="159dp"
android:layout_marginLeft="63dp" >
</ImageSwitcher>

You should be returning 'i' instead of null from the getView and makeView methods.

Related

Getting a Fragment inside a ViewPager in Android using getRegisteredFragment returns null

I've been searching a lot and I can't make it work.
I have a problem trying to get fragments inside a viewpager with a tabstrip.
I've implemented a SparseArray as I read here and several methods that I found here but I can't make it work.
The thing is that everytime I call adapter.getRegisteredFragment(position).. I always receive null unless I made it inside the onPageSelected event of the tabsStrip, there it works.. but I don't want to get the fragments there.
Those are my classes:
My fragment:
public class WeekFragment extends Fragment implements View.OnClickListener
{
private static final String ARG_POSITION = "position";
private int position;
private LinearLayout[] btns;
public static WeekFragment newInstance(int position) {
WeekFragment f = new WeekFragment();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt(ARG_POSITION);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
fillFragment();
}
private void fillFragment()
{
// Irrelevant stuff..
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance)
{
return inflater.inflate(R.layout.week_fragment, container, false);
}
#Override
public void onClick(View v)
{
// Irrelevant stuff
}
public LinearLayout[] getBtns()
{
return btns;
}
public void setBtns(LinearLayout[] btns)
{
this.btns = btns;
}
}
My adapter:
public class WeekAdapter extends FragmentPagerAdapter
{
Calendar cal;
Context context;
SparseArray<Fragment> registeredFragments;
private String[] TITLES = new String[6];
public WeekAdapter(FragmentManager fm, Context context)
{
super(fm);
registeredFragments = new SparseArray<>();
this.context = context;
fillTitles();
}
private void fillTitles()
{
// Fill titles
}
#Override
public CharSequence getPageTitle(int position)
{
return TITLES[position];
}
#Override
public int getCount()
{
return TITLES.length;
}
#Override
public Fragment getItem(int position)
{
return WeekFragment.newInstance(position);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
and my activity:
public class MyActivity extends FragmentActivity
{
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private WeekAdapter adapter;
private List<DayResumeItem> listDayResumesItems;
private User u;
private View mProgressView;
private View mRotaView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rota2);
mProgressView = findViewById(R.id.view_progress);
mRotaView = findViewById(R.id.view_rota);
this.u = this.getIntent().getExtras().getParcelable(getString(R.string.parcel_user));
// Initialize the ViewPager and set an adapter
pager = (ViewPager) findViewById(R.id.pager);
adapter = new WeekAdapter(getSupportFragmentManager(), getApplicationContext());
pager.setAdapter(adapter);
// Bind the tabs to the ViewPager
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabs.setViewPager(pager);
tabs.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
WeekFragment f = (WeekFragment)adapter.getRegisteredFragment(week);
// Do stuff.. Here, f is not null. Here I can work, but I don't want to.
}
#Override
public void onPageSelected(int position)
{
}
#Override
public void onPageScrollStateChanged(int state)
{
}
});
WeekFragment f = (WeekFragment)adapter.getRegisteredFragment(week);
// Do stuff.. Here, f is null and I can't work.
}
#Override
protected void onResume()
{
super.onResume();
getList();
}
}
It is everytime I call adapter.getRegisteredFragment(position) on my activity where it crash because it always return null..
I swear that I've been searching a lot but I'm unable to make it work.
Thank you very much everybody!
I think my problem was that I was calling this adapter.getRegisteredFragment(position) in the onCreate of my activity, and in the onCreate, the viewpager is still not fully loaded and the registeredFragments aren't still instantiated, so the list is still empty..
If you move this callings to another place when the viewpager is fully loaded, it will work.
The items in registeredFragments are initialized in instantiateItem() method, which should be called during the process of drawing views. And this drawing process happens after onCreate()/onResume().
I am not sure what stuff you want to do by getting Fragment in onCreate(), but generally it is not a good idea since the Fragment is not initialized at that moment. You should access the fragment in onPageSelected() as you said.

Data passing between multiple fragment and activity: send different data to activity from multiple fragments

I have two activities, MainActivity, SecondActivity. Main Activity has a button. When I press the button Second Activity starts. Second Activity has 2 fragments, FragmentA and FragmentB. Fragment A has a button (B also), and I want to pass a string from Fragment A or B to Main Activity by clicking the button (Closing second activity).
I have used some references to do my job - When I click the button of Fragment A, second activity closes and a string passed to Main activity. It works But When I click the button of Fragment B (doing the same code as for Fragment A), I got an error,
java.lang.ClassCastException: (packagename).SecondActivity cannot be cast to (packagename).FragmentB$OnDataPass
dataflow:
Fragment A (button click) >> Main Activity (text view) (works)
Fragment B (button click) >> Main Activity (text view) (does not work)
Here is my Fragment A code:
String data ="String from fragment A";
public interface OnDataPass {
public void onDataPass(String data);
}
OnDataPass dataPasser;
#Override
public void onAttach(Activity a) {
super.onAttach(a);
dataPasser = (OnDataPass) a;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view = inflater.inflate(R.layout.fragment_a, container, false);
btn = (Button) view.findViewById(R.id.btn1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
dataPasser.onDataPass(data);
getActivity().finish();
}
});
return view;
}
public void passData(String data) {
dataPasser.onDataPass(data);
}
Here is my Fragment B code:
String data ="String from fragment B";
public interface OnDataPass {
public void onDataPass(String data);
}
OnDataPass dataPasser;
#Override
public void onAttach(Activity a) {
super.onAttach(a);
dataPasser = (OnDataPass) a; // Exception occurs here
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view = inflater.inflate(R.layout.fragment_b, container, false);
btn = (Button) view.findViewById(R.id.btn1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
dataPasser.onDataPass(data);
getActivity().finish();
}
});
return view;
}
public void passData(String data) {
dataPasser.onDataPass(data);
}
My second Activity code:
public class SecondActivity extends FragmentActivity implements OnDataPass {
Button btn1,btn2;
TabHost tabHost;
String dt="";
ViewPager viewPager = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_help);
viewPager = (ViewPager) findViewById(R.id.pager);
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new MyAdapter(fragmentManager));
}
#Override
public void onDataPass(String data) {
// TODO Auto-generated method stub
Log.d("LOG::","hello " + data);
dt= data;
Intent intent = new Intent();
intent.putExtra("key", dt);
setResult(RESULT_OK, intent);
finish();
//startActivity(intent);
}
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int i) {
// TODO Auto-generated method stub
Fragment fragment=null;
if(i==0) {
fragment = new FragmentA();
}
if(i==1) {
fragment = new FragmentB();
}
return fragment;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
// TODO Auto-generated method stub
if(position == 0) {
return "Tab 1";
}
if(position == 1) {
return "Tab 2";
}
return null;
}
}
What would I need to do to this code to get the string in FragmentB to MainActivity?
Please post code.
You have declared the OnDataPass interface in both Fragment A and Fragment B and I suspect you implemented SecondActivity with OnDataPass interface of Fragment A which You have tried to cast in Fragment B resulted in the exception.
Solution :
Move OnDataPass interface to SecondActivity
Remove OnDataPass interface from Fragment A and Fragment B.
Everything should be fine.

onTouchEvent cannot #Override in fragment

The method onTouchEvent(MotionEvent) of type FindPeopleFragment must override or implement a supertype method.
Is there any way to fix it rather than removing the #Override as i suspect removing it is the cause that make the GestureDetector dont work.
public class FindPeopleFragment extends Fragment implements OnGestureListener{
private GestureDetector gDetector;
ImageView iv1;
public FindPeopleFragment(){}
#SuppressWarnings("deprecation")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_find_people, container, false);
gDetector = new GestureDetector(this);
iv1=(ImageView)rootView.findViewById(R.id.imageView1);
return rootView;
}
#Override
public boolean onTouchEvent(MotionEvent me) {
return gDetector.onTouchEvent(me);
}
#Override
public boolean onDown(MotionEvent arg0) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onFling(MotionEvent start, MotionEvent finish, float xVelocity, float yVelocity) {
if (start.getRawY() < finish.getRawY()) {
Log.i("fling", "if");
//((ImageView)findViewById(R.id.image_place_holder)).setImageResource(R.drawable.down);
//startActivity(new Intent(getActivity(),MainActivity.class));
} else {
Log.i("fling", "else");
//((ImageView)findViewById(R.id.image_place_holder)).setImageResource(R.drawable.up);
//startActivity(new Intent(getActivity(),Secc.class));
}
return true;
}
#Override
public void onLongPress(MotionEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
float arg3) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onShowPress(MotionEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean onSingleTapUp(MotionEvent arg0) {
// TODO Auto-generated method stub
return false;
}
}

Let fragment wait for asynctask finished?

I use fragments with viewPager. One of fragment use asynctask to download data. Now the problem is the task hasn't finish but fragment's onCreateView return already.
Can I update fragment while task finished? I tried to call view.invalidate() is not working.
public class LineChartFragment extends Fragment {
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
new Background().execute();
return view;
}
}
class Background extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
if (haveInternet()) {
getter();
}
return null;
}
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//UPDATE fragment
....
view = ChartFactory.getLineChartView(getActivity().getApplicationContext(), dataset, renderer);
....
view.invalidate();
}
I found this
Calling a class from a fragment
inflate a linearLayout and add chart view to the layout. Thanks!

KeyBoard not shown (does not respond) when EditText is selected in android fragment

here is my fragment class:
public class PrayerTimes extends Fragment {
EditText Lat;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
InflaterView = inflater.inflate(R.layout.activity_prayer_times, container, false);
Lat = (EditText) InflaterView.findViewById(R.id.LatitudeEdit);
Lat.addTextChangedListener(new TextWatcher()
{
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
return InflaterView;
}
when the Fragment loads, and The EDitText (Lat) is selected (Get Focused ) no KeyBoard is shown . How To Show The KeyBoard?
Add this line:
Lat.clearFocus();
immediately after the line:
Lat = (EditText) InflaterView.findViewById(R.id.LatitudeEdit);

Resources