Hello Everyone我的应用程序在随机打开选项卡时崩溃了,并且在我的logcat中给出了这样的错误,任何人都可以帮我解决这个问题
在这个片段中,我集成了在Listview标题中显示地图信息,我正在使用SupportMapFragment
这是我的以下代码
public class ChainTab extends Fragment implements ResponseListner, OnMapReadyCallback, LocationListener, GoogleMap.OnMarkerClickListener {
String TAG = ChainTab.class.getSimpleName();
String bottleId;
String url;
ListView bottleChainListView;
// NonScrollListView bottleChainListView;
Context context;
View rootView;
String responseVal;
private GoogleMap mMap;
private LocationManager mLocationManager = null;
private String provider = null;
private Marker mCurrentPosition = null;
ProgressDialog PD;
private List<BottleInfoModel> bottleInfoModelList;
private List<CreatedAt> createdAtList;
private List<UpdatedAt> updatedAtList;
private List<Scans> scansList;
private Polyline mPolyline = null;
private LatLng mSourceLatLng = null;
private LatLng mDestinationLatLng = null;
TextView serialNoTV, entityNameTV, productTypeChainTV, originTV, getQTYUOM, entityType;
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.chain_tab, viewGroup, false);
bottleInfoModelList = new ArrayList<>();
createdAtList = new ArrayList<CreatedAt>();
updatedAtList = new ArrayList<>();
scansList = new ArrayList<>();
context = getActivity();
bottleChainListView = rootView.findViewById(R.id.bottleChainListView);
return rootView;
}
public void displayMsgs(NdefMessage[] msgs) {
if (msgs == null || msgs.length == 0)
return;
StringBuilder builder = new StringBuilder();
List<ParsedNdefRecord> records = NdefMessageParser.parse(msgs[0]);
final int size = records.size();
for (int i = 0; i < size; i++) {
ParsedNdefRecord record = records.get(i);
String str = record.str();
builder.append(str).append("\n");
}
Log.i(TAG,"NFC Id Value is :: "+builder.toString().trim());
// fab.setVisibility(View.VISIBLE);
// bottleSerialNo = textVal.getText().toString().trim();
// bottleSerialNo = "testing";
ServerHit serverHit = new ServerHit();
// url = AppConfig.REGISTER_BOTTLE_INFO + "/" + builder.toString().trim();
url = AppConfig.REGISTER_BOTTLE_INFO + "/" + "testing";
if(context != null)
serverHit.getScannedBottleInfo(context, url, this);
else
Log.i(TAG, "Context Value is Null....154");
}
@Override
public String onResponse(String response) {
responseVal = response;
try {
JSONObject jsonObject = new JSONObject(response.toString());
JSONObject payloadObject = jsonObject.getJSONObject("payload");
// for (int i =0; i<payloadObject.length(); i++){
JSONArray jsonArray = payloadObject.getJSONArray("scans");
BottleInfoModel bottleInfoModel = new BottleInfoModel();
bottleInfoModel.setEntityName(payloadObject.getString("entityName"));
bottleInfoModel.setEntityType(payloadObject.getString("entityType"));
JSONObject createdDateObj = payloadObject.getJSONObject("created_at");
CreatedAt createdAt = new CreatedAt();
createdAt.setDate(createdDateObj.getString("date"));
createdAtList.add(createdAt);
bottleInfoModel.setCreatedAtList(createdAtList);
for (int j = 0; j <= jsonArray.length() - 1; j++) {
JSONObject jsonObjectScan = jsonArray.getJSONObject(j);
Scans scansModel = new Scans();
scansModel.setEntityType(jsonObjectScan.getString("entityType"));
scansModel.setEntityName(jsonObjectScan.getString("entityName"));
scansModel.setCreated_at(jsonObjectScan.getString("created_at"));
scansModel.setLat(jsonObjectScan.getString("lat"));
scansModel.setLongVal(jsonObjectScan.getString("long"));
scansList.add(scansModel);
}
bottleInfoModel.setScansList(scansList);
bottleInfoModelList.add(bottleInfoModel);
// LayoutInflater inflater = getLayoutInflater();
// View viewGroup = inflater.inflate(R.layout.chaintab_lv_header, bottleChainListView, false);
LayoutInflater inflater=(LayoutInflater)context.getSystemService(LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.chaintab_lv_header,bottleChainListView, false);
// viewLand=inflater.inflate(R.layout.activity_main_land,null);
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.fragment_track_order_map_fragment);
mapFragment.getMapAsync(this);
entityNameTV = (TextView) view.findViewById(R.id.entityNameTV);
serialNoTV = (TextView) view.findViewById(R.id.serialNoTV);
entityType = (TextView) view.findViewById(R.id.entityType);
getQTYUOM = (TextView) view.findViewById(R.id.getQTYUOM);
originTV = (TextView) view.findViewById(R.id.originTV);
productTypeChainTV = (TextView) view.findViewById(R.id.productTypeChainTV);
entityNameTV.setText(payloadObject.getString("entityName"));
serialNoTV.setText("#" + payloadObject.getString("serialNumber"));
entityType.setText(payloadObject.getString("entityType"));
getQTYUOM.setText(payloadObject.getString("qtyUOM"));
productTypeChainTV.setText(payloadObject.getString("productDescription"));
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
formatter = new SimpleDateFormat("MMMM yyyy");
String mainChapterNumber = createdDateObj.getString("date").split("\\.", 2)[0];
Log.i("Value iss....", "Value is :: " + mainChapterNumber);
Date date = null;
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date = format.parse(mainChapterNumber);
} catch (ParseException e) {
e.printStackTrace();
}
String originStr = null, dateStr = null;
Pattern pattern = Pattern.compile(" ");
Matcher matcher = pattern.matcher(payloadObject.getString("origin") + " " + formatter.format(date));
if (matcher.find()) {
originStr = payloadObject.getString("origin");
dateStr = formatter.format(date).toString().trim();
}
originStr = setMultiColor(originStr, "#363636");
dateStr = setMultiColor(dateStr, "#87CEFA");
originTV.setText(Html.fromHtml(originStr + " " + dateStr));
ChainItemsAdapter chainItemsAdapter = new ChainItemsAdapter(context, scansList);
// ViewGroup header = (ViewGroup)inflater.inflate(R.layout.chaintab_lv_header,bottleChainListView,false);
bottleChainListView.addHeaderView(view);
bottleChainListView.setAdapter(chainItemsAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
// This block is used while implementing the things with chain api url link
/*
try {
JSONObject jsonObject = new JSONObject(response.toString());
JSONArray payloadJsonArray = jsonObject.getJSONArray("payload");
for (int i=0; i<payloadJsonArray.length(); i++){
BottleInfoModel bottleInfoModel = new BottleInfoModel();
JSONObject payloadJOBJ = payloadJsonArray.getJSONObject(i);
bottleInfoModel.setLongVal(payloadJOBJ.getString("long"));
bottleInfoModel.setLatVal(payloadJOBJ.getString("lat"));
bottleInfoModel.setEntityName(payloadJOBJ.getString("entityName"));
bottleInfoModel.setSerialNumber(payloadJOBJ.getString("bottleId"));
CreatedAt createdAt = new CreatedAt();
JSONObject jsonObjectCreatedAt = payloadJOBJ.getJSONObject("created_at");
createdAt.setDate(jsonObjectCreatedAt.getString("date"));
createdAt.setTimezone(jsonObjectCreatedAt.getString("timezone"));
createdAt.setTimezone_type(jsonObjectCreatedAt.getString("timezone_type"));
createdAtList.add(createdAt);
bottleInfoModel.setCreatedAtList(createdAtList);
bottleInfoModelList.add(bottleInfoModel);
}
entityNameTV.setText(bottleInfoModelList.get(0).getEntityName());
serialNoTV.setText(bottleInfoModelList.get(0).getSerialNumber());
ChainItemsAdapter chainItemsAdapter = new ChainItemsAdapter(context, bottleInfoModelList);
bottleChainListView.setAdapter(chainItemsAdapter);;
}catch (JSONException e){
e.printStackTrace();
}*/
return null;
}
private String setMultiColor(String text, String color) {
String input = "<font color=" + color + ">" + text + "</font>";
return input;
}
@Override
public JSONObject onResponse(JSONObject response) {
return null;
}
@Override
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
break;
case LocationProvider.AVAILABLE:
break;
}
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
@Override
public boolean onMarkerClick(Marker marker) {
return false;
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// LatLng target = mMap.getCameraPosition().target;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
addMarks(mMap);
if (isProviderAvailable() && (provider != null)) {
locateCurrentPosition();
}
}
private void locateCurrentPosition() {
int status = context.getPackageManager().checkPermission(Manifest.permission.ACCESS_COARSE_LOCATION,
context.getPackageName());
if (status == PackageManager.PERMISSION_GRANTED) {
Location location = mLocationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
// mLocationManager.addGpsStatusListener(this);
long minTime = 5000;// ms
float minDist = 5.0f;// meter
mLocationManager.requestLocationUpdates(provider, minTime, minDist,
this);
}
}
private void updateWithNewLocation(Location location) {
if (location != null && provider != null) {
double lng = location.getLongitude();
double lat = location.getLatitude();
mSourceLatLng = new LatLng(lat, lng);
// addBoundaryToCurrentPosition(lat, lng);
CameraPosition camPosition = new CameraPosition.Builder()
.target(new LatLng(lat, lng)).zoom(8).build();
// mMap.getCameraPosition().target
// if (mMap != null)
// mMap.animateCamera(CameraUpdateFactory
// .newCameraPosition(camPosition));
} else {
Log.d("Location error", "Something went wrong");
}
}
private void addBoundaryToCurrentPosition(double lat, double lang) {
MarkerOptions mMarkerOptions = new MarkerOptions();
mMarkerOptions.position(new LatLng(lat, lang));
mMarkerOptions.icon(BitmapDescriptorFactory
.fromResource(R.mipmap.ic_launcher));
mMarkerOptions.anchor(0.5f, 0.5f);
CircleOptions mOptions = new CircleOptions()
.center(new LatLng(lat, lang)).radius(10000)
.strokeColor(0x110000FF).strokeWidth(1).fillColor(0x110000FF);
mMap.addCircle(mOptions);
if (mCurrentPosition != null)
mCurrentPosition.remove();
mCurrentPosition = mMap.addMarker(mMarkerOptions);
}
private boolean isProviderAvailable() {
mLocationManager = (LocationManager) context.getSystemService(
Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = mLocationManager.getBestProvider(criteria, true);
if (mLocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
provider = LocationManager.NETWORK_PROVIDER;
return true;
}
if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
provider = LocationManager.GPS_PROVIDER;
return true;
}
if (provider != null) {
return true;
}
return false;
}
private void addMarks(GoogleMap mMap) {
// displayResponseVal(responseVal);
List<LatLng> latLngsList = new ArrayList<>();
mMap = mMap;
Polyline polylineOptions = null;
LatLng latLng = null;
// for (int i = 0; i < bottleInfoModelList.size(); i++) {
for (int i = 0; i < scansList.size(); i++) {
Scans scanInfoModel = scansList.get(i);
double latval, longVal;
try {
latval = Double.parseDouble(scanInfoModel.getLat());
longVal = Double.parseDouble(scanInfoModel.getLongVal());
} catch (NumberFormatException e) {
e.printStackTrace();
latval = 0;
longVal = 0;
}
latLng = new LatLng(latval, longVal);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(scanInfoModel.getEntityName());
mMap.addMarker(markerOptions);
mMap.setOnMarkerClickListener((GoogleMap.OnMarkerClickListener) this);
latLngsList.add(latLng);
}
drawRouteOnMap(mMap, latLngsList);
}
private void drawRouteOnMap(GoogleMap mMap, List<LatLng> latLngsList) {
PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
options.addAll(latLngsList);
Polyline polyline = mMap.addPolyline(options);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latLngsList.get(0).latitude, latLngsList.get(0).longitude))
.zoom(8)
.build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.context=context;
}
}
相应的日志错误
FATAL EXCEPTION: main
Process: winepoc.tw.net.winepoc, PID: 17576
java.lang.IllegalStateException: onGetLayoutInflater() cannot be executed until the Fragment is attached to the FragmentManager.
at android.support.v4.app.Fragment.getLayoutInflater(Fragment.java:1249)
at android.support.v4.app.Fragment.onGetLayoutInflater(Fragment.java:1201)
at android.support.v4.app.Fragment.performGetLayoutInflater(Fragment.java:1231)
at android.support.v4.app.Fragment.getLayoutInflater(Fragment.java:1217)
at winepoc.tw.net.winepoc.fragments.ChainTab.onResponse(ChainTab.java:199)
\at winepoc.tw.net.winepoc.ServerHit$3.onResponse(ServerHit.java:80)
at winepoc.tw.net.winepoc.ServerHit$3.onResponse(ServerHit.java:71)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:78)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:106)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6692)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
答案 0 :(得分:2)
Activity activity = getActivity();
if(activity != null){
// etc ...
}
试试这个我认为你的活动在编码中是空的