2

I did a quick search in here and didn't find any answers for my qustion, if its already answered please point me to that question ..

I have an ActionBar Tabs with swipe views implemented according to this android training. My activity have 3 tabs Weather Comment Dashboard and these fragments
WeatherFragment CommentsFragment LoginFragment DasboardFragment RegisterFragment

As the activity is started, Weather Tab displays WeatherFragment , Comments Tab displays CommentsFragment and Dashboard Tab displays LoginFragment

If Login is successful in LoginFragment, DasboardFragment should replace the LoginFragment inside the Dashboard Tab. So if user swipes to other tabs and come back to Dashboard Tab DasboardFragment should be visible.

I'm new to android development, so any code snippets or tutorial would be greatly appreciated

Code i've so far MainActivity class

public class MainActivity extends FragmentActivity implements
    ActionBar.TabListener {

AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;

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

    mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(
            getSupportFragmentManager());

    final ActionBar actionBar = getActionBar();
    //actionBar.setDisplayShowTitleEnabled(false);
    //actionBar.setDisplayShowHomeEnabled(false);
    actionBar.setHomeButtonEnabled(false);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mAppSectionsPagerAdapter);
    mViewPager
            .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {                      
                    actionBar.setSelectedNavigationItem(position);
                }
            });

    for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {         
        actionBar.addTab(actionBar.newTab()
                .setText(mAppSectionsPagerAdapter.getPageTitle(i))
                .setTabListener(this));
    }       
}

public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {

    public AppSectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int i) {
        switch (i) {
        case 0:
            return new WeatherInfoFragment();
        case 1:
            return new PostsFragment();
        default: //TODO method to find which fragment to display ?
            return new LoginFragment();
        }
    }

    @Override
    public int getCount() {
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        if (position == 0) {
            return "Weather";
        } else if (position == 1){
            return "Comments";
        }
        else{
            return "Dashboard";
        }
    }
}

@Override
public void onTabReselected(ActionBar.Tab tab,
        android.app.FragmentTransaction ft) {
}

@Override
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
    mViewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
 }
 }

LoginFragment

public class LoginFragment extends Fragment implements AsyncResponse {
Button loginButton;
TextView loginError, login_url;
JSONfunctions task;
JSONObject jsonObject;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    return inflater.inflate(R.layout.login, container, false);
}

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

@Override
public void onStart() {
    super.onStart();

    loginButton = (Button) getView().findViewById(R.id.button_login);
    loginError = (TextView) getView().findViewById(R.id.login_error);

    loginButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {               
            attemptLogin(finalLoginUrl);
            // attemptPost(postURL);
        }
    });
}

private void attemptLogin(String url) {     
        try {
            task = new JSONfunctions(getActivity());
            task.listener = this;
            task.execute(new String[] { url });
        } catch (Exception ex) {
            Log.e("attempt login", ex.getMessage());
        }
    }
}

@Override
public void processFinish(String result) {
    try {
        jsonObject = new JSONObject(result);
        int success = Integer.parseInt(jsonObject.getString("Success"));
        if (success == 0) {             
            // Replace LoginFragment and launch DashboardFragment ?                 
        } else {
            loginError.setText(jsonObject.getString("ErrorMessage"));
        }

    } catch (JSONException e) {
        Log.e("JSON parsing from login result", e.getMessage());
    }
}
}
Ash
  • 49
  • 1
  • 10

2 Answers2

1

I'm not sure this is the best way to handle this but you could define a static boolean inside your MainActivity like so:

public static boolean loggedIn = false;

(e.g. below ViewPager mViewPager;)

And then, in your method processFinish(...) inside the LoginFragment when success is 0 just set MainActivity.loggedIn = true;

This way you can simply put in an if-statement inside your default-case in getItem-method to check whether the user is logged in (if so call the Dashboard-Fragment) or not (display Login-Fragment).

Hope this works for you!

Edit: LoginFragment

public class LoginFragment extends Fragment implements AsyncResponse {
Button loginButton;
TextView loginError, login_url;
JSONfunctions task;
JSONObject jsonObject;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    return inflater.inflate(R.layout.login, container, false);
}

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

@Override
public void onStart() {
    super.onStart();

    loginButton = (Button) getView().findViewById(R.id.button_login);
    loginError = (TextView) getView().findViewById(R.id.login_error);

    loginButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {               
            attemptLogin(finalLoginUrl);
            // attemptPost(postURL);
        }
    });
}

private void attemptLogin(String url) {     
    try {
        task = new JSONfunctions(getActivity());
        task.listener = this;
        task.execute(new String[] { url });
    } catch (Exception ex) {
        Log.e("attempt login", ex.getMessage());
    }
}

@Override
public void processFinish(String result) {
    try {
        jsonObject = new JSONObject(result);
        int success = Integer.parseInt(jsonObject.getString("Success"));
        if (success == 0) {             
            MainActivity.loggedIn = true;                 
        } else {
            loginError.setText(jsonObject.getString("ErrorMessage"));
        }

    } catch (JSONException e) {
        Log.e("JSON parsing from login result", e.getMessage());
    }
}
}
chuky
  • 1,007
  • 1
  • 12
  • 20
  • Hi, thanks for your reply. I tried it out but didn't work :( Think i need to implement some sort of callback method to the my AppSectionsPagerAdapter. I found a similar question here [link] http://stackoverflow.com/questions/7723964/replace-fragment-inside-a-viewpager/ – Ash Apr 07 '13 at 03:50
  • But i keeping getting error when trying to implement it to my code. Would like to see the fragments code from that answer .. any suggetions .. ? – Ash Apr 07 '13 at 03:58
  • I edited the answer and put in the code of the Login-Fragment, was that what you wished for? `if (success==0)` is where I inserted the code. And what error do you get? – chuky Apr 07 '13 at 09:30
  • i meant fragments code from the this answer http://stackoverflow.com/questions/7723964/replace-fragment-inside-a-viewpager?answertab=votes#tab-top btw the i don't get any error but the login fragment doesn't change even after successful login. – Ash Apr 07 '13 at 19:03
  • Have you tried implementing the code from that link? Please share your code once you've done, because right now I can't imagine where you want to include this code into yours. – chuky Apr 07 '13 at 19:22
  • I managed to get the solution working, was my own fault. I din't read the answer from the link clearly enough. I used [this](http://stackoverflow.com/a/12155594/2235914) answer from this [Question](http://stackoverflow.com/questions/7723964/replace-fragment-inside-a-viewpager?) – Ash Apr 12 '13 at 18:32
1

Was my own fault for not reading the answer here thoroughly. Implemented the code from that answer and got the functionality working :)

Community
  • 1
  • 1
Ash
  • 49
  • 1
  • 10