代码之家  ›  专栏  ›  技术社区  ›  Timothy Frisch

我传递的包裹是空的?

  •  1
  • Timothy Frisch  · 技术社区  · 12 年前

    我不知道如何正确地构建这个包裹;我要回来了 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();
            }
        }
    

    当我发送 意图 ? 有什么原因吗 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())));
    

    上面只是构造了一个新对象,并使用键“自定义对象”将其添加到意图中。

    以下是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(“custom_object”)转换回listControlObject?

    [更新]

    新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 回复  |  直到 12 年前
        1
  •  2
  •   Community Mohan Dere    9 年前

    您的跟踪文件似乎已损坏或被其他进程保存。Logcat可能在线上出错: Log.d("LISTACTIVITY", "Intent successfully passed!");

    或者你检查所有 namefield temperatureFrag …,以确保在调用发送活动的onClick()之前,它们的实例都已初始化。

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

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

    [更新]

    更多详情: Passing a custom Object from one Activity to another Parcelable vs Bundle

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

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

    推荐文章