AmberHelpSK AmberHelpSK - 1 year ago 73
Java Question

Onclck listener with fragments

  1. Hello, So I followed the Android Developer website to create some
    simple tabs in Android with fragments. The tabs fully work and
    display the content they are supposed to. However, I am now trying
    to intergrate it with this AndroidHive Login tutorial. I have
    set up the XML properly and the MainActivity from the Login tutorail
    now shows on my first tab. I am now trying to setup the onclick
    listener for the logout button but it seems my intent params are not
    working and also the finish method doesn't work:

    private void logoutUser() {
    Intent intent = new Intent(OneFragment.this, LoginActivity.class);

    I'm guessing it has to do with the fact that my clsss isnt an

    public class TabOne extends Fragment implements View.OnClickListener {.....}

  2. Also I am not following his tutorial exactly and am coding some elements of the project how I prefer it (I've been studying pure Java at university for 2 yeats now). But inside his MainActivity class he has to variables as follows (the classes are available in his login tutorial)

    • private SQLiteHandler db;

    • private SessionManager session;

and he initalises them in the onCreate as follows:

db = new SQLiteHandler(getApplicationContext());
session = new SessionManager(getApplicationContext());

However, because I am using fragments and not activities I can't do this so after some researching I tried this:

db = new SQLiteHandler(getActivity().getApplicationContext());

session = new SessionManager(getActivity().getApplicationContext());

It has removed the errors on Android Studio but I am not 100% sure it will work (I still have the above error in my code so I am unable to test) - Can you please clarify if this would work also - again all his classes are in the link above including session and sqllite.

Edit 1 - Sorry I should have added this, I used cases and called the logout method:

public void onClick(View v) {
switch (v.getId()) {

Thank you, if any further information is required please ask and I shall update this post

Answer Source

You have to access your main activity context from the fragment to able to call methods which belong to activity class. for your case use the folowing

private void logoutUser() {
  Intent intent = new Intent(getActivity(), LoginActivity.class);     
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download