有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么在尝试在评级栏中将值设置为“rating”时出现空指针异常?

我可以看到异常发生在“rtb.setRating(8.0f);” 此外,我还可以在xml文件中手动设置评级,从而产生预期的结果,例如安卓:rating=“3.7”

static String ingredients[] = {"Ingredient1","Ingredient2","Ingredient3","Ingredient4","Ingredient5","Ingredient6","Ingredient7","Ingredient8","Ingredient9","Ingredient10","Ingredient11","Ingredient12","Ingredient13","Ingredient14","Ingredient15","Ingredient16","Ingredient17","Ingredient18","Ingredient19","Ingredient20"};
static String steps[] = {"Step1","Step2","Step3","Step4","Step5","Step6","Step7","Step8","Step9","Step10"};


String url = "http://192.168.1.2/cricketjson.txt";


private ListView mDrawerList;
private ArrayAdapter<String> mAdapter;
static int[] ids = {1,2,3,4,5};



/**
 * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
 */
private NavigationDrawerFragment mNavigationDrawerFragment;

/**
 * Used to store the last screen title. For use in {@link #restoreActionBar()}.
 */
private CharSequence mTitle;
private CharSequence mStep;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    RatingBar rtb = (RatingBar) findViewById(R.id.rb);
    rtb.setRating(8.0f);

    setContentView(R.layout.activity_recipe);
    mDrawerList = (ListView)findViewById(R.id.navList);
   //set visual features
  //set string values
    TextView[] txtStep = {(TextView) findViewById(R.id.txtStep1),        (TextView) findViewById(R.id.txtStep2)};


    //txtStep1.setText("ftUr");

 //set font Title
    TextView mRecipeTitle = (TextView) findViewById(R.id.Title);
    Typeface face = Typeface.createFromAsset(getAssets(),
            "Italianno-Regular.ttf");
    mRecipeTitle.setTypeface(face);
    mRecipeTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 77);
// set scrollview as transparent
    findViewById(R.id.recipScrollView).setBackgroundColor(getResources().getColor(安卓.R.color.transparent));

    // PD = new ProgressDialog(this);
    // PD.setMessage("Loading.....");

    mNavigationDrawerFragment = (NavigationDrawerFragment)
            getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
    mTitle = getTitle();




    // Set up the drawer.
    mNavigationDrawerFragment.setUp(
            R.id.navigation_drawer,
            (DrawerLayout) findViewById(R.id.drawer_layout));


    mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(RecipeActivity.this, "Time for an upgrade!", Toast.LENGTH_SHORT).show();
        }
    });

   //here*#8*#*  put in the steps to the func.jsonrq


  //  Funcs.makejsonobjreq(ingredients, url, this,steps,id);
    Funcs.makejsonobjreq(ingredients, url, this);
    Funcs.makejsonobjreqrecipe(ingredients, url, this, steps, ids[0], txtStep);


}


@Override
public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction()
            .replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
            .commit();
}

public void onSectionAttached(int number) {
    switch (number) {
        case 1:
            mTitle = getString(R.string.title_Recipe);
            break;
        case 2:
            mTitle = ingredients[0];

            break;
        case 3:
            mTitle = ingredients[1];
            break;
        case 4:
            mTitle = ingredients[2];
            break;
        case 5:
            mTitle = ingredients[3];
            break;
        case 6:
            mTitle = ingredients[4];
            break;
        case 7:
            mTitle = ingredients[5];
            break;
        case 8:
            mTitle = ingredients[6];
            break;
        case 9:
            mTitle = ingredients[7];
            break;
        case 10:
            mTitle = ingredients[8];
            break;
        case 11:
            mTitle = ingredients[9];
            break;
        case 12:
            mTitle = ingredients[10];
            break;
        case 13:
            mTitle = ingredients[11];
            break;
        case 14:
            mTitle = ingredients[12];
            break;
        case 15:
            mTitle = ingredients[13];
            break;
        case 16:
            mTitle = ingredients[14];
            break;
        case 17:
            mTitle = ingredients[15];
            break;
        case 18:
            mTitle = ingredients[16];
            break;
        case 19:
            mTitle = ingredients[17];
            break;
        case 20:
            mTitle = ingredients[18];
            break;
        case 21:
            mTitle = ingredients[19];
            break;
    }
}

public void restoreActionBar() {
    ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setTitle(mTitle);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {

    if (!mNavigationDrawerFragment.isDrawerOpen()) {
        // Only show items in the action bar relevant to this screen
        // if the drawer is not showing. Otherwise, let the drawer
        // decide what to show in the action bar.
        getMenuInflater().inflate(R.menu.recipe, menu);
        restoreActionBar();
        return true;
    }
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_recipe, container, false);
        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((RecipeActivity) activity).onSectionAttached(
                getArguments().getInt(ARG_SECTION_NUMBER));
    }
}



}

以及核心响应XML:

<!-- As the main content view, the view below consumes the entire
     space available using match_parent in both dimensions. -->
<FrameLayout 安卓:id="@+id/container" 安卓:layout_width="match_parent"
    安卓:layout_height="match_parent"
   >


    <LinearLayout
        安卓:background="@drawable/background8"
        安卓:layout_width="match_parent"
        安卓:layout_height="match_parent"
        安卓:orientation="vertical"
        安卓:paddingTop="20dip"
        安卓:layout_gravity="right|center_vertical"
        安卓:weightSum="1">

        <TextView
            安卓:layout_marginTop="0dp"
            安卓:layout_width="wrap_content"
            安卓:layout_height="wrap_content"
            安卓:text="New Text"
            安卓:id="@+id/Creator"
            安卓:layout_alignLeft="@id/title"
            安卓:textSize="20dp"
            安卓:layout_gravity="center_horizontal" />

        <TextView
            安卓:layout_marginTop="30dp"
    安卓:layout_width="wrap_content"
    安卓:layout_height="wrap_content"
    安卓:textAppearance="?安卓:attr/textAppearanceLarge"
    安卓:text="Large Text"
    安卓:id="@+id/Title"
    安卓:layout_below="@id/Creator"
            安卓:layout_gravity="center_horizontal" />

        <ScrollView 安卓:layout_width="match_parent"
            安卓:layout_marginTop="0dp"
            安卓:layout_marginLeft="30dp"
            安卓:layout_marginRight="30dp"
            安卓:layout_height="198dp"
            安卓:background="#ffffff"
            安卓:id="@+id/recipScrollView">

            <LinearLayout
                安卓:layout_marginLeft="30dp"

                安卓:layout_width="match_parent"
                安卓:layout_height="wrap_content"
                安卓:orientation="vertical"
                安卓:paddingTop="20dip"
                安卓:weightSum="1">

                <TextView
                    安卓:layout_marginTop="0dp"
                    安卓:layout_width="wrap_content"
                    安卓:layout_height="wrap_content"
                    安卓:text="New Txt"
                    安卓:id="@+id/txtStep1" />

                <TextView
                    安卓:layout_marginTop="30dp"
                    安卓:layout_width="wrap_content"
                    安卓:layout_height="wrap_content"
                    安卓:text="New Txt"
                    安卓:id="@+id/txtStep2"
                    安卓:layout_below="@id/txtStep1"/>/>

            </LinearLayout>
        </ScrollView>

        <RatingBar
            安卓:layout_marginTop="30dp"
            安卓:layout_marginLeft="30dp"
            安卓:id="@+id/rb"
            style="?安卓:attr/ratingBarStyleSmall"
            安卓:layout_width="wrap_content"
            安卓:layout_height="wrap_content"
            安卓:max="10"
            安卓:numStars="10"
            安卓:rating="3.7"
            安卓:stepSize="0.0" />


    </LinearLayout>

</FrameLayout>

<!-- 安卓:layout_gravity="start" tells DrawerLayout to treat
     this as a sliding drawer on the left side for left-to-right
     languages and on the right side for right-to-left languages.
     If you're not building against API 17 or higher, use
     安卓:layout_gravity="left" instead. -->
<!-- The drawer is given a fixed width in dp and extends the full height of
     the container. -->
<fragment 安卓:id="@+id/navigation_drawer"
    安卓:layout_width="@dimen/navigation_drawer_width" 安卓:layout_height="match_parent"
    安卓:layout_gravity="start" 安卓:name="com.example.finnb.rcp.NavigationDrawerFragment"
    tools:layout="@layout/fragment_navigation_drawer" />

<ListView
    安卓:id="@+id/navList"
    安卓:layout_width="200dp"
    安卓:layout_height="match_parent"
    安卓:layout_gravity="left|start"
    安卓:background="#ffeeeeee"/>

以及LogCat错误:

03-08 04:52:30.350    1946-1946/com.example.finnb.rcp D/dalvikvm﹕ Not late-enabling CheckJNI (already on)
03-08 04:52:30.460    1946-1946/com.example.finnb.rcp D/AndroidRuntime﹕ Shutting down VM
03-08 04:52:30.460    1946-1946/com.example.finnb.rcp W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb0ca2b20)
03-08 04:52:30.460    1946-1946/com.example.finnb.rcp E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.finnb.rcp, PID: 1946
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.finnb.rcp/com.example.finnb.rcp.RecipeActivity}: java.lang.NullPointerException
            at 安卓.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
            at 安卓.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
            at 安卓.app.ActivityThread.access$800(ActivityThread.java:135)
            at 安卓.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at 安卓.os.Handler.dispatchMessage(Handler.java:102)
            at 安卓.os.Looper.loop(Looper.java:136)
            at 安卓.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.安卓.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
            at com.安卓.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at com.example.finnb.rcp.RecipeActivity.onCreate(RecipeActivity.java:62)
            at 安卓.app.Activity.performCreate(Activity.java:5231)
            at 安卓.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            at 安卓.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
            at 安卓.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
            at 安卓.app.ActivityThread.access$800(ActivityThread.java:135)
            at 安卓.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at 安卓.os.Handler.dispatchMessage(Handler.java:102)
            at 安卓.os.Looper.loop(Looper.java:136)
            at 安卓.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.安卓.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
            at com.安卓.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)

共 (3) 个答案

  1. # 1 楼答案

    setContentView(R.layout.activity_recipe);这一行应该在这一行的正下方super.onCreate(savedInstanceState);之后,您应该访问/实例化视图

    您正在尝试在链接xml布局之前访问分级栏

  2. # 2 楼答案

    这很简单。假设您在setContentView中使用了正确的布局:

    以下是正确的初始化顺序:

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recipe);
    
        RatingBar rtb = (RatingBar) findViewById(R.id.rb);
        rtb.setRating(8.0f);
    

    如果布局是通过setContentView()设置的,而不是在

  3. # 3 楼答案

    我相信这是因为您在设置分级栏后正在设置内容视图。试着移动

    setContentView(R.layout.activity_recipe);
    

    上前

       RatingBar rtb = (RatingBar) findViewById(R.id.rb);
       rtb.setRating(8.0f