0

내 프로젝트에는 위치를 검색 할 수있는 간단한 클래스가있다. 정적 클래스 인 innerclass를 가진다.프래그먼트에서 액티비티 뷰 얻기

MainActivity.java

public class MainActivity extends Activity { 

    GPSTracker gps; 
    double mylatitude, mylongitude; 
    TextView txt_location; 



    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     txt_location = (TextView) findViewById(R.id.current_location); 


     if (savedInstanceState == null) { 
      getFragmentManager().beginTransaction() 
        .add(R.id.container, new PlaceholderFragment()).commit(); 

      } 


      gps = new GPSTracker(MainActivity.this); 


      if (gps.canGetLocation()) { 

       mylatitude = gps.getLatitude(); 
       mylongitude = gps.getLongitude(); 

       String latis = Double.toString(mylatitude); 
       String longis = Double.toString(mylongitude); 
       Log.d("my",latis+ "location to string is done " + longis); 
       txt_location.setText(latis+longis); 
      } 

    } 



     public static class PlaceholderFragment extends Fragment { 


     public PlaceholderFragment() { 

     } 

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


      return inflater.inflate(R.layout.fragment_main, container, 
        false); 

     } 
    } 

} 

코드는 txt_location.setText(latis+longis);NullPointerException에서 보이고있다.

java.lang.RuntimeException: Unable to start activity ComponentInfo{.MainActivity}: java.lang.NullPointerException 
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956) 
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981) 
      at android.app.ActivityThread.access$600(ActivityThread.java:123) 
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147) 
      at android.os.Handler.dispatchMessage(Handler.java:99) 
      at android.os.Looper.loop(Looper.java:137) 
      at android.app.ActivityThread.main(ActivityThread.java:4424) 
      at java.lang.reflect.Method.invokeNative(Native Method) 
      at java.lang.reflect.Method.invoke(Method.java:511) 
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825) 
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:592) 
      at dalvik.system.NativeStart.main(Native Method) 
    Caused by: java.lang.NullPointerException 
      at MainActivity.onCreate(MainActivity.java:47) 
      at android.app.Activity.performCreate(Activity.java:4465) 
      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1051) 
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920) 
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981) 
            at android.app.ActivityThread.access$600(ActivityThread.java:123) 
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147) 
            at android.os.Handler.dispatchMessage(Handler.java:99) 
            at android.os.Looper.loop(Looper.java:137) 
            at android.app.ActivityThread.main(ActivityThread.java:4424) 
            at java.lang.reflect.Method.invokeNative(Native Method) 
            at java.lang.reflect.Method.invoke(Method.java:511) 
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825) 
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:592) 
            at dalvik.system.NativeStart.main(Native Method) 

내가 그것 (XML 파일에 어떤 실수가 없다) (TextView) findViewById(R.id.current_location);에서 txt_places을 찾을 수 없기 때문에이 조각의 XML로보기 때문 오류입니다 발견 다음과 같이

로그 캣 로그입니다 활동의 것이 아닙니다. 활동에서 어떻게 접근합니까?

+2

을 그냥 sidenode : 이럴 그것에서'Fragment'의'View'를 변경하는 나쁜 디자인이다 '가 부착되어 Activity'. 'Fragment'가 항상 자신의 UI를 처리하도록 부모'Activity'가 아닌'Activity'의'Fragment' 메소드를 호출해야합니다. – shkschneider

+0

대답에서 설명 할 수 있습니까? 나는 그것을 감사 할 것이다. – xyz

답변

1

조각 안에 TextView이 있고 활동의 Location 관련 메소드가 완전히 잘못되었습니다. 모두 한 곳으로 이동하십시오. 프래그먼트 내에서 Location 관련 메소드를 이동하거나 프래그먼트에서 활동으로 레이아웃을 이동하십시오. 그런이

public class MainActivity extends Activity { 




@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 


    if (savedInstanceState == null) { 
     getFragmentManager().beginTransaction() 
       .add(R.id.container, new PlaceholderFragment()).commit(); 

     } 
} 

    public static class PlaceholderFragment extends Fragment { 

    GPSTracker gps; 
    double mylatitude, mylongitude; 
    TextView txt_location; 

    public PlaceholderFragment() { 

    } 

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

     View view = inflater.inflate(R.layout.fragment_main, container, 
       false); 
     txt_location = (TextView) view.findViewById(R.id.current_location); 


     gps = new GPSTracker(getActivity()); 


     if (gps.canGetLocation()) { 

      mylatitude = gps.getLatitude(); 
      mylongitude = gps.getLongitude(); 

      String latis = Double.toString(mylatitude); 
      String longis = Double.toString(mylongitude); 
      Log.d("my",latis+ "location to string is done " + longis); 
      txt_location.setText(latis+longis); 
     } 



     return view; 

    } 
} 

} 
+0

그러면 어떻게 GPS를 작성할 수 있습니까 = 새로운 GPSTracker (MainActivity.this); ... 예상대로 오류가 표시됩니다. – xyz

+0

은'MainActivity.this'에서'getActivity()'를 사용합니다. 그냥 거기에 컨텍스트를 묻는 ... – Panther

+0

대단히 고마워요. .It 작동하고있다 – xyz

1

수정 onCreateView 방법 같은

뭔가 : 답변으로

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 
    View view = inflater.inflate(R.layout.fragment_main, container, 
       false); 
    txt_location = (TextView) view.findViewById(R.id.current_location); 

    return view; 

} 
+0

나는 그것을 시도했다 ...하지만 내 조각이 정적이기 때문에 (내부 클래스 조각이기 때문에) ... 그것은 textview에 액세스 할 수 없습니다 txt_places – xyz

+0

정적 수정자를 제거하십시오. – Mou

+0

그러면 내부 클래스 조각이 정적이되어야한다는 또 다른 오류가 표시됩니다 – xyz

1

내 (!) 참고, 요청 OP있다.

Fragment의보기를 변경하는 것은 나쁜 디자인이므로 Activity에 첨부되어 있습니다.

방법Fragment는 항상 자신의 UI가 아닌 부모 Activity을 처리하므로 Activity에서 Fragment에 호출해야합니다. 그럴 경우 귀하의 Activity (예 :) 변수가 Fragment (예 : MyFragmentAMyFragmentB)으로 유지됩니다.

MainActivityFragment 중 하나의 UI를 업데이트하려면 작업을 수행 할 방법 (myFragmentA.updateUI())을 호출해야합니다. Fragment은 UI를 실제로 만질 수 있습니다. MVC 디자인 패턴이 아니지만 어쨌든 클리너입니다. 귀하의 경우 TextView txt_location

Fragment 내부 View 것 같다, 그래서 변수 txt_location 자체는 Activity에 선언하지 않아야하지만 Fragment에가 표시됩니다.

  1. 이 코드를 많이합니다 청소기.
  2. 당신은 진정한 Activity (onCreate(), onResume() 등) 또는 Fragment (onCreate(), onCreateView(), onViewCreated() 등)하는이 다르다되고, 당신의 객체의 라이프 사이클을 존중 할 수 있습니다.

답변

는 다시, 귀하의 경우 (TextView) findViewById(R.id.current_location)current_location가보기에이 아니므로,보기의 Activity 점에서 더 의미가 없지만, 그 아이 중 하나를하십시오 Fragment.

당신의 FragmentonCreateView()의 장소 txt_location = (TextView) view.findViewById(R.id.current_location); 및합니다 (Fragment 다시) onViewCreate()에서 txt_location.setText() 이상을 사용합니다.

+0

감사합니다. + 1d this – xyz

0

이것은 매우 쉽습니다. 단지 예를 들어 findViewById를하기 전에 getActivity()를 추가

EditText et = (EditText) getActivity().findViewById(R.id.toolbarsrch); 
관련 문제