LayoutInflater.from(context) 报空指针异常

这是打印出来的Log:
Process: com.hql.rssr, PID: 1905
java.lang.NullPointerException
at android.view.LayoutInflater.from(LayoutInflater.java:211)
at com.hql.Adapter.FragmentExpanableListViewAdapter.(FragmentExpanableListViewAdapter.java:32)
at com.hql.fragment.TechnologyFragment$2.showListView(TechnologyFragment.java:94)
at com.hql.fragment.TechnologyFragment$2.handleMessage(TechnologyFragment.java:81)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5045)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)

报错的是这行代码:public FragmentExpanableListViewAdapter(Context context, ArrayList Gp, Map> ChildMap) {
mInflater = LayoutInflater.from(context); //是这里。。。。。
this.Gp = Gp;
this.ChilderMap = ChildMap;
list = new ArrayList();
}

我在碎片里面调用的时候是这样子的: adapter = new FragmentExpanableListViewAdapter(getActivity(), title, list);

能运行,数据的加载和显示也没问题,就是在页面切换的时候会偶尔报这个错。我想问一下 这会不会是和多个碎片共用一个适配器有关,因为碎片的布局的样式都一样,只是加载的数据类型不一样  adapter = new FragmentExpanableListViewAdapter(getActivity(), title, list); (就是像这行代码一样 这是里面的title 和list 不一样而已)  我就直接用多个碎片对应一个适配器了 这是怎么回事呢?/d:

1个回答

代码不全,不能直接定位错误,估计是你的fragment的生命周期函数没控制好,用getActivity方法取Context时取出了空值,这个方法要在onactivitycreated方法里或者这个周期函数以后的函数取才有效

shenshucong520
glustful 回复qq_36522073: 看你分析的这原因,在onresume里创建线程才去初始化,估计是你在线程完成后,你没有判断当前Fragment是否还在存活,你在切换时没被缓存的fragment会被销毁,但你在线程结束时没作判断就直接初始化适配器,造成取了空值,现在只能分析到这了,如果不是提供代码吧,好找原因
大约 3 年之前 回复
qq_36522073
qq_36522073 回复glustful: 我是在Onresume 的时候调用子线程去加载数据的,加载完了才把数据通过handler一起发过来,在界面上显示。
大约 3 年之前 回复
shenshucong520
glustful 回复qq_36522073: 谁知道你是什么时候发的消息,不管怎么传,你前提保证能取到Context才行,多个fragment共用一个Adapter是不会有问题的
大约 3 年之前 回复
qq_36522073
qq_36522073 哦 那就是说要在onactivitycreated 完了之后才取Context嘛?可是我是用的handler传递msg 来更新加载数据的 这不应该已经是在 OnActivityCreated之后了嘛
大约 3 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
android context 空指针 问题
LoginDialog l=new LoginDialog(); l.LoginDialog2(M.this); 我写了个LoginDialog类 如下 结果 老是 报错 public class LoginDialog extends Activity implements OnClickListener { private Context mcontext=null; public void LoginDialog2 (Context context) { this.mcontext = context; LayoutInflater layoutInflater = LayoutInflater.from(context); View longinDialogView = layoutInflater.inflate(MResource.getIdByName(getApplication(), "layout", "logindialog"), null); //获取布局中的控件 EditText mUserName = (EditText)longinDialogView.findViewById( MResource.getIdByName(getApplication(), "id", "edit_username")); EditText mPassword = (EditText)longinDialogView.findViewById( MResource.getIdByName(getApplication(), "id", "edit_password")); //创建一个AlertDialog对话框 AlertDialog longinDialog = new AlertDialog.Builder(context) .setTitle("登录框") .setView(longinDialogView) //加载自定义的对话框式样 .setPositiveButton("确定", this) .setNeutralButton("取消", this) .create(); longinDialog.show(); } @Override public void onClick(DialogInterface arg0, int arg1) { // TODO Auto-generated method stub } } 错误提示 java.lang.NullPointerException
Recyclerview点击item跳转页面报空指针
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) { View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recy_view_item,viewGroup,false); final ViewHolder holder = new ViewHolder(view); //点击事件 holder.relesaTitle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context,NRCommunityActivity.class); context.startActivity(intent); } }); return holder; } 报错: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
Android ListView 自定义Adapter 滑动时报空指针异常
问题背景:在制作一个即时聊天的APP中,聊天界面聊天消息的显示我使用了ListView,并且使用了自定义的Adapter,获取到聊天记录之后ListView可以正常显示,但是一旦滑动就会报空指针异常。我查看了很多博客,都没有提到与这个相关或者类似的错误已经被这个错误逼疯了,希望有了解的大神能够给予指点。 具体相关代码如下: 自定义的Adapter: ``` public class ChatMessageAdapter extends BaseAdapter { private LayoutInflater layoutInflater; private List<MessageShow> messageShowList; public ChatMessageAdapter(Context context, List<MessageShow> messageShowList){ layoutInflater = LayoutInflater.from(context); this.messageShowList = messageShowList; } @Override public int getCount() { return messageShowList.size(); } @Override public Object getItem(int position) { return messageShowList.get(position); } @Override public int getItemViewType(int position) { if(messageShowList.get(position).getMessageType()==0) return 0; else return 1; } //Item类型的总数 @Override public int getViewTypeCount() { return 2; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { MessageShow messageShow = messageShowList.get(position); ViewHolder viewHolder = null; if(convertView == null){ if(messageShow.getMessageType() == 0){ convertView = layoutInflater.inflate(R.layout.from_message_item,null); viewHolder = new ViewHolder(); // viewHolder.imageView = (ImageView) convertView.findViewById(R.id.from_user_icons); viewHolder.time = (TextView) convertView.findViewById(R.id.from_time); viewHolder.message = (TextView) convertView.findViewById(R.id.from_message); } else{ convertView = layoutInflater.inflate(R.layout.to_message_item,null); viewHolder = new ViewHolder(); // viewHolder.imageView = (ImageView) convertView.findViewById(R.id.to_user_icons); viewHolder.time = (TextView) convertView.findViewById(R.id.to_time); viewHolder.message = (TextView) convertView.findViewById(R.id.to_message); } } else { viewHolder = (ViewHolder) convertView.getTag(); } System.out.println("我到了这里"+position); System.out.println("我添加了适配器: "+messageShow.getContents()); // viewHolder.imageView.setImageResource(R.drawable.photo); //报空指针异常的是这里 viewHolder.message.setText(messageShow.getContents()); viewHolder.time.setText(messageShow.getTime()); return convertView; } private final class ViewHolder{ // ImageView imageView; TextView time; TextView message; } ``` ,ChatActivity代码如下: ``` private List<MessageShow> showMessageList; private ChatMessageAdapter chatMessageAdapter; 、、、省略无关 //初始化数据 private void initData(){ showMessageList = new ArrayList<MessageShow>(); chatMessageAdapter = new ChatMessageAdapter(this,showMessageList); listView.setAdapter(chatMessageAdapter); getMessageRecord(); chatMessageAdapter.notifyDataSetChanged(); } ``` 其中获取聊天记录我已经在控制台打印出来检查过了,没有错误,而ListView能够显示说明Apapter也不会有基本的错误,但是还是报空指针。我对错误的猜测如下: 虽然给的数据集可能有几十项,但是Adapter加载的时候只加载了当前显示的几项,后面的没加载,等我我滑动之后去加载的时候没加载到数据就报空指针了。但是这不太科学啊,我看了好多博客发现都没有专门说到这点,仔细检查代码也不知道应该怎么改,求指教。报错信息如下: ``` I/System.out: 我到了这里1 I/System.out: 我添加了适配器: 图片这些不能点击? I/System.out: 我到了这里2 I/System.out: 我添加了适配器: 还没做那些功能呢233 I/System.out: 我到了这里3 I/System.out: 我添加了适配器: 图片和表情 I/System.out: 我到了这里4 I/System.out: 我添加了适配器: 额 I/System.out: 我到了这里5 I/System.out: 我添加了适配器: 准备等APP开发完之后再说 I/System.out: 我到了这里6 I/System.out: 我添加了适配器: 真的挺费脑的 I/System.out: 我到了这里7 I/System.out: 我添加了适配器: 嗯 加油 E/InputEventReceiver: Exception dispatching input event. D/AndroidRuntime: Shutting down VM W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa6160908) E/AndroidRuntime: FATAL EXCEPTION: main java.lang.NullPointerException at cn.justwithme.withme.Adapaer.ChatMessageAdapter$override.getView(ChatMessageAdapter.java:84) at cn.justwithme.withme.Adapaer.ChatMessageAdapter$override.access$dispatch(ChatMessageAdapter.java) at cn.justwithme.withme.Adapaer.ChatMessageAdapter.getView(ChatMessageAdapter.java:0) ``` 本来有十几项的,第一页只有7项,我在Adapter的输出就只出输出了7项。 ![图片说明](https://img-ask.csdn.net/upload/201702/19/1487495789_116858.png) ![图片说明](https://img-ask.csdn.net/upload/201702/19/1487495801_419892.png)
Android中重写SimpleAdapter类引用后报空指针异常
直接粘代码吧 - - 重写的SimpleAdapter类: ``` public class MySimpleAdapter extends BaseAdapter { private LayoutInflater mInflater; private ArrayList<HashMap<String, Object>> list; private int layoutID; private String flag[]; private int ItemIDs[]; public MySimpleAdapter(Context context, ArrayList<HashMap<String, Object>> list, int layoutID, String flag[], int ItemIDs[]) { this.mInflater = LayoutInflater.from(context); this.list = list; this.layoutID = layoutID; this.flag = flag; this.ItemIDs = ItemIDs; } @Override public int getCount() { // TODO Auto-generated method stub return list.size(); } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return 0; } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { convertView = mInflater.inflate(layoutID, null); convertView = mInflater.inflate(layoutID, null); for (int i = 0; i < flag.length; i++) { if (convertView.findViewById(ItemIDs[i]) instanceof ImageView) { ImageView iv = (ImageView) convertView.findViewById(ItemIDs[i]); iv.setBackgroundResource((Integer) list.get(position).get( flag[i])); } else if (convertView.findViewById(ItemIDs[i]) instanceof TextView) { TextView tv = (TextView) convertView.findViewById(ItemIDs[i]); tv.setText((String) list.get(position).get(flag[i])); } } addListener(convertView); return convertView; } public void addListener(View convertView) { ((TextView)convertView.findViewById(R.id.order_mine_show_handle_confirm)).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { new AlertDialog.Builder(OrderMineNonPaymentActivity.onp) .setTitle("自定义通用SimpleAdapter") .setMessage("按钮成功触发监听事件!") .show(); } }); } } ``` 引用的地方 OrderMineNonPaymentActivity: ``` /** * 动态生成订单列表 lipeng */ private void addNonPaymentList() { order_mine_show_non_payment_list_ll = (LinearLayout) findViewById(R.id.order_mine_show_non_payment_list_ll); nonPaymentList = (ListView) findViewById(R.id.order_mine_show_non_payment_list); nonPaymentList.setDivider(null); nonPaymentSimpleAdapter = new SimpleAdapter( OrderMineNonPaymentActivity.this, goodsList, R.layout.activity_order_non_payment_item, new String[] { "shopname", "bigimage", "goodname" }, new int[] { R.id.order_mine_show_shopname, R.id.order_mine_show_goods_img, R.id.order_mine_show_goods_name }); MySimpleAdapter nonPaymentSimpleAdapter = new MySimpleAdapter(this, goodsList, R.layout.activity_order_mine_non_payment, new String[] { "shopname", "bigimage", "goodname" }, new int[] { R.id.order_mine_show_shopname, R.id.order_mine_show_goods_img, R.id.order_mine_show_goods_name }); nonPaymentList.setAdapter(nonPaymentSimpleAdapter); } private class MyOnItemClickListener implements OnItemClickListener { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub } } ``` 异常报的空指针,找了半天也没找到为啥空指针了 ``` 06-17 22:55:32.845: E/AndroidRuntime(1463): FATAL EXCEPTION: main 06-17 22:55:32.845: E/AndroidRuntime(1463): Process: com.zb.stlala, PID: 1463 06-17 22:55:32.845: E/AndroidRuntime(1463): java.lang.NullPointerException 06-17 22:55:32.845: E/AndroidRuntime(1463): at com.zb.stlala.adapter.MySimpleAdapter.addListener(MySimpleAdapter.java:83) 06-17 22:55:32.845: E/AndroidRuntime(1463): at com.zb.stlala.adapter.MySimpleAdapter.getView(MySimpleAdapter.java:75) ```
volley中ImageLoader报空指针异常
public class StoreBookListAdapter extends BaseAdapter{ private List<Book> books; private LayoutInflater inflater; private RequestQueue mQueue; private ImageLoader loader; public StoreBookListAdapter(Context context, List<Book> reCommendBooks) { this.mQueue = MyApplication.geRequestQueue(); this.loader = new ImageLoader(mQueue, new BitmapCache()); Log.i("info", "loader="+loader.toString()); this.books = reCommendBooks; this.inflater = LayoutInflater.from(context); } public class BitmapCache implements ImageCache { private LruCache<String, Bitmap> mCache; public BitmapCache() { int maxSize = 10 * 1024 * 1024; mCache = new LruCache<String, Bitmap>(maxSize) { @Override protected int sizeOf(String key, Bitmap bitmap) { return bitmap.getRowBytes() * bitmap.getHeight(); } }; } @Override public Bitmap getBitmap(String url) { return mCache.get(url); } @Override public void putBitmap(String url, Bitmap bitmap) { mCache.put(url, bitmap); } } @Override public int getCount() { return books.size(); } @Override public Book getItem(int position) { return books.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if(convertView==null) { holder = new ViewHolder(); convertView = inflater.inflate(R.layout.item_store_gv_book,null); holder.iamgeView = (ImageView) convertView.findViewById(R.id.imageView); holder.textView = (TextView) convertView.findViewById(R.id.textView); convertView.setTag(holder); } holder = (ViewHolder) convertView.getTag(); Book book = getItem(position); holder.textView.setText(book.getProductName()); //批量下载 ImageListener listener = ImageLoader.getImageListener(holder.iamgeView, R.drawable.ic_launcher, R.drawable.ic_launcher); loader.get(book.getProduct_pic(), listener); return convertView; } class ViewHolder { ImageView iamgeView; TextView textView; }![图片说明](https://img-ask.csdn.net/upload/201607/23/1469242280_999062.png) ![图片说明](https://img-ask.csdn.net/upload/201607/23/1469242291_816035.png)
Android购物车全选报空指针(文中有给出报空指针的地方)
private List<ShoppingBean> mList=new ArrayList<>(); public static HashMap<Integer,Boolean> isSelected; private Context context; //为单选设置的回调 private Callback mCallback; public static HashMap<Integer,Boolean> getIsSelected() { return isSelected; } public static void setIsSelected(HashMap<Integer, Boolean> isSelected) { ShoppingAdapter.isSelected = isSelected; } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mCallback.click((CheckBox) buttonView, isChecked); } public interface Callback{ void click(CheckBox check, boolean isChecked); } public ShoppingAdapter(List<ShoppingBean> list, Context context, Callback mCallback) { this.mList = list; this.context = context; this.mCallback = mCallback; isSelected=new HashMap<>(); initData(); } //初始化isSelected private void initData() { for (int i = 0; i < mList.size(); i++) { getIsSelected().put(i, false); } } @Override public int getCount() { return mList.size(); } @Override public Object getItem(int position) { return mList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder=null; if (convertView==null){ viewHolder=new ViewHolder(); convertView= LayoutInflater.from(parent.getContext()).inflate(R.layout.item_shopping,null); viewHolder.check= (CheckBox) convertView.findViewById(R.id.item_cb); viewHolder.img_goods= (ImageView) convertView.findViewById(R.id.img_goods); viewHolder.name= (TextView) convertView.findViewById(R.id.name); viewHolder.guige= (TextView) convertView.findViewById(R.id.guige); viewHolder.tv_pay= (TextView) convertView.findViewById(R.id.tv_pay); viewHolder.number= (TextView) convertView.findViewById(R.id.number); convertView.setTag(viewHolder); }else{ viewHolder= (ViewHolder) convertView.getTag(); } ShoppingBean shoppingBean=mList.get(position); viewHolder.name.setText(shoppingBean.getWareName()); viewHolder.guige.setText(shoppingBean.getCaption()); viewHolder.tv_pay.setText(shoppingBean.getPrice()); viewHolder.number.setText(shoppingBean.getQuantity()); viewHolder.check.setOnCheckedChangeListener(this); viewHolder.check.setTag(position); String img=shoppingBean.getWarePicture(); if (img!=null){ Glide.with(context).load(img).placeholder(R.mipmap.picture).error(R.mipmap.picture) .into(viewHolder.img_goods); } //下边这行一直报空指针是为什么呢? // viewHolder.check.setChecked(getIsSelected().get(position)); return convertView; } public static class ViewHolder{ public CheckBox check; public ImageView img_goods; public TextView name,guige,tv_pay,number; }
android 获取menu控件空指针异常
这是我的代码: ``` public class MainActivity extends AppCompatActivity { private static Toolbar action_add; private static Menu menu; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); onPrepareOptionsMenu(menu); action_add.setOnClickListener(new Toolbar.OnClickListener() { public void onClick(View v) { showDialog_Layout(MainActivity.this); } }); } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); menu.findItem(R.id.action_add).setChecked(true); return true; } private void showDialog_Layout(Context context) { LayoutInflater inflater = LayoutInflater.from(this); final View textEntryView = inflater.inflate(R.layout.dialoglayout, null); final EditText edtInput=(EditText)textEntryView.findViewById(R.id.edtInput); final AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setCancelable(false); builder.setIcon(R.drawable.a); builder.setTitle("Title"); builder.setView(textEntryView); builder.setPositiveButton("确认", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { setTitle(edtInput.getText()); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { setTitle(""); } }); builder.show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return super.onCreateOptionsMenu(menu); } } ``` 这是我的错误: Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.Menu.findItem(int)' on a null object reference 在 onPrepareOptionsMenu(menu); menu.findItem(R.id.action_add).setChecked(true); 两行,大神给看看呗!!!
android adapter空指针异常
``` public class MainActivity extends AppCompatActivity { DatabaseHelper databaseHelper; private static Toolbar mToolbar; private static TextView mMaintitle,mMaincontent,mMaintime; public static EditText dlx_Input1,dlx_Input2; public static String datetime; public static View mLine; MyAdapter myAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findName(); setSupportActionBar(mToolbar); databaseHelper = new DatabaseHelper(this, databaseHelper.DATABASE_NAME, null, databaseHelper.DATABASE_VERSION); //myAdapter.getData2(); myAdapter = new MyAdapter(this); myAdapter.lv = (ListView)findViewById(R.id.lv); myAdapter.data = myAdapter.getData(); MyAdapter adapter = new MyAdapter(this); myAdapter.lv.setAdapter(adapter); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_add: showDialog_Layout(MainActivity.this); } return super.onOptionsItemSelected(item); } public void findName() { mToolbar = (Toolbar) findViewById(R.id.toolbar); mMaintitle = (TextView)findViewById(R.id.dlx_maintitle); mMaincontent = (TextView)findViewById(R.id.dlx_maincontent); mMaintime = (TextView)findViewById(R.id.dlx_maintime); mLine = (View)findViewById(R.id.dlx_line); } private void showDialog_Layout(Context context) { dlx_Input1 = (EditText)findViewById(R.id.dlx_Input1); dlx_Input2 = (EditText)findViewById(R.id.dlx_Input2); final AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setCancelable(false); builder.setTitle(R.string.dlx_add); builder.setPositiveButton("CANCEL", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { setTitle(""); } }); builder.setNegativeButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { SQLiteDatabase db = databaseHelper.getWritableDatabase(); ContentValues values = new ContentValues(); SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); datetime = s.format(new java.util.Date()); values.put("title", String.valueOf(dlx_Input1.getText())); values.put("content", String.valueOf(dlx_Input2.getText())); values.put("time", datetime); db.insert(databaseHelper.TABLE_NAME, null, values); myAdapter.getData(); } }); builder.show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); menu.findItem(R.id.action_add).setChecked(true); return super.onCreateOptionsMenu(menu); } } public class MyAdapter extends BaseAdapter { public static ListView lv; public static List<Map<String, Object>> data; public LayoutInflater mInflater = null; MainActivity mainActivity; DatabaseHelper databaseHelper; public MyAdapter(Context context) { this.mInflater = LayoutInflater.from(context); } public List<Map<String, Object>> getData() { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); Map<String, Object> map; for(int i=0;i<10;i++) { map = new HashMap<String, Object>(); map.put("title",String.valueOf(mainActivity.dlx_Input1.getText())); map.put("content", String.valueOf(mainActivity.dlx_Input2.getText())); map.put("time",mainActivity.datetime); list.add(map); } return list; } static class ViewHolder { public TextView title; public TextView content; public TextView time; public View line; } public int getCount() { //How many items are in the data set represented by this Adapter. //在此适配器中所代表的数据集中的条目数 return data.size(); } public Object getItem(int position) { // Get the data item associated with the specified position in the data set. //获取数据集中与指定索引对应的数据项 return position; } public long getItemId(int position) { //Get the row id associated with the specified position in the list. //获取在列表中与指定索引对应的行id return position; } //Get a View that displays the data at the specified position in the data set. //获取一个在数据集中指定索引的视图来显示数据 public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; //如果缓存convertView为空,则需要创建View if(convertView == null) { holder = new ViewHolder(); //根据自定义的Item布局加载布局 convertView = mInflater.inflate(R.layout.commentlayout, null); holder.title = (TextView)convertView.findViewById(R.id.dlx_maintitle); holder.content = (TextView)convertView.findViewById(R.id.dlx_maincontent); holder.time = (TextView)convertView.findViewById(R.id.dlx_maintime); holder.line = (View)convertView.findViewById(R.id.dlx_line); //将设置好的布局保存到缓存中,并将其设置在Tag里,以便后面方便取出Tag convertView.setTag(holder); }else { holder = (ViewHolder)convertView.getTag(); } holder.title.setText((String)data.get(position).get("title")); holder.content.setText((String)data.get(position).get("content")); holder.time.setText((String)data.get(position).get("time")); holder.line.setBackgroundColor(mainActivity.getResources().getColor(R.color.colorPrimaryDark)); return convertView; } ``` 在map.put("title",String.valueOf(mainActivity.dlx_Input1.getText()));和myAdapter.data = myAdapter.getData();报空指针异常 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference,求大神指点!!!
求助大神!android的baseadapter老是报空指针
package com.example.kaoqin; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.ObjectUtils.Null; import android.R.integer; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; public class User_TiaoZhuan_Activity2 extends Activity { private ListView list; private SimpleAdapter SAda; public String huoquuser; private String[] From = new String[]{"yonghu","kaishi","jieshu","zong","yuanyin","zhuangtai","id"}; public ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>(); private ArrayList<ItemBean> datalist = new ArrayList<ItemBean>(); public String NAME; public String START; public String END; public String SUM; public String REASON; public String STATE; public String ID; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.user_tiaozhuan_activity2); list = (ListView)findViewById(R.id.listViewuser); Intent intent = getIntent();//将检索出来的intent赋值给一个Intent类型的变量intent,getIntent()方法用于直接返回Intent实例 Bundle bundle = intent.getExtras();///获取前面的那个activity传过来的数据 huoquuser = bundle.getString("username"); HttpClien httpClien = new HttpClien(); data = httpClien.HTTPLeaveListView(huoquuser, "2"); //SAda = new SimpleAdapter(User_TiaoZhuan_Activity2.this, getdata(data),R.layout.user_tiaozhuan_buju2, From,new int[]{R.id.tiaozhuan_user2, //R.id.tiaozhuan_start2,R.id.tiaozhuan_end2,R.id.tiaozhuan_sum2,R.id.tiaozhuan_reason2,R.id.tiaozhuan_shenhe2,R.id.tiaozhuan_id2}); //list.setAdapter(SAda); Edit nihao = new Edit(this, getdata(data));//把数据源放入baseadapter list.setAdapter(nihao); } public ArrayList<ItemBean> getdata(ArrayList<HashMap<String,Object>> shuju) { for (int i = 0; i < data.size(); i++) { NAME = String.valueOf(shuju.get(i).get("name")); START = String.valueOf(shuju.get(i).get("start")); END = String.valueOf(shuju.get(i).get("end")); SUM = String.valueOf(shuju.get(i).get("sum")); REASON = String.valueOf(shuju.get(i).get("reason")); STATE = String.valueOf(shuju.get(i).get("state")); ID = String.valueOf(shuju.get(i).get("id")); ItemBean it = new ItemBean(NAME, START, END, SUM, REASON, STATE,ID); datalist.add(it); } return datalist; } } class Edit extends BaseAdapter { private Context context; private ArrayList<ItemBean> list; private LayoutInflater miInflater; public Edit(Context context,ArrayList<ItemBean> list) { LayoutInflater miInflater; miInflater = LayoutInflater.from(context); this.context = context; this.list = list; //根据context上下文加载布局,这里的是User_TiaoZhuan_Activity本身,即this } @Override public int getCount() { // TODO Auto-generated method stub //在此适配器中所代表的数据集中的条目数 return list.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub //获取数据集中与指定索引对应的数据项 return list.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub //获取在列表中与指定索引对应的行id return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub ViewHolder kongjian = null; if(convertView == null) { convertView = miInflater.inflate(R.layout.user_tiaozhuan_buju2, null); kongjian = new ViewHolder(); kongjian.TV_sure = (TextView)convertView.findViewById(R.id.yunxu); kongjian.TV_cancel = (TextView)convertView.findViewById(R.id.bohui); kongjian.TVuser = (TextView)convertView.findViewById(R.id.tiaozhuan_user2); kongjian.TVstart = (TextView)convertView.findViewById(R.id.tiaozhuan_start2); kongjian.TVend = (TextView)convertView.findViewById(R.id.tiaozhuan_end2); kongjian.TVsum = (TextView)convertView.findViewById(R.id.tiaozhuan_sum2); kongjian.TVreason = (TextView)convertView.findViewById(R.id.tiaozhuan_reason2); kongjian.TVstate = (TextView)convertView.findViewById(R.id.tiaozhuan_shenhe2); kongjian.TVid = (TextView)convertView.findViewById(R.id.tiaozhuan_id2); //将设置好的布局保存到缓存中,并将其设置在Tag里,以便后面方便取出Tag convertView.setTag(kongjian); }else { kongjian = (ViewHolder)convertView.getTag(); } kongjian.TV_sure.setText("允许请假"); kongjian.TV_cancel.setText("驳回请假"); ItemBean bean = list.get(position); kongjian.TVuser.setText(bean.Itemuser);; kongjian.TVstart.setText(bean.Itemstarttime); kongjian.TVend.setText(bean.Itemendtime); kongjian.TVsum.setText(bean.Itemsumtime); kongjian.TVreason.setText(bean.Itemreason); kongjian.TVstate.setText(bean.Itemstate); kongjian.TVid.setText(bean.ItemId); kongjian.TV_sure.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub System.out.println("通过"); } }); kongjian.TV_cancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub System.out.println("不通过"); } }); return convertView; } } class ViewHolder { TextView TV_sure; TextView TV_cancel; TextView TVuser; TextView TVstart; TextView TVend; TextView TVsum; TextView TVreason; TextView TVid; TextView TVstate; } class ItemBean { public String Itemuser; public String Itemstarttime; public String Itemendtime; public String Itemsumtime; public String Itemreason; public String Itemstate; public String ItemId; public ItemBean(String a,String b,String c, String d,String e,String f,String g) { Itemuser = a; Itemstarttime = b; Itemendtime = c; Itemsumtime = d; Itemreason = e; Itemstate = f; ItemId = g; } }![图片说明](https://img-ask.csdn.net/upload/201611/10/1478771417_684227.png) 错误显示的是121行存在空指针,inflate里的布局文件是存在的啊,R类里也有 地址啊(R.layout.user_tiaozhuan_buju2, null);
求大神指导Android中重写SimpleAdapter类引getCount空指针异常,万分感谢
重写的BaseAdapter: ``` public class MyAdapter extends BaseAdapter { List<UserInfo> userInfos=new ArrayList<UserInfo>(); Context context; public MyAdapter(Context c,List<UserInfo> userInfos) { // TODO Auto-generated constructor stub this.context=c; this.userInfos=userInfos; } public void setcotext(List<UserInfo> userInfos){ this.userInfos=userInfos; } @Override public int getCount() { // TODO Auto-generated method stub return userInfos.size(); } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return userInfos.get(arg0); } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return userInfos.get(arg0).getId(); } @Override public View getView(int arg0, View arg1, ViewGroup arg2) { // TODO Auto-generated method stub if(arg1==null){ arg1=LayoutInflater.from(context).inflate(R.layout.book_item, null); } TextView _context=(TextView) arg1.findViewById(R.id.content); TextView _datetime=(TextView) arg1.findViewById(R.id.datetime); UserInfo u=userInfos.get(arg0); _context.setText(u.getContent()); _datetime.setText(u.getDatetime()); return arg1; } } ``` Activity的: ``` public class MainActivity extends Activity implements OnClickListener{ Button add; Button re; SQLiteDatabase db; ListView listView; MyAdapter adapter; List<UserInfo> liUse; protected void onRestart() { // TODO Auto-generated method stub super.onRestart(); shuaxin(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); DbInit(); add=(Button) findViewById(R.id.add); listView=(ListView) findViewById(R.id.lv); registerForContextMenu(listView); adapter=new MyAdapter(this , liUse); listView.setAdapter(adapter); } public List<UserInfo> selectAll(){ List<UserInfo> ls=new ArrayList<UserInfo>(); Cursor cur=db.rawQuery(" select * from user ", null); while (cur.moveToNext()) { UserInfo u = new UserInfo(); u.setId(cur.getInt(cur.getColumnIndex("_id"))); u.setContent(cur.getString(cur.getColumnIndex("content"))); u.setDatetime(cur.getString(cur.getColumnIndex("datetime"))); ls.add(u); } return liUse; } @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 void onClick(View arg0) { // TODO Auto-generated method stub switch (arg0.getId()) { case R.id.refresh: shuaxin(); break; case R.id.add: Intent intent=new Intent(this,AddConActivity.class); startActivity(intent); break; default: break; } } public void DbInit(){ DBHelper dbHelper=new DBHelper(this, "Cotext.db", null, 1); db=dbHelper.getWritableDatabase(); } class DBHelper extends SQLiteOpenHelper{ public DBHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase arg0) { // TODO Auto-generated method stub SimpleDateFormat formatter = new SimpleDateFormat ("yyyy年MM月dd日 HH:mm:ss "); Date curDate = new Date(System.currentTimeMillis());//获取当前时间 String str = formatter.format(curDate); arg0.execSQL("create table user ( _id integer primary key autoincrement , datetime text not null , content varchar(100))"); ContentValues cv=new ContentValues(); cv.put("datetime", str); cv.put("content", "测试"); arg0.insert("user", "datetime", cv); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub } } private void shuaxin() { liUse=selectAll(); adapter.setcotext(liUse); adapter.notifyDataSetInvalidated(); } } ``` get 和 set : ``` public class UserInfo implements Serializable{ private int id; private String datetime; private String content; public UserInfo() { // TODO Auto-generated constructor stub } public UserInfo(int id,String datetime,String content) { // TODO Auto-generated constructor stub this.setId(id); this.setContent(content); this.setDatetime(datetime); } public UserInfo(String datetime,String content) { // TODO Auto-generated constructor stub this.setContent(content); this.setDatetime(datetime); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getDatetime() { return datetime; } public void setDatetime(String datetime) { this.datetime = datetime; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } } 异常 ``` 04-23 16:48:45.585: E/AndroidRuntime(1823): FATAL EXCEPTION: main 04-23 16:48:45.585: E/AndroidRuntime(1823): Process: com.example.notepad, PID: 1823 04-23 16:48:45.585: E/AndroidRuntime(1823): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.notepad/com.example.notepad.MainActivity}: java.lang.NullPointerException 04-23 16:48:45.585: E/AndroidRuntime(1823): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2219) 04-23 16:48:45.585: E/AndroidRuntime(1823): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269) 04-23 16:48:45.585: E/AndroidRuntime(1823): at android.app.ActivityThread.access$800(ActivityThread.java:135) 04-23 16:48:45.585: E/AndroidRuntime(1823): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 04-23 16:48:45.585: E/AndroidRuntime(1823): at android.os.Handler.dispatchMessage(Handler.java:102) 04-23 16:48:45.585: E/AndroidRuntime(1823): at android.os.Looper.loop(Looper.java:136) 04-23 16:48:45.585: E/AndroidRuntime(1823): at android.app.ActivityThread.main(ActivityThread.java:5045) 04-23 16:48:45.585: E/AndroidRuntime(1823): at java.lang.reflect.Method.invokeNative(Native Method) 04-23 16:48:45.585: E/AndroidRuntime(1823): at java.lang.reflect.Method.invoke(Method.java:515) 04-23 16:48:45.585: E/AndroidRuntime(1823): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 04-23 16:48:45.585: E/AndroidRuntime(1823): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 04-23 16:48:45.585: E/AndroidRuntime(1823): at dalvik.system.NativeStart.main(Native Method) 04-23 16:48:45.585: E/AndroidRuntime(1823): Caused by: java.lang.NullPointerException 04-23 16:48:45.585: E/AndroidRuntime(1823): at com.example.notepad.MyAdapter.getCount(MyAdapter.java:29) 04-23 16:48:45.585: E/AndroidRuntime(1823): at android.widget.ListView.setAdapter(ListView.java:480) 04-23 16:48:45.585: E/AndroidRuntime(1823): at com.example.notepad.MainActivity.onCreate(MainActivity.java:44) 04-23 16:48:45.585: E/AndroidRuntime(1823): at android.app.Activity.performCreate(Activity.java:5231) 04-23 16:48:45.585: E/AndroidRuntime(1823): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104) 04-23 16:48:45.585: E/AndroidRuntime(1823): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2163) 04-23 16:48:45.585: E/AndroidRuntime(1823): ... 11 more ```
关于在listview中隐藏item的某控件
我自定义了一个listview 现在想隐藏其中每个item的某个控件 adapter代码如下 ``` public abstract class MyAdapter<T> extends BaseAdapter { private ArrayList<T> mData; private int mLayoutRes; //布局id public MyAdapter() { } public MyAdapter(ArrayList<T> mData, int mLayoutRes) { this.mData = mData; this.mLayoutRes = mLayoutRes; } @Override public int getCount() { return mData != null ? mData.size() : 0; } @Override public T getItem(int position) { return mData.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = ViewHolder.bind(parent.getContext(), convertView, parent, mLayoutRes , position); bindView(holder, getItem(position)); return holder.getItemView(); } public abstract void bindView(ViewHolder holder, T obj); //添加一个元素 public void add(T data) { if (mData == null) { mData = new ArrayList<T>(); } mData.add(data); notifyDataSetChanged(); } //往特定位置,添加一个元素 public void add(int position, T data) { if (mData == null) { mData = new ArrayList<T>(); } mData.add(position, data); notifyDataSetChanged(); } public void remove(T data) { if (mData != null) { mData.remove(data); } notifyDataSetChanged(); } public void remove(int position) { if (mData != null) { mData.remove(position); } notifyDataSetChanged(); } public void clear() { if (mData != null) { mData.clear(); } notifyDataSetChanged(); } public static class ViewHolder { private SparseArray<View> mViews; //存储ListView 的 item中的View private View item; //存放convertView private int position; //游标 private Context context; //Context上下文 //构造方法,完成相关初始化 private ViewHolder(Context context, ViewGroup parent, int layoutRes) { mViews = new SparseArray<View>(); this.context = context; View convertView = LayoutInflater.from(context).inflate(layoutRes, parent, false); convertView.setTag(this); item = convertView; } //绑定ViewHolder与item public static ViewHolder bind(Context context, View convertView, ViewGroup parent, int layoutRes, int position) { ViewHolder holder; if (convertView == null) { holder = new ViewHolder(context, parent, layoutRes); } else { holder = (ViewHolder) convertView.getTag(); holder.item = convertView; } holder.position = position; return holder; } @SuppressWarnings("unchecked") public <T extends View> T getView(int id) { T t = (T) mViews.get(id); if (t == null) { t = (T) item.findViewById(id); mViews.put(id, t); } return t; } /** * 获取当前条目 */ public View getItemView() { return item; } /** * 获取条目位置 */ public int getItemPosition() { return position; } /** * 设置文字 */ public ViewHolder setText(int id, CharSequence text) { View view = getView(id); if (view instanceof TextView) { ((TextView) view).setText(text); } return this; } /** * 设置图片 */ public ViewHolder setImageResource(int id, int drawableRes) { View view = getView(id); if (view instanceof ImageView) { ((ImageView) view).setImageResource(drawableRes); } else { view.setBackgroundResource(drawableRes); } return this; } /** * 设置点击监听 */ public ViewHolder setOnClickListener(int id, View.OnClickListener listener) { getView(id).setOnClickListener(listener); return this; } /** * 设置可见 */ public ViewHolder setVisibility(int id, int visible) { getView(id).setVisibility(visible); return this; } /** * 设置标签 */ public ViewHolder setTag(int id, Object obj) { getView(id).setTag(obj); return this; } } } ``` 我在activity中设置了 ``` lv_NowOrder = (ListView) findViewById(R.id.lv_Order); mData = new ArrayList<Order_Now>(); myAdapter = new MyAdapter<Order_Now>((ArrayList<Order_Now>)mData,R.layout.item_myorder) { @Override public void bindView(final ViewHolder holder, final Order_Now obj) { LinearLayout layout = findViewById(R.id.openMap);//openMap是item的一个控件 layout.setVisibility(View.GONE); } ``` 但是并不能生效 在activity的oncreat方法中设置 ``` LinearLayout layout = findViewById(R.id.openMap); layout.setVisibility(View.GONE); ``` 报空指针异常 我该怎么隐藏这个openMap控件呢
Android自定义控件中为Button设置自定义监听器出现空指针。
Android自定义TopBar中给ImageButton设置自定义点击监听器,当点击ImageButton时在listener处出现NullPointerException。 会出错的地方我在后面写了//TODO 。 请问为什么会出现listener没有被实例化的情况? 还有为什么在MainActivity中使用findViewById实例化TopBar也会出现不能实例化控件的情况? IDE : Android Studio ; Compile Sdk Version : API 23 ; Build Tool Version : 23.0.1 ; Min Sdk Version : API 15 ; Target Sdk Version : API 19 ; 部分代码: #MainActivity.java ``` public class MainActivity extends AppCompatActivity { private TopBar topBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // topBar = (TopBar) findViewById(R.id.topBar); //TODO 这样无法实例化topBar ??? topBar = new TopBar(getApplicationContext(), null); if (topBar == null) { Toast.makeText(MainActivity.this, "NULL", Toast.LENGTH_SHORT).show(); } topBar.setOnTopBarClickListener(new TopBar.OnClickListener() { @Override public void onLeftButtonClick() { Toast.makeText(MainActivity.this, "Left", Toast.LENGTH_SHORT).show(); } @Override public void onRightButtonClick() { Toast.makeText(MainActivity.this, "Right", Toast.LENGTH_SHORT).show(); } }); } } ``` #TopBar.java ``` public class TopBar extends RelativeLayout { private ImageButton ibtLeft; private ImageButton ibtRight; private TextView tvTitle; private OnClickListener listener; public interface OnClickListener { void onLeftButtonClick(); void onRightButtonClick(); } public void setOnTopBarClickListener(OnClickListener listener) { this.listener = listener; } public TopBar(Context context, AttributeSet attrs) { super(context); LayoutInflater.from(context).inflate(R.layout.layout_top_bar, this); ibtLeft = (ImageButton) findViewById(R.id.ibt_left); ibtRight = (ImageButton) findViewById(R.id.ibt_right); tvTitle = (TextView) findViewById(R.id.tv_title); ibtLeft.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getContext(), "leftButton", Toast.LENGTH_SHORT).show(); //Toast可以显示 // listener.onLeftButtonClick(); //TODO NullPointerException 为什么没有实例化listener? } }); ibtRight.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listener.onRightButtonClick(); //TODO NullPointerException } }); } } ``` #logcat输出 ``` 10-14 13:42:14.442 1366-1366/com.vder.puzzlegame E/AndroidRuntime: FATAL EXCEPTION: main 10-14 13:42:14.442 1366-1366/com.vder.puzzlegame E/AndroidRuntime: java.lang.NullPointerException 10-14 13:42:14.442 1366-1366/com.vder.puzzlegame E/AndroidRuntime: at com.vder.puzzlegame.ui.TopBar$2.onClick(TopBar.java:55) 10-14 13:42:14.442 1366-1366/com.vder.puzzlegame E/AndroidRuntime: at android.view.View.performClick(View.java:4204) 10-14 13:42:14.442 1366-1366/com.vder.puzzlegame E/AndroidRuntime: at android.view.View$PerformClick.run(View.java:17355) 10-14 13:42:14.442 1366-1366/com.vder.puzzlegame E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:725) 10-14 13:42:14.442 1366-1366/com.vder.puzzlegame E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:92) 10-14 13:42:14.442 1366-1366/com.vder.puzzlegame E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137) 10-14 13:42:14.442 1366-1366/com.vder.puzzlegame E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5041) 10-14 13:42:14.442 1366-1366/com.vder.puzzlegame E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method) 10-14 13:42:14.442 1366-1366/com.vder.puzzlegame E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:511) 10-14 13:42:14.442 1366-1366/com.vder.puzzlegame E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 10-14 13:42:14.442 1366-1366/com.vder.puzzlegame E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 10-14 13:42:14.442 1366-1366/com.vder.puzzlegame E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method) ```
((ImageView)viewHolder.image).setImageResource(id)
package com.tyut.gridview01; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class PictureActivity extends Activity { private String[] titles = {"MM1","MM2","MM3","MM4","MM5","MM6","MM7","MM8","MM9","MM10"}; private Integer[] ps =new Integer[]{R.drawable.g1,R.drawable.g2,R.drawable.g3,R.drawable.g4,R.drawable.g5,R.drawable.g6,R.drawable.g7,R.drawable.g8,R.drawable.g9,R.drawable.g10}; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_grid); GridView grid = (GridView) findViewById(R.id.grid); grid.setAdapter(new PictureAdapter(titles, ps, this)); grid.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { Log.i("MainActivity", "position:"+position); Toast.makeText(PictureActivity.this, " "+position, Toast.LENGTH_SHORT).show(); } }); } } class PictureAdapter extends BaseAdapter{ private static final String TAG = "MainActivity"; private LayoutInflater inflater; private List<Picture> pictures; public PictureAdapter(String[] titles ,Integer[] ps,Context context){ super(); pictures = new ArrayList<Picture>(); inflater = LayoutInflater.from(context); for (int i = 0; i < ps.length; i++) { Picture p = new Picture(titles[i],ps[i]); pictures.add(p); } } @Override public int getCount() { // TODO Auto-generated method stub if (null !=pictures) { return pictures.size(); }else{ return 0; } } @Override public Object getItem(int position) { // TODO Auto-generated method stub return pictures.get(position); } @Override public long getItemId(int id) { // TODO Auto-generated method stub return id; } @Override public View getView(int position, View convertview, ViewGroup arg2) { // TODO Auto-generated method stub ViewHolder viewHolder; if (convertview == null) { convertview = inflater.inflate(R.layout.activity_griditem, null); viewHolder = new ViewHolder(); Picture pic =pictures.get(position); int id = pic.getId(); _## ((ImageView)viewHolder.image).setImageResource(id);_ String t =pic.getTitle(); ((TextView)viewHolder.title).setText(t); convertview.setTag(viewHolder); }else{ viewHolder = (ViewHolder) convertview.getTag(); } viewHolder.title.setText(pictures.get(position).getTitle()); viewHolder.image.setImageResource(pictures.get(position).getId()); Log.i(TAG, "<<<<<<<<"+position); return convertview; } class ViewHolder{ public TextView title; public ImageView image; } public class Picture { private String title; private int id ; public Picture(String title,int id){ this.title =title; this.id =id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getId() { return id; } public void setId(int id) { this.id = id; } } } 问题: ## ((ImageView)viewHolder.image).setImageResource(id); 说空指针异常
关于安卓ListView与CheckBox结合
这是我走定义的适配器,为什么说在设置check状态的时候是空指针呀 public class MyAdapter extends BaseAdapter { private ArrayList<Item> list; //记录和控制选中状态 private static HashMap<Integer,Boolean> isSelected; //上下文 private Context context; //为子项导入布局 private LayoutInflater inflater; public MyAdapter(ArrayList<Item> list,Context context) { this.list = list; this.context = context; inflater = LayoutInflater.from(context); isSelected = new HashMap<Integer, Boolean>(); //初始化状态 initDate(); } private void initDate() { for(int i=0; i<list.size();i++) { getIsSelected().put(i,false); } } @Override public int getCount() { // TODO Auto-generated method stub return list.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return list.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(final int position, View convertview,ViewGroup parent) { ViewHolder holder ; if(convertview == null) { // 获得ViewHolder对象 holder = new ViewHolder(); // 导入布局并赋值给convertview convertview = inflater.inflate(R.layout.item_layout, null); holder.project_name = (TextView) convertview.findViewById(R.id.project_name); holder.project_result = (TextView) convertview.findViewById(R.id.project_result); holder.project_resultval = (TextView) convertview.findViewById(R.id.project_resultval); holder.cbox = (CheckBox) convertview.findViewById(R.id.box); holder.cbox.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (isSelected.get(position)) { isSelected.put(position, false); setIsSelected(isSelected); } else { isSelected.put(position, true); setIsSelected(isSelected); } } }); // 为view设置标签 convertview.setTag(holder); } else { holder = (ViewHolder) convertview.getTag(); } holder.project_name.setText(list.get(position).getproject_name()); holder.project_result.setText(list.get(position).getproject_result()); holder.project_resultval.setText(list.get(position).getproject_resultval()); // 根据isSelected来设置checkbox的选中状况 holder.cbox.setChecked(getIsSelected().get(position)); return convertview; } public static HashMap<Integer,Boolean> getIsSelected() { return isSelected; } public static void setIsSelected(HashMap<Integer,Boolean> isSelected) { MyAdapter.isSelected = isSelected; } public final class ViewHolder { public TextView project_name; public TextView project_result; public TextView project_resultval; public CheckBox cbox; } } ![图片说明](https://img-ask.csdn.net/upload/201601/22/1453453627_715696.png)
火大,快崩溃了,这段自定义adapter到底错在哪里啊!!
以下是源码 ``` import java.util.List; import java.util.zip.Inflater; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; public class AdapterPerson extends ArrayAdapter<NewPerson> { Context context; List<NewPerson> persons; int res; public AdapterPerson(Context context, int resource, List<NewPerson> objects) { super(context, resource, objects); context = this.context; persons = objects; res = resource; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub NewPerson person = getItem(position); Holder holder; if(convertView == null){ convertView = View.inflate(context, res, null); //就是这一行在报错空指针异常,但是我死活看不出哪里有空指针异常啊,资源文件也是能链接过去的 holder = new Holder(); holder.age = (TextView) convertView.findViewById(R.id.age); holder.name = (TextView) convertView.findViewById(R.id.name); holder.sex = (TextView) convertView.findViewById(R.id.sex); holder.info = (TextView) convertView.findViewById(R.id.info); convertView.setTag(holder); }else{ holder = (Holder)convertView.getTag(); } holder.name.setText(person.getName()); holder.age.setText(person.getAge()); holder.info.setText(person.getInfo()); return convertView; } private static class Holder { TextView name, age, sex, info; } } ``` 01-17 07:57:48.636: E/AndroidRuntime(17863): FATAL EXCEPTION: main 01-17 07:57:48.636: E/AndroidRuntime(17863): Process: com.sz.sqlitedemo1, PID: 17863 01-17 07:57:48.636: E/AndroidRuntime(17863): java.lang.NullPointerException 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.view.LayoutInflater.from(LayoutInflater.java:211) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.view.View.inflate(View.java:18048) 01-17 07:57:48.636: E/AndroidRuntime(17863): at com.sz.sqlitedemo1.AdapterPerson.getView(AdapterPerson.java:42) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.widget.AbsListView.obtainView(AbsListView.java:3065) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.widget.ListView.makeAndAddView(ListView.java:2125) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.widget.ListView.fillDown(ListView.java:940) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.widget.ListView.fillFromTop(ListView.java:1025) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.widget.ListView.layoutChildren(ListView.java:1949) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.widget.AbsListView.onLayout(AbsListView.java:2897) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.view.View.layout(View.java:15348) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.view.ViewGroup.layout(ViewGroup.java:4662) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.widget.LinearLayout.onLayout(LinearLayout.java:1434) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.view.View.layout(View.java:15348) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.view.ViewGroup.layout(ViewGroup.java:4662) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1055) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.view.View.layout(View.java:15348) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.view.ViewGroup.layout(ViewGroup.java:4662) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.widget.FrameLayout.onLayout(FrameLayout.java:388) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.view.View.layout(View.java:15348) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.view.ViewGroup.layout(ViewGroup.java:4662) 01-17 07:57:48.636: E/AndroidRuntime(17863): at com.android.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:413) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.view.View.layout(View.java:15348) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.view.ViewGroup.layout(ViewGroup.java:4662) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.widget.FrameLayout.onLayout(FrameLayout.java:388) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.view.View.layout(View.java:15348) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.view.ViewGroup.layout(ViewGroup.java:4662) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2355) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2066) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1060) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6175) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.view.Choreographer.doCallbacks(Choreographer.java:580) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.view.Choreographer.doFrame(Choreographer.java:550) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.os.Handler.handleCallback(Handler.java:733) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.os.Handler.dispatchMessage(Handler.java:95) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.os.Looper.loop(Looper.java:136) 01-17 07:57:48.636: E/AndroidRuntime(17863): at android.app.ActivityThread.main(ActivityThread.java:5054) 01-17 07:57:48.636: E/AndroidRuntime(17863): at java.lang.reflect.Method.invokeNative(Native Method) 01-17 07:57:48.636: E/AndroidRuntime(17863): at java.lang.reflect.Method.invoke(Method.java:515) 01-17 07:57:48.636: E/AndroidRuntime(17863): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) 01-17 07:57:48.636: E/AndroidRuntime(17863): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 01-17 07:57:48.636: E/AndroidRuntime(17863): at dalvik.system.NativeStart.main(Native Method)
Android程序在手机上运行崩溃但是在模拟器上能运行但是还有一个模拟器也是崩溃的
package darkhorse.english.app; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.AutoCompleteTextView; import android.widget.CursorAdapter; import android.widget.ImageButton; import android.widget.TextView; public class LookupActivity extends Activity implements OnClickListener, TextWatcher { private final String DATABASE_PATH = android.os.Environment .getExternalStorageDirectory().getAbsolutePath() + "/dictionary"; private AutoCompleteTextView autocompletetextview; private final String DATABASE_FILENAME = "dictionary.db"; private SQLiteDatabase database; private ImageButton lookupbutton; private TextView textview; private ImageButton clearbutton; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.lookup_layout); database = openDatabase(); lookupbutton = (ImageButton) findViewById(R.id.lookupbutton); textview = (TextView) findViewById(R.id.textview); clearbutton = (ImageButton) findViewById(R.id.clearbutton); autocompletetextview = (AutoCompleteTextView) findViewById(R.id.autocompletetextview); lookupbutton.setOnClickListener(this); autocompletetextview.addTextChangedListener(this); clearbutton.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { // TODO Auto-generated method stub autocompletetextview.setText(""); textview.setText(""); } }); } public class DictionaryAdapter extends CursorAdapter { private LayoutInflater layoutInflater; @Override public CharSequence convertToString(Cursor cursor) { return cursor == null ? "" : cursor.getString(cursor.getColumnIndex("_id")); } private void setView(View view, Cursor cursor) { TextView tvWordItem = (TextView) view; tvWordItem.setText(cursor.getString(cursor.getColumnIndex("_id"))); } @Override public void bindView(View view, Context context, Cursor cursor) { setView(view, cursor); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = layoutInflater.inflate(R.layout.word_list_item, null); setView(view, cursor); return view; } public DictionaryAdapter(Context context, Cursor c, boolean autoRequery) { super(context, c, autoRequery); layoutInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } } public void afterTextChanged(Editable s) { // 必须将English字段的别名设为_id Cursor cursor = database.rawQuery( "select english as _id from t_words where english like ?", new String[] { s.toString() + "%" }); DictionaryAdapter dictionaryAdapter = new DictionaryAdapter(this, cursor, true); autocompletetextview.setAdapter(dictionaryAdapter); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } public void onClick(View view) { String sql = "select chinese from t_words where english=?"; Cursor cursor = database.rawQuery(sql, new String[] { autocompletetextview.getText().toString() }); String result = "未找到该单词."; // 如果查找单词,显示其中文的意思 if (cursor.getCount() > 0) { // 必须使用moveToFirst方法将记录指针移动到第1条记录的位置 cursor.moveToFirst(); result = cursor.getString(cursor.getColumnIndex("chinese")); } // 显示查询结果对话框 textview.setText(result); } private SQLiteDatabase openDatabase() { try { // 获得dictionary.db文件的绝对路径 String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME; File dir = new File(DATABASE_PATH); // 如果/sdcard/dictionary目录中存在,创建这个目录 if (!dir.exists()) dir.mkdir(); // 如果在/sdcard/dictionary目录中不存在 // dictionary.db文件,则从res\raw目录中复制这个文件到 // SD卡的目录(/sdcard/dictionary) if (!(new File(databaseFilename)).exists()) { // 获得封装dictionary.db文件的InputStream对象 InputStream is = getResources().openRawResource( R.raw.dictionary); FileOutputStream fos = new FileOutputStream(databaseFilename); byte[] buffer = new byte[8192]; int count = 0; // 开始复制dictionary.db文件 while ((count = is.read(buffer)) > 0) { fos.write(buffer, 0, count); } fos.close(); is.close(); } // 打开/sdcard/dictionary目录中的dictionary.db文件 SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase( databaseFilename, null); return database; } catch (Exception e) { } return null; } } 求高手给看看
为什么我自制的andriod词典一输入就退出
package com.aaaa.aaaa; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.CursorAdapter; import android.widget.TextView; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class MainActivity extends Activity implements OnClickListener, TextWatcher { // 定义数据库的存放路径 private final String DATABASE_PATH = android.os.Environment .getExternalStorageDirectory().getAbsolutePath() + "/dictionary"; // 用户输入文本框 private AutoCompleteTextView word; // 定义数据库的名字 private final String DATABASE_FILENAME = "dictionary.db"; private SQLiteDatabase database; private Button searchWord; // 用户显示查询结果 private TextView showResult; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 打开数据库 database = openDatabase(); searchWord = (Button) findViewById(R.id.searchWord); word = (AutoCompleteTextView) findViewById(R.id.word); // 绑定监听器 searchWord.setOnClickListener(this); word.addTextChangedListener(this); showResult = (TextView) findViewById(R.id.result); } public class DictionaryAdapter extends CursorAdapter { private LayoutInflater layoutInflater; public DictionaryAdapter(Context context, Cursor c, boolean flags) { super(context, c, flags); layoutInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public CharSequence convertToString(Cursor cursor) { return cursor == null ? "" : cursor.getString(cursor .getColumnIndex("_id")); } // 生成新的选项 @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = layoutInflater.inflate(R.layout.word_list_item, null); setView(view, cursor); return view; } // 绑定选项到列表中 @Override public void bindView(View view, Context context, Cursor cursor) { setView(view, cursor); } // 将单词信息显示到列表中 private void setView(View view, Cursor cursor) { TextView tvWordItem = (TextView) view; tvWordItem.setText(cursor.getString(cursor.getColumnIndex("_id"))); } } // 打开数据库 private SQLiteDatabase openDatabase() { try { // 获得dictionary.db文件的绝对路径 String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME; File dir = new File(DATABASE_PATH); // 如果目录不存在,则创建这个目录 if (!dir.exists()) { dir.mkdir(); } // 如果在/sdcard/dictionary目录中不存在 // dictionary.db文件,则从res\raw目录中复制这个文件到 // SD卡的目录(/sdcard/dictionary) if (!(new File(databaseFilename)).exists()) { // 获得封装dictionary.db文件的InputStream对象 InputStream is = getResources().openRawResource( R.raw.dictionary); FileOutputStream fos = new FileOutputStream(databaseFilename); byte[] buffer = new byte[8192]; int count = 0; // 开始复制dictionary.db文件 while ((count = is.read(buffer)) > 0) { fos.write(buffer, 0, count); } // 关闭文件流 fos.close(); is.close(); } // 打开/sdcard/dictionary目录中的dictionary.db文件 SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase( databaseFilename, null); return database; } catch (Exception e) { e.printStackTrace(); } return null; } @Override public void onClick(View v) { // 查询指定的单词 String sql = "select chinese from t_words where english=?"; Cursor cursor = database.rawQuery(sql, new String[] { word.getText() .toString() }); String result = "未找到该单词."; // 如果查找单词,显示其中文的意思 if (cursor.getCount() > 0) { // 必须使用moveToFirst方法将记录指针移动到第1条记录的位置 cursor.moveToFirst(); result = cursor.getString(cursor.getColumnIndex("chinese")) .replace("&", "&"); } // 将结果显示到TextView中 showResult.setText(word.getText() + "\n" + result.toString()); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { // 必须将english字段的别名设为_id Cursor cursor = database.rawQuery( "select english as _id from t_words where english like ?", new String[] { s.toString() + "%" }); // 新建新的Adapter DictionaryAdapter dictionaryAdapter = new DictionaryAdapter(this, cursor, true); // 绑定适配器 word.setAdapter(dictionaryAdapter); } }
爬虫福利二 之 妹子图网MM批量下载
爬虫福利一:27报网MM批量下载    点击 看了本文,相信大家对爬虫一定会产生强烈的兴趣,激励自己去学习爬虫,在这里提前祝:大家学有所成! 目标网站:妹子图网 环境:Python3.x 相关第三方模块:requests、beautifulsoup4 Re:各位在测试时只需要将代码里的变量 path 指定为你当前系统要保存的路径,使用 python xxx.py 或IDE运行即可。
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、PDF搜索网站推荐 对于大部
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 顺便拉下票,我在参加csdn博客之星竞选,欢迎投票支持,每个QQ或者微信每天都可以投5票,扫二维码即可,http://m234140.nofollow.ax.
比特币原理详解
一、什么是比特币 比特币是一种电子货币,是一种基于密码学的货币,在2008年11月1日由中本聪发表比特币白皮书,文中提出了一种去中心化的电子记账系统,我们平时的电子现金是银行来记账,因为银行的背后是国家信用。去中心化电子记账系统是参与者共同记账。比特币可以防止主权危机、信用风险。其好处不多做赘述,这一层面介绍的文章很多,本文主要从更深层的技术原理角度进行介绍。 二、问题引入  假设现有4个人
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 欢迎 改进 留言。 演示地点跳到演示地点 html代码如下`&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;music&lt;/title&gt; &lt;meta charset="utf-8"&gt
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。 1. for - else 什么?不是 if 和 else 才
数据库优化 - SQL优化
前面一篇文章从实例的角度进行数据库优化,通过配置一些参数让数据库性能达到最优。但是一些“不好”的SQL也会导致数据库查询变慢,影响业务流程。本文从SQL角度进行数据库优化,提升SQL运行效率。 判断问题SQL 判断SQL是否有问题时可以通过两个表象进行判断: 系统级别表象 CPU消耗严重 IO等待严重 页面响应时间过长
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 c/c++ 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7
通俗易懂地给女朋友讲:线程池的内部原理
餐厅的约会 餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”我楞了一下,心里想女朋友今天是怎么了,怎么突然问出这么专业的问题,但做为一个专业人士在女朋友面前也不能露怯啊,想了一下便说:“我先给你讲讲我前同事老王的故事吧!” 大龄程序员老王 老王是一个已经北漂十多年的程序员,岁数大了,加班加不动了,升迁也无望,于是拿着手里
经典算法(5)杨辉三角
写在前面: 我是 扬帆向海,这个昵称来源于我的名字以及女朋友的名字。我热爱技术、热爱开源、热爱编程。技术是开源的、知识是共享的。 这博客是对自己学习的一点点总结及记录,如果您对 Java、算法 感兴趣,可以关注我的动态,我们一起学习。 用知识改变命运,让我们的家人过上更好的生活。 目录一、杨辉三角的介绍二、杨辉三角的算法思想三、代码实现1.第一种写法2.第二种写法 一、杨辉三角的介绍 百度
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹
面试官:你连RESTful都不知道我怎么敢要你?
面试官:了解RESTful吗? 我:听说过。 面试官:那什么是RESTful? 我:就是用起来很规范,挺好的 面试官:是RESTful挺好的,还是自我感觉挺好的 我:都挺好的。 面试官:… 把门关上。 我:… 要干嘛?先关上再说。 面试官:我说出去把门关上。 我:what ?,夺门而去 文章目录01 前言02 RESTful的来源03 RESTful6大原则1. C-S架构2. 无状态3.统一的接
为啥国人偏爱Mybatis,而老外喜欢Hibernate/JPA呢?
关于SQL和ORM的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行了一番讨论,感触还是有一些,于是就有了今天这篇文。 声明:本文不会下关于Mybatis和JPA两个持久层框架哪个更好这样的结论。只是摆事实,讲道理,所以,请各位看官勿喷。 一、事件起因 关于Mybatis和JPA孰优孰劣的问题,争论已经很多年了。一直也没有结论,毕竟每个人的喜好和习惯是大不相同的。我也看
SQL-小白最佳入门sql查询一
一 说明 如果是初学者,建议去网上寻找安装Mysql的文章安装,以及使用navicat连接数据库,以后的示例基本是使用mysql数据库管理系统; 二 准备前提 需要建立一张学生表,列分别是id,名称,年龄,学生信息;本示例中文章篇幅原因SQL注释略; 建表语句: CREATE TABLE `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // dosho
【图解经典算法题】如何用一行代码解决约瑟夫环问题
约瑟夫环问题算是很经典的题了,估计大家都听说过,然后我就在一次笔试中遇到了,下面我就用 3 种方法来详细讲解一下这道题,最后一种方法学了之后保证让你可以让你装逼。 问题描述:编号为 1-N 的 N 个士兵围坐在一起形成一个圆圈,从编号为 1 的士兵开始依次报数(1,2,3…这样依次报),数到 m 的 士兵会被杀死出列,之后的士兵再从 1 开始报数。直到最后剩下一士兵,求这个士兵的编号。 1、方
致 Python 初学者
文章目录1. 前言2. 明确学习目标,不急于求成,不好高骛远3. 在开始学习 Python 之前,你需要做一些准备2.1 Python 的各种发行版2.2 安装 Python2.3 选择一款趁手的开发工具3. 习惯使用IDLE,这是学习python最好的方式4. 严格遵从编码规范5. 代码的运行、调试5. 模块管理5.1 同时安装了py2/py35.2 使用Anaconda,或者通过IDE来安装模
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,
程序员:我终于知道post和get的区别
IT界知名的程序员曾说:对于那些月薪三万以下,自称IT工程师的码农们,其实我们从来没有把他们归为我们IT工程师的队伍。他们虽然总是以IT工程师自居,但只是他们一厢情愿罢了。 此话一出,不知激起了多少(码农)程序员的愤怒,却又无可奈何,于是码农问程序员。 码农:你知道get和post请求到底有什么区别? 程序员:你看这篇就知道了。 码农:你月薪三万了? 程序员:嗯。 码农:你是怎么做到的? 程序员:
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU
加快推动区块链技术和产业创新发展,2019可信区块链峰会在京召开
      11月8日,由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办,科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。   区块链技术被认为是继蒸汽机、电力、互联网之后,下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力,电力解决了人类基本的生活需求,互联网彻底改变了信息传递的方式,区块链作为构造信任的技术有重要的价值。   1
程序员把地府后台管理系统做出来了,还有3.0版本!12月7号最新消息:已在开发中有github地址
第一幕:缘起 听说阎王爷要做个生死簿后台管理系统,我们派去了一个程序员…… 996程序员做的梦: 第一场:团队招募 为了应对地府管理危机,阎王打算找“人”开发一套地府后台管理系统,于是就在地府总经办群中发了项目需求。 话说还是中国电信的信号好,地府都是满格,哈哈!!! 经常会有外行朋友问:看某网站做的不错,功能也简单,你帮忙做一下? 而这次,面对这样的需求,这个程序员
网易云6亿用户音乐推荐算法
网易云音乐是音乐爱好者的集聚地,云音乐推荐系统致力于通过 AI 算法的落地,实现用户千人千面的个性化推荐,为用户带来不一样的听歌体验。 本次分享重点介绍 AI 算法在音乐推荐中的应用实践,以及在算法落地过程中遇到的挑战和解决方案。 将从如下两个部分展开: AI 算法在音乐推荐中的应用 音乐场景下的 AI 思考 从 2013 年 4 月正式上线至今,网易云音乐平台持续提供着:乐屏社区、UGC
【技巧总结】位运算装逼指南
位算法的效率有多快我就不说,不信你可以去用 10 亿个数据模拟一下,今天给大家讲一讲位运算的一些经典例子。不过,最重要的不是看懂了这些例子就好,而是要在以后多去运用位运算这些技巧,当然,采用位运算,也是可以装逼的,不信,你往下看。我会从最简单的讲起,一道比一道难度递增,不过居然是讲技巧,那么也不会太难,相信你分分钟看懂。 判断奇偶数 判断一个数是基于还是偶数,相信很多人都做过,一般的做法的代码如下
日均350000亿接入量,腾讯TubeMQ性能超过Kafka
整理 | 夕颜出品 | AI科技大本营(ID:rgznai100) 【导读】近日,腾讯开源动作不断,相继开源了分布式消息中间件TubeMQ,基于最主流的 OpenJDK8开发的
8年经验面试官详解 Java 面试秘诀
    作者 | 胡书敏 责编 | 刘静 出品 | CSDN(ID:CSDNnews) 本人目前在一家知名外企担任架构师,而且最近八年来,在多家外企和互联网公司担任Java技术面试官,前后累计面试了有两三百位候选人。在本文里,就将结合本人的面试经验,针对Java初学者、Java初级开发和Java开发,给出若干准备简历和准备面试的建议。   Java程序员准备和投递简历的实
面试官如何考察你的思维方式?
1.两种思维方式在求职面试中,经常会考察这种问题:北京有多少量特斯拉汽车? 某胡同口的煎饼摊一年能卖出多少个煎饼? 深圳有多少个产品经理? 一辆公交车里能装下多少个乒乓球? 一
so easy! 10行代码写个"狗屁不通"文章生成器
前几天,GitHub 有个开源项目特别火,只要输入标题就可以生成一篇长长的文章。背后实现代码一定很复杂吧,里面一定有很多高深莫测的机器学习等复杂算法不过,当我看了源代码之后这程序不到50
知乎高赞:中国有什么拿得出手的开源软件产品?(整理自本人原创回答)
知乎高赞:中国有什么拿得出手的开源软件产品? 在知乎上,有个问题问“中国有什么拿得出手的开源软件产品(在 GitHub 等社区受欢迎度较好的)?” 事实上,还不少呢~ 本人于2019.7.6进行了较为全面的 回答 - Bravo Yeung,获得该问题下回答中得最高赞(236赞和1枚专业勋章),对这些受欢迎的 Github 开源项目分类整理如下: 分布式计算、云平台相关工具类 1.SkyWalk
相关热词 c# clr dll c# 如何orm c# 固定大小的字符数组 c#框架设计 c# 删除数据库 c# 中文文字 图片转 c# 成员属性 接口 c#如何将程序封装 16进制负数转换 c# c#练手项目
立即提问