简体   繁体   English

为什么我的Android程序第73行出现Null指针异常?

[英]Why am I getting a Null Pointer Exception on my Android Program line 73?

I am not entirely sure why I am getting a NullPointerException . 我不完全确定为什么会收到NullPointerException If anybody could help me out that would be great. 如果有人可以帮助我,那就太好了。 I labeled Line 73 below. 我在下面标记了73行。

    package com.shantanu.report;


import java.io.File;
import java.util.Locale;


import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
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.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.ipaulpro.afilechooser.utils.FileUtils;

public class MainActivity extends FragmentActivity implements
        ActionBar.TabListener {
    SectionsPagerAdapter mSectionsPagerAdapter;
    ViewPager mViewPager;

    Button b1, b2, b3, b4, b5;

    private static final int REQUEST_CODE = 6384; // onActivityResult request code


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


        b1 = (Button) findViewById(R.id.b1);
        b2 = (Button) findViewById(R.id.b2);
        b3 = (Button) findViewById(R.id.b3);
        b4 = (Button) findViewById(R.id.b4);    
        b5 = (Button) findViewById(R.id.b5);

        b5.setOnClickListener(new OnClickListener() { //line 73
            public void onClick(View v) {
                // Display the file chooser dialog
                showChooser();
            }
        });

        setContentView(b5);

        mSectionsPagerAdapter = new SectionsPagerAdapter(
                getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        // 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 ViewPager.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));
        }
    }
private void showChooser() {
    // Use the GET_CONTENT intent from the utility class
    Intent target = FileUtils.createGetContentIntent();
    // Create the chooser Intent
    Intent intent = Intent.createChooser(
            target, getString(R.string.chooser_title));
    try {
        startActivityForResult(intent, REQUEST_CODE);
    } catch (ActivityNotFoundException e) {
        // The reason for the existence of aFileChooser

    }               
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case REQUEST_CODE:  
        // If the file selection was successful
        if (resultCode == RESULT_OK) {      
            if (data != null) {
                // Get the URI of the selected file
                final Uri uri = data.getData();

                try {
                    // Create a file instance from the URI
                    final File file = FileUtils.getFile(uri);
                    Toast.makeText(MainActivity.this, 
                            "File Selected: "+file.getAbsolutePath(), Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    Log.e("FileSelectorTestActivity", "File select error", e);
                }
            }
        } 
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

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

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



/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a DummySectionFragment (defined as a static inner class
        // below) with the page number as its lone argument.
        Fragment fragment; 
        fragment=null;

        switch(position){
        case 0:
             fragment = new MyFragment0();
             break;
        case 1:
             fragment = new MyFragment1();
             break;
        case 2:
             fragment = new MyFragment2();
             break;

        }

        //set args if necessary
        Bundle args = new Bundle();
        args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
        fragment.setArguments(args);

        //return fragment
        return fragment;
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Locale l = Locale.getDefault();
        switch (position) {
        case 0:
            return getString(R.string.title_section1).toUpperCase(l);
        case 1:
            return getString(R.string.title_section2).toUpperCase(l);
        case 2:
            return getString(R.string.title_section3).toUpperCase(l);
        }
        return null;
    }
}

/**
 * A dummy fragment representing a section of the app, but that simply
 * displays dummy text.
 */
public static class DummySectionFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    public static final String ARG_SECTION_NUMBER = "section_number";

    public DummySectionFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main_dummy,
                container, false);
        TextView dummyTextView = (TextView) rootView
                .findViewById(R.id.section_label);
        dummyTextView.setText(Integer.toString(getArguments().getInt(
                ARG_SECTION_NUMBER)));
        return rootView;
    }
}

} }

The Error log is below: 错误日志如下:

08-14 18:21:09.375: E/AndroidRuntime(1303): FATAL EXCEPTION: main
08-14 18:21:09.375: E/AndroidRuntime(1303): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.shantanu.report/com.shantanu.report.MainActivity}: java.lang.NullPointerException
08-14 18:21:09.375: E/AndroidRuntime(1303):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
08-14 18:21:09.375: E/AndroidRuntime(1303):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
08-14 18:21:09.375: E/AndroidRuntime(1303):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-14 18:21:09.375: E/AndroidRuntime(1303):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
08-14 18:21:09.375: E/AndroidRuntime(1303):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-14 18:21:09.375: E/AndroidRuntime(1303):     at android.os.Looper.loop(Looper.java:137)
08-14 18:21:09.375: E/AndroidRuntime(1303):     at android.app.ActivityThread.main(ActivityThread.java:5103)
08-14 18:21:09.375: E/AndroidRuntime(1303):     at java.lang.reflect.Method.invokeNative(Native Method)
08-14 18:21:09.375: E/AndroidRuntime(1303):     at java.lang.reflect.Method.invoke(Method.java:525)
08-14 18:21:09.375: E/AndroidRuntime(1303):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
08-14 18:21:09.375: E/AndroidRuntime(1303):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-14 18:21:09.375: E/AndroidRuntime(1303):     at dalvik.system.NativeStart.main(Native Method)
08-14 18:21:09.375: E/AndroidRuntime(1303): Caused by: java.lang.NullPointerException
08-14 18:21:09.375: E/AndroidRuntime(1303):     at com.shantanu.report.MainActivity.onCreate(MainActivity.java:73)

It looks to me, that line 在我看来,那条线

(ViewPager) findViewById(R.id.pager);

returns null and therefore the statement mViewPager.setAdapter(mSectionsPagerAdapter); 返回null,因此返回语句mViewPager.setAdapter(mSectionsPagerAdapter); crashes. 崩溃。 Make sure, there is a ViewPager in your xml layout. 确保您的xml布局中有一个ViewPager。

there are 2 problems I see here, b5 is null, check your xml layout to make sure you have the id right 我在这里看到2个问题,b5为空,请检查您的xml布局以确保您拥有正确的ID

second you are setting the content view again to a button after you already set it when you started the activity 第二,您在开始活动时已经将内容视图设置为按钮之后再次将其设置为按钮

setContentView(b5);

so you are changing the view to a button which I assume you dont want to do 所以您将视图更改为一个按钮,我认为您不想这样做

It's probably an issue in your activity_main.xml file. 这可能是您的activity_main.xml文件中的问题。

I noticed in your comment that you declare b5 in your xml like this: 我在您的评论中注意到,您在xml中这样声明b5:

<Button android:id="@+id/b5" android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:layout_below="@id/b4"/>

I can see a problem with your layout_below field. 我可以看到您的layout_below字段有问题。 The id should match exactly how the id was declared. ID应该与ID声明的方式完全匹配。 So, instead of "@id/b4", it should be "@+id/b4". 因此,它应该是“ @ + id / b4”而不是“ @ id / b4”。

I would recommend posting your xml as well, because that's probably where the problem lies. 我也建议您发布xml,因为这可能就是问题所在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM