Java 尝试在片段生命周期中实例化新类时出错
描述:我有两个班,如下所示 伪码 现在我的问题是,当我试图初始化类A中的类B时,比如Java 尝试在片段生命周期中实例化新类时出错,java,android,asynchronous,android-fragments,google-geocoder,Java,Android,Asynchronous,Android Fragments,Google Geocoder,描述:我有两个班,如下所示 伪码 现在我的问题是,当我试图初始化类A中的类B时,比如B=new B()My崩溃在我尝试初始化B类的线路上(我尝试在各种活动回调方法中初始化B类,如onActivityCreated(),OnCreateView()等,它们都不起作用。具体错误如下: 空指针异常 在 &在 更详细的信息类A由MainActivity调用,MainActivity用两个选项卡填充ActionBar public class rookWork extends FragmentActivi
B=new B()
My崩溃在我尝试初始化B类的线路上(我尝试在各种活动回调方法中初始化B类,如onActivityCreated()
,OnCreateView()
等,它们都不起作用。具体错误如下:
空指针异常
在
&在
更详细的信息类A由MainActivity调用,MainActivity用两个选项卡填充ActionBar
public class rookWork extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
LocationClient mLocationClient = new LocationClient(this, this, this);
public LocationClient setup() {
return mLocationClient;
}
@Override
public void onConnected(Bundle connectionHint) {
Toast.makeText(getApplicationContext(), "Connected!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onDisconnected() {
Toast.makeText(getApplicationContext(), "Disconnected!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects. If the
* error has a resolution, try sending an Intent to start a Google
* Play services activity that can resolve error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult
.startResolutionForResult(
this,
LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
// If no resolution is available, display a dialog to the user
// with the error.
showErrorDialog(connectionResult.getErrorCode());
}
}
public void getAddress(View v) {
// In Gingerbread and later, use Geocoder.isPresent() to see if a
// geocoder is available.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD
&& !Geocoder.isPresent()) {
// No geocoder is present. Issue an error message
Toast.makeText(getActivity(), R.string.no_geocoder_available,
Toast.LENGTH_LONG).show();
return;
}
if (servicesConnected()) {
// Get the current location
Location currentLocation = mLocationClient.getLastLocation();
// Turn the indefinite activity indicator on
mActivityIndicator.setVisibility(View.VISIBLE);
// Start the background task
GetAddressTask getAddressTask = new GetAddressTask(
getActivity());
getAddressTask.execute(currentLocation);
// (new
// GetAddressTask.GetAddressTask(this)).execute(currentLocation);
} else {
Toast.makeText(getActivity(), "servicesConnected() == false",
Toast.LENGTH_SHORT).show();
}
}
private boolean servicesConnected() {
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
// In debug mode, log the status
Log.d(LocationUtils.APPTAG,
getString(R.string.play_services_available));
// Continue
return true;
// Google Play services was not available for some reason
} else {
// Display an error dialog
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
resultCode, this, 0);
if (dialog != null) {
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
errorFragment.setDialog(dialog);
errorFragment.show(getSupportFragmentManager(),
LocationUtils.APPTAG);
}
return false;
}
}
private void showErrorDialog(int errorCode) {
// Get the error dialog from Google Play services
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
errorCode, this,
LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST);
// If Google Play services can provide an error dialog
if (errorDialog != null) {
// Create a new DialogFragment in which to show the error dialog
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
// Set the dialog in the DialogFragment
errorFragment.setDialog(errorDialog);
// Show the error dialog in the DialogFragment
errorFragment.show(getSupportFragmentManager(),
LocationUtils.APPTAG);
}
}
/**
* Define a DialogFragment to display the error dialog generated in
* showErrorDialog.
*/
@SuppressLint("ValidFragment")
public class ErrorDialogFragment extends DialogFragment {
// Global field to contain the error dialog
private Dialog mDialog;
/**
* Default constructor. Sets the dialog field to null
*/
@SuppressLint("ValidFragment")
public ErrorDialogFragment() {
super();
mDialog = null;
}
/**
* Set the dialog to display
*
* @param dialog
* An error dialog
*/
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
/*
* This method must return a Dialog to the DialogFragment.
*/
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mDialog;
}
}
异步类:
/*
*谷歌进口
*/
/*
*Android导入
*/
导入java.io.IOException;
导入java.util.ArrayList;
导入java.util.List;
导入java.util.Locale;
导入android.os.AsyncTask;
导入android.content.Context;
导入android.location.Address;
导入android.location.Geocoder;
导入android.location.location;
导入android.util.Log;
导入android.view.view;
导入android.widget.EditText;
导入android.widget.ProgressBar;
导入android.widget.TextView;
导入android.widget.Toast;
公共类GetAddressTask扩展了AsyncTask{
语境;
字符串地址文本;
智力测验;
公共GetAddressTask(上下文){
超级();
mContext=上下文;
}
@凌驾
受保护字符串doInBackground(位置…参数){
/*
*获取新的地理编码服务实例,为本地化地址设置。
*本例使用android.location.Geocoder,但其他地理编码器
*也可以使用符合地址标准的。
*/
Geocoder Geocoder=新的地理编码器(mContext,Locale.getDefault());
//从输入参数列表中获取当前位置
位置=参数[0];
//创建包含结果地址的列表
列表地址=空;
//尝试获取当前位置的地址。捕获IO或网络
//问题。
试一试{
/*
*使用latitude调用同步getFromLocation()方法
*和当前位置的经度。最多返回1个地址。
*/
addresses=geocoder.getFromLocation(location.getLatitude(),
location.getLongitude(),1);
//捕获网络或其他I/O问题。
}捕获(IOException例外1){
//记录错误并返回错误消息
Log.e(LocationUtils.APPTAG,
mContext.getString(R.string.IO_Exception_getFromLocation));
//打印堆栈跟踪
例外情况1.printStackTrace();
//返回错误消息
返回(mContext.getString(R.string.IO_Exception_getFromLocation));
//捕获错误的纬度或经度值
}捕获(IllegalArgumentException异常2){
//构造包含无效参数的消息
String errorString=mContext.getString(
R.string.unliked_参数_异常,
location.getLatitude(),location.getLatitude());
//记录错误并打印堆栈跟踪
Log.e(LocationUtils.APPTAG,errorString);
例外2.printStackTrace();
//
返回错误字符串;
}
//如果反向地理代码返回一个地址
if(addresses!=null&&addresses.size()>0){
//获取第一个地址
地址=地址。获取(0);
//格式化地址的第一行
字符串地址text=mContext.getString(
R.string.address\u output\u string,
//如果有街道地址,请添加它
address.getMaxAddressLineIndex()>0?地址
.getAddressLine(0):“”,
//地点通常是一个城市
address.getLocation(),
//地址所在国
address.getCountryName());
//返回文本
返回地址文本;
//如果没有任何地址,请发布消息
}否则{
返回mContext.getString(R.string.no\u address\u);
}
}
受保护的void onPostExecute(字符串结果){
/*
*Toast.makeText(mContext.getApplicationContext(),“执行完成”,
*吐司。长度(短)。show();
*/
Toast.makeText(mContext.getApplicationContext(),
参数长度:“+Integer.toString(测试),Toast.Length_SHORT)
.show();
}
}
遗言
如果我注释掉B类(RookWork)的安装,一切都会正常运行。我以前能够使用geocoder运行异步任务。但是,该安装不涉及在a类中嵌入B类
B类(RookWork)的安装
RookWork是一个活动
。不能在Android中直接实例化活动。若要创建新活动,必须使用Intents
如果理解正确,您需要一个活动实例,因为一些与Google Play服务相关的方法(如startResolutionForResult()
)需要一个活动实例
最简单的解决方案可能是将所有这些代码(即接口的实现)移动到片段本身,然后在需要活动时使用getActivity()
。它将返回片段当前附加到的活动
例如:
public class A extends Fragment
implements GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener
{
...
@Override
public void onConnectionFailed(ConnectionResult connectionResult)
{
...
connectionResult.startResolutionForResult(getActivity(), LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST);
...
}
...
你说得很有道理。你能解释一下我的问题吗。我需要B类保持原样,但我必须调用它在a类中拥有的函数。有什么方法可以做到这一点吗…?你能举个例子吗。事实上我想我已经解决了。谢谢。一个
android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
public class rookWork extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
LocationClient mLocationClient = new LocationClient(this, this, this);
public LocationClient setup() {
return mLocationClient;
}
@Override
public void onConnected(Bundle connectionHint) {
Toast.makeText(getApplicationContext(), "Connected!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onDisconnected() {
Toast.makeText(getApplicationContext(), "Disconnected!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects. If the
* error has a resolution, try sending an Intent to start a Google
* Play services activity that can resolve error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult
.startResolutionForResult(
this,
LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
// If no resolution is available, display a dialog to the user
// with the error.
showErrorDialog(connectionResult.getErrorCode());
}
}
public void getAddress(View v) {
// In Gingerbread and later, use Geocoder.isPresent() to see if a
// geocoder is available.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD
&& !Geocoder.isPresent()) {
// No geocoder is present. Issue an error message
Toast.makeText(getActivity(), R.string.no_geocoder_available,
Toast.LENGTH_LONG).show();
return;
}
if (servicesConnected()) {
// Get the current location
Location currentLocation = mLocationClient.getLastLocation();
// Turn the indefinite activity indicator on
mActivityIndicator.setVisibility(View.VISIBLE);
// Start the background task
GetAddressTask getAddressTask = new GetAddressTask(
getActivity());
getAddressTask.execute(currentLocation);
// (new
// GetAddressTask.GetAddressTask(this)).execute(currentLocation);
} else {
Toast.makeText(getActivity(), "servicesConnected() == false",
Toast.LENGTH_SHORT).show();
}
}
private boolean servicesConnected() {
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
// In debug mode, log the status
Log.d(LocationUtils.APPTAG,
getString(R.string.play_services_available));
// Continue
return true;
// Google Play services was not available for some reason
} else {
// Display an error dialog
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
resultCode, this, 0);
if (dialog != null) {
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
errorFragment.setDialog(dialog);
errorFragment.show(getSupportFragmentManager(),
LocationUtils.APPTAG);
}
return false;
}
}
private void showErrorDialog(int errorCode) {
// Get the error dialog from Google Play services
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
errorCode, this,
LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST);
// If Google Play services can provide an error dialog
if (errorDialog != null) {
// Create a new DialogFragment in which to show the error dialog
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
// Set the dialog in the DialogFragment
errorFragment.setDialog(errorDialog);
// Show the error dialog in the DialogFragment
errorFragment.show(getSupportFragmentManager(),
LocationUtils.APPTAG);
}
}
/**
* Define a DialogFragment to display the error dialog generated in
* showErrorDialog.
*/
@SuppressLint("ValidFragment")
public class ErrorDialogFragment extends DialogFragment {
// Global field to contain the error dialog
private Dialog mDialog;
/**
* Default constructor. Sets the dialog field to null
*/
@SuppressLint("ValidFragment")
public ErrorDialogFragment() {
super();
mDialog = null;
}
/**
* Set the dialog to display
*
* @param dialog
* An error dialog
*/
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
/*
* This method must return a Dialog to the DialogFragment.
*/
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mDialog;
}
}
/*
* Google Imports
*/
/*
* Android Imports
*/
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import android.os.AsyncTask;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class GetAddressTask extends AsyncTask<Location, Void, String> {
Context mContext;
String addressText;
int test;
public GetAddressTask(Context context) {
super();
mContext = context;
}
@Override
protected String doInBackground(Location... params) {
/*
* Get a new geocoding service instance, set for localized addresses.
* This example uses android.location.Geocoder, but other geocoders that
* conform to address standards can also be used.
*/
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
// Get the current location from the input parameter list
Location location = params[0];
// Create a list to contain the result address
List<Address> addresses = null;
// Try to get an address for the current location. Catch IO or network
// problems.
try {
/*
* Call the synchronous getFromLocation() method with the latitude
* and longitude of the current location. Return at most 1 address.
*/
addresses = geocoder.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
// Catch network or other I/O problems.
} catch (IOException exception1) {
// Log an error and return an error message
Log.e(LocationUtils.APPTAG,
mContext.getString(R.string.IO_Exception_getFromLocation));
// print the stack trace
exception1.printStackTrace();
// Return an error message
return (mContext.getString(R.string.IO_Exception_getFromLocation));
// Catch incorrect latitude or longitude values
} catch (IllegalArgumentException exception2) {
// Construct a message containing the invalid arguments
String errorString = mContext.getString(
R.string.illegal_argument_exception,
location.getLatitude(), location.getLongitude());
// Log the error and print the stack trace
Log.e(LocationUtils.APPTAG, errorString);
exception2.printStackTrace();
//
return errorString;
}
// If the reverse geocode returned an address
if (addresses != null && addresses.size() > 0) {
// Get the first address
Address address = addresses.get(0);
// Format the first line of address
String addressText = mContext.getString(
R.string.address_output_string,
// If there's a street address, add it
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(0) : "",
// Locality is usually a city
address.getLocality(),
// The country of the address
address.getCountryName());
// Return the text
return addressText;
// If there aren't any addresses, post a message
} else {
return mContext.getString(R.string.no_address_found);
}
}
protected void onPostExecute(String result) {
/*
* Toast.makeText(mContext.getApplicationContext(), "Execution Done",
* Toast.LENGTH_SHORT).show();
*/
Toast.makeText(mContext.getApplicationContext(),
"Params Length: " + Integer.toString(test), Toast.LENGTH_SHORT)
.show();
}
}
public class A extends Fragment
implements GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener
{
...
@Override
public void onConnectionFailed(ConnectionResult connectionResult)
{
...
connectionResult.startResolutionForResult(getActivity(), LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST);
...
}
...