试图调用虚拟方法无效android.widget.ListView.setAdapter [英] Attempt to invoke virtual method 'void android.widget.ListView.setAdapter
问题描述
我试图让包含这是与选项卡的viewpager片段中的图片和文字列表视图,这样我就可以向左或向右滑动以打开另一个片段。
我是比较新到Android所以我可能会做可能是完全错误的。我可以建立项目完全正常,但那么当模拟器运行它崩溃(LOG在页面底部显示的)。
我创建了一个单独的应用程序,并成功能够创建一个列表视图,但是当我尝试它,就像这样的片段中结合,这是行不通的。
这是我下面code
MainActivity.java
块引用>进口的java.util.ArrayList;
进口的java.util.List;
进口java.util.Locale中;进口android.app.ListFragment;
进口android.content.Intent;
进口android.support.v7.app.ActionBarActivity;
进口android.support.v7.app.ActionBar;
进口android.support.v4.app.Fragment;
进口android.support.v4.app.FragmentManager;
进口android.support.v4.app.FragmentTransaction;
进口android.support.v4.app.FragmentPagerAdapter;
进口android.os.Bundle;
进口android.support.v4.view.ViewPager;
进口android.view.Gravity;
进口android.view.LayoutInflater;
进口android.view.Menu;
进口android.view.MenuItem;
进口android.view.View;
进口android.view.ViewGroup;
进口android.widget.AdapterView;
进口android.widget.ArrayAdapter;
进口android.widget.ImageView;
进口android.widget.ListView;
进口android.widget.TextView;
进口android.widget.Toast;
公共类MainActivity扩展ActionBarActivity实现ActionBar.TabListener { / **
*本{@link android.support.v4.view.PagerAdapter},将提供
*对于每个部分的片段。我们使用
* {@link FragmentPagerAdapter}衍生,这将让每一个
*加载到内存中的片段。如果这成为太内存密集型,它
*可能是最好切换到
* {@link android.support.v4.app.FragmentStatePagerAdapter}。
* /
SectionsPagerAdapter mSectionsPagerAdapter; / **
*本{@link ViewPager}将承载部分内容。
* /
ViewPager mViewPager;
私人列表<岗位> myPosts =新的ArrayList<邮电GT;();
@覆盖
保护无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.activity_main);
//设置操作栏。
最后的动作条动作条= getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); //创建将返回一个片段为三个的适配器
//活性的主要部分。
mSectionsPagerAdapter =新SectionsPagerAdapter(getSupportFragmentManager()); //设置的ViewPager与部分适配器。
mViewPager =(ViewPager)findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter); //当不同部分之间滑动,选择对应的
// 标签。我们也可以使用ActionBar.Tab#select()来做到这一点,如果我们有
//为Tab的参考。
mViewPager.setOnPageChangeListener(新ViewPager.SimpleOnPageChangeListener(){
@覆盖
公共无效使用onPageSelected(INT位置){
actionBar.setSelectedNavigationItem(位置);
}
}); //对于每一个应用中的部分,添加标签,操作栏。
的for(int i = 0; I< mSectionsPagerAdapter.getCount();我++){
//创建对应于定义的页面标题文字标签
//适配器。同时,指定此活动的对象,它实现
//将TabListener接口,回调(监听程序)进行时
//这个选项卡中选择。
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(I))
.setTabListener(本)); } 意向意图=新意图(MainActivity.this,NotMainActivity.class);
startActivity(意向);
完();
} @覆盖
公共布尔onCreateOptionsMenu(菜单菜单){
//充气菜单;如果是present这增加了项目操作栏。
。getMenuInflater()膨胀(R.menu.menu_main,菜单);
返回true;
} @覆盖
公共布尔onOptionsItemSelected(菜单项项){
//处理动作栏项目点击这里。操作栏会
//自动处理上点击主页/向上按钮,只要
//你在AndroidManifest.xml中指定一个父活动。
INT ID = item.getItemId(); // noinspection SimplifiableIfStatement
如果(ID == R.id.action_settings){
返回true;
} 返回super.onOptionsItemSelected(项目);
} @覆盖
公共无效onTabSelected(ActionBar.Tab选项卡,FragmentTransaction fragmentTransaction){
//当选择给定的标签上,切换到相应的页面
//的ViewPager。
mViewPager.setCurrentItem(tab.getPosition());
} @覆盖
公共无效onTabUnselected(ActionBar.Tab选项卡,FragmentTransaction fragmentTransaction){
} @覆盖
公共无效onTabReselected(ActionBar.Tab选项卡,FragmentTransaction fragmentTransaction){
}
/ **
* A {@link FragmentPagerAdapter}返回对应片段
*章节/标签/页面。
* /
公共类SectionsPagerAdapter扩展FragmentPagerAdapter { 公共SectionsPagerAdapter(FragmentManager FM){
超(FM);
} @覆盖
公共片段的getItem(INT位置){
//的getItem被称为实例化片段为给定的页面。
//返回一个PlaceholderFragment(定义如下静态内部类)。
开关(位置){
情况下0:
返回新TheWallFragment();
情况1:
返回新PeekFragment();
案例2:
返回新CameraFragment();
默认:
打破; } 返回PlaceholderFragment.newInstance(位置+ 1);
}
@覆盖
公众诠释的getCount(){
//显示3总页数。
返回3;
} @覆盖
公共CharSequence的getPageTitle(INT位置){
区域设置L = Locale.getDefault();
开关(位置){
情况下0:
返回的getString(R.string.title_section1).toUpperCase(升);
情况1:
返回的getString(R.string.title_section2).toUpperCase(升);
案例2:
返回的getString(R.string.title_section3).toUpperCase(升);
}
返回null;
}
} / **
*包含一个简单视图中的占位符片段。
* /
公共静态类PlaceholderFragment扩展片段{
/ **
*片段参数重新presenting本节号
*片段。
* /
私有静态最后弦乐ARG_SECTION_NUMBER =SECTION_NUMBER; / **
*返回该片段的一个新实例为给定的部
*号。
* /
公共静态的newInstance PlaceholderFragment(INT sectionNumber){
PlaceholderFragment片段=新PlaceholderFragment();
捆绑ARGS =新包();
args.putInt(ARG_SECTION_NUMBER,sectionNumber);
fragment.setArguments(参数);
返回片段;
} 公共PlaceholderFragment(){
} @覆盖
公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,
捆绑savedInstanceState){
查看rootView = inflater.inflate(R.layout.wall_layout,集装箱,FALSE); 返回rootView;
}
}}
NotMainActivity.java
块引用>公共类NotMainActivity扩展FragmentActivity { 私人列表<岗位> myPosts =新的ArrayList<邮电GT;(); @覆盖
保护无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.activity_main);
populatePostList();
populateListView(); registerClickCallBack();
System.out.print(主要活动开始); }
私人无效populatePostList(){
myPosts.add(新帖子(渥太华,安大略省,787,图片我的狗!,R.drawable.dog));
myPosts.add(新帖子(渥太华,安大略省,787,图片我的狗!,R.drawable.dog));
myPosts.add(新帖子(渥太华,安大略省,787,图片我的狗!,R.drawable.dog));
myPosts.add(新帖子(渥太华,安大略省,787,图片我的狗!,R.drawable.dog));
myPosts.add(新帖子(渥太华,安大略省,787,图片我的狗!,R.drawable.dog));
myPosts.add(新帖子(渥太华,安大略省,787,图片我的狗!,R.drawable.dog));
myPosts.add(新帖子(渥太华,安大略省,787,图片我的狗!,R.drawable.dog));
myPosts.add(新帖子(渥太华,安大略省,787,图片我的狗!,R.drawable.dog)); } 私人无效populateListView(){
ArrayAdapter<岗位>适配器=新MyListAdapter();
ListView控件列表=(ListView控件)findViewById(android.R.id.list);
list.setAdapter(适配器); }
//把手上的列表项点击
私人无效registerClickCallBack(){
ListView控件列表=(ListView控件)findViewById(android.R.id.list);
list.setOnItemClickListener(新AdapterView.OnItemClickListener(){
@覆盖
公共无效onItemClick(适配器视图<>母公司,观景,INT位置,长的id){
帖子clickedPost = myPosts.get(位置);
字符串消息=你点击+位置
+后的定位是+ clickedPost.getPostlocation();
Toast.makeText(NotMainActivity.this,消息,Toast.LENGTH_LONG).show();
}
});
}
私有类MyListAdapter扩展ArrayAdapter<岗位> {
公共MyListAdapter(){
超(NotMainActivity.this,R.layout.item_view,myPosts);
}
@覆盖
公共查看getView(INT位置,查看convertView,父母的ViewGroup){
//确保我们有一个观点一起工作{可能给空}
查看ItemView控件= convertView;
如果(ItemView控件!= NULL){
。ItemView控件= getLayoutInflater()膨胀(R.layout.item_view,父母,假);
}
//找到邮局的工作。
帖子currentPost = myPosts.get(位置);
//填充视图
ImageView的ImageView的=(ImageView的)itemView.findViewById(R.id.item_postImage);
imageView.setImageResource(currentPost.getIconID()); //在标题填写 TextView的titleText =(TextView中)itemView.findViewById(R.id.item_postText);
titleText.setText(currentPost.getPosttitle()); //设置票数
TextView的voteText =(TextView中)itemView.findViewById(R.id.item_postVoteText);
voteText.setText(currentPost.getPostvote()); 返回ItemView控件;
} }}
Posts.java
块引用>公共类职位{
私人字符串postlocation;
私人字符串postvote;
私人字符串posttitle;
私人诠释iconID; 公共帖子(字符串postlocation,字符串postvote,字符串posttitle,诠释iconID){
this.postlocation = postlocation;
this.postvote = postvote;
this.posttitle = posttitle;
this.iconID = iconID;
} 公共字符串getPostlocation(){
返回postlocation;
} 公共字符串getPostvote(){
返回postvote;
} 公共字符串getPosttitle(){
返回posttitle;
}
公众诠释getIconID(){
返回iconID;
}
TheWallFragment.java
块引用>公共类TheWallFragment扩展android.support.v4.app.ListFragment {
清单<岗位> myPosts =新的ArrayList<邮电GT;();
私有String [] strListView;
私人的ListView myListView;
私人诠释数目;
公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,
捆绑savedInstanceState){
查看rootView = inflater.inflate(R.layout.wall_layout,集装箱,FALSE);
返回rootView;
}
}
activity_main.xml中
块引用>< android.support.v4.view.ViewPager的xmlns:机器人=http://schemas.android.com/apk/res/android
的xmlns:工具=http://schemas.android.com/tools机器人:ID =@ + ID /寻呼机
机器人:layout_width =match_parent机器人:layout_height =match_parent
工具:上下文=。MainActivity/>
AndroidManifest.xml中
块引用><?XML版本=1.0编码=UTF-8&GT?;
<清单的xmlns:机器人=http://schemas.android.com/apk/res/android
包=com.gnumbu.errolgreen.testing> <应用
机器人:allowBackup =真
机器人:图标=@的mipmap / ic_launcher
机器人:标签=@字符串/ APP_NAME
机器人:主题=@风格/ AppTheme>
<活动
机器人:名字=。MainActivity
机器人:标签=@字符串/ APP_NAME>
&所述;意图滤光器>
<作用机器人:名字=android.intent.action.MAIN/> <类机器人:名字=android.intent.category.LAUNCHER/>
&所述; /意图滤光器>
< /活性GT;
<活动
机器人:名字=。NotMainActivity>
< /活性GT;
< /用途>< /清单>
item_view.xml
块引用><?XML版本=1.0编码=UTF-8&GT?;
<的RelativeLayout的xmlns:机器人=http://schemas.android.com/apk/res/android
机器人:layout_width =match_parent机器人:layout_height =match_parent> < ImageView的
机器人:layout_width =WRAP_CONTENT
机器人:layout_height =WRAP_CONTENT
机器人:ID =@ + ID / item_postImage
机器人:SRC =@绘制/狗
安卓了maxWidth =80dp
安卓了minHeight =80dp
机器人:adjustViewBounds =真
机器人:layout_marginLeft =14dp
机器人:layout_marginStart =14dp
机器人:layout_alignParentTop =真
机器人:layout_toRightOf =@ + ID / item_upvoteArrow
机器人:layout_toEndOf =@ + ID / item_upvoteArrow
机器人:layout_alignBottom =@ + ID / item_downvotearrow/> <的TextView
机器人:layout_width =WRAP_CONTENT
机器人:layout_height =WRAP_CONTENT
机器人:文字=这是我的狗我的狗是惊人的,给它舔!
机器人:ID =@ + ID / item_postText
机器人:paddingStart =5DP
机器人:layout_above =@ + ID / item_downvotearrow
机器人:layout_toRightOf =@ + ID / item_postImage
机器人:layout_toEndOf =@ + ID / item_postImage/> < ImageView的
机器人:layout_width =WRAP_CONTENT
机器人:layout_height =WRAP_CONTENT
机器人:ID =@ + ID / item_upvoteArrow
机器人:SRC =@绘制/ upvotearrow
安卓了maxHeight =24dp
安卓了maxWidth =24dp
机器人:adjustViewBounds =真
机器人:layout_alignParentTop =真
机器人:layout_alignLeft =@ + ID / item_downvotearrow
机器人:layout_alignStart =@ + ID / item_downvotearrow
机器人:可点击=真/> < ImageView的
机器人:layout_width =WRAP_CONTENT
机器人:layout_height =WRAP_CONTENT
机器人:ID =@ + ID / item_downvotearrow
机器人:SRC =@绘制/ downvotearrow
安卓了maxWidth =24dp
安卓了maxHeight =24dp
机器人:adjustViewBounds =真
机器人:layout_marginLeft =9dp
机器人:layout_marginStart =9dp
机器人:layout_below =@ + ID / item_postVoteText
机器人:layout_alignParentLeft =真
机器人:layout_alignParentStart =真
机器人:longClickable =假
机器人:可点击=真/> <的TextView
机器人:layout_height =WRAP_CONTENT
机器人:文字=22
机器人:ID =@ + ID / item_postVoteText
安卓了maxHeight =20dp
机器人:focusableInTouchMode =假
机器人:知名度=看得见
机器人:单线=真
机器人:比重=中心
机器人:启用=真
机器人:layout_below =@ + ID / item_upvoteArrow
机器人:layout_alignLeft =@ + ID / item_upvoteArrow
机器人:layout_alignStart =@ + ID / item_upvoteArrow
机器人:nestedScrollingEnabled =假
机器人:layout_width =WRAP_CONTENT
机器人:layout_toStartOf =@ + ID / item_postImage/>< / RelativeLayout的>
wall_layout.xml
块引用><?XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=http://schemas.android.com/apk/res/android
机器人:方向=垂直的android:layout_width =match_parent
机器人:layout_height =match_parent> <的TextView
机器人:layout_width =WRAP_CONTENT
机器人:layout_height =WRAP_CONTENT
机器人:文字=新文本
机器人:ID =@ + ID / TextView的
机器人:layout_gravity =CENTER_HORIZONTAL/> < ListView控件
机器人:ID =@机器人:ID /列表
机器人:layout_width =WRAP_CONTENT
机器人:layout_height =WRAP_CONTENT
/>
< / LinearLayout中>
错误日志
块引用>显示java.lang.NullPointerException:尝试对空对象引用调用虚拟方法无效android.widget.ListView.setAdapter(android.widget.ListAdapter)'
在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
在android.app.ActivityThread.access $ 800(ActivityThread.java:144)
在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1278)
在android.os.Handler.dispatchMessage(Handler.java:102)
在android.os.Looper.loop(Looper.java:135)
在android.app.ActivityThread.main(ActivityThread.java:5223)
在java.lang.reflect.Method.invoke(本机方法)
在java.lang.reflect.Method.invoke(Method.java:372)
在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:899)
在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
显示java.lang.NullPointerException:引起尝试在空对象引用调用虚拟方法无效android.widget.ListView.setAdapter(android.widget.ListAdapter)'
在com.gnumbu.errolgreen.testing.NotMainActivity.populateListView(NotMainActivity.java:70)
在com.gnumbu.errolgreen.testing.NotMainActivity.onCreate(NotMainActivity.java:43)
在android.app.Activity.performCreate(Activity.java:5937)
在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
在android.app.ActivityThread.access $ 800(ActivityThread.java:144)
在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1278)
在android.os.Handler.dispatchMessage(Handler.java:102)
在android.os.Looper.loop(Looper.java:135)
在android.app.ActivityThread.main(ActivityThread.java:5223)
在java.lang.reflect.Method.invoke(本机方法)
在java.lang.reflect.Method.invoke(Method.java:372)
在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:899)
在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
新的错误
块引用>流程:com.gnumbu.errolgreen.testing,PID:5304
显示java.lang.NullPointerException:尝试调用虚方法对空对象引用'诠释android.view.View.getImportantForAccessibility()
在android.widget.AbsListView.obtainView(AbsListView.java:2360)
在android.widget.ListView.measureHeightOfChildren(ListView.java:1270)
在android.widget.ListView.onMeasure(ListView.java:1182)
在android.view.View.measure(View.java:17430)
在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
在android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
在android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
在android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
在android.view.View.measure(View.java:17430)
在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
在android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
在android.view.View.measure(View.java:17430)
在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
在android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
在android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
在android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
在android.view.View.measure(View.java:17430)
在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
在android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
在com.android.internal.policy.impl.PhoneWindow $ DecorView.onMeasure(PhoneWindow.java:2560)
在android.view.View.measure(View.java:17430)
在android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2001)
在android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1166)
在android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1372)
在android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054)
在android.view.ViewRootImpl $ TraversalRunnable.run(ViewRootImpl.java:5779)
在android.view.Choreographer $ CallbackRecord.run(Choreographer.java:767)
在android.view.Choreographer.doCallbacks(Choreographer.java:580)
在android.view.Choreographer.doFrame(Choreographer.java:550)
在android.view.Choreographer $ FrameDisplayEventReceiver.run(Choreographer.java:753)
在android.os.Handler.handleCallback(Handler.java:739)
在android.os.Handler.dispatchMessage(Handler.java:95)
在android.os.Looper.loop(Looper.java:135)
在android.app.ActivityThread.main(ActivityThread.java:5221)
在java.lang.reflect.Method.invoke(本机方法)
在java.lang.reflect.Method.invoke(Method.java:372)
在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:899)
在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
解决方案
NotMainActivity
要求的setContentView
与R.layout.activity_main
为包含参数ViewPager
,而不是的ListView
。既然你没有一个ListView申报到布局,findViewById(android.R.id.list)
返回null,并且当您尝试访问它(调用setAdapter
)的NullPointerException异常
被抛出。在
变化MyAdapter
,从如果(ItemView控件!= NULL){
。ItemView控件= getLayoutInflater()膨胀(R.layout.item_view,父母,假);
}到
如果(ItemView控件== NULL){
。ItemView控件= getLayoutInflater()膨胀(R.layout.item_view,父母,假);
}I am trying to make a list view that contains pictures and text within a fragment that is on a viewpager with tabs, so I can swipe left or right to bring up another fragment.
I'm relatively new to android so what I may be doing could be completely wrong. I can build the project perfectly fine but then when the emulator runs it crashes (log displayed at bottom of page).
I created a separate application and successfully was able to create a list view, but when I try to combine it within a fragment like so, it doesn't work. Here is my following code
MainActivity.java
import java.util.ArrayList; import java.util.List; import java.util.Locale; import android.app.ListFragment; import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.FragmentPagerAdapter; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends ActionBarActivity implements ActionBar.TabListener { /** * The {@link android.support.v4.view.PagerAdapter} that will provide * fragments for each of the sections. We use a * {@link FragmentPagerAdapter} derivative, which will keep every * loaded fragment in memory. If this becomes too memory intensive, it * may be best to switch to a * {@link android.support.v4.app.FragmentStatePagerAdapter}. */ SectionsPagerAdapter mSectionsPagerAdapter; /** * The {@link ViewPager} that will host the section contents. */ ViewPager mViewPager; private List<Posts> myPosts = new ArrayList<Posts>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Set up the action bar. final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Create the adapter that will return a fragment for each of the three // primary sections of the activity. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); // When swiping between different sections, select the corresponding // tab. We can also use ActionBar.Tab#select() to do this if we have // a reference to the Tab. mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); // For each of the sections in the app, add a tab to the action bar. for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { // Create a tab with text corresponding to the page title defined by // the adapter. Also specify this Activity object, which implements // the TabListener interface, as the callback (listener) for when // this tab is selected. actionBar.addTab( actionBar.newTab() .setText(mSectionsPagerAdapter.getPageTitle(i)) .setTabListener(this)); } Intent intent = new Intent(MainActivity.this, NotMainActivity.class); startActivity(intent); finish(); } @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(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { // When the given tab is selected, switch to the corresponding page in // the ViewPager. mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. // Return a PlaceholderFragment (defined as a static inner class below). switch (position){ case 0: return new TheWallFragment(); case 1: return new PeekFragment(); case 2: return new CameraFragment(); default: break; } return PlaceholderFragment.newInstance(position + 1); } @Override public int getCount() { // Show 3 total pages. return 3; } @Override public CharSequence getPageTitle(int position) { Locale l = Locale.getDefault(); switch (position) { case 0: return getString(R.string.title_section1).toUpperCase(l); case 1: return getString(R.string.title_section2).toUpperCase(l); case 2: return getString(R.string.title_section3).toUpperCase(l); } return null; } } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { /** * The fragment argument representing the section number for this * fragment. */ private static final String ARG_SECTION_NUMBER = "section_number"; /** * Returns a new instance of this fragment for the given section * number. */ public static PlaceholderFragment newInstance(int sectionNumber) { PlaceholderFragment fragment = new PlaceholderFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.wall_layout, container, false); return rootView; } } }
NotMainActivity.java
public class NotMainActivity extends FragmentActivity { private List<Posts> myPosts = new ArrayList<Posts>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); populatePostList(); populateListView(); registerClickCallBack(); System.out.print("Main Activity Started"); } private void populatePostList() { myPosts.add(new Posts("Ottawa, Ontario", "787", "Picture of my Dog!", R.drawable.dog)); myPosts.add(new Posts("Ottawa, Ontario", "787", "Picture of my Dog!", R.drawable.dog)); myPosts.add(new Posts("Ottawa, Ontario", "787", "Picture of my Dog!", R.drawable.dog)); myPosts.add(new Posts("Ottawa, Ontario", "787", "Picture of my Dog!", R.drawable.dog)); myPosts.add(new Posts("Ottawa, Ontario", "787", "Picture of my Dog!", R.drawable.dog)); myPosts.add(new Posts("Ottawa, Ontario", "787", "Picture of my Dog!", R.drawable.dog)); myPosts.add(new Posts("Ottawa, Ontario", "787", "Picture of my Dog!", R.drawable.dog)); myPosts.add(new Posts("Ottawa, Ontario", "787", "Picture of my Dog!", R.drawable.dog)); } private void populateListView() { ArrayAdapter<Posts> adapter = new MyListAdapter(); ListView list = (ListView) findViewById(android.R.id.list); list.setAdapter(adapter); } //Handles clicks on the list items private void registerClickCallBack(){ ListView list = (ListView) findViewById(android.R.id.list); list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Posts clickedPost = myPosts.get(position); String message = "You clicked" + position +"Location of post is" + clickedPost.getPostlocation(); Toast.makeText(NotMainActivity.this, message, Toast.LENGTH_LONG).show(); } }); } private class MyListAdapter extends ArrayAdapter<Posts> { public MyListAdapter() { super(NotMainActivity.this, R.layout.item_view, myPosts); } @Override public View getView(int position, View convertView, ViewGroup parent) { // Make sure we have a view to work with {may have given null} View itemView = convertView; if (itemView != null) { itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false); } // Find the post to work with. Posts currentPost = myPosts.get(position); //Fill the view ImageView imageView = (ImageView)itemView.findViewById(R.id.item_postImage); imageView.setImageResource(currentPost.getIconID()); //Fill in Title TextView titleText = (TextView) itemView.findViewById(R.id.item_postText); titleText.setText(currentPost.getPosttitle()); //Set Vote Number TextView voteText = (TextView) itemView.findViewById(R.id.item_postVoteText); voteText.setText(currentPost.getPostvote()); return itemView; } } }
Posts.java
public class Posts { private String postlocation; private String postvote; private String posttitle; private int iconID; public Posts(String postlocation, String postvote, String posttitle, int iconID) { this.postlocation = postlocation; this.postvote = postvote; this.posttitle = posttitle; this.iconID = iconID; } public String getPostlocation() { return postlocation; } public String getPostvote() { return postvote; } public String getPosttitle() { return posttitle; } public int getIconID() { return iconID; }
TheWallFragment.java
public class TheWallFragment extends android.support.v4.app.ListFragment { List<Posts> myPosts = new ArrayList<Posts>(); private String[] strListView; private ListView myListView; private int number; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.wall_layout, container, false); return rootView; } }
activity_main.xml
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" />
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.gnumbu.errolgreen.testing" > <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".NotMainActivity"> </activity> </application> </manifest>
item_view.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/item_postImage" android:src="@drawable/dog" android:maxWidth="80dp" android:minHeight="80dp" android:adjustViewBounds="true" android:layout_marginLeft="14dp" android:layout_marginStart="14dp" android:layout_alignParentTop="true" android:layout_toRightOf="@+id/item_upvoteArrow" android:layout_toEndOf="@+id/item_upvoteArrow" android:layout_alignBottom="@+id/item_downvotearrow" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This is my dog! My Dog is amazing, give it a lick!" android:id="@+id/item_postText" android:paddingStart="5dp" android:layout_above="@+id/item_downvotearrow" android:layout_toRightOf="@+id/item_postImage" android:layout_toEndOf="@+id/item_postImage" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/item_upvoteArrow" android:src="@drawable/upvotearrow" android:maxHeight="24dp" android:maxWidth="24dp" android:adjustViewBounds="true" android:layout_alignParentTop="true" android:layout_alignLeft="@+id/item_downvotearrow" android:layout_alignStart="@+id/item_downvotearrow" android:clickable="true" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/item_downvotearrow" android:src="@drawable/downvotearrow" android:maxWidth="24dp" android:maxHeight="24dp" android:adjustViewBounds="true" android:layout_marginLeft="9dp" android:layout_marginStart="9dp" android:layout_below="@+id/item_postVoteText" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:longClickable="false" android:clickable="true" /> <TextView android:layout_height="wrap_content" android:text="22" android:id="@+id/item_postVoteText" android:maxHeight="20dp" android:focusableInTouchMode="false" android:visibility="visible" android:singleLine="true" android:gravity="center" android:enabled="true" android:layout_below="@+id/item_upvoteArrow" android:layout_alignLeft="@+id/item_upvoteArrow" android:layout_alignStart="@+id/item_upvoteArrow" android:nestedScrollingEnabled="false" android:layout_width="wrap_content" android:layout_toStartOf="@+id/item_postImage" /> </RelativeLayout>
wall_layout.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="New Text" android:id="@+id/textView" android:layout_gravity="center_horizontal" /> <ListView android:id="@android:id/list" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
Error Log
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) at android.app.ActivityThread.access$800(ActivityThread.java:144) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5223) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference at com.gnumbu.errolgreen.testing.NotMainActivity.populateListView(NotMainActivity.java:70) at com.gnumbu.errolgreen.testing.NotMainActivity.onCreate(NotMainActivity.java:43) at android.app.Activity.performCreate(Activity.java:5937) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) at android.app.ActivityThread.access$800(ActivityThread.java:144) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5223) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
New Error
Process: com.gnumbu.errolgreen.testing, PID: 5304 java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference at android.widget.AbsListView.obtainView(AbsListView.java:2360) at android.widget.ListView.measureHeightOfChildren(ListView.java:1270) at android.widget.ListView.onMeasure(ListView.java:1182) at android.view.View.measure(View.java:17430) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436) at android.widget.LinearLayout.measureVertical(LinearLayout.java:722) at android.widget.LinearLayout.onMeasure(LinearLayout.java:613) at android.view.View.measure(View.java:17430) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463) at android.widget.FrameLayout.onMeasure(FrameLayout.java:430) at android.view.View.measure(View.java:17430) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436) at android.widget.LinearLayout.measureVertical(LinearLayout.java:722) at android.widget.LinearLayout.onMeasure(LinearLayout.java:613) at android.view.View.measure(View.java:17430) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463) at android.widget.FrameLayout.onMeasure(FrameLayout.java:430) at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2560) at android.view.View.measure(View.java:17430) at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2001) at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1166) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1372) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5779) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767) at android.view.Choreographer.doCallbacks(Choreographer.java:580) at android.view.Choreographer.doFrame(Choreographer.java:550) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5221) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
解决方案
NotMainActivity
callssetContentView
withR.layout.activity_main
as parameter that contains aViewPager
and not aListView
. Since you don't have a ListView declare in to that layout,findViewById(android.R.id.list)
returns null, and when you try access it (callingsetAdapter
) theNullPointerException
is thrown.in your
MyAdapter
, change fromif (itemView != null) { itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false); }
to
if (itemView == null) { itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false); }
这篇关于试图调用虚拟方法无效android.widget.ListView.setAdapter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!