Rate us In Android fragment - button

I'm trying to rewrite this project using fragments. I'm replacing activities with fragments.
This is XML file :
'<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="#+id/rate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Rate Us" />
and this is the Full Source Code java:-
'public class MainActivity extends Activity{
Button rate;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rate=(Button)findViewById(R.id.rate);
rate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse ("market://details?id=APP ID"));
startActivity(intent);
}
});
}}`
what is the java right code for use this in a fragment?
Thanks in advance....

This is how it is done:
public class MainActivity extends Fragment {
Button rate;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_main, container, false);
rate = (Button) rootView.findViewById(R.id.rate);
rate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse ("market://details?id=APP ID"));
startActivity(intent);
}
});
return rootView;
}
There is no need to change anything in the xml file.
Hope this helps :)

Related

Fragments in MVVMCross 4.1.4 will not be displayed in the Activity (Android)

I try to add a fragment to an activity and have already looked at the example from Martijn00.
My problem is, that the activity will be displayed but the fragment will not and in debugging mode, the debugger is not running into the fragment's method OnCreateView. So the attribute of the fragment will be used, but not the fragment. I see only my activity with the green background. I am sure I do something wrong, but after 6 hours I do give up and ask you guys for help :)
Fragment:
namespace TopDownTodoList.Mobile.Droid.Views.Fragments{
[MvxFragment(typeof(MainViewModel), Resource.Id.content_frame, true)]
[Register("topdowntodolist.mobile.droid.views.fragments.TodoOverviewFragment")]
public class TodoOverviewFragment : MvxFragment<TodoOverviewViewModel>
{
protected int LayoutId => Resource.Layout.f_todo_overview_fragment;
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
this.Init();
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return this.BindingInflate(this.LayoutId, null);
//return inflater.Inflate(this.LayoutId, container, false);
}
public virtual void Init() { }
}}
Activity:
namespace TopDownTodoList.Mobile.Droid.Views{
[Activity(Label = "MainView")]
public class MainView : MvvmCross.Droid.FullFragging.Views.MvxActivity<MainViewModel>
{
protected int LayoutId => Resource.Layout.main_view;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(this.LayoutId);
this.Init();
}
public virtual void Init(){}
}}
App.cs:
protected override void RegisterClasses()
{
RegisterAppStart<TodoOverviewViewModel>();
}
ViewModels:
public class VMName : MvvmCross.Core.ViewModels.MvxViewModel{...}
FragmentLayout (f_todo_overview_fragment):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mvx="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:background="#0000aa"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:gravity="center"/></LinearLayout>
ActivityLayout (main_view):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:background="#aa0000"
android:layout_width="fill_parent"
android:layout_height="fill_parent"><FrameLayout
android:id="#+id/content_frame"
android:background="#00bb00"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true" /></LinearLayout>
Your Activity needs to be of the type MvxCachingFragmentCompatActivity or MvxCachingFragmentActivity to support hosting of fragments.
Secondly you need to ignore the normal inflator, and use binding inflate after that:
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var ignore = base.OnCreateView(inflater, container, savedInstanceState);
return this.BindingInflate(FragmentId, null);
}

How to load a fragment view in a tab

I am trying to create tabs inside a fragment. I manage to create tab inside the fragment, but now I want to load different fragment for each tab (fragment1.class and fragment2.class).
Can anybody please suggest how can i load each fragment to their respective tabs?
Below is my main fragment that is holding the tabs.
Thanks a lot!
public class BusFragment extends Fragment {
private TabHost mTabHost;
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_bus, container, false);
mTabHost = (TabHost) rootView.findViewById(R.id.tabHost);
mTabHost.setup();
TabHost.TabSpec spec = mTabHost.newTabSpec("tag");
spec.setIndicator("Fragment1");
spec.setContent(new TabHost.TabContentFactory() {
#Override
public View createTabContent(String tag) {
// TODO Auto-generated method stub
return (new AnalogClock(getActivity()));
}
});
mTabHost.addTab(spec);
spec = mTabHost.newTabSpec("tag1");
spec.setIndicator("Fragment2");
spec.setContent(new TabHost.TabContentFactory() {
#Override
public View createTabContent(String tag) {
// TODO Auto-generated method stub
return (new AnalogClock(getActivity()));
}
});
mTabHost.addTab(spec);
spec = mTabHost.newTabSpec("tag2");
spec.setIndicator("Fragment3");
spec.setContent(new TabHost.TabContentFactory() {
#Override
public View createTabContent(String tag) {
// TODO Auto-generated method stub
return (new AnalogClock(getActivity()));
}
});
mTabHost.addTab(spec);
return rootView;
}
}
Hello If you want to load the fragment inside the fragment android provide the Child Fragment Manager instead of ordinary fragment manager. I had the same issue I had the fragment inside that tab when click on tab want to load the different fragments. see the below steps hope will help you.
Step 1. See I have StatisticsFragment with it layout fragment_statistics.
public class StatisticsFragment extends Fragment {
private FragmentTabHost mTabHost;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_statistics,container, false);
mTabHost = (FragmentTabHost) rootView.findViewById(R.id.tabhost);
mTabHost.setup(getActivity(), getChildFragmentManager(),R.id.tabFrameLayout);
mTabHost.addTab(mTabHost.newTabSpec("WEEK").setIndicator(buildTabLayout(EnumStatistics.WEEKLY)),WeekFragment_.class, null);
mTabHost.addTab(mTabHost.newTabSpec("ALL").setIndicator(buildTabLayout(EnumStatistics.ALL)),DetailedFragment_.class, null);
mTabHost.getTabWidget().getChildAt(0).setOnClickListener(new WeekTabClick());
mTabHost.getTabWidget().getChildAt(1).setOnClickListener(new AllTabClick());
return rootView;
}
#Override
public void onResume() {
super.onResume();
}
private View buildTabLayout(EnumStatistics enumStatistics) {
View tab;
if (enumStatistics == EnumStatistics.WEEKLY) {
tab = getActivity().getLayoutInflater().inflate(R.layout.tab_week_layout, null);
} else if (enumStatistics == EnumStatistics.MONTHLY) {
tab = getActivity().getLayoutInflater().inflate(R.layout.tab_month_layout, null);
} else if (enumStatistics == EnumStatistics.YEAR) {
tab = getActivity().getLayoutInflater().inflate(R.layout.tab_year_layout, null);
} else {
tab = getActivity().getLayoutInflater().inflate(R.layout.tab_detailed_layout, null);
}
return tab;
}
public class WeekTabClick implements View.OnClickListener {
#Override
public void onClick(View v) {
mTabHost.getTabWidget().focusCurrentTab(0);
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.replace(R.id.tabFrameLayout, WeekFragment_.instantiate(getActivity(), WeekFragment_.class.getName()));
ft.addToBackStack(null);
ft.commit();
}
}
public class AllTabClick implements View.OnClickListener {
#Override
public void onClick(View v) {
mTabHost.getTabWidget().focusCurrentTab(1);
FragmentTransaction ft = getChildFragmentManager()
.beginTransaction();
ft.replace(R.id.tabFrameLayout, DetailedFragment_.instantiate(
getActivity(), DetailedFragment_.class.getName()));
ft.addToBackStack(null);
ft.commit();
}
}
}
In above buildTabLayout function intent to build the custom layout of tab widget you can put simple text or image that you want to show inside the tab widget.
Steps 2. fragment_statistics.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:relaxis="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.app.FragmentTabHost
android:id="#+id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/croutonview"
android:gravity="center" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dp"
android:orientation="horizontal"
/>
<FrameLayout
android:id="#+id/tabFrameLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
</RelativeLayout>
As you see in the above inside the layout tabFrameLayout we load the all child fragment Programmaticly.
Let me know if you have any question and doubt. thank you

Using a progressBar in a listview item

I have this listview and it's coded in a fragment class. When selecting a listview item it goes to another fragment and displays the details . But it takes several seconds to load the data because the data i display is using AsyncTask,so it takes some time to get data from the JSON and display . So i need to use a progressBar when an item is clicked in the listview and it should close when the data is ready to display. How can i do this? I referred several tutorials and tried many of them. But i couldn't accomplish what i'm looking for.Hope some of you can help me.
NewsFragment class
private ListView listView;
private ArrayList<BaseElement> News;
private LazyAdapter adapter;
private Activity activity;
private CommonVariable commonVariable;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.news_fragment, container,
false);
activity = this.getActivity();
commonVariable = (CommonVariable) activity.getApplication();
listView = (ListView) view.findViewById(R.id.list);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id){
android.support.v4.app.Fragment detail = new NewsDetailFragment();
android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().add(R.id.content_frame, detail).addToBackStack("back").commit();
}
});
new BackGround().execute();
return view;
}
public class BackGround extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
News = JSONServices.getNewsDescription();
return null;
}
#Override
/* check again */
protected void onPostExecute(Void result) {
commonVariable.setNewsDescription(News);
adapter = new LazyAdapter(News, activity,Element.NEWS_LIST.getType());
listView.setAdapter(adapter);
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
}
}
NewsDetailFragment
public class NewsDetailFragment extends Fragment {
private View view1;
private ArrayList<BaseElement> newsdetail;
private LazyAdapter adapter;
private Activity activity;
private CommonVariable commonVariable;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.newsdetail_fragment, container,
false);
activity = this.getActivity();
commonVariable = (CommonVariable) activity.getApplication();
view1 = (View) view.findViewById(R.id.list);
new BackGround().execute();
return view;
}
public class BackGround extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
newsdetail = JSONServices.getNewsDescription();
return null;
}
#SuppressWarnings("unchecked")
#Override
/* check again */
protected void onPostExecute(Void result) {
commonVariable.setTheater(newsdetail);
adapter = new LazyAdapter(newsdetail, activity,Element.NEWS_DETAIL.getType());
((AdapterView<ListAdapter>) view1).setAdapter(adapter);
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
}
}
NewsList layout
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/grey"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#drawable/listview" >
<ImageView
android:id="#+id/thumb_image"
android:layout_width="150dp"
android:layout_height="120dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp"
/>
<TextView
android:id="#+id/news_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:layout_toRightOf="#+id/thumb_image"
android:layout_marginTop="10dp"
android:layout_marginLeft="7dp"
android:textStyle="bold"
android:textSize="20dp" />
<!-- <TextView
android:id="#+id/news_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textStyle="bold"
android:layout_below="#+id/news_title"
android:textSize="15dp" /> -->
</LinearLayout>
</RelativeLayout>
NewsFragment 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"
android:background="#color/grey" >
<!-- <GridView
android:id="#+id/gridView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:numColumns="2"
android:stretchMode="columnWidth"
android:layout_margin="5dp"
android:columnWidth="100dp"/> -->
<ListView
android:id="#+id/list"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:dividerHeight="10dp"
android:layout_margin="6dp">
</ListView>
</LinearLayout>
Add ProgressBar to your NewsFragment layout:
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:indeterminate="true"
android:visibility="gone" />
Then in onItemClick method change it's visibility to true progressBar.setVisibility(View.VISIBLE) to show it and change it's visibility to false to hide it progressBar.setVisibility(View.GONE) in onPostExecute of AsyncTask.
Ok i got it now. I modified my 2nd fragment like this. When an item in the listview is clicked it goes to my second class.So i added a progressBar to my second class and it worked!
public class NewsDetailFragment extends Fragment {
private View view1;
private ArrayList<BaseElement> newsdetail;
private LazyAdapter adapter;
private Activity activity;
private CommonVariable commonVariable;
private ProgressDialog dialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.newsdetail_fragment, container,
false);
activity = this.getActivity();
commonVariable = (CommonVariable) activity.getApplication();
view1 = (View) view.findViewById(R.id.list);
dialog = new ProgressDialog(NewsDetailFragment.this.getActivity());
dialog.setMessage("Loading News");
dialog.setCancelable(true);
new BackGround().execute();
return view;
}
public class BackGround extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
newsdetail = JSONServices.getNewsDescription();
return null;
}
#SuppressWarnings("unchecked")
#Override
/* check again */
protected void onPostExecute(Void result) {
commonVariable.setTheater(newsdetail);
adapter = new LazyAdapter(newsdetail, activity,Element.NEWS_DETAIL.getType());
((AdapterView<ListAdapter>) view1).setAdapter(adapter);
dialog.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog.show();
super.onPreExecute();
}
}
}

How to transfer variables to a fragment was created using the ActionBarActivity?

The activity is called from another activity delivering a string array, which needs to be displayed in a fragment of the target activity.
MainActivity (string array) -> Result2Activity: Tab1 should display string index0, Tab2 should display string index1 etc.
I followed a similar problem here:
Access Fragment View from Activity's onCreate
My problem is right now that the onActivityCreated method is never called in the Result2Activity.
I am also not sure if this method is the right way to address the fragment:
getSupportFragmentManager().findFragmentByTag("Out1");
What is the best way to achieve that ?
Result2Activity:
public class Result2Activity extends ActionBarActivity implements
ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a {#link FragmentPagerAdapter}
* derivative, which will keep every loaded fragment in memory. If this
* becomes too memory intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
public List<String> fragments = new Vector<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result2_activity);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
Log.d("DEBUG","1: onCreate finished");
}
public void onActivityCreated (Bundle savedInstanceState) {
Log.d("DEBUG","2: onActivityCreated finished");
//super.onActivityCreated(savedInstanceState);
// retrieve data from MainActivity
Intent intent = getIntent();
String message[] = intent.getStringArrayExtra(MainActivity.OUTPUT);
//send data to fragment Out1Fragment
Out1Fragment set_out1 =
(Out1Fragment)
getSupportFragmentManager().findFragmentByTag("Out1");
set_out1.settext(message[0]);
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
fragments.add(Out1Fragment.class.getName());
fragments.add(Out2Fragment.class.getName());
fragments.add(Out3Fragment.class.getName());
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new Out1Fragment();
break;
case 1:
fragment = new Out2Fragment();
break;
case 2:
fragment = new Out3Fragment();
break;
}
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.out_section1).toUpperCase(l);
case 1:
return getString(R.string.out_section2).toUpperCase(l);
case 2:
return getString(R.string.out_section3).toUpperCase(l);
}
return null;
}
}
}
Out1Fragment:
public class Out1Fragment extends Fragment {
private static TextView textview;
public Out1Fragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View dataView = inflater.inflate(R.layout.out1_fragment, container,
false);
textview = (TextView) dataView.findViewById(R.id.outPut1);
return dataView;
}
public void settext(String text)
{
textview.setText(text);
}
}
XML Resource:
result2_activity.xml
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="dd.testing.finance.Result2Activity" />
out1_fragment.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/ScrollView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:tag="Out1"
tools:context="dd.testing.finance.Result2Activity$Out1Fragment" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical" >
<TextView
android:id="#+id/outPut1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10sp"
android:layout_marginRight="10sp"
android:textSize="16sp" />
</LinearLayout>
</ScrollView>
Not really sure if this was the right way, but at least it does exaclty what I needed.
In the Out1Fragment.class added the onActivityCreated method:
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
settext(((Result2Activity)getActivity()).getOutput1());
}
From there calling the added method getOutput1 in the Result2Activity:
public String getOutput1 () {
// retrieve data from MainActivity
Intent intent = getIntent();
String message[] = intent.getStringArrayExtra(MainActivity.OUTPUT);
return message[0];
}

Nullpoint Exception on image gallery

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.

Resources