向上导航的空指针android

Posted

技术标签:

【中文标题】向上导航的空指针android【英文标题】:Nullpointer at Upnavigation android 【发布时间】:2014-10-02 21:42:12 【问题描述】:

当点击操作栏的向上导航时,我想通过意图发送两个额外内容。在清单上声明父活动,在 OnCreate 处设置第二个活动getActionBar().setDisplayHomeAsUpEnabled(true);。但是父活动需要一个意图值才能工作(citySave)。我已经尝试了很多,但我没有得到它的工作,向上导航将意图值发送到父活动(R.id.home)。

我没有从第二个活动中添加整个代码,因为它会出现太多迹象。我在第二个活动中使用了 2 个片段,它们被定义为静态的。我不知道,这是否与问题有关。

第二个活动:

public class RouteView extends ActionBarActivity 

    Integer citySave;
    String cityTitle;
    Integer routeSave;
    String routeTitel;
    private static int NUM_ITEMS = 2;
    SectionsPagerAdapter mSectionsPagerAdapter;
    ListView listView;
    ArrayList<RowItem> pois;

    /**
     * The @link ViewPager that will host the section contents.
     */
    ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_route_view);
        Bundle b = getIntent().getExtras();
        citySave = b.getInt("stadt");
        cityTitle = b.getString("titel_stadt");
        routeSave = b.getInt("route");
        routeTitel = b.getString("titel_route");
        b.putString("titel_route",routeTitel);
        b.putInt("route", routeSave);
        getActionBar().setDisplayHomeAsUpEnabled(true);
        //RouteItemFragment fragobj = new RouteItemFragment();
        //fragobj.setArguments(b);

        final ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        setTitle("Route:" + " " + routeTitel);


public void onBackPressed() 
        super.onBackPressed();
        Intent intent = new Intent();
        intent.setClass(RouteView.this, RouteChooseActivity.class);
        Bundle b = new Bundle();
        b.putInt("stadt", citySave);
        b.putString("titel_stadt", cityTitle);
        intent.putExtras(b);
        startActivity(intent);
        finish();
    

    public void onPause() 
        super.onPause();
        Bundle b = new Bundle();
        b.putInt("stadt", citySave);
        b.putInt("route", routeSave);
        b.putString("route_titel",routeTitel);
        finish();
    

    public void onResume() 
        super.onResume();

        Bundle b = getIntent().getExtras();
        citySave = b.getInt("stadt");
        routeSave = b.getInt("route");
        routeTitel = b.getString("route_titel");

    

    public void onStop() 
        super.onStop();
        finish();
    

    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
        switch (item.getItemId()) 
            case R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                Intent upIntent = NavUtils.getParentActivityIntent(this);
                Bundle b = new Bundle();
                b.putInt("stadt", citySave);
                b.putString("titel_stadt", cityTitle);
                upIntent.putExtras(b);
                //startActivity(upIntent);
                return true;
            case R.id.action_stadt:
                setContentView(R.layout.activity_stadt);
                Intent stadt = new Intent(RouteView.this, StadtActivity.class);
                startActivity(stadt);
                return true;
            case R.id.action_route:
                setContentView(R.layout.activity_route_choose);
                Intent route = new Intent(RouteView.this, RouteChooseActivity.class);
                route.putExtra("stadt", citySave);
                route.putExtra("titel_stadt", cityTitle);
                startActivity(route);
                return true;
            case R.id.action_help:
                setContentView(R.layout.activity_help);
                Intent help = new Intent(RouteView.this, Help.class);
                startActivity(help);
                return true;
            case R.id.action_exit:
                moveTaskToBack(true);
                System.exit(0);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        
    


家长活动:

    public class RouteChooseActivity extends ActionBarActivity implements OnItemClickListener 

        Integer citySave;
        Integer routeSave;
        String cityTitle;
        ListView listView;
        List<RowItem> cities;
        CityParser parser = new CityParser();

        @Override
        protected void onCreate(Bundle savedInstanceState) 
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_route_choose);
            Bundle b = getIntent().getExtras();
            citySave = b.getInt("stadt");
            cityTitle = b.getString("titel_stadt");
            TextView headingRoute = (TextView) findViewById(R.id.routeTitel);
            headingRoute.setText(String.format(getResources().getString(R.string.route_text)) + " " + cityTitle + " aus:");
            listView = (ListView) findViewById(R.id.listRoute);
   if (citySave.equals(1)) 
            try 
                cities = parser.parse(getAssets().open("route_passau.xml"));
                CityListViewAdapter adapter = new CityListViewAdapter(this, R.layout.row_items, (ArrayList<RowItem>) cities);
                Collections.sort(cities, new Comparator<RowItem>() 
                    public int compare(RowItem s1, RowItem s2) 
                        return s1.getTitle().compareTo(s2.getTitle());
                    
                );
                listView.setAdapter(adapter);

             catch (IOException e) 
                e.printStackTrace();
            
         else if (citySave.equals(2)) 
            try 
                cities = parser.parse(getAssets().open("route_bamberg.xml"));
                CityListViewAdapter adapter = new CityListViewAdapter(this, R.layout.row_items, (ArrayList<RowItem>) cities);
                Collections.sort(cities, new Comparator<RowItem>() 
                    public int compare(RowItem s1, RowItem s2) 
                        return s1.getTitle().compareTo(s2.getTitle());
                    
                );
                listView.setAdapter(adapter);
             catch (IOException e) 
                e.printStackTrace();
            
         else if (citySave.equals(3)) 
            try 
                cities = parser.parse(getAssets().open("route_augsburg.xml"));
                CityListViewAdapter adapter = new CityListViewAdapter(this, R.layout.row_items, (ArrayList<RowItem>) cities);
                Collections.sort(cities, new Comparator<RowItem>() 
                    public int compare(RowItem s1, RowItem s2) 
                        return s1.getTitle().compareTo(s2.getTitle());
                    
                );
                listView.setAdapter(adapter);
             catch (IOException e) 
                e.printStackTrace();
            
         else 
            try 
                TextView errorMessage = (TextView) findViewById(R.id.routeTitel);
                errorMessage.setText(R.string.errorroute);
             catch (NullPointerException e) 
                Context context = getApplicationContext();
                CharSequence text = getResources().getString(R.string.errorroute);
                int duration = Toast.LENGTH_LONG;
                Toast toast = Toast.makeText(context, text, duration);
                toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                toast.show();
            
        
        listView.setOnItemClickListener(this);

        final ActionBar actionBar = getSupportActionBar();
        setTitle("Routen in" + " " + cityTitle);
    

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
        Intent intent = new Intent();
        intent.setClass(RouteChooseActivity.this, RouteView.class);
        RowItem cities = (RowItem) parent.getItemAtPosition(position);
        Bundle b = new Bundle();
        b.putInt("stadt", citySave);
        b.putString("titel_stadt", cityTitle);
        b.putInt("route", cities.getID());
        b.putString("titel_route", cities.getTitle());
        intent.putExtras(b);
        startActivity(intent);
    

     @Override
protected void onSaveInstanceState (Bundle outState) 
    super.onSaveInstanceState(outState);
    outState.putInt("stadt", citySave);
    outState.getString("titel_stadt", cityTitle);


    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) 
        super.onRestoreInstanceState(savedInstanceState);
        // Restore UI state from the savedInstanceState.
        // This bundle has also been passed to onCreate.
        citySave = savedInstanceState.getInt("stadt");
        Log.i("debug", "saved data: " + citySave);
    

    @Override
    public void onResume() 
        super.onResume();

            Bundle b = getIntent().getExtras();
            citySave = b.getInt("stadt");
            cityTitle = b.getString("titel_stadt");

    

    @Override
    public void onPause() 
        super.onPause();
        Bundle b = new Bundle();
        b.putInt("stadt", citySave);
        b.putString("titel_stadt", cityTitle);
        unbindDrawables(findViewById(R.id.Bild));
        System.gc();
    

    @Override
    public void onStop() 
        super.onStop();
        Bundle b = new Bundle();
        b.putInt("stadt", citySave);
        b.putString("titel_stadt", cityTitle);
        finish();
    

    @Override
    protected void onDestroy()
    
        super.onDestroy();
        unbindDrawables(findViewById(R.id.Bild));
        System.gc();
    

    @Override
    public void onRestart() 
        super.onRestart();
        Bundle b = getIntent().getExtras();
        citySave = b.getInt("stadt");
        cityTitle = b.getString("titel_stadt");
    

    private void unbindDrawables(View view)
    
        if (view.getBackground() != null)
        
            view.getBackground().setCallback(null);
        
        if (view instanceof ViewGroup && !(view instanceof AdapterView))
        
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++)
            
                unbindDrawables(((ViewGroup) view).getChildAt(i));
            
            ((ViewGroup) view).removeAllViews();
        
    

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
        getMenuInflater().inflate(R.menu.route, menu);
        return true;
    

    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
        switch (item.getItemId()) 
            case R.id.action_stadt:
                setContentView(R.layout.activity_stadt);
                Intent stadt = new Intent(RouteChooseActivity.this, StadtActivity.class);
                startActivity(stadt);
                return true;
            case R.id.action_help:
                setContentView(R.layout.activity_help);
                Intent help = new Intent(RouteChooseActivity.this, Help.class);
                startActivity(help);
                return true;
            case R.id.action_exit:
                moveTaskToBack(true);
                System.exit(0);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        
    

Logcat:

java.lang.RuntimeException: Unable to start activity ComponentInfode.cityknight.app/de.cityknight.app.RouteChooseActivity: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at de.cityknight.app.RouteChooseActivity.onCreate(RouteChooseActivity.java:44)
            at android.app.Activity.performCreate(Activity.java:5231)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)

【问题讨论】:

检查Bundle b是否为空。 它不能为空,因为 OnBackPressed 正在工作。 查看pastebin.com/N0fgWWYw 并告诉我发生了什么 您的 NullPointerException 发生在 RouteChooseActivity 的第 44 行,其余代码在哪里? 我已经添加了整个代码,但是第 44 行是 citySave = b.getInt("stadt"); 【参考方案1】:

在 Activity 的 onCreate() 方法中,Bundle 将具有以下值:(来自 official documentation)

如果活动在之前关闭后重新初始化 向下,则此 Bundle 包含它最近提供的数据 onSaveInstanceState(捆绑)。注意:否则为空。

getIntent().getExtras() 也是如此。所以你应该检查这个值以避免 NullPointerException。

Bundle b = getIntent().getExtras();
if (b != null) 
  citySave = b.getInt("stadt");
  cityTitle = b.getString("titel_stadt");

【讨论】:

谢谢,我会尽快尝试。如果我理解正确,我必须设置 onRestoreInstanceState? 已编辑答案。您必须检查该值是否为空。 谢谢,否则是什么条件?我已经测试过: else citySave = savedInstanceState.getInt("stadt"); cityTitle = savedInstanceState.getString("titel_stadt"); 但 NullPointer。没有其他条件 NullPointer 在 citySave.equals... 如果Bundle为null,表示没有数据。所以不要尝试处理数据,因为会有 NullPointerException。 如你所见,我是一个该死的初学者。好的,我明白了。如何获取数据?【参考方案2】:

在 *** 上找到正确答案:https://***.com/a/17342137/3762248

“android 活动的“标准”行为是,每次有新意图时,都会创建一个新的活动实例(请参阅此处的 launchMode-docu)。因此,您的附加功能似乎走吧,如果你调用 navigateUpTo。

在你的情况下,我建议使用

android:launchMode="singleTop"

AndroidManifest.xml 中的父活动。这样,您将返回到您现有的活动(只要它位于任务的后堆栈的顶部)。这样您的额外内容将被保留。

我也是,不明白为什么您引用的 Google 文档中没有提到这一点,因为这似乎是使用向上导航时所期望的行为。”

【讨论】:

以上是关于向上导航的空指针android的主要内容,如果未能解决你的问题,请参考以下文章

带有 ListView 的导航抽屉。 ListView 上的空指针异常

从 Android 的 LocationManager 请求 getLastKnownLocation 时的空指针

android 中遇到的空指针异常

android 中遇到的空指针异常

使用android相机捕获图像后的空指针

对话框中按钮的空指针异常 -- Android -- JAVA