在Android中调用方法时遇到的问题

时间:2015-07-12 12:13:50

标签: java android methods nullpointerexception

我收到NullPointerException但我不确定为什么因为这段代码应该正常工作。下面是调用方法,我需要从'raw'文件夹中的文件创建JSONObject。

JSONObject currenciesJsonObject = MiscHelper.getJsonObjectFromResource(R.raw.app_currencies, getActivity());

以下是由DialogFragment扩展的完整类文件:

    package uk.co.example.calculator.ui.fragments;


import android.app.Dialog;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import uk.co.example.calculator.R;
import uk.co.example.calculator.adapters.SimpleItemRecyclerViewAdapter;
import uk.co.example.calculator.ui.activities.DividerItemDecoration;
import uk.co.example.calculator.ui.activities.ExchangeRate;
import uk.co.example.utils.MiscHelper;

/**
 * A simple {@link Fragment} subclass.
 */
public class CurrencyConverterDialogFrag extends android.app.DialogFragment {

    // Declare UI elements
    private RecyclerView recyclerView;


    public CurrencyConverterDialogFrag() {
        // Required empty public constructor
    }


    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_currency_converter_dialog_calc, new LinearLayout(getActivity()), false);

        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        initializeRecyclerView();

        Dialog dialog = new Dialog(getActivity());
        dialog.setTitle("Choose currency");

        dialog.setContentView(view);


        return dialog;
    }



        JSONObject currenciesJsonObject = MiscHelper.getJsonObjectFromResource(R.raw.app_currencies, getActivity());




    private ArrayList<ExchangeRate> getSampleArrayList() {
        ArrayList<ExchangeRate> items = new ArrayList<>();
        try {
            items.add(new ExchangeRate(currenciesJsonObject.getJSONObject("GBP").getString("name"), "Valyria"));
            items.add(new ExchangeRate("Rob Stark", "Winterfell"));
            items.add(new ExchangeRate("Jon Snow", "Castle Black"));
            items.add(new ExchangeRate("Tyrion Lanister", "King's Landing"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return items;
    }

        private void initializeRecyclerView() {

        // Setup layout manager for items
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());

        // Control orientation of the items
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        //Customize the position you want to default scroll to
        layoutManager.scrollToPosition(0);

        // Attach layout manager to the RecyclerView
        recyclerView.setLayoutManager(layoutManager);

        // allows for optimizations if all item views are of the same size:
        recyclerView.setHasFixedSize(true);


        RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST);
        recyclerView.addItemDecoration(itemDecoration);

        bindDataToAdapter();
    }

    private void bindDataToAdapter() {
        // Bind adapter to recycler view object
        recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(getSampleArrayList()));
    }


}

下面是MiscHelper类中发生异常的方法:

     public static JSONObject getJsonObjectFromResource(int resource, Context context) {

        // PROBLEM OCCURS ON THIS NEXT LINE AS STATED BY THE LOGCAT. LINE:252
        InputStream inputStream = context.getResources().openRawResource(resource);
        BufferedReader r = new BufferedReader( new InputStreamReader( inputStream ) );
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        String jsonString = null;
        JSONObject jsonObject = null;
        try {
            while (( line = r.readLine() ) != null) {

                stringBuilder.append( line );
            }
            jsonString = stringBuilder.toString();
        }
        catch (Exception e) {
            Log.e("GetJsonFromResource", Log.getStackTraceString(e));
        }


        try {
            jsonObject = new JSONObject(jsonString);
        } catch (JSONException e) {
            Log.e("GetJsonFromResource", Log.getStackTraceString(e));
        }
        return jsonObject;
    }

以下是LogCat,但有例外:

    07-12 12:38:01.999: E/AndroidRuntime(6793): FATAL EXCEPTION: main
07-12 12:38:01.999: E/AndroidRuntime(6793): Process: uk.co.codepix.calculator, PID: 6793
07-12 12:38:01.999: E/AndroidRuntime(6793): java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
07-12 12:38:01.999: E/AndroidRuntime(6793):     at uk.co.codepix.utils.MiscHelper.getJsonObjectFromResource(MiscHelper.java:252)
07-12 12:38:01.999: E/AndroidRuntime(6793):     at uk.co.codepix.calculator.ui.fragments.CurrencyConverterDialogFrag.<init>(CurrencyConverterDialogFrag.java:56)
07-12 12:38:01.999: E/AndroidRuntime(6793):     at uk.co.codepix.calculator.ui.fragments.CurrencyConverterInputCalcFrag$1.onClick(CurrencyConverterInputCalcFrag.java:73)
07-12 12:38:01.999: E/AndroidRuntime(6793):     at android.view.View.performClick(View.java:4780)
07-12 12:38:01.999: E/AndroidRuntime(6793):     at android.view.View$PerformClick.run(View.java:19866)
07-12 12:38:01.999: E/AndroidRuntime(6793):     at android.os.Handler.handleCallback(Handler.java:739)
07-12 12:38:01.999: E/AndroidRuntime(6793):     at android.os.Handler.dispatchMessage(Handler.java:95)
07-12 12:38:01.999: E/AndroidRuntime(6793):     at android.os.Looper.loop(Looper.java:135)
07-12 12:38:01.999: E/AndroidRuntime(6793):     at android.app.ActivityThread.main(ActivityThread.java:5254)
07-12 12:38:01.999: E/AndroidRuntime(6793):     at java.lang.reflect.Method.invoke(Native Method)
07-12 12:38:01.999: E/AndroidRuntime(6793):     at java.lang.reflect.Method.invoke(Method.java:372)
07-12 12:38:01.999: E/AndroidRuntime(6793):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
07-12 12:38:01.999: E/AndroidRuntime(6793):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

任何人都可以告诉我我做错了什么吗?任何关于如何解决问题的详细解释都将受到高度赞赏。

2 个答案:

答案 0 :(得分:1)

据我所知,您在实例初始化程序中初始化变量xlink:href,这意味着当您执行此操作时,currenciesJsonObject并未附加到Fragment

移动此电话:

Activity

到生命周期回调,其中MiscHelper.getJsonObjectFromResource(R.raw.app_currencies, getActivity()); 不会返回null。 getActivityonAttach()可能是一个好地方。

答案 1 :(得分:0)

我没有足够的声誉来评论,所以这里只是一个快速输入: 尝试使用getBaseContext()代替getActivity()

getBaseContext()是ContextWrapper的一种方法。可以在不更改原始上下文的情况下修改此ContextWrapper。在Javadoc中:“代理实现Context,简单地将其所有调用委托给另一个Context。可以子类化以修改行为而不改变原始Context。”

还有一种方法可行: getApplicationContext()。另一方面,此方法返回应用程序上下文(整个应用程序生命周期)。这意味着当调用onDestroy()时,此方法返回null。

希望它有所帮助。