android studio null指针异常对findViewById-int

时间:2018-09-18 20:42:52

标签: java android

我得到的错误:

  

由于:java.lang.NullPointerException:尝试调用虚拟   方法'android.view.View com.github.irshulx.Editor.findViewById(int)'   在空对象引用上           在com.example.verma.inspire.PostActivity.onCreate(PostActivity.java:45)           在android.app.Activity.performCreate(Activity.java:6975)           在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)*

文件PostActivity.java

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.github.irshulx.models.EditorTextStyle;
import com.github.irshulx.Editor;

public class PostActivity extends AppCompatActivity {

    private Toolbar mToolbar;
    private Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post);

        mToolbar = (Toolbar) findViewById(R.id.update_post_page_toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setTitle("Update Post");

        editor = (Editor) editor.findViewById(R.id.editor); //error here
        setUpEditor();
    }

    ...
}

和XML布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".PostActivity">

    <include
        android:id="@+id/update_post_page_toolbar"
        layout="@layout/app_bar_layout" />

    <com.github.irshulx.Editor
        android:layout_width="match_parent"
        android:id="@+id/editor"
        app:render_type="Editor"
        app:placeholder="Start writing here..."
        android:paddingTop="10dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:layout_height="wrap_content"
        android:paddingBottom="100dp" />

</RelativeLayout>

1 个答案:

答案 0 :(得分:4)

您试图以错误的视图查找编辑器。

尝试在您的根视图中查找它,像这样:

 editor = (Editor) findViewById(R.id.editor);