Search code examples
androidandroid-fragmentsandroid-fragmentactivityandroid-cursoradapterandroid-cursor

How to cast the cursor from a fragment to a new activity?


I have a working ListView, in a fragment and when the ListItem is clicked
I want to link the data to a new Activity. I am getting an error that my db object
cannot be cast to the db Cursor

import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.mlaffan.giftpal.sqlite.adapter.PersonAdapter;
import com.mlaffan.giftpal.sqlite.db.DatabaseHelper;
import com.mlaffan.giftpal.sqlite.db.Person;

import java.util.ArrayList;

public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
    public PersonAdapter personAdapter;
    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the
     * four primary sections of the app. We use a {@link android.support.v4.app.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}.
     */
    AppSectionsPagerAdapter mAppSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will display the four primary sections of the app, one at a
     * time.
     */
    ViewPager mViewPager;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DatabaseHelper dbHelp = new DatabaseHelper(getApplicationContext());

        // Create the adapter that will return a fragment for each of the four primary sections
        // of the app.
        mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());

        // Set up the action bar.
        final ActionBar actionBar = getActionBar();

        // Specify that the Home/Up button should not be enabled, since there is no hierarchical
        // parent.
        actionBar.setHomeButtonEnabled(false);

        // Specify that we will be displaying tabs in the action bar.
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Set up the ViewPager, attaching the adapter and setting up a listener for when the
        // user swipes between sections.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mAppSectionsPagerAdapter);
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                // When swiping between different app sections, select the corresponding tab.
                // We can also use ActionBar.Tab#select() to do this if we have a reference to the
                // Tab.
                actionBar.setSelectedNavigationItem(position);
            }
        });

        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mAppSectionsPagerAdapter.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
            // listener for when this tab is selected.
            actionBar.addTab(
                    actionBar.newTab()
                            .setText(mAppSectionsPagerAdapter.getPageTitle(i))
                            .setTabListener(this));
        }
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    @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 onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
     * sections of the app.
     */
    public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {

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

        @Override
        public Fragment getItem(int i) {
            switch (i) {
                case 0:
                    // The first section of the app is the most interesting -- it offers
                    // a launchpad into the other demonstrations in this example application.
                    return new LaunchpadSectionFragment();

                case 1:
                    return new AddPeopleFragment();

                case 2:
                    return new PeopleSectionFragment();

                default:
                    return new SnapGiftFragment();

//                default:
                    // The other sections of the app are dummy placeholders.
//                    Fragment fragment = new DummySectionFragment();
//                    Bundle args = new Bundle();
//                    args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
//                    fragment.setArguments(args);
//                    return fragment;
            }
        }

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

        @Override
        public CharSequence getPageTitle(int position) {
            if (position == 0) {
                return "Events";
            } else if (position == 1) {
                return "Add People";
            } else if (position == 2) {
                return "Your People";
            } else {
                return "Snap Gift";
            }
        }
    }

    /**
     * A fragment that launches other parts of the demo application.
     */
    public static class LaunchpadSectionFragment extends Fragment {

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_section_launchpad, container, false);

            // Demonstration of navigating to external activities.
            rootView.findViewById(R.id.demo_external_activity)
                    .setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            // Create an intent that asks the user to pick a photo, but using
                            // FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET, ensures that relaunching
                            // the application from the device home screen does not return
                            // to the external activity.
                            Intent externalActivityIntent = new Intent(Intent.ACTION_PICK);
                            externalActivityIntent.setType("image/*");
                            externalActivityIntent.addFlags(
                                    Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                            startActivity(externalActivityIntent);
                        }
                    });

            // link to Profiles Activitys.
            rootView.findViewById(R.id.profiles_button)
                    .setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent(getActivity(), ProfileActivity.class);
                            startActivity(intent);
                        }
                    });

            return rootView;
        }
    }

    /**
     * A fragment lets the user create a new profile.
     */
    public static class AddPeopleFragment extends Fragment {
        private String sex = "male";
        private EditText firstName;
        private EditText lastName;
        private DatePicker birthday;

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

        @Override
        public void onViewCreated(View view, final Bundle bundle) {
            super.onViewCreated(view, bundle);
            firstName = (EditText) view.findViewById(R.id.firstName);
            lastName = (EditText) view.findViewById(R.id.lastName);
            RadioButton male = (RadioButton) view.findViewById(R.id.male);
            RadioButton female = (RadioButton) view.findViewById(R.id.female);
            birthday = (DatePicker) view.findViewById(R.id.datePicker);
            Button button = (Button) view.findViewById(R.id.button);

            male.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sex = "male";
                }
            });

            female.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sex = "female";
                }
            });

            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String fName = firstName.getText().toString();
                    String lName = lastName.getText().toString();
                    int day = birthday.getDayOfMonth();
                    int month = birthday.getMonth();
                    int year = birthday.getYear();
                    Person person = new Person();
                    person.setFirstName(fName);
                    person.setLastName(lName);
                    person.setSex(sex);
                    person.setBirthday("" + day + "/" + month + "/" + year);
                    DatabaseHelper dbHelper = new DatabaseHelper(getActivity().getApplicationContext());
                    dbHelper.addPerson(person);
                    Toast.makeText(getActivity(), "Profile added!", Toast.LENGTH_SHORT).show();

                    if (PeopleSectionFragment.adapter != null) {
                        PeopleSectionFragment.adapter.add(person);
                    }

                }
            });
        }
    }

    /**
     * A fragment that contains a list of profiles.
     */
    public static class PeopleSectionFragment extends Fragment {

        public static PersonAdapter adapter;

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

        @Override
        public void onViewCreated(View view, Bundle bundle) {
            super.onViewCreated(view, bundle);
            DatabaseHelper dbHelp = new
                    DatabaseHelper(getActivity().getApplicationContext());
            ArrayList<Person> people = dbHelp.getPeople();
            adapter = new PersonAdapter(getActivity().getApplicationContext(),
                    R.layout.fragment_people_list_item, people);
            ListView listView = (ListView) getActivity().findViewById(R.id.list);
            listView.setAdapter(adapter);
            listView.setOnItemClickListener(new ItemClicked());
        }

        class ItemClicked implements AdapterView.OnItemClickListener {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Person person = adapter.getItem(position);
                Log.i("ItemClicked", person.getFirstName());

                // When a listitem is clicked
                Intent intent = new Intent(getActivity(), Profile.class);
                Cursor cursor = (Cursor) person;
                intent.putExtra("PERSON_ID", cursor.getInt(cursor.getColumnIndex("_id")));
                startActivity(intent);


            }
        }


    }


    public static class SnapGiftFragment extends Fragment {

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

This code seems to be where the trouble is;

Intent intent = new Intent(getActivity(), Profile.class);
                    Cursor cursor = (Cursor) person;
                    intent.putExtra("PERSON_ID", cursor.getInt(cursor.getColumnIndex("_id")));
                    startActivity(intent);

This is the error message;

05-05 12:27:54.575    2231-2231/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.mlaffan.giftpal, PID: 2231
    java.lang.ClassCastException: com.mlaffan.giftpal.sqlite.db.Person cannot be cast to android.database.Cursor
            at com.mlaffan.giftpal.MainActivity$PeopleSectionFragment$ItemClicked.onItemClick(MainActivity.java:306)
            at android.widget.AdapterView.performItemClick(AdapterView.java:300)
            at android.widget.AbsListView.performItemClick(AbsListView.java:1143)
            at android.widget.AbsListView$PerformClick.run(AbsListView.java:3044)
            at android.widget.AbsListView$3.run(AbsListView.java:3833)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Here is the target activity;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.TextView;

import com.mlaffan.giftpal.sqlite.db.DatabaseHelper;

/**
 * Created by Mark on 05/05/2015.
 */
public class Profile extends Activity  {

    protected TextView profileFirst;
    protected TextView profileLast;
    protected TextView profileBirthday;
    protected TextView profileSex;
    protected int profileId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.profile_view);

        profileId = getIntent().getIntExtra("PERSON_ID", 0);
        SQLiteDatabase db = (new DatabaseHelper(this)).getWritableDatabase();
        Cursor cursor = db.rawQuery("SELECT _id, firstName, lastName, sex, birthday FROM people WHERE _id = ?",
                new String[]{""+profileId});

        if (cursor.getCount() == 1){
            cursor.moveToFirst();

            profileFirst = (TextView) findViewById(R.id.profileFirst);
            profileFirst.setText(cursor.getString(cursor.getColumnIndex("firstName")));

            profileLast = (TextView) findViewById(R.id.lastName);
            profileLast.setText(cursor.getString(cursor.getColumnIndex("lastName")));

            profileSex = (TextView) findViewById(R.id.profileSex);
            profileSex.setText(cursor.getString(cursor.getColumnIndex("sex")));

            profileBirthday = (TextView) findViewById(R.id.profileBirthday);
            profileBirthday.setText(cursor.getString(cursor.getColumnIndex("birthday")));


        }
    }
}

Apologies if this is a messy one, if I need to give more information please ask.


Solution

  • Extend your Person class as Serializable and than you can try this way:

        Person person = (Person)adapter.getItem(position);
        Intent intent = new Intent(getActivity(), Profile.class);                    
        intent.putExtra("person", person);
        startActivity(intent);
    

    Now in your Profile activity, do this way:

        Person person;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.profile_view);
    
            person = (Person) getIntent().getSerializableExtra("person");        
    
            profileFirst = (TextView) findViewById(R.id.profileFirst);
            profileFirst.setText(person.firstName);
    
            profileLast = (TextView) findViewById(R.id.lastName);
            profileLast.setText(person.lastName");
            ...
            ...        
       }