NullPointerException,是啥导致我的错误?

Posted

技术标签:

【中文标题】NullPointerException,是啥导致我的错误?【英文标题】:NullPointerException, what is causing my error?NullPointerException,是什么导致我的错误? 【发布时间】:2015-03-04 17:22:22 【问题描述】:

Logcat 在 Records.java 的第 42 行返回一个 nullPointerException。第 42 行说“daily_record.setText(Daily_Record_Option);”你们能看一下这段代码吗?我已经尝试解决这个问题几个小时了,但我尝试过的没有任何帮助。谢谢! Records.java

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import android.view.Menu;
import android.view.MenuItem;

import android.widget.TextView;
import android.widget.Toast;
public class Records extends MainActivity 

public int default_int_day = 0;
public int default_int_week = 0;
static boolean daily_recieved = false;
static boolean weekly_recieved = false;


@Override
public void onCreate(Bundle savedInstanceState) 
    TextView daily_record = (TextView) findViewById(R.id.daily_textview);
    TextView weekly_record = (TextView) findViewById(R.id.weekly_textview);



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

    SharedPreferences sharedPrefs = getSharedPreferences("Data", Context.MODE_PRIVATE);

    int Daily_Record_Option = sharedPrefs.getInt("daily", counter);
    int Weekly_Record_Option = sharedPrefs.getInt("weekly", counter_weekly);
    if(isSavedDaily)
        if(Daily_Record_Option > default_int_day)
            daily_record.setText(Daily_Record_Option);
            default_int_day = Daily_Record_Option;
            daily_recieved = true;
        else if(default_int_day > Daily_Record_Option)
            daily_record.setText(default_int_day);
            daily_recieved = false;
        else
            daily_record.setText("No records yet!");
        

    else
        Toast.makeText(this, "No daily data saved yet", Toast.LENGTH_LONG).show();
    
      if(isSavedWeekly)
          if(Weekly_Record_Option > default_int_week)
              weekly_record.setText(Weekly_Record_Option);
              default_int_week = Weekly_Record_Option;
              weekly_recieved = true;
           else if(default_int_week > Weekly_Record_Option)
              weekly_record.setText(default_int_week);
              weekly_recieved = false;
          

      else
          Toast.makeText(this, "No  weekly data saved yet", Toast.LENGTH_LONG).show();

      









@Override
public boolean onCreateOptionsMenu(Menu menu) 
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.records_menu, 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.Back)
        Intent records_intent = new Intent(this, MainActivity.class);
        startActivity(records_intent);

        return true;

    

    return super.onOptionsItemSelected(item);


还有布局文件: personal_records.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_ android:layout_
android:background="#FF8B00"
android:id="@+id/Personal_Records">

<TextView
android:layout_
android:layout_
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@string/Your_Records"
android:id="@+id/textView5"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_margin="40dp"
android:layout_centerHorizontal="true"
android:gravity="center_horizontal"/>

<TextView
android:layout_
android:layout_
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="@string/Weekly_Record"
android:id="@+id/textView6"
android:layout_below="@+id/textView5"
android:layout_alignLeft="@+id/textView5"
android:layout_alignStart="@+id/textView5"
android:layout_marginBottom="20dp" />

<TextView
android:layout_
android:layout_
android:id="@+id/weekly_textview"
android:layout_below="@+id/textView6"
android:layout_alignLeft="@+id/textView6"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_alignStart="@+id/textView6"
android:gravity="center_horizontal"
android:text="\@null"/>
<TextView
android:layout_
android:layout_
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="@string/Daily_Record"
android:id="@+id/textView7"
android:layout_below="@+id/weekly_textview"
android:layout_alignLeft="@+id/textView5"
android:layout_alignStart="@+id/textView5"
android:layout_marginBottom="20dp"
android:paddingTop="20dp"/>

<TextView
android:layout_
android:layout_
android:id="@+id/daily_textview"
android:layout_below="@+id/textView7"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_alignLeft="@+id/textView6"
android:layout_alignStart="@+id/textView6"
android:text="\@null"
android:gravity="center_horizontal"/>

</RelativeLayout

还有日志猫:

java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2359)
at android.app.ActivityThread.access$700(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1326)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5455)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at haveabeer.two.padc.haveabeer.Records.onCreate(Records.java:43)
//Here ^^^
at android.app.Activity.performCreate(Activity.java:5372)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2267)

第 43 行说:“daily_record.setText(Daily_Record_Option);” 现在是第 43 行,因为我在顶部移动了一些东西。但是引发错误的区域在同一区域内/附近。

MainActivity.java

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;


import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.widget.ImageButton;

import android.widget.TextView;
import android.widget.Toast;

import java.util.Calendar;


public class MainActivity extends ActionBarActivity 
public int counter = 0;
public int counter_weekly = 0;
Calendar daily_calender = Calendar.getInstance();
int hour = daily_calender.get(Calendar.HOUR);
int second = daily_calender.get(Calendar.SECOND);
int minute = daily_calender.get(Calendar.MINUTE);
int day = daily_calender.get(Calendar.DAY_OF_WEEK);
public boolean isSavedDaily = true;
public boolean isSavedWeekly = false;

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ImageButton beer = (ImageButton) findViewById(R.id.imageButton);
    SharedPreferences sharedPrefs = getSharedPreferences("Data",Context.MODE_PRIVATE);
    counter = sharedPrefs.getInt("daily", counter);
    counter_weekly = sharedPrefs.getInt("weekly", counter_weekly);
    TextView beer_count_onLoad = (TextView) findViewById(R.id.textView);
    beer_count_onLoad.setText(getResources().getString(R.string.beerCount) + "" + counter);
    TextView beer_week_count_onLoad = (TextView) findViewById(R.id.textView2);
    beer_week_count_onLoad.setText(getResources().getString(R.string.beerWeek) + "" +     counter_weekly);
    final TextView beer_count = (TextView) findViewById(R.id.textView);
    final TextView beer_week = (TextView) findViewById(R.id.textView2);


    beer.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View v) 
            counter++;
            counter_weekly++;
            beer_count.setText(getResources().getString(R.string.beerCount) + "" + counter );
            beer_week.setText(getResources().getString(R.string.beerWeek) + "" + counter_weekly );


        
    );

    ResetVariablesTimers();





private void ResetVariablesTimers() 
    SharedPreferences sharedPrefs = getSharedPreferences("Data",Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPrefs.edit();
    if(hour == 0 && second == 0 && minute == 0 )
        TextView reset_notification = (TextView)findViewById(R.id.textView3);
        reset_notification.setText("Daily was reset to 0, was at 400");
        editor.putInt("daily", counter);

        editor.commit();
        isSavedDaily=true;

        ResetVariables();





    else
        Toast.makeText(this, "Not time of the day yet", Toast.LENGTH_LONG).show();
        isSavedDaily=true;

        if(day == 2 && second == 0 && minute == 0 && hour == 0 )
            TextView reset_notification_weekly = (TextView) findViewById(R.id.textView4);
            reset_notification_weekly.setText("Weekly was reset to 0, was at 400");
            editor.putInt("weekly", counter_weekly);
            editor.commit();
            isSavedWeekly=true;
            ResetVariables();
        else
            Toast.makeText(this, "Not time of the month yet", Toast.LENGTH_LONG).show();
            isSavedWeekly=false;
        


    

public void ResetVariables() 
    if(Records.daily_recieved = true)
        counter = 0;
    
    if(Records.weekly_recieved = true)
        counter_weekly = 0;
    





@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) 
    SharedPreferences sharedPrefs = getSharedPreferences("Data", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPrefs.edit();
    editor.putInt("daily", counter);
    editor.putInt("weekly", counter_weekly);
    editor.commit();
    // 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;
    else if (id == R.id.Personal_Records && isSavedDaily)

        Intent records_intent = new Intent(this, Records.class);
        startActivity(records_intent);

        return true;

    else
        Toast.makeText(this, "No records available yet!", Toast.LENGTH_LONG).show();
    

    return super.onOptionsItemSelected(item);


@Override
protected void onSaveInstanceState(Bundle outState) 
    SharedPreferences sharedPrefs = getSharedPreferences("Data", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPrefs.edit();
    editor.putInt("daily", counter);
    editor.putInt("weekly", counter_weekly);
    editor.commit();
    super.onSaveInstanceState(outState);
    outState.putInt("daily_counter", counter);
    outState.putInt("weekly_counter", counter_weekly);
    ResetVariablesTimers();



@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) 
    super.onRestoreInstanceState(savedInstanceState);
    counter = savedInstanceState.getInt("daily_counter");
    counter_weekly = savedInstanceState.getInt("weekly_counter");
    TextView daily = (TextView) findViewById(R.id.textView);
    daily.setText(getResources().getString(R.string.beerCount) + counter);
    TextView weekly = (TextView) findViewById(R.id.textView2);
    weekly.setText(getResources().getString(R.string.beerWeek) + counter);


@Override
protected void onDestroy() 
    SharedPreferences sharedPrefs = getSharedPreferences("Data", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPrefs.edit();
    editor.putInt("daily", counter);
    editor.putInt("weekly", counter_weekly);
    editor.commit();
    super.onDestroy();
    ResetVariablesTimers();


@Override
protected void onStop() 
    SharedPreferences sharedPrefs = getSharedPreferences("Data", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPrefs.edit();
    editor.putInt("daily", counter);
    editor.putInt("weekly", counter_weekly);
    editor.commit();
    ResetVariablesTimers();

    super.onStop();


您能否就如何使 ResetVariableTimers() 变得更好提出您的想法?我想要做的是在新的一天/一周到来时重置每日和每周计数器。我在想这可能应该是一个后台服务,但我不知道该去哪里。

【问题讨论】:

尝试将daily_record.setText(Daily_Record_Option);换成daily_record.setText(Daily_Record_Option + ""); @Rohit5k2 不,那没用。 你正在扩展MainActivity;那里可能有问题。这个类似乎没有任何错误,除了你不应该像你正在做的那样在setText 方法中使用整数。在setText 中使用整数具有完全不同的含义。 我删除了扩展 MainActivity 并且到处都有错误。所以为了解决这个问题,我显然按下了 ALT+ENTER 来查看 Android Studio 的建议,但这没有帮助。在我的其他一项活动中,我在 setText 中使用了一个 int,它运行良好。所以我完全不知道还有什么可以尝试的。 @Rohit5k2 您是否认为问题可能源于当用户单击右上角名为“Your Records”的 ActionBar 项时启动 Records.java 活动这一事实?那是一个片段吗? 【参考方案1】:

您正在尝试获取您的TextView 而不在活动中设置内容。

将这些行放在setContentView(R.layout.personal_records); 之后

TextView daily_record = (TextView) findViewById(R.id.daily_textview);
TextView weekly_record = (TextView) findViewById(R.id.weekly_textview);

另外,你不应该在setText 中使用整数;它具有完全不同的含义。如果您这样做,它将寻找具有该整数值的资源。

【讨论】:

【参考方案2】:

在引用其中的任何元素之前,您首先需要扩充您的视图。当时你有这两行代码,

TextView daily_record = (TextView) findViewById(R.id.daily_textview);
TextView weekly_record = (TextView) findViewById(R.id.weekly_textview);

您的视图仍然为空,因此出现 NullPointer 异常。在引用任何元素之前,您应该首先调用 setContentView(R.layout.myView)。

【讨论】:

我刚刚这样做了,我仍然得到 nullPointerException。 你需要将super.onCreate(savedInstanceState); setContentView(R.layout.personal_records);移动到@Override public void onCreate(Bundle savedInstanceState) 之后的右边 你能告诉我第 42 行对应的是什么吗?您能否发布堆栈跟踪。

以上是关于NullPointerException,是啥导致我的错误?的主要内容,如果未能解决你的问题,请参考以下文章

java.lang.NullPointerException错误是啥意思

为啥@ManyToMany 会导致 NullPointerException?

ProGuard 导致 NullPointerException

textout.getText() 导致“可能产生'java.lang.NullPointerException'”消息

Facebook Audience Network 导致 NullPointerException

ListView.set.adapter 导致 NullPointerException