Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从片段类访问非活动类中的共享首选项_Java_Android_Android Layout_Android Fragments - Fatal编程技术网

Java 从片段类访问非活动类中的共享首选项

Java 从片段类访问非活动类中的共享首选项,java,android,android-layout,android-fragments,Java,Android,Android Layout,Android Fragments,我有一个片段: public class TodayVerse extends Fragment { TextView textView; DailyQuranMethods dailyQuranMethods; public TodayVerse() { // Required empty public constructor } @Override public View onCreateView(LayoutInfla

我有一个片段:

public class TodayVerse extends Fragment
{
    TextView textView;

    DailyQuranMethods dailyQuranMethods;

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


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_today_verse, container, false);
        textView = (TextView) view.findViewById(R.id.verse);
//        setChapterVerse();

        textView.setText(dailyQuranMethods.getVerseToday(dailyQuranMethods.DateToday(),getActivity().getApplicationContext()) + "\nChapter:" + dailyQuranMethods.getChapterTodayName(dailyQuranMethods.DateToday(),getActivity().getApplicationContext()));
        return view;
    }
}
此片段调用非活动类: 使用共享引用的日常QuranMethods。为此,我必须传递一个上下文作为参数。我通过了:

getActivity().getApplicationContext()

DailyQuran方法中的方法如下:

   public String getVerseToday(String today,Context context){
...
}
在运行应用程序时,我有以下日志:

06-19 06:07:56.5879887-9887/?E/AndroidRuntime﹕ 致命异常: 主要的 java.lang.NullPointerException 在com.example.shiza.dailyquranverses.TodayVerse.onCreateView(TodayVerse.java:35)上 位于android.support.v4.app.Fragment.performCreateView(Fragment.java:1789) 位于android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955) 位于android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138) 位于android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740) 位于android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501) 位于android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:490) 位于android.support.v4.app.FragmentTabHost.onAttachedToWindow(FragmentTabHost.java:283) 在android.view.view.dispatchAttachedToWindow(view.java:9788) 在android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2198) 在android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2206) 在android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2206) 在android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2206) 在android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2206) 在android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2206) 在android.view.ViewRootImpl.performTraversals上(ViewRootImpl.java:971) 在android.view.ViewRootImpl.handleMessage上(ViewRootImpl.java:2467) 位于android.os.Handler.dispatchMessage(Handler.java:99) 位于android.os.Looper.loop(Looper.java:137) 位于android.app.ActivityThread.main(ActivityThread.java:4424) 位于java.lang.reflect.Method.Invokenactive(本机方法) 位于java.lang.reflect.Method.invoke(Method.java:511) 在com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)上 位于com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 在dalvik.system.NativeStart.main(本机方法)

错误出现在以下行中:

textView.setText(dailyQuranMethods.getVerseToday(dailyQuranMethods.DateToday(),getActivity().getApplicationContext()) +“\n答案:”+dailyQuranMethods.getChapterTodayName(dailyQuranMethods.DateToday(),getActivity().getApplicationContext())

看起来,我无法在非活动类中获取上下文。我试了很多,但都没用。请帮我解决这个问题

编辑1:非活动类为:

package com.example.shiza.dailyquranverses;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.MatrixCursor;
import android.preference.PreferenceManager;
import android.provider.BaseColumns;
import android.widget.SimpleCursorAdapter;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Random;
import com.example.shiza.dailyquranverses.TodayChapter;
import android.preference.Preference;

/**
 * Created by Shiza on 19-06-2015.
 */
public class DailyQuranMethods {

    //    generate a random number.
    SharedPreferences sharedPreferencesChapter;
    SharedPreferences sharedPreferencesVerse;
    private static String TODAY_CHAPTER = "TODAY_CHAPTER";
    private static String TODAY_VERSE = "TODAY_VERSE";
    Context context;




    public int GetRandom(int min, int max) {
        Random ran = new Random();
        return ran.nextInt((max - min) + 1) + min;
    }


    public void setChapterVerseOfToday(Context context)
    {

        sharedPreferencesChapter = context.getSharedPreferences(TODAY_CHAPTER, Context.MODE_PRIVATE);
        sharedPreferencesVerse = context.getApplicationContext().getSharedPreferences(TODAY_VERSE, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor_chapter = sharedPreferencesChapter.edit();
        SharedPreferences.Editor editor_verse = sharedPreferencesVerse.edit();


        int chapter_no = GetRandom(1, 114);

        String chapter_array_name = "chapter_" + chapter_no;

        String verse = sharedPreferencesVerse.getString(DateToday(),null);

        if ( verse == null )
        {
            editor_verse.putString(DateToday(), getVerse(context,chapter_array_name));
            editor_verse.apply();
        }

        int chapter_number = sharedPreferencesChapter.getInt(DateToday(),0);

        if ( chapter_number == 0 )
        {

            editor_chapter.putInt(DateToday(),chapter_no);
            editor_chapter.apply();
        }


    }
    public String getVerseToday(String today,Context context)
    {
        sharedPreferencesVerse = context.getSharedPreferences(TODAY_VERSE, Context.MODE_PRIVATE);
        return sharedPreferencesVerse.getString(today,"7. The Way of those on whom You have bestowed Your Grace, not (the way) of those who earned Your Anger (such as the Jews), nor of those who went astray (such as the Christians).");
    }

    public String getVerse(Context context,String chapter_array_name)
    {
        int id = context.getResources().getIdentifier(chapter_array_name, "array", context.getPackageName());
        String[] chapter = context.getResources().getStringArray(id);
        int random_verse = GetRandom(1, chapter.length - 1);
        return chapter[random_verse];
    }


    public String[] getChapterTodayContent(String today,Context context)
    {
        sharedPreferencesChapter = context.getSharedPreferences(TODAY_CHAPTER, Context.MODE_PRIVATE);
        int chapter_no = sharedPreferencesChapter.getInt(today, 2);
        String chapter_array_name = "chapter_" + chapter_no;
        int id = context.getResources().getIdentifier(chapter_array_name, "array", context.getApplicationContext().getPackageName());
        return context.getResources().getStringArray(id);
    }

    public String getChapterTodayName(String today,Context context)
    {
        sharedPreferencesChapter = context.getApplicationContext().getSharedPreferences(TODAY_CHAPTER,Context.MODE_PRIVATE);
        int chapter_no = sharedPreferencesChapter.getInt(today, 0);
        String[] chapterName = context.getResources().getStringArray(R.array.chapters);
        return chapterName[chapter_no - 1];
    }



    public String DateToday()
   {
       Calendar c = Calendar.getInstance();

       SimpleDateFormat df = new SimpleDateFormat("ddMMyyyy");
       return df.format(c.getTime());
   }


    //    Get quran verses in android
    public String[] getQuranVerses(Context context) {
        String[] whole_quran = new String[7000];
        String[] current_chapter;
        String chapterSize = "";
        String[] chapter_names;
        String chapter_array_name;
        int total_verse = 0, verse_in_current_chapter, chapter_number;

        chapter_names = context.getResources().getStringArray(R.array.chapters);

        for (chapter_number = 1; chapter_number < 114; chapter_number++) {
//            Grab each chapter containing verse from Quran
            chapter_array_name = "chapter_" + chapter_number;
            int id = context.getResources().getIdentifier(chapter_array_name, "array", context.getPackageName());
            current_chapter = context.getResources().getStringArray(id);

            for (verse_in_current_chapter = 1; verse_in_current_chapter < current_chapter.length - 1; verse_in_current_chapter++) {
                whole_quran[total_verse] = current_chapter[verse_in_current_chapter] + "," + chapter_names[chapter_number - 1];
                total_verse++;
            }
            chapterSize += chapter_number + ":" + chapter_names[chapter_number - 1] + ":" + current_chapter.length + "\n";
        }
        return whole_quran;

    }

    //    public void search()
//    {
//        //      Use search view on the top of your app
//
//        search = (SearchView) findViewById(R.id.mySearchView);
//        search.setQueryHint("Search Qur'an");
//
////      create a suggestion adapter for dropdown
//        final String[] from = new String[] {"cityName"};
//        final int[] to = new int[] {android.R.id.text1};
//        mAdapter = new SimpleCursorAdapter(this,
//                android.R.layout.simple_list_item_2,
//                null,
//                from,
//                to,
//                CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
//
//        search.setSuggestionsAdapter(mAdapter);
//
//        search.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
//            @Override
//            public boolean onSuggestionClick(int position) {
//                // Your code here
//
//
//                Cursor theCursor = (Cursor) mAdapter.getCursor();
//                String selectedItem = theCursor.getString(position);
////                Toast.makeText(getBaseContext(), " on suggestion click position and item is" + position + selectedItem, Toast.LENGTH_LONG).show();
//
//
//                startActivity(new Intent(getBaseContext(), MainActivity.class));
//
//                return true;
//            }
//
//            @Override
//            public boolean onSuggestionSelect(int position) {
//                // Your code here
////                Toast.makeText(getBaseContext(), " on suggestion select position is" + position, Toast.LENGTH_LONG).show();
//
//                startActivity(new Intent(getBaseContext(), MainActivity.class));
//
//                return true;
//            }
//        });
//
//        search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
//
//
//            @Override
//            public boolean onQueryTextSubmit(String query) {
//                startActivity(new Intent(getBaseContext(), MainActivity.class));
//
//                return false;
//            }
//
//            @Override
//            public boolean onQueryTextChange(String newText) {
//                //
//                dailyQuranMethods.populateAdapter(newText,getApplicationContext());
//
//                return false;
//            }
//
//
//        });
//
//
//
//    }


    public void populateAdapter(String query, Context context, SimpleCursorAdapter mAdapter) {
        String[] SUGGESTIONS = getQuranVerses(context);
        final MatrixCursor c = new MatrixCursor(new String[]{BaseColumns._ID, "cityName"});
        int j = 0;
        int k = 0;
        if (query.length() > 3) {
            k = GetRandom(0, 60);
//            Toast.makeText(getApplicationContext(),"K is " + k,Toast.LENGTH_LONG).show();
            for (int i = 0; i < 6144; i++) {

                if (SUGGESTIONS[i].toLowerCase().contains(query.toLowerCase()) && SUGGESTIONS[i].length() > 0) {
                    c.addRow(new Object[]{i, SUGGESTIONS[i]});
                    j++;

                    if (j > 100) {
                        break;
                    }
                }
            }
            if (j == 0) {
                c.addRow(new Object[]{0, "No results found."});
            }
        } else {
            c.addRow(new Object[]{0, "Please enter at least 3 characters."});
            c.addRow(new Object[]{1, "Please be patient, we have to find in more than 6,000 verses"});
        }


        mAdapter.changeCursor(c);
    }

}
package com.example.shiza.dailyquranverses;
导入android.content.Context;
导入android.content.SharedReferences;
导入android.database.MatrixCursor;
导入android.preference.PreferenceManager;
导入android.provider.BaseColumns;
导入android.widget.SimpleCursorAdapter;
导入java.text.simpleDataFormat;
导入java.util.Calendar;
导入java.util.Random;
导入com.example.shiza.dailyquranverses.TodayChapter;
导入android.preference.preference;
/**
*由Shiza于2015年6月19日创建。
*/
公共类DailyQuran方法{
//生成一个随机数。
SharedReferences SharedReferences章节;
共享引用共享引用;
私有静态字符串TODAY\u CHAPTER=“TODAY\u CHAPTER”;
私有静态字符串TODAY\u VERSE=“TODAY\u VERSE”;
语境;
公共整数GetRandom(整数最小值,整数最大值){
Random ran=新的Random();
返回run.nextInt((max-min)+1)+min;
}
public void setChapterVerseOfToday(上下文)
{
sharedPreferencesChapter=context.getSharedPreferences(今天的章节,context.MODE\u PRIVATE);
SharedReferencesVerse=context.getApplicationContext().getSharedReferences(今天的版本,context.MODE\u PRIVATE);
SharedReferences.Editor编辑器_chapter=SharedReferencesChapter.edit();
SharedReferences.Editor编辑器=SharedReferencesVerse.edit();
int chapter_no=GetRandom(1114);
字符串chapter\u array\u name=“chapter\u”+chapter\u no;
String verse=SharedPreferenceVerse.getString(DateToday(),null);
如果(韵文==null)
{
编辑器_verse.putString(DateToday(),getVerse(上下文,章数组_名称));
editor_verse.apply();
}
int chapter_number=SharedReferencesChapter.getInt(DateToday(),0);
如果(章节号==0)
{
编辑者_chapter.putInt(DateToday(),chapter_no);
编辑器_chapter.apply();
}
}
公共字符串getVerseToday(今天字符串,上下文)
{
sharedPreferencesVerse=context.getSharedPreferences(今天,context.MODE\u PRIVATE);
return sharedPreferencesVerse.getString(今天,“7.你所赐恩典之人的道路,而不是那些赢得你愤怒的人(如犹太人)的道路,也不是那些误入歧途的人(如基督徒)。”;
}
公共字符串getVerse(上下文上下文、字符串章节\数组\名称)
{
int id=context.getResources().getIdentifier(第章数组名称,“数组”,context.getPackageName());
String[]chapter=context.getResources().getStringArray(id);
int random_verse=GetRandom(1,chapter.length-1);
返回章节[随机诗];
}
公共字符串[]getChapterTodayContent(今天的字符串,上下文)
{
共享参考资料
public TodayVerse() {
    DailyQuranMethods dailyQuranMethods = new DailyQuranMethods();
}