2017-02-04 3 views
0

Я новичок в Android и сожалеет о моем уродливом английскомне удался выполнить метод деятельности в контейнере фрагмента

У меня есть 2-фрагмент и основная задача них является:

ProfileFragment.java

private void initUI(View parent) { 

    /** 
    * referencing of fragment_profile 
    */ 
    fragmentImageProfile = (CircleImageView) parent.findViewById(R.id.fragment_profile_picture); 
    fragmentName = (EditText) parent.findViewById(R.id.fragment_profile_editText_name); 
    fragmentFamily = (EditText) parent.findViewById(R.id.fragment_profile_editText_family); 
    fragmentPhoneNumber = (EditText) parent.findViewById(R.id.fragment_profile_editText_phone); 

    /** 
    * get contact by invoke from CallBack on ProfileActivity 
    */ 
    Contact contact = profileCallBack.getContact(); 
    fragmentName.setText(contact.getName()); 
    fragmentFamily.setText(contact.getFamily()); 
    fragmentPhoneNumber.setText(contact.getPhonNumber()); 

    Log.i("==>", "initUI: "+ contact.getName()); 

} 

и его Lauout

<LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content"> 

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Name: " 
      android:textSize="20dp" /> 

     <EditText 
      android:id="@+id/fragment_profile_editText_name" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:cursorVisible="true" 
      android:enabled="false" 
      android:focusable="false" /> 

    </LinearLayout> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content"> 

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Family: " 
      android:textSize="20dp" /> 

     <EditText 
      android:id="@+id/fragment_profile_editText_family" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:enabled="false" 
      android:focusable="false" 
      android:inputType="none" /> 

    </LinearLayout> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content"> 

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Phone: " 
      android:textSize="20dp" /> 

     <EditText 
      android:id="@+id/fragment_profile_editText_phone" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:enabled="false" 
      android:focusable="false" 
      android:inputType="none" /> 

    </LinearLayout> 

в этом фрагменте я устанавливаю поле контакта в 3-е изд это текст. EditProfileFragment.java

public void updateContact() { 
    int id = contact.get_id(); 
    String name = fragmentEditEditTextName.getText().toString(); 
    Log.i("==>", "Name Update: " + name); 
    String family = fragmentEditEditTextFamily.getText().toString(); 
    String phoneNumber = fragmentEditEditTextPhoneNumber.getText().toString(); 
    int rowUpdate = App.getInstanceImplementation().updateContact(
      new Contact(id, name, family, phoneNumber, "image")); 
    Log.i("==>", "btnUpdateContact: " + rowUpdate); 

} 

и этот макет

<LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content"> 

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Name: " 
      android:textSize="20dp" /> 

     <EditText 
      android:id="@+id/fragment_edit_editText_name" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:cursorVisible="true" 
      android:inputType="text"/> 

    </LinearLayout> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content"> 

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Family: " 
      android:textSize="20dp" /> 

     <EditText 
      android:id="@+id/fragment_edit_editText_family" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:inputType="text" /> 

    </LinearLayout> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content"> 

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Phone: " 
      android:textSize="20dp" /> 

     <EditText 
      android:id="@+id/fragment_edit_editText_phone" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:inputType="phone" /> 

    </LinearLayout> 


    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content"> 

     <Button 
      android:id="@+id/fragment_edit_btn_save" 
      style="@style/Widget.AppCompat.Button.Borderless.Colored" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_marginBottom="24dp" 
      android:layout_marginRight="2dp" 
      android:onClick="btnUpdateContact" 
      android:layout_weight="1" 
      android:background="#8d860000" 
      android:padding="12dp" 
      android:text="Update" /> 

     <Button 
      android:id="@+id/fragment_edit_btn_exit" 
      style="@style/Widget.AppCompat.Button.Borderless.Colored" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_marginBottom="24dp" 
      android:onClick="btnExitContact" 
      android:layout_weight="1" 
      android:background="#8d860000" 
      android:padding="12dp" 
      android:text="Exit" /> 
    </LinearLayout> 

Я обновить базу данных. В моем профиле активности я использую ViewPager для отображения этого фрагмента, и эти фрагменты соединяются с активностью через CallBack Listener.

public class ProfileActivity extends FragmentActivity implements ProfileFragment.ProfileCallBack , EditProfileFragment.EditFragmentCallBack { 
private ProfileFragment profileFragment; 
private EditProfileFragment editProfileFragment; 
private PagerAdapterFragment adapterFragment; 
private List<Fragment> fragments; 

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


} 



@Override 
protected void onResume() { 
    super.onResume(); 
    getProfileFragment(); 
    getEditProfileFragment(); 
    initFragment(); 
} 

private void initFragment() { 
    fragments = new Vector<>(); 
    fragments.add(Fragment.instantiate(this, ProfileFragment.class.getName())); 
    fragments.add(Fragment.instantiate(this, EditProfileFragment.class.getName())); 

    adapterFragment = new PagerAdapterFragment(this.getSupportFragmentManager(), fragments); 
    ViewPager pager = (ViewPager) findViewById(R.id.vpg_main_content); 
    pager.setAdapter(adapterFragment); 

} 

private ProfileFragment getProfileFragment() { 
    if (profileFragment == null) { 
     profileFragment = new ProfileFragment(); 
    } 
    Log.i("==>", "getProfileFragment:" + profileFragment.getId()); 
    return profileFragment; 
} 

private EditProfileFragment getEditProfileFragment() { 
    if (editProfileFragment == null) { 
     editProfileFragment = new EditProfileFragment(); 
    } 
    Log.i(">", "getEditProfileFragment: "+ editProfileFragment.getId()); 
    return editProfileFragment; 
} 


@Override 
public Contact getContact() { 
    Intent intent = getIntent(); 
    return (Contact) intent.getSerializableExtra(Contact.class.getName()); 
} 

@Override 
public void finishProfile() { 
    // TODO: 2/3/2017 
//  finish(); 
} 


public void btnUpdateContact(View view) { 
    getEditProfileFragment().updateContact(); 

} 

public void btnExitContact(View view) { 
//  getEditProfileFragment().btnExitContact(); 
     finish(); 
} 

, но в этой линии public void btnUpdateContact(View view) я получил эту ошибку:

02-04 01:23:40.953 4545-4545/com.example.sayres.myapplication7 E/AndroidRuntime: FATAL EXCEPTION: main 
                      Process: com.example.sayres.myapplication7, PID: 4545 
                      java.lang.IllegalStateException: Could not execute method of the activity 
                       at android.view.View$1.onClick(View.java:3823) 
                       at android.view.View.performClick(View.java:4438) 
                       at android.view.View$PerformClick.run(View.java:18422) 
                       at android.os.Handler.handleCallback(Handler.java:733) 
                       at android.os.Handler.dispatchMessage(Handler.java:95) 
                       at android.os.Looper.loop(Looper.java:136) 
                       at android.app.ActivityThread.main(ActivityThread.java:5001) 
                       at java.lang.reflect.Method.invokeNative(Native Method) 
                       at java.lang.reflect.Method.invoke(Method.java:515) 
                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) 
                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 
                       at dalvik.system.NativeStart.main(Native Method) 
                       Caused by: java.lang.reflect.InvocationTargetException 
                       at java.lang.reflect.Method.invokeNative(Native Method) 
                       at java.lang.reflect.Method.invoke(Method.java:515) 
                       at android.view.View$1.onClick(View.java:3818) 
                       at android.view.View.performClick(View.java:4438)  
                       at android.view.View$PerformClick.run(View.java:18422)  
                       at android.os.Handler.handleCallback(Handler.java:733)  
                       at android.os.Handler.dispatchMessage(Handler.java:95)  
                       at android.os.Looper.loop(Looper.java:136)  
                       at android.app.ActivityThread.main(ActivityThread.java:5001)  
                       at java.lang.reflect.Method.invokeNative(Native Method)  
                       at java.lang.reflect.Method.invoke(Method.java:515)  
                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)  
                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)  
                       at dalvik.system.NativeStart.main(Native Method)  
                       Caused by: java.lang.NullPointerException 
                       at com.example.sayres.myapplication7.mvp.view.profile.EditProfileFragment.updateContact(EditProfileFragment.java:70) 
                       at com.example.sayres.myapplication7.mvp.view.profile.ProfileActivity.btnUpdateContact(ProfileActivity.java:97) 
                       at java.lang.reflect.Method.invokeNative(Native Method)  
                       at java.lang.reflect.Method.invoke(Method.java:515)  
                       at android.view.View$1.onClick(View.java:3818)  
                       at android.view.View.performClick(View.java:4438)  
                       at android.view.View$PerformClick.run(View.java:18422)  
                       at android.os.Handler.handleCallback(Handler.java:733)  
                       at android.os.Handler.dispatchMessage(Handler.java:95)  
                       at android.os.Looper.loop(Looper.java:136)  
                       at android.app.ActivityThread.main(ActivityThread.java:5001)  
                       at java.lang.reflect.Method.invokeNative(Native Method)  
                       at java.lang.reflect.Method.invoke(Method.java:515)  
                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)  
                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)  
                       at dalvik.system.NativeStart.main(Native Method)  
+0

Вызванный: java.lang.NullPointerException на com.example.sayres.myapplication7.mvp.view. profile.EditProfileFragment.updateContact (EditProfileFragment.java:70) at com.example.sayres.myapplication7.mvp.view.profile.ProfileActivity.btnUpdateContact (ProfileActivity.java:97) – adi9090

+0

Думаю, вам нужно изменить getEditProfileFragment(); реализация. Вместо создания нового экземпляра фрагмента попробуйте получить его из списка, который вы создали для представления pager – Sanjeet

+0

ok, но он не является нулевым, потому что он инициализируется в этом методе 'private EditProfileFragment getEditProfileFragment() { if (editProfileFragment == null) { editProfileFragment = new EditProfileFragment(); } ', что я запускал метод onResume –

ответ

0

Проблема здесь:

private ProfileFragment getProfileFragment() { 
if (profileFragment == null) { 
    profileFragment = new ProfileFragment(); //you need to change this as this will only create an object and doesn't initialize any view; 
} 
Log.i("==>", "getProfileFragment:" + profileFragment.getId()); 
return profileFragment; 
} 

Теперь, если вы звоните в updateCon тактом() метод на объект, полученный из метода выше, он будет генерировать исключение, поскольку вы пытаетесь получить доступ к текстовому представлению фрагментаEditEditTextName.

Изменение ниже линии в getProfileFragment():

profileFragment = new ProfileFragment(); 

к:

profileFragment = fragments.get(1);