我在我的应用中使用片段布局,此应用包含列表视图。点击项目可以完成一些工作。在横向模式下工作正常,但如果在轻拍模式下单击项目则会崩溃。可能是什么问题?
这是我的代码:
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 //显示列表视图
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 //单击项目时的操作
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>
landscpae的ActivityMain.xml
<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 //
<?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>
屏幕截图
在遵循答案中建议的建议后的肖像模式的当前情况:
更新
我能够克服崩溃问题并在当前处于<strong> portait模式时从列表视图中点击项目后移至下一个屏幕,但视图返回null那里;表示我想在那里显示的内容(屏幕截图的蓝色部分)未显示,屏幕为空白。
以下是更新后的代码:
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();
//////////////这里更新的代码///////////////
**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");
/////////////////////这里更新的代码////////////////
Bundle bundle = 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
}
}
}
////////////////////*/
}
已解决的问题
将公共视图oncreateView更改为受保护的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);
}
肖像模式的屏幕截图:
答案 0 :(得分:1)
您正在调用正在尝试使用具有空引用的change
的方法TextView add
。请在使用之前初始化它。
这就是问题的根本原因:
add.setText(txt1);
这里,add指向null,并且您正在使用该空引用。
如@Syed Nazar Muhammad所提到的那样,问题的另一个问题似乎是fragment2
fragment
ActivityMain.xml
TextFragment txt = (TextFragment) getFragmentManager().findFragmentById(R.id.fragment2);
。谢谢你。
R.id.fragment2
ActivityMain.xml
中缺少 actionBar.setTitle(Html.fromHtml("<font color='#ff0000'>ActionBarTitle </font>"));
希望有所帮助!!!
答案 1 :(得分:1)
问题在于:
TextFragment txt = (TextFragment)getFragmentManager().findFragmentById(R.id.fragment2);
您正在尝试找到仅在MainActivity的横向布局中的R.id.fragment2,当您旋转到横向时,它会找到id fragment2,但是当您将设备旋转到纵向模式时,找不到ID,因为它在MainActivity的纵向模式中不存在。
答案 2 :(得分:0)
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);
}