MainActivity.java文件中的字符串使我的Android应用程序崩溃

时间:2015-06-07 10:01:32

标签: java android string android-studio

我在String文件中添加了MainActivity.java,现在我的应用程序一启动就崩溃了(当调试器到达带有String的代码行时)。

这是产生问题的代码行:

CharSequence Total = "Total:"; // getString(R.string.total);
如果我使用String代替CharSequence

也会产生问题。

当我删除该行时,该应用程序可以正常运行。

这是我在Gradle控制台中遇到的错误:

  

Note : /Users/ishayfrenkel1/AndroidStudioProjects/JustJava/app/src/main/java/com/howtoevery/justjava/MainActivity.java uses or overrides a deprecated API. Note: Recompile with -Xlint:deprecation for details.

应用程序使用或覆盖已弃用的API意味着什么? 我怎样才能在Android Studio中Recompile with -Xlint:deprecation?它甚至意味着什么?

MainActivity.java代码:

    package com.howtoevery.justjava;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.text.NumberFormat;
/**
 * This app displays an order form to order coffee.
 */


public class MainActivity extends ActionBarActivity {
    CharSequence totalString = "Total:"; // getString(R.string.total);
    Context context = getApplicationContext();
    int duration = Toast.LENGTH_SHORT;
    CharSequence toastText;
    // String total = getString(R.string.total);

    int num = 0;

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

    /**
     * This method displays the given price on the screen.
     */
    private void displayPrice(int number, CharSequence message) { // Used to be , String message
        TextView priceTextView = (TextView) findViewById(R.id.price_text_view);
        priceTextView.setText(message + " " + NumberFormat.getCurrencyInstance().format(number)); // was message before Number Format
    }

    public void addOne(View view) {
        num++;
        display(num);
        displayPrice(num*5, totalString); //used to have total
    }

    public void removeOne(View view) {
        if (num > 0) {
            num--;
            display(num);
            displayPrice(num * 5, totalString); //used to have total
        }

        else {
            Context context = getApplicationContext();

            toastText = getString(R.string.negativeCups);
            Toast toast = Toast.makeText(context, toastText, duration);
            toast.show();
        }
    }

    public void reset(View view) {
        if (num > 0) {
            num = 0;
            display(num);
            displayPrice(num, totalString); //used to have total
        }
        else {
            toastText = getString(R.string.resetted);

            Toast toast = Toast.makeText(context, toastText, duration);
            toast.show();
        }

    }

    public void submitOrder(View view) {
        displayToast(num);
    }

    /**
     * This method displays the given quantity value on the screen.
     */
    private void display(int number) {
        TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
        quantityTextView.setText("" + number);
    }

    private void displayToast(int number) {
        Context context = getApplicationContext();

        if (number > 0) {
            toastText = getString(R.string.ordering) + num + getString(R.string.ordering_cups_price) + NumberFormat.getCurrencyInstance().format(num*5);
        }

        else
            toastText = getString(R.string.empty_order);


            Toast toast = Toast.makeText(context, toastText, duration);
            toast.show();
        }
    }

这是我从logcat获得的:

06-07 13:39:06.275  22308-22308/com.howtoevery.justjava I/art﹕ Late-enabling -Xcheck:jni
06-07 13:39:06.391  22308-22308/com.howtoevery.justjava D/AndroidRuntime﹕ Shutting down VM
06-07 13:39:06.392  22308-22308/com.howtoevery.justjava E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.howtoevery.justjava, PID: 22308
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.howtoevery.justjava/com.howtoevery.justjava.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2216)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2367)
            at android.app.ActivityThread.access$800(ActivityThread.java:148)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5274)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
            at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:105)
            at com.howtoevery.justjava.MainActivity.<init>(MainActivity.java:16)
            at java.lang.reflect.Constructor.newInstance(Native Method)
            at java.lang.Class.newInstance(Class.java:1572)
            at android.app.Instrumentation.newActivity(Instrumentation.java:1065)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2206)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2367)
            at android.app.ActivityThread.access$800(ActivityThread.java:148)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5274)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
06-07 13:39:08.374  22308-22318/com.howtoevery.justjava W/art﹕ Suspending all threads took: 8.600ms

2 个答案:

答案 0 :(得分:1)

您的上下文存在问题。应该在onCreate()方法内移动getApplicationContext()。这样做

public class MainActivity extends ActionBarActivity {
CharSequence totalString = "Total:"; // getString(R.string.total);
Context context;
int duration = Toast.LENGTH_SHORT;
CharSequence toastText;
// String total = getString(R.string.total);

int num = 0;

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

    context = getApplicationContext();
}
...

答案 1 :(得分:0)

在构造函数/实例方法之外发生的类成员初始化不能使用需要功能对象实例的非静态方法,因为此时您的对象实例尚未完全创建。您必须在构造函数或实例方法中移动此类初始化,您将从构造函数或对象引用中调用它们。

您必须将初始化调用移至getString(R.string.total)getApplicationContext()OnCreate方法。

public class MainActivity extends ActionBarActivity {
    String totalString;
    Context context;
    ....

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       totalString = getString(R.string.total);
       context = getApplicationContext();
    }

在您的代码中,您实际上根本不必抓取应用程序上下文,因为您可以使用活动上下文来显示您的Toast消息。只需使用this

参考当前活动参考
Toast toast = Toast.makeText(this, toastText, duration);