2017-10-08 2 views
-1

断片私のフラグメントの内部インタフェースを介してMainActivityに私onPause()から保存したデータを渡すの作業interface-nullリファレンスを使用してデータを送信しています。 Androidのメーカー

public class page2_saved_notes extends Fragment { 
     public static final String SAVE = "MyPrefsArrays"; 
     private String mTitleArray = "titlesArray"; 
     private String mNotesArray = "notesArray"; 

     ArrayList<String> arrayListTitle = new ArrayList<>(); 
     ArrayList<String> arrayListNotes = new ArrayList<>(); 
     communicateCheckboxes cc; 
     String json; 
     Gson gson; 
     Type type; 
     String jsonNotes; 
     Type typeNotes; 
     SharedPreferences settings; 

    //update 
     private Listener listener; 
     public interface Listener { 
      void sendData(String title, String Notes); 
     } 


     public page2_saved_notes() { 
     } 

     public static page2_saved_notes newInstance() { 
      page2_saved_notes fragment = new page2_saved_notes(); 
      Bundle args = new Bundle(); 
      fragment.setArguments(args); 
      return fragment; 
     } 

     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
           Bundle savedInstanceState) { 
      View rootView = inflater.inflate(R.layout.page2_saved_notes, container, false); 

      //interface/preferences/gson initialize 
    //update 
      listener = (Listener) getActivity(); 
      settings = getActivity().getSharedPreferences(SAVE, Context.MODE_PRIVATE); 
      gson = new Gson(); 

      //retrieve title from memory 
      json = settings.getString(mTitleArray, null); 
      type = new TypeToken<ArrayList<String>>() { 
      }.getType(); 
      arrayListTitle = gson.fromJson(json, type); 

      //retrieve notes from memory 
      jsonNotes = settings.getString(mNotesArray, null); 
      typeNotes = new TypeToken<ArrayList<String>>() { 
      }.getType(); 
      arrayListNotes = gson.fromJson(jsonNotes, typeNotes); 


     //update 
       if(listener!= null) 
       listener.sendData("check","check"); 

      return rootView; 
     } 

主な活動

public class MainActivity extends AppCompatActivity 
     implements NavigationView.OnNavigationItemSelectedListener, page1_user_notes.communicate,page2_saved_notes.communicateCheckboxes{ 

    private SectionsPagerAdapter mSectionsPagerAdapter; 
    private ViewPager mViewPager; 

    //checkbox array list 
    public ArrayList<CheckBox> checkBoxArrayList = new ArrayList<>(); 
    //user titleText Array List 
    public ArrayList<String> titleTextArrayList = new ArrayList<>(); 
    //user notesArrayList 
    public ArrayList<String> notesArrayList = new ArrayList<>(); 

    DateFormat df = new SimpleDateFormat("EEE, MMM d, ''yy"); 
    String date = df.format(Calendar.getInstance().getTime()); 
    // PopupMenu popup 
    LinearLayout ll; 
    LinearLayout.LayoutParams lp; 
    PopupMenu popup; 
    CheckBox checkbox; 
    private int checkboxPopupCheck; 

    String checkTitle; 
    String checkNotes; 

    //shared preferences 
    public static final String SAVE = "MyPrefsArrays"; 
    private String mTitleArray = "titlesArray"; 
    private String mNotesArray = "notesArray"; 

    //might not need this.Just recreate the checkboxes in onCreate 
    //private String mCheckBoxArray = "checkBoxArray"; 



    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD) 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     // recovering the instance state 
     if (savedInstanceState != null) { 

     } 
     setContentView(R.layout.activity_main); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
       this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); 
     drawer.setDrawerListener(toggle); 
     toggle.syncState(); 

     NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); 
     navigationView.setNavigationItemSelectedListener(this); 

     /***-----------Added after----------*/ 
     mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); 
     // Set up the ViewPager with the sections adapter. 
     mViewPager = (ViewPager) findViewById(R.id.container); 
     mViewPager.setAdapter(mSectionsPagerAdapter); 


    } 

    @Override 
    public void onPause() { 
     super.onPause(); 
     //initialize shared preferences 
     SharedPreferences settings = getSharedPreferences(SAVE, Context.MODE_PRIVATE); 
     SharedPreferences.Editor editor = settings.edit(); 
     Gson gson = new Gson(); 

     //add titles array to saved preferences 
     String jsonTitle = gson.toJson(titleTextArrayList); 
     editor.putString(mTitleArray,jsonTitle); 

     //may not need this 
     //add notes array to saved preferences 
     String jsonNotes = gson.toJson(notesArrayList); 
     editor.putString(mNotesArray,jsonNotes); 

     //add checkbox array to saved preferences 

     editor.commit(); 

    } 



    //might not need this 
/* public void onResume(){ 
     super.onResume(); 

    }*/ 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 

    @Override 
    public void sendData(String userText, String userNotes) { 
     //----Start of checkbox layout 
     ll = (LinearLayout)findViewById(R.id.myLayout); 
     lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); 
     checkbox = new CheckBox(getApplicationContext()); 
     checkbox.setTextSize(20); 
     checkbox.setText(userText + " \n" + date); 
     checkbox.setLayoutParams(lp); 
     checkbox.setClickable(false); 
     checkbox.setButtonDrawable(null); 
     //----End of checkbox layout 

     //save text components to the file 
     writeToFile(userText,userNotes); 

     //Add text components to the arrays 
     titleTextArrayList.add(userText); 
     notesArrayList.add(userNotes); 

     //add the checkbox to the array 
     //so that we can delete it or whatever later 
     checkBoxArrayList.add(checkbox); 

     //add checkbox to the Linear layout 
     ll.addView(checkbox); 

     //-----Delete the Checkbox,Title,and Notes in the arrays if it already exists----Data is saved to previous version----// 
     //check the data being sent through 
     //erases the text from title text array if it is equal to the same title name. 
     //this avoids same data from being saved 
     datacheck(userText); 

     //set touch listener for the checkboxes. 
     for(int i = 0; i < checkBoxArrayList.size(); i++){ 

      checkBoxArrayList.get(i).setOnLongClickListener(new View.OnLongClickListener() { 
       @Override 
       public boolean onLongClick(View view) { 

         view.postDelayed(runnable, 0); 

         for(int i = 0; i < checkBoxArrayList.size();i++) { 
          checkBoxArrayList.get(i).setId(i); 

         } 
         checkboxPopupCheck = view.getId(); 
         checkTitle = titleTextArrayList.get(checkboxPopupCheck) +".txt"; 
         checkNotes = titleTextArrayList.get(checkboxPopupCheck)+"_Notes.txt"; 
         //Log.i("I Value = ",Integer.toString(checkboxPopupCheck)); 
         //Toast.makeText(MainActivity.this, changeToast(checkBoxArrayList.get(view.getId()).getText()) + "is selected.", Toast.LENGTH_SHORT).show(); 
         //set check var to the checkbox that's pressed down. 
         //test for which item is selected 
         //Toast.makeText(MainActivity.this,Integer.toString(checkboxPopupCheck)+ "is selected.",Toast.LENGTH_SHORT).show(); 

        return false; 
       } 


      }); 
      } 
     } 

。私がこれを行うのは、ユーザーがプログラムを閉じて再起動した後にsendDataでチェックボックスを作成してMain Activityに作成する前に、フラグメントを初期化する必要があるからです。

ログの猫

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.addView(android.view.View)' on a null object reference 

at com.MyApp.notes.MainActivity.sendData(MainActivity.java:169) 
at com.MyApp.notes.page2_saved_notes.onCreateView(page2_saved_notes.java:89) 

私はデータを送信する前に、ビューがフラグメントの内部でまだ初期化されていないかのように思えます。

保存したデータで私のフラグメントのsendDataを電話してチェックボックスを再作成するにはどうすればよいですか?

回答: Moshe Edriを援助してくれてありがとう。ここで私が間違っていたところです...

私はフラグメントの内部でレイアウトを初期化し、main(新しいメソッドのLinearLayoutパラメータ/新しい名前の追加を除いて、基本的にコピー&ペースト)で新しいメソッドを作成する必要がありました。データ+レイアウト。

フラグメント

1)Iは、インターフェイス変更:

public interface communicateCheckboxes { 
     void sendData2(String title, String Notes, LinearLayout layout); 
    } 

2))断片とのonCreate(で初期化するために、レイアウト変数を追加しました。

LinearLayout ll;//initalize 

ll = (LinearLayout)rootView.findViewById(R.id.myLayout);//onCreate() 

3)onCreate()でデータを送信します。

for (int i = 0; i < arrayListNotes.size(); i++) { 
      Log.i("CHECKING",arrayListTitle.get(i)); 
      if(cc!= null) { 
      cc.sendData2(arrayListTitle.get(i), arrayListNotes.get(i),ll); 
      } 
     } 

答えて

2

あなたはそのようにこれを実行する必要があるフラグメントに話をするためのインタフェースを宣言します。あなたが名前を選ぶために得ることはありません

public interface Listener { 
     void sendData(String title, String Notes); 
    } 

、それは任意のオブジェクト

を拡張するようなものです

あなたは

はそのような変数を作成するには、同じようにあなたのリスナーを実装する必要がありますが...:

01あなたのフラグメントで

public void onAttach(Context context) { 
    super.onAttach(context); 
    if (context instanceof Activity) { 
     listener = (Listener) context; 
    } 
} 

は、あなたは、リスナーの

if(listener != null){ 
listener.sendData("title" , "notes"); 
} 
+0

どのようなあなたの関数を呼び出すことができますか? – pewpew

+0

私はメソッドを呼び出す前に、フラグメント内のビューを膨らませるためです。だから私は、なぜそれが表示することができないということがわからないのですか? – pewpew

+0

'//主なアクティビティにデータを送ります (int i = 0; i pewpew

関連する問題