返回 listView 的最后一个元素并将其设置为文本视图 - 落在 NullPointerException
Posted
技术标签:
【中文标题】返回 listView 的最后一个元素并将其设置为文本视图 - 落在 NullPointerException【英文标题】:Return last element of listView and set it into text view - falls on NullPointerException 【发布时间】:2015-01-07 19:45:50 【问题描述】:请帮我解决一些让我发疯的小事
我正在尝试在作为动态数组的最后一个元素的 textview 中设置文本。
我在我的适配器中添加了一个函数,它返回数组的最后一个元素。
我要回到主要活动,我想在其中显示文本,并且在此期间它落在“nullpointerexception”。
请帮忙
这是我的代码:
public class MainActivity extends Activity implements OnClickListener
private static Context mContext;
public Button mExit, mHistory, mRating;
public TextView mSignal;
HistoryAdapt myLastItem;
List<HistoryItems> m_myLastItem;
@SuppressWarnings("unchecked")
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainActivity.mContext=getApplicationContext();
mExit=(Button)findViewById(R.id.ExitButton);
mExit.setOnClickListener(this);
mHistory=(Button)findViewById(R.id.HistoryButton);
mHistory.setOnClickListener(this);
mRating=(Button)findViewById(R.id.RateButton);
mRating.setOnClickListener(this);
mSignal=(TextView)findViewById(R.id.SignalOfTheDayTV);
//### SET LAST ELEMENT INTO TEXTVIEW
m_myLastItem = new ArrayList<HistoryItems>();
myLastItem=new HistoryAdapt(mContext, m_myLastItem );
m_myLastItem= (List<HistoryItems>) myLastItem.getLastElement();
mSignal.setText(( (HistoryItems) m_myLastItem).getTitle());
// AppRater.app_launched(this);
// AppRater.showRateDialog(this, null);
//Get a Tracker (should auto-report)
((AppManager) getApplication()).getTracker(AppManager.TrackerName.APP_TRACKER);
//oncreate
@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();
if (id == R.id.action_settings)
return true;
return super.onOptionsItemSelected(item);
public static Context getAppContext()
return MainActivity.mContext;
public void ExitState()
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("You're about to quit Signals4Trading");
builder.setIcon(R.drawable.five);
//builder.setMessage("Your device has been registered successfully. You'll receive signals very soon.");
builder.setMessage("Are you sure you want to quit?");
builder.setCancelable(false);//can't click on the background of the activity
builder.setPositiveButton("Yes",new DialogInterface.OnClickListener()
@Override
public void onClick(DialogInterface dialog, int which)
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"See you soon", Toast.LENGTH_LONG).show();
finish();
//OnClickListener PositiveButton
);//anonymous class PositiveButton
builder.setNegativeButton("No", new DialogInterface.OnClickListener()
@Override
public void onClick(DialogInterface dialog, int which)
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"Enjoy your visit", Toast.LENGTH_LONG).show();
);
AlertDialog alertDialog = builder.create();
alertDialog.show();
//ExitState
public void goToHistoryActivity()
Intent intent = new Intent(MainActivity.this, HistoryAct.class );
startActivity(intent);
public void rateApp()
Intent intent = new Intent(MainActivity.this, Rate.class);
startActivity(intent);
@Override
public void onClick(View v)
// TODO Auto-generated method stub
switch (v.getId())
case R.id.ExitButton:
ExitState();
break;
case R.id.HistoryButton:
goToHistoryActivity();
break;
case R.id.RateButton:
rateApp();
break;
@Override
protected void onStart()
// TODO Auto-generated method stub
super.onStart();
//Get an Analytics tracker to report app starts & uncaught exceptions etc.
GoogleAnalytics.getInstance(this).reportActivityStart(this);
@Override
protected void onStop()
// TODO Auto-generated method stub
super.onStop();
//Stop the analytics tracking
GoogleAnalytics.getInstance(this).reportActivityStop(this);
//MainActivity
**Adapter:**
package com.Signals4Trading.push.android;
import java.util.List;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class HistoryAdapt extends BaseAdapter
private final List<HistoryItems>items;
private final Context context;
public HistoryAdapt(Context context,List<HistoryItems>items)
this.context=context;
this.items=items;
//constructor
@Override
public int getCount()
// TODO Auto-generated method stub
return items.size();
@Override
public Object getItem(int position)
// TODO Auto-generated method stub
return items.get(position);
@Override
public long getItemId(int id)
// TODO Auto-generated method stub
return id;
//###FUNCTION THAT RETURN LAST ELEMENT
public HistoryItems getLastElement()
HistoryItems lastItem = items.get(items.size());
if(items!=null && !items.isEmpty())
lastItem = items.get(items.size()-1);
return lastItem;
@Override
public View getView(int position, View convertView, ViewGroup parent)
// TODO Auto-generated method stub
ViewHolder holder;
if (convertView == null)
convertView = View.inflate(context, R.layout.historyitems, null);
holder = new ViewHolder();
holder.itemTitle = (TextView) convertView.findViewById(R.id.itemTitleTV);
holder.itemDate=(TextView) convertView.findViewById(R.id.itemDateTV);
convertView.setTag(holder);
else
holder = (ViewHolder) convertView.getTag();
holder.itemTitle.setText(items.get(position).getTitle());
holder.itemDate.setText(items.get(position).getDate());
return convertView;
class ViewHolder
TextView itemTitle;
TextView itemDate;
//HistoryAdapt
【问题讨论】:
【参考方案1】:您收到此错误是因为您从未初始化适配器类的对象
HistoryAdapt in requires a context and and list to pass into it ,as defined in your constructor
【讨论】:
好的,所以我知道在我的 MainActivity 中,我必须添加: HistoryAdapt myLastItem=new HistoryAdapt(getApplicationContext(), ???? );我应该写什么而不是“???” 不,你必须适当地初始化它,传递上下文和一个包含 HistoryItems 对象的列表 你应该写一个包含 HistoryItems 对象的列表,而不是 ???? 类似这样的东西:HistoryAdapt myLastItem;列表这可能是因为 Listitems 仍然引用空对象。在调用之前你有没有调用 HistoryAdapt(context,items) 构造函数
HistoryItems l_myLastItem= (HistoryItems) myLastItem.getLastElement(0); ?
【讨论】:
嗨做了类似的事情,但看起来很奇怪:类似这样的事情:HistoryAdapt myLastItem;列表照Haresh Chhelana说的做
public HistoryItems getLastElement()
return items.get(items.size()-1);
您收到空指针异常的原因是您的列表尚未初始化,因此它引用了空值。要消除此错误,您应该首先初始化 ArrayList,然后将其填充为
//### SET LAST ELEMENT INTO TEXTVIEW
m_myListItem = new ArrayList();
//then add some data to arrayList for eg:
for (i=1;i<=10;i++)
m_myListItem.add(new HistoryItem().setTitle("title " + i));
myLastItem=new HistoryAdapt(mContext, m_myListItem ); //this should be m_myListItem not m_myLastItem
m_myLastItem= myLastItem.getLastElement();// m_myLastItem should be of type HistoryItem as HistoryItem m_myLastItem not List<HistoryItems> m_myLastItem
mSignal.setText(m_myLastItem.getTitle());
附:请查看您的变量命名约定
【讨论】:
嗯,谢谢,但是 m_myListItem.add(new HistoryItem().setTitle("title" + i)) 中的函数 add();不适用于参数 void。我应该用这个功能做什么? 它也落在: 引起:java.lang.ClassCastException:com.Signals4Trading.push.android.HistoryItems 不能转换为 java.util.List 11-11 14:52:14.802: E/AndroidRuntime(30384): 在 com.Signals4Trading.push.android.MainActivity.onCreate(MainActivity.java:91) 11-11 14:52:14.802: E/AndroidRuntime(30384): 在 android.app.Activity.performCreate (Activity.java:5231) 11-11 14:52:14.802: 抱歉,我刚刚复制并粘贴了您的代码,忘记删除演员表,现在它应该可以工作了 对不起,但它仍然不起作用..请有人可以帮助我。我对这些更改感到非常困惑,因为当我将它们插入到我的代码中时。它根本不适合。他们要求我提供很多不同的演员阵容,但没有任何效果。我正在尝试大约 1 小时..【参考方案4】:无需传递最后一项索引,而是直接从适配器列表大小获取索引。
public HistoryItems getLastElement()
return items.get(items.size()-1);
【讨论】:
谢谢,我做到了,但它再次落在同一个 nullpointerexception 上以上是关于返回 listView 的最后一个元素并将其设置为文本视图 - 落在 NullPointerException的主要内容,如果未能解决你的问题,请参考以下文章