Android:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“java.lang.String java.lang.Object.toString()" [英] Android: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference

查看:42
本文介绍了Android:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“java.lang.String java.lang.Object.toString()"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发的练习应用遇到问题.我正面临与 toString 方法相关的 NullPointerException 问题.作为 Android 应用程序开发的新手,即使在对此进行研究之后,我也不确定确切的原因.因此,我请求更熟悉堆栈跟踪的人来帮助我.

Facing a problem with a practice app I'm working on. I'm facing a NullPointerException problem relating to the toString method. Being new to android app development, I'm unsure of the exact cause even after my research into this. Hence I ask for someone who is more familiar with the stack trace to kindly help me out.

注意:当我单击列表视图条目以访问日记条目的编辑页面时发生错误.但是它似乎根本没有进入编辑页面.

Note: The error occurs when I click on the listview entry to access an edit page for the diary entry. However it doesn't seem to go to the edit page at all.

您会在下面找到我的活动代码和堆栈跟踪.

Below you'll find my activity code it occurs on and the stack trace.

活动代码:

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import android.content.Intent;

import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;


public class ViewDiaryEntries extends AppCompatActivity {

// Database Helper
MyDBHandler db;

// Listview
ListView data_list;

// Test var
public final static String KEY_EXTRA_DATA_ID = "KEY_EXTRA_DATA_ID";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_diary_entries);

    db = new MyDBHandler(this);

    // Displays the database items.
    displayItems();
}

// To display items in the listview.
public void displayItems(){
    // To display items in a listview.
    ArrayList db_data_list = db.getDiaryDBDataList();
    ArrayAdapter listAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, db_data_list);

    // Set the adapter for the listview
    data_list = (ListView) findViewById(R.id.dataListView);
    data_list.setAdapter(listAdapter);

    /* Experiment -------------------------------------------------------------*/

    data_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // Selected item store
            String selectedEntry = ((TextView) view).getText().toString();

            // Test for regular expression
            String[] listViewItemSplit = selectedEntry.split(" - ");
            String listViewItempt1 = listViewItemSplit[0]; // For date and time
            //String listViewItempt2 = listViewItemSplit[1]; // For save file name

            //Toast.makeText(ViewDiaryEntries.this, listViewItempt1, Toast.LENGTH_LONG).show();

            if(listViewItempt1.equals("")){
                Toast.makeText(ViewDiaryEntries.this, "Error. Unable to detect entry ID.", Toast.LENGTH_LONG).show();
            }
            else{
                // Pass on the data:
                Intent editEntry = new Intent(ViewDiaryEntries.this, editdiaryentry.class);
                editEntry.putExtra(KEY_EXTRA_DATA_ID, listViewItempt1);
                startActivity(editEntry);
            }
        }
    });
}

// For the go back button.
public void viewdiarytoinitialdiary_backbutt(View v){
    // Create and start new intent going back ot main page.
    Intent main_page = new Intent(ViewDiaryEntries.this, User_Main_Menu_Options.class);
    main_page.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(main_page);
}

// For the about button.
public void viewdiarypage_directionabout_butt(View v){
    // Create an alert dialog
    final AlertDialog.Builder about_page_dialog = new AlertDialog.Builder(ViewDiaryEntries.this);
    about_page_dialog.setTitle("About This Page:");

    // Inputs values for the dialog message.
    final String dialog_message = "This page will show you any saved diary entries you've.

 To edit an entry, do the following: 

- Take note of the Entry ID# (first value on entry display) 
- Type it in the number box at the bottom. 
- Press Edit Record icon next to number box, and wait for it to load.";

    about_page_dialog.setMessage(dialog_message);

    about_page_dialog.setPositiveButton("Got it!", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // Closes the dialog.
            dialog.cancel();
        }
    });

    // Shows the dialog.
    about_page_dialog.show();
}

// Main menu button.
public void viewDiaryEntriesMainMenushortcut_butt(View v){
    // Creates main menu alert dialog.
    AlertDialog.Builder mainMenu_Dialog = new AlertDialog.Builder(this);
    mainMenu_Dialog.setIcon(R.drawable.main_menu_symbol);
    mainMenu_Dialog.setTitle("Main Menu");

    // Creates array adapter with items to fill the menu with.
    final ArrayAdapter<String> menuItemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
    menuItemsAdapter.add("Home Screen");
    menuItemsAdapter.add("Diary");
    menuItemsAdapter.add("Tests");
    menuItemsAdapter.add("Activity");
    menuItemsAdapter.add("Media");
    menuItemsAdapter.add("Thought of the Day");
    menuItemsAdapter.add("Inspirational Quotes");
    menuItemsAdapter.add("Resources");
    menuItemsAdapter.add("Settings");

    // To close menu.
    mainMenu_Dialog.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    // To go to appropriate page upon selection.
    mainMenu_Dialog.setAdapter(menuItemsAdapter, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            String selectedItem = menuItemsAdapter.getItem(which);

            if(selectedItem.equals("Home Screen")){
                // Goes to main menu.
                Intent mainMenu = new Intent(ViewDiaryEntries.this, User_Main_Menu_Options.class);
                mainMenu.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(mainMenu);
            }
            else if(selectedItem.equals("Diary")){
                // Goes to diary page.
                Intent diaryPage = new Intent(ViewDiaryEntries.this, ViewDiaryEntries.class);
                diaryPage.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(diaryPage);
            }
            else if(selectedItem.equals("Tests")){
                // Goes to tests page.
                Intent testsPage = new Intent(ViewDiaryEntries.this, TestChoices.class);
                testsPage.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(testsPage);
            }
            else if(selectedItem.equals("Media")){
                // Goes to media page.
                Intent mediaPage = new Intent(ViewDiaryEntries.this, initialMediaPage.class);
                mediaPage.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(mediaPage);
            }
            else if(selectedItem.equals("Thought of the Day")){
                // Goes to thought of the day page.
                Intent thoughtofthedayPage = new Intent(ViewDiaryEntries.this, thoughtQuotes.class);
                thoughtofthedayPage.putExtra("quote_or_thought", 2);
                thoughtofthedayPage.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(thoughtofthedayPage);
            }
            else if(selectedItem.equals("Inspirational Quotes")){
                // Goes to inspirational quotes page.
                Intent inspirationalquotesPage = new Intent(ViewDiaryEntries.this, thoughtQuotes.class);
                inspirationalquotesPage.putExtra("quote_or_thought", 1);
                inspirationalquotesPage.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(inspirationalquotesPage);
            }
            else if(selectedItem.equals("Settings")){
                // Goes to settings page.
                Intent settingsPage = new Intent(ViewDiaryEntries.this, settings.class);
                settingsPage.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(settingsPage);
            }
        }
    });

    mainMenu_Dialog.show();
}

// For the settings button.
public void viewdiarypagelisttoSettings_butt(View v){
    // Goes to settings page.
    Intent settingsPage = new Intent(ViewDiaryEntries.this, settings.class);
    settingsPage.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(settingsPage);
}

// For new entry.
public void viewdiarypageaddEntry_butt(View v){
    // Opening up the diary add intent.
    Intent newdiaryEntry = new Intent(ViewDiaryEntries.this, newdiaryentry.class);
    startActivity(newdiaryEntry);
}
}

这是我看到的堆栈跟踪:

Here is my stack trace that I see:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
        at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:401)
        at android.widget.ArrayAdapter.getView(ArrayAdapter.java:369)
        at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:194)
        at android.widget.Spinner.onMeasure(Spinner.java:580)
        at android.support.v7.widget.AppCompatSpinner.onMeasure(AppCompatSpinner.java:407)
        at android.view.View.measure(View.java:18794)
        at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
        at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
        at android.view.View.measure(View.java:18794)
        at android.widget.ScrollView.measureChildWithMargins(ScrollView.java:1283)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at android.widget.ScrollView.onMeasure(ScrollView.java:340)
        at android.view.View.measure(View.java:18794)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
        at android.view.View.measure(View.java:18794)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
        at android.view.View.measure(View.java:18794)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at android.view.View.measure(View.java:18794)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
        at android.view.View.measure(View.java:18794)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
        at android.view.View.measure(View.java:18794)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
        at android.view.Choreographer.doCallbacks(Choreographer.java:670)
        at android.view.Choreographer.doFrame(Choreographer.java:606)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

对解决方案的任何帮助将不胜感激.

Any help towards a solution will be appreciated.

因此,在从数据库与其交互的活动之间来回查看代码之后,我设法让它再次工作.以下是我按确切顺序执行的操作:

So after staring back and forth from the code between the database and the activity it interacts with, I managed to get it working again. Below is what I did in the exact order:

  1. 我意识到我有一个没有接收数据的日期字段,对此进行了纠正.
  2. 清理项目.
  3. 重新启动 Android Studio(基本上停止了开发环境的所有操作).
  4. 从我的开发手机上卸载了该应用.
  5. 重新启动 android studio 并重新安装应用.
  6. 我以某种方式工作了=_=,是的,这很神奇.

老实说,我不知道哪一步真正解决了它.我猜是数据库中的日期字段在它没有接收到任何数据时把事情搞砸了.

Honestly I've no idea which step actually solved it. I'm guessing it was the date field in the database that was messing things up for me while it was receiving no data.

推荐答案

ArrayAdapter 中的数组至少包含一个 null 条目.那里不能有空值.

The array in your ArrayAdapter contains at least one entry that is null. There must be no nulls there.

数组填充在 getDiaryDBDataList() 中,所以问题也存在.

The array is populated in getDiaryDBDataList() so the problem is also there.

这篇关于Android:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“java.lang.String java.lang.Object.toString()"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆