Aovin Mahmud
Aovin Mahmud

Reputation: 214

Android Tab Selecting Error

I have created a apps which have a list-view and swipe with tabs. My problem is when i click on the any of the button of listview,in the tab activity its opening first tab but i want to do that if i click 1st button of the listview, on the tab view will open 1st tab and if i click 2nd button of the listview, on the tab view will open 2nd tab.In my apps it's always opening first tab on the tab view :( see the code below

MainActivity

public class MainActivity extends Activity {


ActionBar actionBar;
Context c;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    actionBar=getActionBar();
    actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#36B0B6")));

    ListView lv = (ListView) findViewById(R.id.Main_listView);
    lv.setSelector(new ColorDrawable(0));

    String[] adobe_products = getResources().getStringArray(R.array.adobe_products);
    final String[] sentitem = getResources().getStringArray(R.array.sent_item);

   lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, adobe_products));


      lv.setOnItemClickListener(new OnItemClickListener() {

          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
              Intent i = new Intent(getApplicationContext(), CodeActivity.class);
              i.putExtra("product", position );
              startActivity(i);

          }
        });


}
}

CodeActivity

public class CodeActivity extends FragmentActivity implements TabListener {


Context context;;
ViewPager viewPager;
ActionBar actionBar;
private String[] days = new String[]{"Monday","Tuesday","Wednesday","Tuesday","Wednesday"};




@Override
protected void onCreate(Bundle savedInstanceState) {      
    super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_code);





        Bundle bundle = getIntent().getExtras();
        int position = bundle.getInt("product");
        viewPager.setCurrentItem(position);  // Problem is here 






    viewPager = (ViewPager)findViewById(R.id.view_pager);
    FragmentPagerAdapter adapter = new PagerViewAdapter(getSupportFragmentManager(),this);
    viewPager.setAdapter(adapter);

    actionBar=getActionBar();
    actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#36B0B6")));
    actionBar.setStackedBackgroundDrawable(new ColorDrawable(Color.parseColor("#2979FF")));



    final ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);


    viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {

        @Override
        public void onPageSelected(int arg0) {
         actionBar.setSelectedNavigationItem(arg0);


        }
    });




    for (int i = 0; i < days.length; i++) {
        actionBar.addTab(actionBar.newTab().setText(days[i]).setTabListener(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;




}
public void onTabChanged(String tabId) {
    if (tabId.equals(days)) {
          // Show your actual activity here
    } 
}

@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
    //  Auto-generated method stub

}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {

    viewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    //  Auto-generated method stub

}


    //-----------------------------------------------------------------------
static //----------------------------------------------------------
class TestFragment extends Fragment {

    private static final String KEY_CONTENT = "  ";

    public static TestFragment newInstance(String content) {
        TestFragment fragment = new TestFragment();

        StringBuilder builder = new StringBuilder();

        for (int i = 0; i < 1; i++) {
            builder.append(content).append("");
        }

        builder.deleteCharAt(builder.length() - 1);
        fragment.mContent = builder.toString();

        return fragment;
    }

    private String mContent = "???";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if ((savedInstanceState != null)
                && savedInstanceState.containsKey(KEY_CONTENT)) {
            mContent = savedInstanceState.getString(KEY_CONTENT);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        TextView text = new TextView(getActivity());
        text.setGravity(Gravity.CENTER);
        text.setText(mContent);
        text.setTextSize(20 * getResources().getDisplayMetrics().density);
        text.setPadding(20, 20, 20, 20);

        LinearLayout layout = new LinearLayout(getActivity());
        layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
        layout.setGravity(Gravity.CENTER);
        layout.addView(text);

        return layout;
    }

}
//-----------------------------------------------------------------------
class PagerViewAdapter extends FragmentPagerAdapter {

    private String[] days;


    public PagerViewAdapter(FragmentManager fm, Context context ) {
        super(fm);

        Resources resources = context.getResources();
        days = resources.getStringArray(R.array.adobe_products);


    }



    @Override
    public Fragment getItem(int position) {
    return TestFragment.newInstance(days[position % days.length]);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        viewPager.setCurrentItem(position);
        return days[position % days.length];
    }

    @Override
    public int getCount() {
      return days.length;
    }
}




   }

LogCat

09-11 09:09:41.085: E/AndroidRuntime(1318): FATAL EXCEPTION: main
09-11 09:09:41.085: E/AndroidRuntime(1318): java.lang.RuntimeException: Unable to start activity  ComponentInfo{com.offtechitbd.essentialussd/com.offtechitbd.essentialussd.CodeActivity}: java.lang.NullPointerException
09-11 09:09:41.085: E/AndroidRuntime(1318): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
09-11 09:09:41.085: E/AndroidRuntime(1318): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
09-11 09:09:41.085: E/AndroidRuntime(1318): at android.app.ActivityThread.access$600(ActivityThread.java:141)
09-11 09:09:41.085: E/AndroidRuntime(1318): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
09-11 09:09:41.085: E/AndroidRuntime(1318): at android.os.Handler.dispatchMessage(Handler.java:99)
09-11 09:09:41.085: E/AndroidRuntime(1318): at android.os.Looper.loop(Looper.java:137)
09-11 09:09:41.085: E/AndroidRuntime(1318): at android.app.ActivityThread.main(ActivityThread.java:5041)
09-11 09:09:41.085: E/AndroidRuntime(1318): at java.lang.reflect.Method.invokeNative(Native Method)
09-11 09:09:41.085: E/AndroidRuntime(1318): at java.lang.reflect.Method.invoke(Method.java:511)
09-11 09:09:41.085: E/AndroidRuntime(1318): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-11 09:09:41.085: E/AndroidRuntime(1318): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-11 09:09:41.085: E/AndroidRuntime(1318): at dalvik.system.NativeStart.main(Native Method)
09-11 09:09:41.085: E/AndroidRuntime(1318): Caused by: java.lang.NullPointerException
09-11 09:09:41.085: E/AndroidRuntime(1318): at com.offtechitbd.essentialussd.CodeActivity.onCreate(CodeActivity.java:50)
09-11 09:09:41.085: E/AndroidRuntime(1318): at android.app.Activity.performCreate(Activity.java:5104)
09-11 09:09:41.085: E/AndroidRuntime(1318): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
09-11 09:09:41.085: E/AndroidRuntime(1318): at   android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
09-11 09:09:41.085: E/AndroidRuntime(1318):     ... 11 more

Upvotes: 0

Views: 481

Answers (2)

Prokash Sarkar
Prokash Sarkar

Reputation: 11873

According to,

Caused by: java.lang.NullPointerException

you are trying to change the viewPager's item before casting,

Bundle bundle = getIntent().getExtras();
int position = bundle.getInt("product");
viewPager.setCurrentItem(position);  // viewPager is null as it's been casted after the setCurrentItem() is called,

viewPager = (ViewPager)findViewById(R.id.view_pager);

Solution?

Cast the viewPager before trying to change the item

viewPager = (ViewPager)findViewById(R.id.view_pager);
FragmentPagerAdapter adapter = new PagerViewAdapter(getSupportFragmentManager(),this);
viewPager.setAdapter(adapter);

Bundle bundle = getIntent().getExtras();
int position = bundle.getInt("product");
viewPager.setCurrentItem(position);

Special notes:

Make sure you are setting the first item of the viewPager from the index 0

Upvotes: 0

Sachin Kottary
Sachin Kottary

Reputation: 189

Inside CodeActivity classes onCreated write the below code

    Bundle bundle = getActivity().getIntent().getExtras();
    int position = bundle.getInt("product");
    mViewPager.setCurrentItem(position);

Upvotes: 1

Related Questions