List crashes in portrait mode when clicking on items (using fragments)

I use a snippet in my application, this application contains a listview. Clicking on items will do a specific job. works fine when in landscape mode, but gets broken if items are clicked in portait mode. What could be the problem?

Here is my code:

MainAcitivity.java

package com.example.newfragment; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.widget.Toast; public class MainActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); /*/ Checks the orientation of the screen if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { setContentView(R.layout.activity_main); Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show(); } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){ setContentView(R.layout.activity_main); Toast.makeText(this, "portait", Toast.LENGTH_SHORT).show(); }*/ } } 

MenuFragment.java // display list view

  package com.example.newfragment; import java.io.File; import java.util.ArrayList; import android.support.v4.app.ListFragment; import android.os.Bundle; import android.os.Environment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; public class MenuFragment extends ListFragment { int i; private String[] FilePathStrings; private String[] FileNameStrings; File[] listFile;//for photo String[] name = new String[] { "Sri","Sud","Urmila","Amrita","Indra","Ayan", "Leo","Neymar","Robin","Ian","Suarez","Mesut","Bastin", "Rooney","Ranti","Dong Hyun","Barisich","Andrew" }; String[] address = new String[] {"Dumdum","Dumdum","Dumdum","Dumdum","Lake Town", "Salkia","Argentina","Brazil","Netherlands"}; String [] mobile = new String[]{"456456456","56564565","787687866", "645645645","5654576457","76897978978","768768567"}; String [] photo = new String[]{}; @Override public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) { View view =inflater.inflate(R.layout.list_fragment, container, false); ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, name); setListAdapter(adapter); return view; } /////////////////////sending data to TextFragment////////////////// @Override public void onListItemClick(ListView l, View v, int position, long id) { ///////////accessing files from sd card/////// File file = new File(Environment.getExternalStorageDirectory() +"/Frag_list/"); if (file.isDirectory()) { listFile = file.listFiles(); // Create a String array for FilePathStrings FilePathStrings = new String[listFile.length]; for (i = 0; i < listFile.length; i++) { // Get the path of the image file FilePathStrings[i] = listFile[i].getAbsolutePath(); } } ////////////////////////////// TextFragment txt = (TextFragment)getFragmentManager().findFragmentById(R.id.fragment2); txt.change(position,address[position],mobile[position]); getListView().setSelector(android.R.color.holo_blue_dark); } } 

TextFragment.java // for actions when clicking elements

  package com.example.newfragment; import java.io.File; import java.io.FileNotFoundException; import java.io.FilenameFilter; import java.io.InputStream; import android.R.string; import android.support.v4.app.Fragment; import android.app.Activity; import android.content.ContentResolver; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.PixelFormat; import android.hardware.Camera; import android.hardware.Camera.Parameters; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class TextFragment extends Fragment implements OnClickListener { TextView text,add; private ImageView img; Button b; int value; String mobile; File photo; private static final int CAMERA_REQUEST = 1888; Camera camera; ////////////data received here//////////// public void change(int txt, String txt1, String txt2 ){ add.setText(txt1 ); value = txt; mobile = txt2; //photo = f; //File image = new File(Environment.getExternalStorageDirectory() +"/Frag_list/"+value+".jpg"); /*if(photo.exists()) { img.setImageBitmap(BitmapFactory.decodeFile(photo.getAbsolutePath())); } else img.setImageResource(R.drawable.ic_launcher);*/ } @Override public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.text_fragment, container, false); //text= (TextView) view.findViewById(R.id.AndroidOs); add= (TextView)view.findViewById(R.id.address); img= (ImageView)view.findViewById(R.id.img); ////////////////// /*File image = new File(Environment.getExternalStorageDirectory() +"/Frag_list/"+value+".jpg"); if(image.exists()) { img.setImageBitmap(BitmapFactory.decodeFile(image.getAbsolutePath()));/////////////setting image in imageview }*/ ////////////////////// b= (Button)view.findViewById(R.id.b); img.setOnClickListener(this); b.setOnClickListener(this); return view; } @Override public void onClick(View v) { // TODO Auto-generated method stub if(v.equals(img)) { //Toast.makeText(getContext(), "Camera", Toast.LENGTH_LONG).show(); /*///////////camera hardware/////////// Parameters parameters = camera.getParameters();//////////////PROBLEM: APP GETTING CRASHED WHEN USED parameters.setPictureSize(80, 80); camera.setParameters(parameters); camera = Camera.open(); ///////////////////////////////////////*/ /*Clicking and saving image to sd card*/ ////////////////////////////////////// File file = new File(Environment.getExternalStorageDirectory(), "Frag_list"); file.mkdirs(); String path = Environment.getExternalStorageDirectory() +"/Frag_list/"+value+".jpg"; File file2= new File(path); Uri outputFileUri = Uri.fromFile( file2 ); Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE ); //intent.putExtra("android.media.action.IMAGE_CAPTURE", outputFileUri ); ///////for displaying image intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri ); //////////for saving image /*Bundle b = new Bundle(); b.putString("android.media.action.IMAGE_CAPTURE", outputFileUri);*/ startActivityForResult( intent, CAMERA_REQUEST ); ///////////////////////////////////// } if(v.equals(b)) { //Toast.makeText(getContext(), "mobile:"+mobile, Toast.LENGTH_LONG).show(); /*Calling number*/ //////////////////////////////////////////////// Uri number = Uri.parse("tel:" +mobile); Intent callIntent = new Intent(Intent.ACTION_CALL, number); startActivity(callIntent); //////////////////////////////////////////////// } } ///setting image in display /////////////////////////////////////////////////////////// public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) { /*if (data != null) { File photo = new File(Environment.getExternalStorageDirectory()+"/Frag_list/"+value+".jpg"); Uri imgUri=Uri.fromFile(photo); img.setImageURI(imgUri); /* img.setImageBitmap((Bitmap) data.getExtras().get("data")); // this is image view where you want to set image Log.d("camera ---- > ", "" + data.getExtras().get("data")); }*/ File image = new File(Environment.getExternalStorageDirectory() +"/Frag_list/"+value+".jpg"); if(image.exists()){ img.setImageBitmap(BitmapFactory.decodeFile(image.getAbsolutePath()));/////////////setting image in imageview } } } ////////////////////*/ } 

AndroidManifest.xml

  <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.newfragment" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="21" /> <uses-permission android:name="android.permission.CAMERA" /> <uses-feature android:name="android.hardware.camera" android:required="false" /> <uses-feature android:name="android.hardware.camera.autofocus" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.CALL_PHONE" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" > <activity android:name=".MainActivity" android:configChanges="orientation" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> 

Logcat

  10-05 11:07:06.480: E/AndroidRuntime(4921): FATAL EXCEPTION: main 10-05 11:07:06.480: E/AndroidRuntime(4921): java.lang.NullPointerException 10-05 11:07:06.480: E/AndroidRuntime(4921): at com.example.newfragment.TextFragment.change(TextFragment.java:48) 10-05 11:07:06.480: E/AndroidRuntime(4921): at com.example.newfragment.MenuFragment.onListItemClick(MenuFragment.java:85) 10-05 11:07:06.480: E/AndroidRuntime(4921): at android.support.v4.app.ListFragment$2.onItemClick(ListFragment.java:58) 10-05 11:07:06.480: E/AndroidRuntime(4921): at android.widget.AdapterView.performItemClick(AdapterView.java:298) 10-05 11:07:06.480: E/AndroidRuntime(4921): at android.widget.AbsListView.performItemClick(AbsListView.java:1128) 10-05 11:07:06.480: E/AndroidRuntime(4921): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2815) 10-05 11:07:06.480: E/AndroidRuntime(4921): at android.widget.AbsListView$1.run(AbsListView.java:3574) 10-05 11:07:06.480: E/AndroidRuntime(4921): at android.os.Handler.handleCallback(Handler.java:800) 10-05 11:07:06.480: E/AndroidRuntime(4921): at android.os.Handler.dispatchMessage(Handler.java:100) 10-05 11:07:06.480: E/AndroidRuntime(4921): at android.os.Looper.loop(Looper.java:194) 10-05 11:07:06.480: E/AndroidRuntime(4921): at android.app.ActivityThread.main(ActivityThread.java:5371) 10-05 11:07:06.480: E/AndroidRuntime(4921): at java.lang.reflect.Method.invokeNative(Native Method) 10-05 11:07:06.480: E/AndroidRuntime(4921): at java.lang.reflect.Method.invoke(Method.java:525) 10-05 11:07:06.480: E/AndroidRuntime(4921): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833) 10-05 11:07:06.480: E/AndroidRuntime(4921): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600) 10-05 11:07:06.480: E/AndroidRuntime(4921): at dalvik.system.NativeStart.main(Native Method) 

ActivityMain.xml

  <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <fragment android:id="@+id/list_Fragment" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" class="com.example.newfragment.MenuFragment" > </fragment> </LinearLayout> 

ActivityMain.xml of landscpae

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" tools:context="com.example.newfragment.MainActivity"> <fragment android:layout_height="match_parent" android:layout_width="0dp" android:layout_weight="1" class="com.example.newfragment.MenuFragment" android:id="@+id/fragment"/> <fragment android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="2" class="com.example.newfragment.TextFragment" android:id="@+id/fragment2"/> </LinearLayout> 

ListFragment.xml // for the list

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@android:id/list" /> </LinearLayout> 

TextFragment.xml

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#5ba4e5" > <ImageView android:id="@+id/img" android:layout_width="100dp" android:layout_height="100dp" android:layout_marginTop="20dp" android:layout_marginLeft="30dp" android:onClick="imageClick" android:src="@drawable/ic_launcher" /> <TableLayout android:id="@+id/tb" android:layout_width="match_parent" android:layout_height="match_parent" > <TableRow> <TextView android:id="@+id/address" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Address" android:textColor="#ffffff" android:textSize="20sp" android:layout_marginLeft="40dp" android:layout_marginTop="30dp" /> </TableRow> <TableRow android:layout_width="match_parent" android:layout_height="match_parent" > <Button android:id="@+id/b" android:layout_marginLeft="40dp" android:layout_marginTop="30dp" android:layout_span="2" android:background="#ffffff" android:text="Mobile" android:textColor="#000000" /> </TableRow> </TableLayout> </LinearLayout> 

Screenshots

image of the application in landscape mode after clicking an item from the list

The current situation in portait mode after the following suggestions suggested in the answers:

portait application image after clicking an item from a list

UPDATE

I can overcome the failure problem and move on to the next screen after clicking items from the list in portait mode at present, but the view returns null there; means the content that I want to display there (the blue part of the screenshot) is not displayed , the screen is blank .

Here is the updated code:

MenuFragment.java

 public class MenuFragment extends ListFragment { int i; private String[] FilePathStrings; private String[] FileNameStrings; File[] listFile;//for photo String[] name = new String[] { "Sri","Sud","Urmila","Amrita","Indra","Ayan", "Leo","Neymar","Robin","Ian","Suarez","Mesut","Bastin", "Rooney","Ranti","Dong Hyun","Barisich","Andrew" }; String[] address = new String[] {"Dumdum","Dumdum","Dumdum","Dumdum","Lake Town", "Salkia","Argentina","Brazil","Netherlands"}; String [] mobile = new String[]{"456456456","56564565","787687866", "645645645","5654576457","76897978978","768768567"}; String [] photo = new String[]{}; @Override public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) { View view =inflater.inflate(R.layout.list_fragment, container, false); ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, name); setListAdapter(adapter); return view; } /////////////////////sending data to TextFragment////////////////// @Override public void onListItemClick(ListView l, View v, int position, long id) { ///////////accessing files from sd card/////// File file = new File(Environment.getExternalStorageDirectory() +"/Frag_list/"); if (file.isDirectory()) { listFile = file.listFiles(); // Create a String array for FilePathStrings FilePathStrings = new String[listFile.length]; for (i = 0; i < listFile.length; i++) { // Get the path of the image file FilePathStrings[i] = listFile[i].getAbsolutePath(); } } ////////////////////////////// int orientation = getResources().getConfiguration().orientation; if (Configuration.ORIENTATION_LANDSCAPE == orientation) { //Do SomeThing; // Landscape TextFragment txt = (TextFragment)getFragmentManager().findFragmentById(R.id.fragment2); txt.change(position,address[position],mobile[position]); getListView().setSelector(android.R.color.holo_blue_dark); } else { //Do SomeThing; // Portrait //Toast.makeText(getContext(),address[position] , Toast.LENGTH_SHORT).show(); 

////////////// updated code here ///////////////

  **Intent intent = new Intent(getActivity(), TextFragment2.class); Bundle bundle = new Bundle(); bundle.putString("message", address[position]); intent.putExtras(bundle); getActivity().startActivity(intent);** } } 

}

TextFragment.java

 public class TextFragment2 extends Activity implements OnClickListener { TextView text,add; private ImageView img; Button b; int value; String mobile,txt; File photo; private static final int CAMERA_REQUEST = 1888; Camera camera; public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.text_fragment, container, false); add= (TextView)view.findViewById(R.id.address); img= (ImageView)view.findViewById(R.id.img); ////////////////// /*File image = new File(Environment.getExternalStorageDirectory() +"/Frag_list/"+value+".jpg"); if(image.exists()) { img.setImageBitmap(BitmapFactory.decodeFile(image.getAbsolutePath()));/////////////setting image in imageview }*/ ////////////////////// b= (Button)view.findViewById(R.id.b); img.setOnClickListener(this); b.setOnClickListener(this); //Intent intent = getActivity().getIntent(); //String message = intent.getStringExtra("message"); 

///////////////////// updated code here ////////////////

Bundle package = getIntent (). getExtras (); txt = bundle.getString ("message");

  **add.setText(txt);** return view; } @Override public void onClick(View v) { // TODO Auto-generated method stub if(v.equals(img)) { //Toast.makeText(getContext(), "Camera", Toast.LENGTH_LONG).show(); /*///////////camera hardware/////////// Parameters parameters = camera.getParameters();//////////////PROBLEM: APP GETTING CRASHED WHEN USED parameters.setPictureSize(80, 80); camera.setParameters(parameters); camera = Camera.open(); ///////////////////////////////////////*/ /*Clicking and saving image to sd card*/ ////////////////////////////////////// File file = new File(Environment.getExternalStorageDirectory(), "Frag_list"); file.mkdirs(); String path = Environment.getExternalStorageDirectory() +"/Frag_list/"+value+".jpg"; File file2= new File(path); Uri outputFileUri = Uri.fromFile( file2 ); Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE ); //intent.putExtra("android.media.action.IMAGE_CAPTURE", outputFileUri ); ///////for displaying image intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri ); //////////for saving image /*Bundle b = new Bundle(); b.putString("android.media.action.IMAGE_CAPTURE", outputFileUri);*/ startActivityForResult( intent, CAMERA_REQUEST ); ///////////////////////////////////// } if(v.equals(b)) { //Toast.makeText(getContext(), "mobile:"+mobile, Toast.LENGTH_LONG).show(); /*Calling number*/ //////////////////////////////////////////////// Uri number = Uri.parse("tel:" +mobile); Intent callIntent = new Intent(Intent.ACTION_CALL, number); startActivity(callIntent); //////////////////////////////////////////////// } } ///setting image in display /////////////////////////////////////////////////////////// public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) { /*if (data != null) { File photo = new File(Environment.getExternalStorageDirectory()+"/Frag_list/"+value+".jpg"); Uri imgUri=Uri.fromFile(photo); img.setImageURI(imgUri); /* img.setImageBitmap((Bitmap) data.getExtras().get("data")); // this is image view where you want to set image Log.d("camera ---- > ", "" + data.getExtras().get("data")); }*/ File image = new File(Environment.getExternalStorageDirectory() +"/Frag_list/"+value+".jpg"); if(image.exists()){ img.setImageBitmap(BitmapFactory.decodeFile(image.getAbsolutePath()));/////////////setting image in imageview } } } ////////////////////*/ 

}


CASE SOLVED

Changed public view oncreateView for protected void onCreate! :)

 public class TextFragment2 extends Activity implements OnClickListener { TextView text,add; private ImageView img; Button b; int value; String mobile,txt; File photo; private static final int CAMERA_REQUEST = 1888; Camera camera; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.text_fragment); add= (TextView)findViewById(R.id.address); img= (ImageView)findViewById(R.id.img); b= (Button)findViewById(R.id.b); img.setOnClickListener(this); b.setOnClickListener(this); Bundle bundle= getIntent().getExtras(); txt= bundle.getString("message"); add.setText(txt); } 

Screenshots of portrait mode:

after clicking an item

+5
source share
3 answers
 public class TextFragment2 extends Activity implements OnClickListener { TextView text,add; private ImageView img; Button b; int value; String mobile,txt; File photo; private static final int CAMERA_REQUEST = 1888; Camera camera; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.text_fragment); add= (TextView)findViewById(R.id.address); img= (ImageView)findViewById(R.id.img); b= (Button)findViewById(R.id.b); img.setOnClickListener(this); b.setOnClickListener(this); Bundle bundle= getIntent().getExtras(); txt= bundle.getString("message"); add.setText(txt); } 
0
source

You call the change method, which tries to use TextView add , which has a null reference. Please initialize it before use.

Here is the root cause of the problem:

 add.setText(txt1); 

Here add points to null and you use this null reference.

Another point of the problem appears in id, i.e. fragment2 of fragment in the ActivityMain.xml layout as mentioned by @Syed Nazar Muhammad. Thanks for this.

 TextFragment txt = (TextFragment) getFragmentManager().findFragmentById(R.id.fragment2); 

R.id.fragment2 missing from ActivityMain.xml

Hope this helps !!!

+1
source

The problem is here:

 TextFragment txt = (TextFragment)getFragmentManager().findFragmentById(R.id.fragment2); 

you are trying to find the file R.id.fragment2, which is found only in the landscape layout of MainActivity, when you rotate into the landscape, it finds the id of fragment2, but when you rotate the device into portrait mode, the identifier is not found as it does not exist in portrait mode MainActivity.

+1
source

Source: https://habr.com/ru/post/1232933/


All Articles