I want to change the sheet from the activation in the fragment.
Throws a string error:

Fragment frag1 = getFragmentManager().findFragmentById(R.id.fragment2); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.rowlayout, R.id.label, list1); ListView lIstView = (ListView) frag1.getView().findViewById(R.id.listView); 

The last line displays the error:

12-18 11: 00: 01.066 9961-9961 / com.example.eldos.callreport E / AndroidRuntime ﹕ FATAL EXCEPTION: main Process: com.example.eldos.callreport, PID: 9961 java.lang.IllegalStateException: Could not execute method of the activity at android.view.View $ 1.onClick (View.java.3823) at android.view.View.performClick (View.java:4438) at android.view.View $ PerformClick.run (View.java:18422 ) at android.os.Handler.handleCallback (Handler.java:733) at android.os.Handler.dispatchMessage (Handler.java:95) at android.os.Looper.loop (Looper.java:136) at android.app .ActivityThread.main (ActivityThread.java 19971) at java.lang.reflect.Method.invokeNative (Native Method) at java.lang.reflect.Method.invoke (Method.java ind15) at com.android.internal.os .ZygoteInit $ MethodAndArgsCaller.run (ZygoteInit.java:785) at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:601) at dalvik.system.NativeStart.main (Native Method) Caused by: java.lang .reflect.InvocationTargetException at java.lang.reflect.Method.invokeNative (Native Meth od) at java.lang.reflect.Method.invoke (Method.java including 15) at android.view.View $ 1.onClick (View.java:3818) at android.view.View.performClick (View.java:4438) at android.view.View $ PerformClick.run (View.java:18422) at android.os.Handler.handleCallback (Handler.java:733) at android.os.Handler.dispatchMessage (Handler.java:95) at android. os.Looper.loop (Looper.java:136) at android.app.ActivityThread.main (ActivityThread.javaCl001) at java.lang.reflect.Method.invokeNative (Native Method) at java.lang.reflect.Method. invoke (Method.java Lower 15) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run (ZygoteInit.java:785) at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:601) at dalvik .system.NativeStart.main (Native Method) Caused by: java.lang.NullPointerException at com.example.eldos.callreport.MainActivity.call (MainActivity.java:122) at java.lang.reflect.Method.invokeNative (Native Method ) at java.lang.reflect.Method.invoke (Method.java including 15) at android.view.View $ 1.onClick (View.java:3818) at a ndroid.view.View.performClick (View.java:4438) at android.view.View $ PerformClick.run (View.java:18422) at android.os.Handler.handleCallback (Handler.java:733) at android.os .Handler.dispatchMessage (Handler.java:95) at android.os.Looper.loop (Looper.java:136) at android.app.ActivityThread.main (ActivityThread.java partner1001) at java.lang.reflect.Method. invokeNative (Native Method) at java.lang.reflect.Method.invoke (Method.javaCl15) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run (ZygoteInit.java:785) at com.android.internal. os.ZygoteInit.main (ZygoteInit.java:601) at dalvik.system.NativeStart.main (Native Method)

  • one
    At what point is this string called (on which the error occurs)? Maybe the fragment onCreateView () method does not have time to be called, and, as a result, getView () == null ?? - Vladyslav Matviienko
  • one
    As already written above, by chance frag1 you have a non null hour? Let's take a complete (relatively) code, because no one will tell you exactly what and how. - CROSP

1 answer 1

You have chosen not the most successful approach to solving the problem.

The relationship between activism and fragments is complex, ambiguous and leads to a multitude of problems when misinterpreting the life cycle of both elements.

It is best (according to my experience) not to communicate with the fragment directly from the activation, but to use, for example, LocalBroadcastManager

Task:

Update the list of activations by assigning to it an adapter with the data that is in the activation. For this:

Decision:

1) In the onCreateView () fragment, we find the ListView and assign it to a fragment variable.

 ListView lV; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //inflate root view View v; v = inflater.inflate(R.layout.YOURS_FRAGMENT_LAYOUT_WITH_LIST_VIEW, container, false); this.lV=v.findViewById(R.id.YOURS_LIST_VIEW_IN_FRAGMENTS_LAYOUT_ID); return v; } 

2) Create a method in the fragment that accepts data for the list, initializes the adapter and assigns it to the list:

 private void setAdapterForListView(String[] yoursStringArrayWithData) { ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.rowlayout, R.id.label, yoursStringArrayWithData); this.lv.setAdapter(adapter); } 

3) Describe how the fragment should respond to the LocalBroadcastManager messages:

 private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { //наши данные из активити придут внутри Intent //значит надо их вытащить String[] yoursStringArrayWithDataFromIntent = intent.getStringArrayExtra("stringKeyToExtractData"); //вызываем наш метод, коий сделает адаптер с пришедшими данными //и присвоит его списку setAdapterForListView(yoursStringArrayWithDataFromIntent ) } }; 

4) The fragment should know that it can receive messages and respond to them. We write this line in the onCreate () of the fragment.

 LocalBroadcastManager.getInstance(this.act).registerReceiver(receiver, new IntentFilter("setAdapterToListView")); 

5) It is important to teach the fragment how to de-register a message and clear the memory. We write:

  @Override public void onDestroy() { //если reciver существует, то отменяем регистрацию и стираем его. if (receiver != null) { LocalBroadcastManager.getInstance(act).unregisterReceiver(receiver); receiver = null; } // Не забываем вызвать super метод в конце super.onDestroy(); } 

6) It remains only to activate the message with the data for the adapter, which will be received and processed by the fragment. We write in the right place to activate:

 //Наши данные для адаптера String[] data={"раз", "два", "три", "рубль", "расти"}; //Создаём интент, пихаем в него наши данные Intent intent=new Intent("setAdapterToListView"); Bundle b=new Bundle(); b.putStringArray("stringKeyToExtractData", data); intent.putExtras(b); //Посылаем сообщение с данными LocalBroadcastManager.getInstance(context).sendBroadcast(intent); 

Total:

1) At the right time (by clicking or by the arrival of data) from the activation we send a message with the data.

2) The fragment catches the message (determines that this message is to it by line, which is passed to the intent constructor.

3) Does everything you need. In this case, it pulls out the data, transfers it to the list.

Possible problems:

We must remember about the life cycle. There is no sense in sending a message with data from onCreate () activation, because there are no fragments yet, no markup in them, the application crashes.

  • Thank you very much. I run it and it seems to not reach the fragment, in the debugger it is written like this. intent = {android.content.Intent@831700928368} "Intent {act = setAdapterToListView}" b = {android.os.Bundle@831700929696} "Bundle [{stringKeyToExtractData = [Ljava.lang.String; @ 529e6ca6}" mprData; Cannot find local variable 'mParcelledData' mClassLoader = Cannot find local variable 'mClassLoader' mMap = Cannot find local variable 'mMap' Maybe this is not a problem. I now have this way in activism I inherit from FragmentActivity and in the fragment I inherit from Fragment - J Mas
  • and if I use Oncreate activit gives an error in setContentView (R.layout.activity_main); so I did the initialization in onCreateView, public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {LocalBroadcastManager.getInstance (getActivity ()). registerReceiver (receiver, new IntentFilter ("setAdaperToListView")); and so it works but the broadcast does not reach it, as I understood what could be the problem, I put the debagers in the fragment in the broadcast acceptance points and methods, but they didn’t work apparently did not reach - J Mas
  • that is, I mean that if oncreate is in the fragment, then for some reason it gives an error, that's why I have to use onCreateView - J Mas
  • @eldqs, where do you send the message? By clicking on the button? And I do not know how the debager works ... I use the logs:> Log.d ("myLog", "myMessage"); And they check where the code went, where it doesn’t, the values ​​of variables, etc. - Yuriy SPb