无法膨胀gridview内容,得到空指针异常错误

时间:2015-05-05 07:28:25

标签: android eclipse gridview

是的,我是android编程的新手,所以我需要帮助我的项目

我试图通过膨胀gridview来在标签布局中创建一个gridview,然后膨胀gridview内容,但似乎无法正常工作,我无法找到解决方案,感谢任何想要帮助我的人。< / p>

所以这里是我的主要活动代码

此代码包含我的标签:

&#13;
&#13;
package id.WKKR.ktcafe;

import java.util.ArrayList;

import gridAdapter.CafeAdapter;
import tabs.SlidingTabLayout;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v7.widget.Toolbar;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;

@SuppressWarnings("deprecation")
public class MenuUtama extends ActionBarActivity{

	
	Toolbar toolbar;
	private ViewPager mPager;
	private SlidingTabLayout mTabs;
	private GridView makananGrid;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_menu_utama);
		
		toolbar = (Toolbar) findViewById(R.id.app_bar);
		setSupportActionBar(toolbar);
		getSupportActionBar().setHomeButtonEnabled(true);
		NavDrawerFragment drawerFragment = (NavDrawerFragment)getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
		drawerFragment.setUp(R.id.fragment_navigation_drawer,(DrawerLayout)findViewById(R.id.drawer_layout),toolbar);
		
		mPager = (ViewPager) findViewById(R.id.MyPager);
		mPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
		
		mTabs = (SlidingTabLayout) findViewById(R.id.MyTabs);
		mTabs.setDistributeEvenly(true);
		mTabs.setCustomTabView(R.layout.custom_tab_view, R.id.tabsText);
		mTabs.setBackgroundColor(getResources().getColor(R.color.orange));
		mTabs.setSelectedIndicatorColors(getResources().getColor(R.color.brown));
		
		mTabs.setViewPager(mPager);
      
        //the problem is here, i got null pointer exception error
		makananGrid = (GridView) findViewById(R.id.gridView);
		makananGrid.setAdapter(new MyCafe(this));
		

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_utama, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			Toast.makeText(this, "This Is " + item.getTitle() + " Button", Toast.LENGTH_SHORT).show();
			return true;
		}
		
		if (id == R.id.bill) {
			startActivity(new Intent(this, BillTagihanAnda.class));
		}
		
		if (id == R.id.pesanan) {
			startActivity(new Intent(this, DaftarPesananAnda.class));
		}
		
		if (id == R.id.callwaiter){
			startActivity(new Intent(this, PanggilPelayan.class));
			finish();
		}
		return super.onOptionsItemSelected(item);
	}
	
	class MyPagerAdapter extends FragmentPagerAdapter{
		
		int icon[] = {R.drawable.ic_food, R.drawable.ic_drink,R.drawable.ic_desserts};
		String[] tabsText = getResources().getStringArray(R.array.tabs);
		

		public MyPagerAdapter(FragmentManager fm) {
			super(fm);
			tabsText = getResources().getStringArray(R.array.tabs);
			
		}

		@Override
		public Fragment getItem(int position) {
			MyFragment myFragment = MyFragment.getInstance(position);
			return myFragment;
		}
		
		@Override
		public CharSequence getPageTitle(int position) {
			Drawable drawable = getResources().getDrawable(icon[position]);
			drawable.setBounds(0, 0, 40, 40);
			ImageSpan imageSpan = new ImageSpan(drawable);
			SpannableString spannableString = new SpannableString(" ");
			spannableString.setSpan(imageSpan, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			
			return spannableString;
		}

		@Override
		public int getCount() {
			return 3;
		}
		
	}
	
	public static class MyFragment extends Fragment {
		private TextView textView;
		private GridView myGridView;

		public static MyFragment getInstance(int position) {
			MyFragment myFragment = new MyFragment();
			Bundle args = new Bundle();
			args.putInt("position", position);
			myFragment.setArguments(args);
			return myFragment;
		}

		@Override
		public View onCreateView(LayoutInflater inflater,
				@Nullable ViewGroup container,
				@Nullable Bundle savedInstanceState) {
			
			View layout = inflater.inflate(R.layout.my_fragment, container, false);
			textView = (TextView) layout.findViewById(R.id.position);
			myGridView = (GridView) layout.findViewById(R.id.gridView);
			Bundle bundle = getArguments();
			if (bundle != null)
			{
				textView.setText("The Page Selected is "+bundle.getInt("position"));

//i was trying to set the adapter here but always got an error, and i don't know why.
				myGridView.setAdapter(new MyCafe(this));

			}

			return layout;
		}
	}
	
	
&#13;
&#13;
&#13;

这是我的适配器,它会使gridview内容膨胀:

&#13;
&#13;
class Menus {
  int imageId = 0;
  String menus = "";
  String menusPrices = "";

  Menus(int imageId, String menus, String menusPrices) {
    this.imageId = imageId;
    this.menus = menus;
    this.menusPrices = menusPrices;
  }
}

class MyCafe extends BaseAdapter {

  ArrayList < Menus > list;
  Context context;

  MyCafe(Context context) {
    this.context = context;
    list = new ArrayList < Menus > ();
    Resources res = context.getResources();
    String[] tempMenusNames = res.getStringArray(R.array.food);
    String[] tempMenusPrices = res.getStringArray(R.array.foodprices);
    int[] menusImages = {
      R.drawable.makanana, R.drawable.makananb,
        R.drawable.makananc, R.drawable.makanand,
        R.drawable.makanane, R.drawable.makananf
    };
    for (int i = 0; i < 6; i++) {
      Menus tempMenus = new Menus(menusImages[i], tempMenusNames[i],
        tempMenusPrices[i]);
      list.add(tempMenus);
    }

  }

  public int getCount() {
    // TODO Auto-generated method stub
    return list.size();
  }

  public Object getItem(int i) {
    // TODO Auto-generated method stub
    return list.get(i);
  }

  public long getItemId(int i) {
    // TODO Auto-generated method stub
    return i;
  }

  class ViewHolder {
    ImageView myMenus;
    TextView myMenusText;
    TextView MyMenusPrice;

    ViewHolder(View v) {
      myMenus = (ImageView) v.findViewById(R.id.imageView1);
      myMenusText = (TextView) v.findViewById(R.id.textView1);
      MyMenusPrice = (TextView) v.findViewById(R.id.textView2);
    }
  }

  public View getView(int i, View view, ViewGroup viewGroup) {
    // TODO Auto-generated method stub
    View row = view;
    ViewHolder holder = null;
    if (row == null) {
      LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      row = inflater.inflate(R.layout.single_item, viewGroup, false);
      holder = new ViewHolder(row);
      row.setTag(holder);
    } else {
      holder = (ViewHolder) row.getTag();
    }

    Menus temp = list.get(i);
    holder.myMenus.setImageResource(temp.imageId);
    holder.myMenusText.setText(temp.menus);
    holder.MyMenusPrice.setText(temp.menusPrices);

    return row;
  }

}
}
&#13;
&#13;
&#13;

这是我的activity_menu_utama.xml:

&#13;
&#13;
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:yourapp="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="id.WKKR.ktcafe.MenuUtama" >

        <include
            android:id="@+id/app_bar"
            layout="@layout/app_bar" />

        <tabs.SlidingTabLayout
            android:id="@+id/MyTabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <android.support.v4.view.ViewPager
            android:id="@+id/MyPager"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />
    </LinearLayout>

    <fragment
        android:id="@+id/fragment_navigation_drawer"
        android:name="id.WKKR.ktcafe.NavDrawerFragment"
        android:layout_width="@dimen/navigation_drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        tools:layout="@layout/activity_nav_drawer_fragment"
        yourapp:layout="@layout/activity_nav_drawer_fragment" />

</android.support.v4.widget.DrawerLayout>
&#13;
&#13;
&#13;

这是我的错误logcat:

&#13;
&#13;
05 - 05 14: 43: 40.576: E / AndroidRuntime(4347): FATAL EXCEPTION: main
05 - 05 14: 43: 40.576: E / AndroidRuntime(4347): Process: id.WKKR.ktcafe, PID: 4347
05 - 05 14: 43: 40.576: E / AndroidRuntime(4347): java.lang.RuntimeException: Unable to start activity ComponentInfo {
  id.WKKR.ktcafe / id.WKKR.ktcafe.MenuUtama
}: java.lang.NullPointerException
05 - 05 14: 43: 40.576: E / AndroidRuntime(4347): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java: 2318)
05 - 05 14: 43: 40.576: E / AndroidRuntime(4347): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java: 2396)
05 - 05 14: 43: 40.576: E / AndroidRuntime(4347): at android.app.ActivityThread.access$800(ActivityThread.java: 139)
05 - 05 14: 43: 40.576: E / AndroidRuntime(4347): at android.app.ActivityThread$H.handleMessage(ActivityThread.java: 1293)
05 - 05 14: 43: 40.576: E / AndroidRuntime(4347): at android.os.Handler.dispatchMessage(Handler.java: 102)
05 - 05 14: 43: 40.576: E / AndroidRuntime(4347): at android.os.Looper.loop(Looper.java: 149)
05 - 05 14: 43: 40.576: E / AndroidRuntime(4347): at android.app.ActivityThread.main(ActivityThread.java: 5257)
05 - 05 14: 43: 40.576: E / AndroidRuntime(4347): at java.lang.reflect.Method.invokeNative(Native Method)
05 - 05 14: 43: 40.576: E / AndroidRuntime(4347): at java.lang.reflect.Method.invoke(Method.java: 515)
05 - 05 14: 43: 40.576: E / AndroidRuntime(4347): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java: 793)
05 - 05 14: 43: 40.576: E / AndroidRuntime(4347): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java: 609)
05 - 05 14: 43: 40.576: E / AndroidRuntime(4347): at dalvik.system.NativeStart.main(Native Method)
05 - 05 14: 43: 40.576: E / AndroidRuntime(4347): Caused by: java.lang.NullPointerException
05 - 05 14: 43: 40.576: E / AndroidRuntime(4347): at id.WKKR.ktcafe.MenuUtama.onCreate(MenuUtama.java: 66)
05 - 05 14: 43: 40.576: E / AndroidRuntime(4347): at android.app.Activity.performCreate(Activity.java: 5411)
05 - 05 14: 43: 40.576: E / AndroidRuntime(4347): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java: 1087)
05 - 05 14: 43: 40.576: E / AndroidRuntime(4347): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java: 2270)
05 - 05 14: 43: 40.576: E / AndroidRuntime(4347): ...11 more
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

xml中没有gridView id的视图,因此findViewById(R.id.gridView)返回null。将带有android:id="@+id/gridView"的GridView添加到您的xml中,或者不要尝试将其添加到您的代码中。