Question

I am not sure how I can construct this parcel correctly; and I am returning null when I try to add the parcel's object from my MainActivity.

Sending intent:

public void onClick(View v) {
            Intent myIntent = new Intent(listaddactivity.this,
                    MainActivity.class);

            myIntent.putExtra(
                    "custom_object",
                    new listControlObject(namefield.getText().toString(),
                            iterator, temperatureFrag.getCurrentTempType(), Integer
                                    .valueOf(powerPercent.getText()
                                            .toString()), Integer
                                    .valueOf(frequencyField.getText()
                                            .toString()),
                            temperatureFrag.temperaturenumberpicker
                                    .getValue(), cycleFrag.startTimeField
                                    .getCurrentHour(),
                            cycleFrag.startTimeField.getCurrentMinute(),
                            cycleFrag.cycleDatePicker.getDayOfMonth(),
                            cycleFrag.cycleDatePicker.getMonth(), Integer
                                    .valueOf(cycleFrag.numberOfCyclesField
                                            .getText().toString()))); // Optional
                                                                        // parameters
            startActivity(myIntent);
            Log.d("LISTACTIVITY", "Intent successfully passed!");
            iterator++;  
        }

    });
}

Receiving activity:

 public class MainActivity extends FragmentActivity implements
        ActionBar.TabListener {
    String TAG;


    HomeFragment homeFragment;
    cycleviewfragment cyclefragment;
    SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@linkCustomViewPager} that will host the section contents.
     */
    CustomViewPager mViewPager;

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

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

        homeFragment = new HomeFragment();
        cyclefragment = new cycleviewfragment();
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the app.
        mSectionsPagerAdapter = new SectionsPagerAdapter(
                getSupportFragmentManager());

        // Set up theCustomViewPager with the sections adapter.
        mViewPager = (CustomViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        mViewPager.setPagingEnabled(false);
        // 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 CustomViewPager.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));
        }
        processNewIntent(getIntent());


    }
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        processNewIntent(intent);
    }

    private void processNewIntent(Intent intent) {
        Log.v("TEST", "METHOD CALLED TEST");
        if (intent.hasExtra("custom_object")) {
            cyclefragment.a1.add((listControlObject) intent.getParcelableExtra("custom_object"));
            cyclefragment.adapter.notifyDataSetChanged();
        }
    }

Am I implemented parcel incorrectly when I send the intent? Is there a reason my processNewIntent is giving me a NullPointerException?

I'm guessing there is a specific way to construct a parcel and pass it through the intent I am not correctly implementing but I cannot find any good resources on it.

Logcat:

   03-24 01:13:30.846: E/Trace(7974): error opening trace file: No such file or directory (2)
03-24 01:13:44.374: E/AndroidRuntime(7974): FATAL EXCEPTION: main
03-24 01:13:44.374: E/AndroidRuntime(7974): java.lang.NullPointerException
03-24 01:13:44.374: E/AndroidRuntime(7974):     at com.nanospark.upcdemo.listaddactivity$1.onClick(listaddactivity.java:72)
03-24 01:13:44.374: E/AndroidRuntime(7974):     at android.view.View.performClick(View.java:4091)
03-24 01:13:44.374: E/AndroidRuntime(7974):     at android.view.View$PerformClick.run(View.java:17072)
03-24 01:13:44.374: E/AndroidRuntime(7974):     at android.os.Handler.handleCallback(Handler.java:615)
03-24 01:13:44.374: E/AndroidRuntime(7974):     at android.os.Handler.dispatchMessage(Handler.java:92)
03-24 01:13:44.374: E/AndroidRuntime(7974):     at android.os.Looper.loop(Looper.java:153)
03-24 01:13:44.374: E/AndroidRuntime(7974):     at android.app.ActivityThread.main(ActivityThread.java:4987)
03-24 01:13:44.374: E/AndroidRuntime(7974):     at java.lang.reflect.Method.invokeNative(Native Method)
03-24 01:13:44.374: E/AndroidRuntime(7974):     at java.lang.reflect.Method.invoke(Method.java:511)
03-24 01:13:44.374: E/AndroidRuntime(7974):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
03-24 01:13:44.374: E/AndroidRuntime(7974):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
03-24 01:13:44.374: E/AndroidRuntime(7974):     at dalvik.system.NativeStart.main(Native Method)

Thanks guys.

Edits:

Line 72 of listaddactivity.java:

myIntent.putExtra(
                    "custom_object",
                    new listControlObject(namefield.getText().toString(),
                            iterator, temperatureFrag.getCurrentTempType(), Integer
                                    .valueOf(powerPercent.getText()
                                            .toString()), Integer
                                    .valueOf(frequencyField.getText()
                                            .toString()),
                            temperatureFrag.temperaturenumberpicker
                                    .getValue(), cycleFrag.startTimeField
                                    .getCurrentHour(),
                            cycleFrag.startTimeField.getCurrentMinute(),
                            cycleFrag.cycleDatePicker.getDayOfMonth(),
                            cycleFrag.cycleDatePicker.getMonth(), Integer
                                    .valueOf(cycleFrag.numberOfCyclesField
                                            .getText().toString())));

The above just constructs a new object and adds it to the intent with the key "custom object".

Here is the code for the parcelable object:

    package com.nanospark.upcdemo;

import android.os.Parcel;
import android.os.Parcelable;

public class listControlObject implements Parcelable {
    private String name;
    private int id;
    private int tempType;// 0 for fahrenheit, 1 for celsius.
    private int powerPercent;
    private int freq;
    private int temp;
    private int cycleDateDay;
    private int cycleDateMonth;
    private int numberOfCycles;
    private int cycleTimeHour;
    private int cycleTimeMinute;

    public listControlObject(String name, int id, int tempType,
            int powerPercent, int freq, int temp, int cycleTimeHour,
            int cycleTimeMinute, int cycleDateDay, int cycleDateMonth,
            int numberOfCycles) {
        this.id = id;
        this.name = name;
        this.cycleDateDay = cycleDateDay;
        this.cycleDateMonth = cycleDateMonth;
        this.cycleTimeHour = cycleTimeHour;
        this.cycleTimeMinute = cycleTimeMinute;
        this.freq = freq;
        this.numberOfCycles = numberOfCycles;
        this.powerPercent = powerPercent;
        this.temp = temp;
        this.tempType = tempType;

    }

    private listControlObject(Parcel in){
        this.id = in.readInt();
        this.name = in.readString();
        this.cycleDateDay = in.readInt();
        this.cycleDateMonth = in.readInt();
        this.cycleTimeHour = in.readInt();
        this.cycleTimeMinute = in.readInt();
        this.freq = in.readInt();
        this.numberOfCycles = in.readInt();
        this.powerPercent = in.readInt();
        this.temp = in.readInt();
        this.tempType = in.readInt();

    }

    public int getCycleDateDay() {
        return cycleDateDay;
    }

    public void setCycleDateDay(int cycleDateDay) {
        this.cycleDateDay = cycleDateDay;
    }

    public int getCycleDateMonth() {
        return cycleDateMonth;
    }

    public void setCycleDateMonth(int cycleDateMonth) {
        this.cycleDateMonth = cycleDateMonth;
    }

    public int getCycleTimeHour() {
        return cycleTimeHour;
    }

    public void setCycleTimeHour(int cycleTimeHour) {
        this.cycleTimeHour = cycleTimeHour;
    }

    public int getCycleTimeMinute() {
        return cycleTimeMinute;
    }

    public void setCycleTimeMinute(int cycleTimeMinute) {
        this.cycleTimeMinute = cycleTimeMinute;
    }

    public int getNumberOfCycles() {
        return numberOfCycles;
    }

    public void setNumberOfCycles(int numberOfCycles) {
        this.numberOfCycles = numberOfCycles;
    }

    public int getTempType() {
        return tempType;
    }

    public void setTempType(int tempType) {
        this.tempType = tempType;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPowerPercent() {
        return powerPercent;
    }

    public void setPowerPercent(int powerPercent) {
        this.powerPercent = powerPercent;
    }

    public int getFreq() {
        return freq;
    }

    public void setFreq(int freq) {
        this.freq = freq;
    }

    public int getTemp() {
        return temp;
    }

    public void setTemp(int temp) {
        this.temp = temp;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {

        return this.name;
    }

    @Override
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int flags) {
        parcel.writeInt(id);
        parcel.writeString(name);
        parcel.writeInt(cycleDateDay);
        parcel.writeInt(cycleDateMonth);
        parcel.writeInt(cycleTimeHour);
        parcel.writeInt(cycleTimeMinute);
        parcel.writeInt(freq);
        parcel.writeInt(numberOfCycles);
        parcel.writeInt(powerPercent);
        parcel.writeInt(temp);
        parcel.writeInt(tempType);

    }
    public static Creator<listControlObject> CREATOR = new Creator<listControlObject>() {
        public listControlObject createFromParcel(Parcel parcel) {
            return new listControlObject(parcel);
        }

        public listControlObject[] newArray(int size) {
            return new listControlObject[size];
        }

    };


}

Edit:

I have discovered the source of my error:

I am passing a parcel here when I need to pass a listControlObject.

cyclefragment.a1.add(intent.getParcelableExtra("custom_object"));
            cyclefragment.adapter.notifyDataSetChanged();

How do I transform that intent.getParcelableExtra("custom_object") back into a listControlObject?

[UPDATE]

New Logcat error:

    03-24 02:29:46.177: E/AndroidRuntime(9685): FATAL EXCEPTION: main
03-24 02:29:46.177: E/AndroidRuntime(9685): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nanospark.upcdemo/com.nanospark.upcdemo.MainActivity}: java.lang.NullPointerException
03-24 02:29:46.177: E/AndroidRuntime(9685):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
03-24 02:29:46.177: E/AndroidRuntime(9685):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2211)
03-24 02:29:46.177: E/AndroidRuntime(9685):     at android.app.ActivityThread.access$600(ActivityThread.java:149)
03-24 02:29:46.177: E/AndroidRuntime(9685):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1300)
03-24 02:29:46.177: E/AndroidRuntime(9685):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-24 02:29:46.177: E/AndroidRuntime(9685):     at android.os.Looper.loop(Looper.java:153)
03-24 02:29:46.177: E/AndroidRuntime(9685):     at android.app.ActivityThread.main(ActivityThread.java:4987)
03-24 02:29:46.177: E/AndroidRuntime(9685):     at java.lang.reflect.Method.invokeNative(Native Method)
03-24 02:29:46.177: E/AndroidRuntime(9685):     at java.lang.reflect.Method.invoke(Method.java:511)
03-24 02:29:46.177: E/AndroidRuntime(9685):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
03-24 02:29:46.177: E/AndroidRuntime(9685):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
03-24 02:29:46.177: E/AndroidRuntime(9685):     at dalvik.system.NativeStart.main(Native Method)
03-24 02:29:46.177: E/AndroidRuntime(9685): Caused by: java.lang.NullPointerException
03-24 02:29:46.177: E/AndroidRuntime(9685):     at com.nanospark.upcdemo.MainActivity.processNewIntent(MainActivity.java:88)
03-24 02:29:46.177: E/AndroidRuntime(9685):     at com.nanospark.upcdemo.MainActivity.onCreate(MainActivity.java:70)
03-24 02:29:46.177: E/AndroidRuntime(9685):     at android.app.Activity.performCreate(Activity.java:5020)
03-24 02:29:46.177: E/AndroidRuntime(9685):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
03-24 02:29:46.177: E/AndroidRuntime(9685):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
03-24 02:29:46.177: E/AndroidRuntime(9685):     ... 11 more

Relevant code:

@Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        processNewIntent(intent);
    }

    private void processNewIntent(Intent intent) {
        Log.v("TEST", "METHOD CALLED TEST");
        if (intent.hasExtra("custom_object")) {
            if (intent.getParcelableExtra("custom_object")
                    .equals(null)) {
                Log.v("Testing null", "Object is null");
            } else {
                Log.v("Testing null", "Object is not null");
                cyclefragment.a1.add((listControlObject) intent.getParcelableExtra("custom_object"));
                cyclefragment.adapter.notifyDataSetChanged();
            }
        }
    }

logcat error refers to this line:

cyclefragment.a1.add((listControlObject) intent.getParcelableExtra("custom_object"));

I made

private listControlObject(Parcel in){

public listControlObject(Parcel in){

as per request from comments. Still receiving error.

Was it helpful?

Solution

It seems that your trace file is corrupted or holding by another process. The Logcat may got error on line: Log.d("LISTACTIVITY", "Intent successfully passed!");

Or you check all the namefield or temperatureFrag ... in the activity to ensure that their instances are all initialized be fore calling onClick() of your sending activity.

Because you made your call of all instances in one code line, so it's hard to figure out the bug. Try DDMS for debugging!

P/S: where is line 72 in your code?

[UPDATE]

More details: Passing a custom Object from one Activity to another Parcelable vs Bundle

If you already "Parcel" well, in your destination activity, just simply cast your received object to the original type, like what you did in your code.

The error of your code is private listControlObject(Parcel in) with private. Change to public so that Intent can use this constructor to restore object from previously parceled string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top