gpt4 book ai didi

java - Android Google Maps Api v2 fragment : NullPointerException error

转载 作者:行者123 更新时间:2023-12-01 13:42:55 27 4
gpt4 key购买 nike

当我在 Fragment 中使用 MapFragment 时,出现 NullPointerException 错误。

我无法发布图片,这是 LogCat:

  • java.lang.NullPointerException
  • com.ps.admin.EventsFragment.onCreateView(EventsFragment.Java:103)

基本上当 Activity 开始两次时就已经停止了!!

    package com.ps.admin;

@SuppressLint("NewApi")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

v = inflater.inflate(R.layout.fragment_events, container, false);

app = getActivity();
month = Calendar.getInstance();
prevMonth = (Calendar) month.clone();
prevMonth.roll(Calendar.MONTH, false);

try{
map = ((MapFragment) app.getFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}catch (Exception e){
Toast.makeText(app, e.toString(), Toast.LENGTH_LONG).show();
}

int lastDay = month.getActualMaximum(Calendar.DAY_OF_MONTH);
if(Integer.valueOf(getDayOfMonth())>1){
for (int i = 0; i < Integer.valueOf(getDayOfMonth())-1; i++) {
days.add("");
}
space = Integer.valueOf(getDayOfMonth())-1;
}
for (int i = 1; i <= lastDay; i++) {

days.add(String.valueOf(i));
}
tx = (TextView)v.findViewById(R.id.textView1);

cCalendar = (GridView)v.findViewById(R.id.gridView1);

cCalendar.setAdapter(new ProductAdapter(app, android.R.layout.simple_expandable_list_item_1, days));
readCalendarEvent(app);
cCalendar.setOnTouchListener(gestureListener);
cCalendar.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
RelativeLayout rld = (RelativeLayout)arg1.findViewById(R.id.rld);
try{
popupHoney(rld.getTag().toString(),getRelativeLeft(arg1),getRelativeTop(arg1));
}catch (Exception e){

}
}

});
cCalendar.setOnItemLongClickListener(new OnItemLongClickListener() {

@Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
int arg2, long arg3) {
RelativeLayout mn = (RelativeLayout)view.findViewById(R.id.main);
TextView tx = (TextView)view.findViewById(R.id.textView1);

addCalendarEvent(arg2);
tx.setText("+");
mn.setBackgroundResource(R.color.Green);


return false;
}
});
return v;

}
private int getRelativeLeft(View myView) {
if (myView.getParent() == myView.getRootView())
return myView.getLeft();
else
return myView.getLeft() + getRelativeLeft((View) myView.getParent());
}

private int getRelativeTop(View myView) {
if (myView.getParent() == myView.getRootView())
return myView.getTop();
else
return myView.getTop() + getRelativeTop((View) myView.getParent());
}
private String getDayOfMonth() {
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, 1);
String date = c.getTime().toString().substring(0, 3).toString();
if (date.equals("Mon")){
return "1";
}else
if (date.equals("Tue")){
return "2";
}else
if (date.equals("Wed")){
return "3";
}else
if (date.equals("Thu")){
return "4";
}else
if (date.equals("Fri")){
return "5";
}else
if (date.equals("Sat")){
return "6";
}else
if (date.equals("Sun")){
return "7";
}
return date;
}



public String getFirstDay(int day, int month, int year)
{
Calendar cal = new GregorianCalendar();
cal.set(Calendar.DATE, day);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.YEAR, year);
cal.set(Calendar.DAY_OF_MONTH, 1);
switch (cal.get(Calendar.DAY_OF_WEEK)) {
case Calendar.SUNDAY:
return "SUNDAY";
case Calendar.MONDAY:
return "MONDAY";
case Calendar.TUESDAY:
return "TUESDAY";
case Calendar.WEDNESDAY:
return "WEDNESDAY";
case Calendar.THURSDAY:
return "THURSDAY";
case Calendar.FRIDAY:
return "FRIDAY";
case Calendar.SATURDAY:
return "SATURDAY";
}
return null;
}
public static ArrayList<String> readCalendarEvent(Context context) {
Cursor cursor = context.getContentResolver()
.query(
Uri.parse("content://com.android.calendar/events"),
new String[] { "calendar_id", "title", "description",
"dtstart", "dtend", "eventLocation" }, null,
null, null);
cursor.moveToFirst();

String CNames[] = new String[cursor.getCount()];

nameOfEvent.clear();
startDates.clear();
endDates.clear();
descriptions.clear();

for (int i = 0; i < CNames.length; i++) {

nameOfEvent.add(cursor.getString(1));
startDates.add(getDate(Long.parseLong(cursor.getString(3))));
endDates.add(getDate(Long.parseLong(cursor.getString(4))));
descriptions.add(cursor.getString(2));

CNames[i] = cursor.getString(1);
cursor.moveToNext();

}
return nameOfEvent;
}

@SuppressLint("SimpleDateFormat")
public static String getDate(long milliSeconds) {
SimpleDateFormat formatter = new SimpleDateFormat(
"dd/MM/yyyy hh:mm:ss a");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
return formatter.format(calendar.getTime());
}
private void addCalendarEvent(int day){
long startTime = 0;

Calendar calendar = Calendar.getInstance();
String startDate = calendar.get(Calendar.YEAR)+"-"+(calendar.get(Calendar.MONTH)+1)+"-"+(day-space+1);
try {
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(startDate);
startTime=date.getTime();
}catch (Exception e){

}
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime",startTime);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
app.startActivity(intent);
}

private void editCalendarEvent(int calendarEventID){

Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setData(Uri.parse("content://com.android.calendar/events/" + String.valueOf(calendarEventID)));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
app.startActivity(intent);
}
public class ProductAdapter extends ArrayAdapter<String> {
ArrayList<String> items;
LayoutInflater vi;
public ProductAdapter(Context context, int textViewResourceId,
ArrayList<String> objects) {
super(context, textViewResourceId, objects);
this.items = objects;
vi = (LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
}
@SuppressLint({ "NewApi", "SimpleDateFormat" })
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {

convertView = vi.inflate(R.layout.product_event, null);
}
try {
RelativeLayout bg = (RelativeLayout)convertView.findViewById(R.id.rld);
RelativeLayout mn = (RelativeLayout)convertView.findViewById(R.id.main);
TextView name = (TextView)convertView.findViewById(R.id.textView1);
name.setText(items.get(position).toString());
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
String localTime = format1.format(month.getTime());
System.out.println(localTime);
if (Integer.valueOf(days.get(position))<10) {
if (("0"+days.get(position)+""+localTime.substring(2, localTime.length())).equals(localTime)){
mn.setBackgroundResource(R.color.Blue_Trans);
}
}else{
if ((days.get(position)+""+localTime.substring(2, localTime.length())).equals(localTime)){
mn.setBackgroundResource(R.color.Blue_Trans);
}
}
for (int j = 0; j < startDates.size(); j++) {
if (days.get(position).equals("")){
System.out.println(days.get(position));
}else{
if (Integer.valueOf(days.get(position))<10) {
if (("0"+days.get(position)+""+localTime.substring(2, localTime.length())).equals(startDates.get(j).substring(0, 10))){
bg.setBackgroundResource(R.color.Green);
bg.setTag(j);
}
}else{
if ((days.get(position)+""+localTime.substring(2, localTime.length())).equals(startDates.get(j).substring(0, 10))){
bg.setBackgroundResource(R.color.Green);
bg.setTag(j);
}
}
}
}

} catch (Exception e) {

}finally{
app.setProgressBarIndeterminateVisibility(false);
}
return convertView;
}

}

class MyGestureDetector extends SimpleOnGestureListener {
@SuppressLint("NewApi")
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// right to left swipe
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
month.set(month.get(Calendar.YEAR), month.get(Calendar.MONTH)+1,month.get(Calendar.DAY_OF_MONTH),month.get(Calendar.HOUR),month.get(Calendar.MINUTE));

int lastDay = month.getActualMaximum(Calendar.DAY_OF_MONTH);
days.clear();
if(Integer.valueOf(getDayOfMonth())>1){
for (int i = 0; i < Integer.valueOf(getDayOfMonth())-1; i++) {
days.add("");
}
space = Integer.valueOf(getDayOfMonth())-1;
}
for (int i = 1; i <= lastDay; i++) {

days.add(String.valueOf(i));
}
cCalendar.startAnimation(AnimationUtils.loadAnimation(app, R.anim.righttoleft));
cCalendar.setAdapter(new ProductAdapter(app, android.R.layout.simple_expandable_list_item_1, days));
SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy");
app.getActionBar().setTitle(format1.format(month.getTime()));

} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
month.set(month.get(Calendar.YEAR), month.get(Calendar.MONTH)-1,month.get(Calendar.DAY_OF_MONTH),month.get(Calendar.HOUR),month.get(Calendar.MINUTE));

int lastDay = month.getActualMaximum(Calendar.DAY_OF_MONTH);
days.clear();
if(Integer.valueOf(getDayOfMonth())>1){
for (int i = 0; i < Integer.valueOf(getDayOfMonth())-1; i++) {
days.add("");
}
space = Integer.valueOf(getDayOfMonth())-1;
}
for (int i = 1; i <= lastDay; i++) {

days.add(String.valueOf(i));
}
cCalendar.startAnimation(AnimationUtils.loadAnimation(app, R.anim.lefttoright));
cCalendar.setAdapter(new ProductAdapter(app, android.R.layout.simple_expandable_list_item_1, days));
SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy");
app.getActionBar().setTitle(format1.format(month.getTime()));

}

} catch (Exception e) {
// nothing
}
return false;
}
}
@Override
public void onResume(){
super.onResume();

int lastDay = month.getActualMaximum(Calendar.DAY_OF_MONTH);
days.clear();
if(Integer.valueOf(getDayOfMonth())>1){
for (int i = 0; i < Integer.valueOf(getDayOfMonth())-1; i++) {
days.add("");
}
space = Integer.valueOf(getDayOfMonth())-1;
}
for (int i = 1; i <= lastDay; i++) {

days.add(String.valueOf(i));
}
cCalendar.setAdapter(new ProductAdapter(app, android.R.layout.simple_expandable_list_item_1, days));
}
@SuppressLint("NewApi")
private void popupHoney(final String builded,float f,float g) {
try {

LayoutInflater inflater = (LayoutInflater) app
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.toast_popup,
(ViewGroup) v.findViewById(R.id.popup_element));

pwindow = new PopupWindow(layout,WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,true);

pwindow.showAtLocation(layout, Gravity.NO_GRAVITY, Math.round(f)-40, Math.round(g)-30);
TextView tx = (TextView)layout.findViewById(R.id.textView2);
TextView tx1 = (TextView)layout.findViewById(R.id.textView1);
RelativeLayout close = (RelativeLayout)layout.findViewById(R.id.popup);

tx.setText(" "+nameOfEvent.get(Integer.valueOf(builded))+" ");
tx1.setText(" "+nameOfEvent.get(Integer.valueOf(builded))+" ");

tx.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
try{
String loca = descriptions.get(Integer.valueOf(builded));
String[] separated = loca.split(",");
setLatLang(Double.valueOf(separated[0]),Double.valueOf(separated[1]),nameOfEvent.get(Integer.valueOf(builded)),startDates.get(Integer.valueOf(builded)).substring(0, startDates.get(Integer.valueOf(builded)).length()-6)+"\n"+
endDates.get(Integer.valueOf(builded)).substring(0, endDates.get(Integer.valueOf(builded)).length()-6));

pwindow.dismiss();
}catch(Exception e){
Toast.makeText(app, "Bu bir harita notu değildir!", Toast.LENGTH_LONG).show();
}}
});
close.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
pwindow.dismiss();
}
});

} catch (Exception e) {

}
app.setProgressBarIndeterminateVisibility(false);
}
public void setLatLang(final double lat,final double lon,final String tit,String date){
sydney = new LatLng(lat, lon);

//map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(sydney, 16));
//map.addCircle(new CircleOptions().center(sydney).fillColor(Color.TRANSPARENT).radius(100).strokeColor(Color.BLUE));
map.addMarker(new MarkerOptions()
.title(tit)
.snippet(date)
.flat(true)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_action_mic))
.visible(true)
.anchor(0.5f, 1)
.position(sydney));
map.addPolyline(new PolylineOptions().geodesic(true)
.add(new LatLng(lat, lon)) // Sydney
/*.add(new LatLng(-18.142, 178.431)) // Fiji
.add(new LatLng(21.291, -157.821)) // Hawaii
.add(new LatLng(37.423, -122.091)) */ // Mountain View
);
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {

@Override
public void onInfoWindowClick(Marker arg0) {

/*String label = tit;
String uriBegin = "geo:" + lat + "," + lon;
String query = lat + "," + lon + "(" + label + ")";
String encodedQuery = Uri.encode(query);
String uriString = uriBegin + "?q=" + encodedQuery + "&z=16";
Uri uri = Uri.parse(uriString);
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, uri);
startActivity(intent);*/

}
});
}
}

最佳答案

问题是您在 onCreateView 中保存了 Activity 引用,并且还尝试取消引用它。

错误可能来自代码中的以下几行:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//your code ...
app = getActivity(); //getActivity() can return null, so app will be null
//your code ...
map = ((MapFragment) app.getFragmentManager().findFragmentById(R.id.map)).getMap(); //possible NPE

正确的方法是将 Activity 引用保存在 onAttach 中,并取消引用它。

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
app = activity; //correct place to get activity reference
//your code ...
map = ((MapFragment) app.getFragmentManager().findFragmentById(R.id.map)).getMap();
}

关于java - Android Google Maps Api v2 fragment : NullPointerException error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20562443/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com