NullPointerException,是什么导致我的错误?

时间:2015-01-06 23:13:50

标签: java android xml error-handling nullpointerexception

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_width="match_parent" android:layout_height="match_parent"
android:background="#FF8B00"
android:id="@+id/Personal_Records">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
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_width="wrap_content"
android:layout_height="wrap_content"
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_width="match_parent"
android:layout_height="wrap_content"
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_width="wrap_content"
android:layout_height="wrap_content"
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_width="match_parent"
android:layout_height="wrap_content"
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

和logcat:

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)

LINE 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()更好地提出您的想法?我想要做的就是重新设置每天/每周新的一天或每周计数器。我当时认为这应该是一个后台服务,但我不知道该去哪里。

2 个答案:

答案 0 :(得分:4)

您试图在未设置活动内容的情况下获取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中使用整数;它有完全不同的含义。如果这样做,它将查找具有该整数值的资源。

答案 1 :(得分:0)

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

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

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