我通过的包裹是空的?

时间:2014-03-24 06:09:07

标签: android android-intent nullpointerexception parcelable parcel

我不确定如何正确构建这个包裹;当我尝试从null添加包裹的对象时,我将返回MainActivity

发送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++;  
        }

    });
}

接收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();
        }
    }

发送intent时,我是否错误地实施了包裹?我的processNewIntent是否有理由给我NullPointerException

我猜测有一种特定的方法可以构建一个包裹,并通过我没有正确实施的意图传递它,但我找不到任何好的资源。

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)

谢谢你们。

编辑:

listaddactivity.java的第72行:

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())));

上面只是构造一个新对象,并使用键&#34;自定义对象&#34;将其添加到intent中。

以下是parcelable对象的代码:

    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];
        }

    };


}

编辑:

我发现了我的错误来源:

当我需要传递listControlObject时,我正在传递一个包裹。

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

如何将intent.getParcelableExtra(&#34; custom_object&#34;)转换回l​​istControlObject?

[UPDATE]

新的Logcat错误:

    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

相关代码:

@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错误指的是这一行:

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

我做了

private listControlObject(Parcel in){

public listControlObject(Parcel in){

根据评论的要求。仍然收到错误。

1 个答案:

答案 0 :(得分:1)

您的跟踪文件似乎已损坏或由另一个进程保留。 Logcat可能会出现错误:Log.d("LISTACTIVITY", "Intent successfully passed!");

或者您检查活动中的所有namefieldtemperatureFrag ...,以确保在调用发送活动的onClick()之前已初始化其实例。

因为您在一个代码行中调用了所有实例,所以很难找出错误。尝试使用DDMS进行调试!

P / S:您的代码中的第72行在哪里?

<强> [UPDATE]

更多细节: Passing a custom Object from one Activity to another Parcelable vs Bundle

如果您已经很好地“包裹”了,那么在您的目标活动中,只需将收到的对象转换为原始类型,就像您在代码中所做的那样。

您的代码错误为private listControlObject(Parcel in) private。更改为public,以便Intent可以使用此构造函数从先前包含的字符串中恢复对象。