2016-09-18 65 views
0

中調用的片段上加載列表視圖時我剛剛進入android編程。我無法在ListFragment上顯示Listview。我已經在一個活動上嘗試過它,但它工作得很完美,但是,我試圖在導航抽屜中調用的Listfragment上顯示相同的ListView,但是我的應用程序在單擊時崩潰。我已經這麼久了,試圖從不同的網站獲得答案,但都無濟於事。無法在導航菜單項

PLS:有點幫助將是好的,非常感謝

在logcat的顯示的錯誤是:

09-18 14:35:53.285 
3602-3602/com.example.ceede.classwork E/AndroidRuntime: FATAL 
EXCEPTION: main Process: com.example.ceede.classwork, PID: 3602  
java.lang.NullPointerException at          
com.example.ceede.classwork.MainActivity.onNavigationItemSelected(MainActivity.java:92) 
at 
android.support.design.widget.NavigationView$1.onMenuItemSelected(NavigationView.java:152) 

content_main.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    app:layout_behavior="@string/appbar_scrolling_view_behavior" 
    tools:context="com.example.ceede.classwork.MainActivity" 
    tools:showIn="@layout/app_bar_main"> 

    <fragment 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:name="android.support.v4.app.ListFragment" 
     android:id="@+id/fragment" 
     android:layout_alignParentTop="true" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" /> 

</RelativeLayout> 

CustomAdapter.java

package com.example.ceede.classwork; 

import android.content.Context; 
import android.content.res.Resources; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.BaseAdapter; 
import android.widget.ImageView; 
import android.widget.TextView; 

import java.util.ArrayList; 
public class CustomAdapter extends BaseAdapter { 
    ArrayList<SingleRow> list; 
    Context context; 

    CustomAdapter(Context context) { 
     list = new ArrayList<>(); 
     this.context = context; 
     Resources res = context.getResources(); 
     String[] titles = res.getStringArray(R.array.Titles); 
     int[] images = {R.drawable.admisntrationicon, R.drawable.articon, R.drawable.businesseducationicon, 
       R.drawable.homeicon, R.drawable.drivericon, R.drawable.stafficon, 
       R.drawable.counciloricon, R.drawable.physicalcon, R.drawable.englishicon, 
       R.drawable.mathsicon, R.drawable.scienceicon, R.drawable.historyicon, 
       R.drawable.suporticon}; 

     for (int i = 0; i < titles.length; i++) { 
      list.add(new SingleRow(titles[i], images[i])); 
     } 
    } 

    @Override 
    public int getCount() { 
     return list.size(); 
    } 

    @Override 
    public Object getItem(int i) { 
     return list.get(i); 
    } 

    @Override 
    public long getItemId(int i) { 
     return i; 
    } 

    @Override 
    public View getView(int i, View view, ViewGroup viewGroup) { 

     SingleRow temp = list.get(i); 
     View row = null; 
     if(view==null) 
     { 
      LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      row=inflater.inflate(R.layout.single_row,viewGroup,false); 
     } 

     TextView titles= (TextView) row.findViewById(R.id.textAdmin); 
     ImageView image= (ImageView)row.findViewById(R.id.adminImage); 

     return row; 
    } 
} 

SingleRow.java

class SingleRow { 

    public String titles; 
    public int images; 

    SingleRow(String titles, int images) { 
     this.titles = titles; 
     this.images = images; 
    } 
} 

MyFragmentClass.java

package com.example.ceede.classwork; 

import android.os.Bundle; 
import android.support.annotation.Nullable; 
import android.support.v4.app.Fragment; 
import android.support.v4.app.ListFragment; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ListView; 

public class MyFirstFragment extends ListFragment { 

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

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

    @Override 
    public void onActivityCreated(@Nullable Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 

     ListView listView= (ListView) getActivity().findViewById(R.id.listView); 
     listView.setAdapter(new CustomAdapter(getActivity())); 


    } 

    public static Fragment newInstance() { 

     MyFirstFragment frag=new MyFirstFragment(); 

     return frag; 
    } 
} 

MainActivity

package com.example.ceede.classwork; 

import android.os.Bundle; 
import android.support.design.widget.FloatingActionButton; 
import android.support.design.widget.Snackbar; 
import android.support.v4.app.FragmentManager; 
import android.support.v4.app.FragmentTransaction; 
import android.view.View; 
import android.support.design.widget.NavigationView; 
import android.support.v4.view.GravityCompat; 
import android.support.v4.widget.DrawerLayout; 
import android.support.v7.app.ActionBarDrawerToggle; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.Toolbar; 
import android.view.Menu; 
import android.view.MenuItem; 

public class MainActivity extends AppCompatActivity 
    implements NavigationView.OnNavigationItemSelectedListener { 

FragmentManager manager; 
FragmentTransaction transaction; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
    fab.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 
        .setAction("Action", null).show(); 
     } 
    }); 

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
      this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); 
    drawer.setDrawerListener(toggle); 
    toggle.syncState(); 

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); 
    navigationView.setNavigationItemSelectedListener(this); 


} 

@Override 
public void onBackPressed() { 
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
    if (drawer.isDrawerOpen(GravityCompat.START)) { 
     drawer.closeDrawer(GravityCompat.START); 
    } else { 
     super.onBackPressed(); 
    } 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.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(); 

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

    return super.onOptionsItemSelected(item); 
} 

@SuppressWarnings("StatementWithEmptyBody") 
@Override 
public boolean onNavigationItemSelected(MenuItem item) { 
    // Handle navigation view item clicks here. 
    int id = item.getItemId(); 

    if (id == R.id.contact) { 
     // Handle the camera action 
     //Line 92. This is the Line of code causing the error 
     FragmentManager manager=getSupportFragmentManager(); 
     FragmentTransaction transaction=manager.beginTransaction(); 
     transaction.replace(R.id.fragment, MyFirstFragment.newInstance()); 
     transaction.commit(); 
    } 

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
    drawer.closeDrawer(GravityCompat.START); 
    return true; 
} 

}

+0

您的logcat顯示NPE出現在MainActivity.java行92.您爲** MainActivity.java **提供的代碼僅包含83行...請更正此錯誤並向我們顯示錯誤發生的位置(例如在MainActivity代碼中插入註釋)。 – gus27

+0

@ gus42我編輯了代碼,並對標記錯誤的代碼行進行了評論。 (92行),但是,我仍然得到同樣的錯誤。謝謝 –

回答

0

您不應初始化FragmentManager並在onCreate中調用beginTransactionbeginTransactioncommit應該配對。如果onNavigationItemSelected被調用兩次,當事務已經提交時會遇到麻煩。

更好地使用這種方式:

if (id == R.id.contact) { 
    FragmentManager manager=getSupportFragmentManager(); 
    FragmentTransaction transaction=manager.beginTransaction(); 
    // Handle the camera action 
    transaction.replace(R.id.fragment, MyFirstFragment.newInstance()); 
    transaction.commit(); 
} 
0

試試這個:

使用

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { 
    View view=inflater.inflate(R.layout.my_list_fragment,container,false); 
    ListView listView= (ListView) view.findViewById(R.id.listView); 
    listView.setAdapter(new CustomAdapter(getActivity())); 

    return view; 
} 

的問題是,你的列表視圖連接到片段,而不是活動。