当前位置: 首页 > 知识库问答 >
问题:

实现调用空对象引用的工具栏

禹德水
2023-03-14

我在实现actionbar(我认为它现在已经被工具栏取代)时遇到了问题。我想要的是一个小的下拉菜单与3个点,我可以有一些选项,如设置和学分。我已经尝试设置它,以便菜单出现在HomeListView.java页面上。我觉得我一直在兜圈子,尝试不同的解决方案,每次都得到一个新的错误,它总是指向下面提到的相同的位置。

setSupportActionBar(toolbar);

styles.xml

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

</style>

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

------------------Menu_main.xml----------------

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="cs495capstone.edu.bsu.myapplication.MainActivity">
<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    app:showAsAction="never" />
<item
    android:id="@+id/action_credits"
    android:orderInCategory="100"
    android:title="@string/action_credits"
    app:showAsAction="never" />
<item
    android:id="@+id/action_lovely"
    android:orderInCategory="100"
    android:title="@string/action_lovely"
    app:showAsAction="never" />
</menu>

-------activity_main.xml---------

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="cs495capstone.edu.bsu.myapplication.HomeActivityListview">

<android.support.design.widget.AppBarLayout
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/activity_add_appointment" />
<include layout="@layout/activity_add_history" />
<include layout="@layout/activity_appointments" />
<include layout="@layout/activity_dog_profile" />
<include layout="@layout/activity_history" />
<include layout="@layout/activity_home" />
<include layout="@layout/activity_home_activity_listview" />
<include layout="@layout/activity_login" />
<include layout="@layout/activity_new_dog" />
<include layout="@layout/activity_registration" />
<include layout="@layout/activity_splash_screen" />
<include layout="@layout/activity_update_dog" />

</android.support.design.widget.CoordinatorLayout>

----------------------HomeActivityListView.xml-----------------------------------------------------------------------------

public class HomeActivityListview extends AppCompatActivity {

    ListView lv;
    Context context;
    ArrayList dogName;
    ArrayList dogID;
    public static int [] dogImages={R.drawable.dogpic};
    public static String [] dogNames={};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_activity_listview);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        context=this;

        lv=(ListView) findViewById(R.id.listView);
        lv.setAdapter(new CustomAdapter(this, dogImages));
    }


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

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


public void sendProfile(View view) {
        Intent intent = new Intent(getApplicationContext(), DogProfileActivity.class);
        startActivity(intent);

    }

    public void NumberOne(View view) {
        AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);
        alertDlg.setMessage("Confirm Dog went number one");
        alertDlg.setCancelable(false);

        alertDlg.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //HomeActivity.super.onBackPressed();
            }
        });

        alertDlg.setNegativeButton("Change", new DialogInterface.OnClickListener(){

            @Override
            public void onClick(DialogInterface dialog, int which) {
                //HomeActivity.super.onBackPressed();
            }
        });
        alertDlg.create().show();

    }
    public void NumberTwo(View view) {
        AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);
        alertDlg.setMessage("Confirm Dog went number two");
        alertDlg.setCancelable(false);

        alertDlg.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //HomeActivity.super.onBackPressed();
            }
        });

        alertDlg.setNegativeButton("Change", new DialogInterface.OnClickListener(){

            @Override
            public void onClick(DialogInterface dialog, int which) {
                //HomeActivity.super.onBackPressed();
            }
        });
        alertDlg.create().show();

    }

    public void AddNewDog(View view) {
        Intent intent = new Intent(getApplicationContext(), NewDogActivity.class);
        startActivity(intent);
    }

}

----------------------Main_Activity.java--------------

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

}

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

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

----------------HomeListView.java-----------------------

public class HomeActivityListview extends AppCompatActivity {

    ListView lv;
    Context context;
    ArrayList dogName;
    ArrayList dogID;
    public static int [] dogImages={R.drawable.dogpic};
    public static String [] dogNames={};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_activity_listview);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        context=this;

        lv=(ListView) findViewById(R.id.listView);
        lv.setAdapter(new CustomAdapter(this, dogImages));
    }


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

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


public void sendProfile(View view) {
        Intent intent = new Intent(getApplicationContext(), DogProfileActivity.class);
        startActivity(intent);

    }

    public void NumberOne(View view) {
        AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);
        alertDlg.setMessage("Confirm Dog went number one");
        alertDlg.setCancelable(false);

        alertDlg.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //HomeActivity.super.onBackPressed();
            }
        });

        alertDlg.setNegativeButton("Change", new DialogInterface.OnClickListener(){

            @Override
            public void onClick(DialogInterface dialog, int which) {
                //HomeActivity.super.onBackPressed();
            }
        });
        alertDlg.create().show();

    }
    public void NumberTwo(View view) {
        AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);
        alertDlg.setMessage("Confirm Dog went number two");
        alertDlg.setCancelable(false);

        alertDlg.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //HomeActivity.super.onBackPressed();
            }
        });

        alertDlg.setNegativeButton("Change", new DialogInterface.OnClickListener(){

            @Override
            public void onClick(DialogInterface dialog, int which) {
                //HomeActivity.super.onBackPressed();
            }
        });
        alertDlg.create().show();

    }

    public void AddNewDog(View view) {
        Intent intent = new Intent(getApplicationContext(), NewDogActivity.class);
        startActivity(intent);
    }

}

-------------------------------------------------------------------------

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cs495capstone.edu.bsu.doggydid" >

<uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity android:name=".SplashScreenActivity" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".RegistrationActivity"
        android:label="Registration" />
    <activity
        android:name=".NewDogActivity"
        android:label="Dog Information" />
    <activity
        android:name=".LoginActivity"
        android:label="Login" />
    <activity
        android:name=".HomeActivity"
        android:label="@string/title_activity_home" />
    <activity
        android:name=".DogProfileActivity"
        android:label="@string/title_activity_dog_profile" />
    <activity
        android:name=".HistoryActivity"
        android:label="@string/title_activity_records" />
    <activity
        android:name=".addHistoryActivity"
        android:label="@string/title_activity_add_record" />
    <activity
        android:name=".EventsActivity"
        android:label="@string/title_activity_events" />
    <activity
        android:name=".addEventsActivity"
        android:label="@string/title_activity_add_events" />
    <activity
        android:name=".UpdateDogActivity"
        android:label="@string/title_activity_update_dog" />
    <activity
        android:name=".HomeActivityListview"
        android:label="@string/title_activity_home_activity_listview"
        android:theme="@style/AppTheme.NoActionBar">
    </activity>
</application>

</manifest>

----------------------------------------------------------------------

04-14 13:35:36.905 311 7-3117/cs495capstone.edu.bsu.doggydid e/androidruntime:致命异常:main process:cs495capstone.edu.bsu.doggydid,pid:3117 java.lang.runtimeexception:无法启动活动ComponentInfo{cs495capstone.edu.bsu.doggydid/cs495capstone.edu.bsu.doggydid.homeactivitylistview}在Android.app.activityThread.performLaunchActivity(activityThread.java:2298),在Android.app.activityThread.java:2360),在Android.app.activityThread.access$800(activityThread.java:144),在Android.app.activityThread.java:1278),在Android.os.handler.dispatchMessage(activityThread.java:1278),在Android.os.handler.loop(looper.java:135),在reflect.method.invoke(本机方法),位于java.lang.reflect.method.invocom.android.internal.os.zygoteInit$methodandArgsCaller.run(zygoteinit.java:899)在com.android.internal.os.zygoteinit.main(zygoteinit.java:694),原因是:java.lang.nullpointerException:试图在Android.support.v7.widget.toolbarwidgetWrapper的空对象引用上调用虚拟方法'java.lang.charsequence Android.support.v7.widget.toolbarwidgetWrapper。er.(toolbarwidgetWrapper.java:91)在Android.support.v7.app.toolbaractionBar.(toolbaractionBar.java:73)在Android.support.v7.app.appcompatdelegateimplv7.setsupportActionBar(appcompatdelegateimplv7.java:205)在Android.support.v7.app.appcompatactivity.setsupportActionBar(appcompatdelegateimplv7.java:205)在callActivityonCreate(Instrumentation.java:1105)atAndroid.app.ActivityThread.PerformLaunchActivity(ActivityThread.java:2251)在 的Android.app.ActivityThread.HandleLaunchActivity(ActivityThread.java:2360)在Android.app.activitythread.access$800(activitythread.java:144) 在Android.app.activitythread$h.handleMessage(activitythread.java:1278) 在Android.os.handler.DispatchMessage(Handler.java:102) 在Android.os.looper.loop(looper.java:135) 在Android.app.activitythread.main(activitythread.java:5221), 在java.lang.reflect.Method.invoke(本机方法) 在java.lang.reflect.method.invoke(Method.java:372) 在com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:899) 在com.android.internal.os.zygoteinit.main(zygoteinit.java:694) 

共有1个答案

宣星光
2023-03-14

您的工具栏工具栏只在onCreate中声明/初始化,因此范围超出了该方法...

将对象定义为活动变量,并在oncreate中初始化它

public class HomeActivityListview extends AppCompatActivity {

    ListView lv;
    Context context;
    ArrayList dogName;
    ArrayList dogID;
    public static int [] dogImages={R.drawable.dogpic};
    public static String [] dogNames={};
    private Toolbar toolbar;  //define it  here
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_activity_listview);
        toolbar = (Toolbar) findViewById(R.id.toolbar);  //but init here
        setSupportActionBar(toolbar);

        context=this;

        lv=(ListView) findViewById(R.id.listView);
        lv.setAdapter(new CustomAdapter(this, dogImages));
    }
 类似资料:
  • 因此,我试图从firebase向recyclerview显示图像,但它抛出了一个错误。错误提示E/nite competitive:[qarth _ debug:]get patch store::createDisableExceptionQarthFile方法失败。E/AndroidRuntime:致命异常:主进程:com . example . fortnite competitive,PI

  • 问题内容: 指针是仅用于实现Java参考变量还是实际上如何实现?以下是Java语言规范中的代码行 4.3.1对象对象是类实例或数组。引用值(通常只是引用)是指向这些对象的指针,还有一个特殊的空引用,它不引用任何对象。 这是否意味着一直都是指针? 问题答案: 在现代JVM中,引用被实现为地址。 回到HotSpot的第一个版本(对于“经典VM”来说更早一些),引用被实现为句柄。那是指向指针的固定指针。

  • 问题内容: 我不知道我的代码有什么问题 这是我的片段课 这是我的SessionManager.java 运行项目时出现的错误: java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“ void com.example.gandi.symanlub.SessionManager.logoutUser()” 问题答案: 您收到错误消息是因为在此行您正在调用: 会

  • 我的应用程序有问题,我想解决它,但我无法访问解决方案,请帮助我,,,

  • 我正在开发一个具有蓝牙功能的应用程序。我使用一个片段来扫描并列出蓝牙设备。单击时,会回调到提供所选蓝牙设备的主要活动。 我一开始使用的是Android 6(API 23)的智能手机,然后不得不调整代码以适应Android 5.0(API 21)的使用。 我只是将minSDK更改为API21并重新构建了项目,没有任何问题。 该应用程序在智能手机上运行时没有任何问题。安装了Android5的平板电脑运

  • 我是Android的新手,我正在开发一个应用程序,该应用程序试图连接服务器并获取Json响应,将其解析为类并使其可用。 为此,我上了三门课 公共类顾客{} 公共类ServerConnect{} 公共类JsonParser{} Serverconnect使用Volley库在异步线程上下载网页源代码。下载后,Server Connect类启动OnServerResponsed(String Respo