2015-06-04 89 views
0

我一直在爲類開發一個項目,並且我已經達成了一個觀點,即在Google中進行大量搜索後仍然無法找到解決方案。把手方向變化

這是錯誤我得到

06-04 15:07:55.398 3480-3480/com.example.chema.agenda E/AndroidRuntime﹕ FATAL EXCEPTION: main 
Process: com.example.chema.agenda, PID: 3480 
java.lang.NullPointerException 
     at com.example.chema.agenda.MainActivity_detalleFragment.onActivityCreated(MainActivity_detalleFragment.java:50) 
     at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1797) 
     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:979) 
     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138) 
     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740) 
     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501) 
     at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:458) 
     at android.os.Handler.handleCallback(Handler.java:808) 
     at android.os.Handler.dispatchMessage(Handler.java:103) 
     at android.os.Looper.loop(Looper.java:193) 
     at android.app.ActivityThread.main(ActivityThread.java:5296) 
     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:824) 
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640) 
     at dalvik.system.NativeStart.main(Native Method) 

這是我得到的錯誤時,我可是從橫向旋轉爲縱向類。

public class MainActivity_detalleFragment extends Fragment { 

public MainActivity_detalleFragment() { 
} 


public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    // retain this fragment 

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

    ViewGroup root = (ViewGroup) inflater 
      .inflate(R.layout.fragment_detalle, null); 


    return root; 

} 
public void onActivityCreated(Bundle savedInstanceState){ 
    super.onActivityCreated(savedInstanceState); 
    TextView campoTexto = (TextView)getActivity().findViewById(R.id.textViewNombre); 
    TextView campoTexto2 = (TextView)getActivity().findViewById(R.id.textView8); 
    ImageView im = (ImageView)getActivity().findViewById(R.id.imageView); 
    im.setImageBitmap(MainActivity.getContacto().getImagen()); 
    campoTexto.setText(MainActivity.getContacto().getName() +" "+ MainActivity.getContacto().getApellidos()); 
    campoTexto2.setText(MainActivity.getContacto().getPhoneNumber()); 


} 

}

正如本車道 im.setImageBitmap(MainActivity.getContacto()getImagen());

這是我的主要活動

public class MainActivity extends ActionBarActivity implements FragmentListar.OnItemClickedListener{ 
private DrawerLayout desplegable; 
private ActionBarDrawerToggle toggle; 
Integer[] imgid = { 
     R.mipmap.create_contact, 
     R.mipmap.delete_action_bar, 
     R.mipmap.edit_contact 
}; 
public ListView opciones; 
private boolean dosFragmentos; 
static Contact contacto; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 


    String[] valores = getResources().getStringArray(R.array.despl); 
    CustomListAdapter adapter = new CustomListAdapter(this, valores, imgid); 
    desplegable = (DrawerLayout) findViewById(R.id.drawer_layout); 
    opciones = (ListView) findViewById(R.id.left_drawer); 
    opciones.setAdapter(adapter); 

    toggle = new ActionBarDrawerToggle(this, desplegable, R.mipmap.white_background, 
      R.string.drawer_open, R.string.drawer_close); 
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
    getSupportActionBar().setHomeButtonEnabled(true); 

    FragmentTransaction tx = getSupportFragmentManager().beginTransaction(); 
    tx.replace(R.id.content_frame, Fragment.instantiate(MainActivity.this, "com.example.chema.agenda.FragmentListar")); 
    tx.commit(); 

    opciones.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
      TextView c = (TextView) view.findViewById(R.id.item); 
      String item = c.getText().toString(); 
      if (item.equals("Crear")) { 
       desplegable.setDrawerListener(new DrawerLayout.SimpleDrawerListener() { 
        @Override 
        public void onDrawerClosed(View drawerView) { 
         super.onDrawerClosed(drawerView); 
         if(getResources().getConfiguration().orientation== Configuration.ORIENTATION_LANDSCAPE){ 
          FragmentManager fragMgr = getSupportFragmentManager(); 
          Fragment currentFragment = fragMgr.findFragmentById(R.id.content_frame2); 
          FragmentTransaction fragTrans = fragMgr.beginTransaction(); 
          fragTrans.remove(currentFragment); 

          FragmentTransaction tx = getSupportFragmentManager().beginTransaction(); 
          tx.replace(R.id.content_frame_landscape, Fragment.instantiate(MainActivity.this, "com.example.chema.agenda.CountFragment")); 
          tx.commit(); 
         }else { 
          FragmentTransaction tx = getSupportFragmentManager().beginTransaction(); 
          tx.replace(R.id.content_frame, Fragment.instantiate(MainActivity.this, "com.example.chema.agenda.CountFragment")); 
          tx.commit(); 
         } 
        } 
       }); 
       desplegable.closeDrawer(opciones); 
      } 
      if (item.equals("Borrar")) { 
       desplegable.setDrawerListener(new DrawerLayout.SimpleDrawerListener() { 
        @Override 
        public void onDrawerClosed(View drawerView) { 
         super.onDrawerClosed(drawerView); 
         FragmentTransaction tx = getSupportFragmentManager().beginTransaction(); 
         tx.replace(R.id.content_frame, Fragment.instantiate(MainActivity.this, "com.example.chema.agenda.FragmentDelete")); 
         tx.commit(); 
        } 
       }); 
       desplegable.closeDrawer(opciones); 
      } 
     } 
    }); 



} 

public void onBackPressed() { 
    Log.d("CDA", "onBackPressed Called"); 
    Intent setIntent = new Intent(this, MainActivity.class); 

    startActivity(setIntent); 
} 

public void OnItemClicked(int id) { 
    DatabaseHandler d1 = new DatabaseHandler(this.getApplicationContext()); 
    contacto = d1.getContact(id); 


    FragmentTransaction tx = getSupportFragmentManager().beginTransaction(); 
    if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){ 
     tx.replace(R.id.content_frame2, Fragment.instantiate(MainActivity.this, "com.example.chema.agenda.MainActivity_detalleFragment")); 
     tx.commit(); 
    } 

    else { 
     if ((getResources().getConfiguration().screenLayout & 
       Configuration.SCREENLAYOUT_SIZE_MASK) == 
       Configuration.SCREENLAYOUT_SIZE_LARGE) { 
      tx.replace(R.id.content_frame2, Fragment.instantiate(MainActivity.this, "com.example.chema.agenda.MainActivity_detalleFragment")); 
      tx.commit(); 

     } else { 
      tx.replace(R.id.content_frame, Fragment.instantiate(MainActivity.this, "com.example.chema.agenda.MainActivity_detalleFragment")); 
      tx.commit(); 
     } 
    } 

} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_main, menu); 
    return true; 
} 



@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 
    if (toggle.onOptionsItemSelected(item)) { 

    } 
    //noinspection SimplifiableIfStatement 
    if (id == R.id.action_settings) { 
     return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 
protected void onPostCreate(Bundle savedInstanceState) { 
    super.onPostCreate(savedInstanceState); 
    toggle.syncState(); 
} 

public void onConfigurationChanged(Configuration newConfig) { 
    super.onConfigurationChanged(newConfig); 
    toggle.onConfigurationChanged(newConfig); 


    // Checks the orientation of the screen 

} 
static public Contact getContacto(){ 
    return contacto; 
} 

而且我FragmentListar類:

public class FragmentListar extends ListFragment { 

private List<Contact> c1; 
OnItemClickedListener mListener = sDummyCallbacks; 

private static OnItemClickedListener sDummyCallbacks = new OnItemClickedListener() { 
    @Override 
    public void OnItemClicked(int id) { 
    } 
}; 

public FragmentListar() { 
    c1 = null; 
} 


public interface OnItemClickedListener { 
    public void OnItemClicked(int id); 
} 

public void onAttach(Activity activity) { 
    super.onAttach(activity); 
    try { 
     mListener = (OnItemClickedListener) activity; 
    } catch (ClassCastException e) { 
     throw new ClassCastException(activity.toString() + " must implement OnItemClickedListener"); 
    } 
} 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 

    DatabaseHandler d1 = new DatabaseHandler(getActivity().getApplicationContext()); 
    this.c1 = d1.getAllContacts(); 

    d1.close(); 

    // Estable cemos el Adapter a la Lista del Fragment 
    setListAdapter(new ContactListAdapter(getActivity(), 
      c1)); 
} 

@Override 
public void onListItemClick(ListView l, View v, int position, long id) { 
    // TODO Auto-generated method stub 
    super.onListItemClick(l, v, position, id); 

    // Mostramos un mensaje con el elemento pulsado 


    mListener.OnItemClicked(c1.get(position).getID()); 

} 

我真的不知道爲什麼MainActivity_detalleFragment被調用一次我上旋轉MainActivity重新啓動。它應該是FragmentListar所調用的那個。

固定CONTACTO是非靜態

public void OnItemClicked(int id) { 

    Bundle bundle = new Bundle(); 
    bundle.putString("id", Integer.toString(id)); 
    // set Fragmentclass Arguments 
    MainActivity_detalleFragment fragobj = new MainActivity_detalleFragment(); 
    fragobj.setArguments(bundle); 

    FragmentTransaction tx = getSupportFragmentManager().beginTransaction(); 
    if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){ 
     tx.replace(R.id.content_frame2, Fragment.instantiate(MainActivity.this, "com.example.chema.agenda.MainActivity_detalleFragment")); 
     tx.commit(); 
    } 

    else { 
     if ((getResources().getConfiguration().screenLayout & 
       Configuration.SCREENLAYOUT_SIZE_MASK) == 
       Configuration.SCREENLAYOUT_SIZE_LARGE) { 
      tx.replace(R.id.content_frame2, Fragment.instantiate(MainActivity.this, "com.example.chema.agenda.MainActivity_detalleFragment")); 
      tx.commit(); 

     } else { 
      tx.replace(R.id.content_frame, Fragment.instantiate(MainActivity.this, "com.example.chema.agenda.MainActivity_detalleFragment")); 
      tx.commit(); 
     } 
    } 

} 
+0

只是出於好奇。爲什麼你需要知道這一點? –

+0

那麼我正在開發一個聯繫人應用程序。當我啓動mainActivity時,它會獲得已經從sqlite數據庫創建的聯繫人。 因爲在我的肖像mainactivity xml中,我只是在風景列表中,我已經列出和詳細信息,如果你點擊任何聯繫人。 如果我在清單中添加android:configChanges =「keyboardHidden | orientation | screenSize」 它不能很好地工作 –

+0

我想爲縱向和橫向使用不同的xml,但由於每次旋轉設備時主要活動都會重置,每當發生這種情況時,它會從bbdd加載每個xml的聯繫人,並用我的main_activity佈局覆蓋 –

回答

0

永遠不要使用靜態方法來從活動中獲取的信息!

這裏發生的情況是,點擊列表中的某個項目後,即會填充contacto。該變量及其指向的內容不會在屏幕方向上保留,這意味着在旋轉屏幕後它將爲空,因此爲NullPointerException。

老實說,你的代碼有兩個錯誤的問題,但問題是關於NPE,所以我將重點放在這裏。

解決此問題的quick'n'dirty方法是檢查getContacto()是否返回Null。還使MainActivity.getContacto()成爲非靜態方法(getActivity()。getContacto())。

你需要深入瞭解的是,爲什麼細節片段被保留,因爲佈局應該不包含細節片段,但列表片段,對不對?

你需要考慮的是如何使用我在評論中提到的Loader。加載程序結果會保留在方向更改中,您完全不會遇到此問題。另外,如果在每次方向更改後不必重新加載,它顯然會更有效。

另外要考慮的是爲什麼您需要檢索活動中的聯繫人。據我可以告訴你的代碼,你需要在細節片段中,爲什麼不把這些代碼移動到你的片段?

DatabaseHandler d1 = new DatabaseHandler(this.getApplicationContext()); 
contacto = d1.getContact(id); 

當然,片段需要知道id,但這是一件好事,因爲這是細節片段應該具有的真正的信息。

+0

是的我知道這將是空的,但據我所見MainActivity不應該調用fragmentdetails,直到我點擊列表中的一個項目,所以它不應該是一個問題,對吧? 關於非靜態方法。如何從 MainActivity_detalleFragment調用'getContacto()'? 最後,你對數據庫是正確的,我不應該在MainActivity上調用它。 謝謝伊曼紐爾,我真的很感謝你的回答! –

+0

關於你說的最後一件事,關於把ID傳給碎片。這會工作嗎? 發佈在主帖子上。 –