在android中,使用handler出现空指针异常

public class Floating_windowActivity extends Activity {
private SliderRelativeLayout sliderLayout = null;
private Handler mHandler =new Handler (){
public void handleMessage(Message msg){
Log.i(TAG, "handleMessage : #### " );
if(MSG_LOCK_SUCESS == msg.what){
closeLig();
android.os.Process.killProcess(android.os.Process.myPid());
}
super.handleMessage(msg);
}
};

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    sliderLayout = (SliderRelativeLayout)findViewById(R.id.slider_layout);
    sliderLayout.setMainHandler(mHandler); // 运行到这里报空指针异常,求大神解释。。。
}

}

public class SliderRelativeLayout extends RelativeLayout {
public Handler mainHandler = null;
public void setMainHandler(Handler handler){
mainHandler = handler;//activity所在的Handler对象
}

private void handleActionUpEvent(MotionEvent event){
    Message message = new Message();  

    message.what = 1;   
    mainHandler.sendMessage(message);
}

}

3个回答

首先你连View都没有,那么findViewById肯定是有问题的

你把super.handleMessage(msg); 移到上边试试。

还没setcontent?
拿不到sliderlayout

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
android安卓handler报空指针错

有2个按钮 一个是扫描一个查询 按扫描可以扫描二维码(二维码包含json信息)然后解析后显示在二维码信息那里 然后点查询 把二维码所含的json信息发送出去 得到返回值显示在返回信息那里 如果我只做查询 解析结果可以正常显示 如果我再点查询就会报一个空指针 说我解析那一步错 如果我不做解析 那发送也正常 有没有大神帮我看看为什么 错误信息 Process: com.abc.smartpos.cash, PID: 25086 java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference at com.abc.smartpos.cash.ScanQR.parseJSONWithGSONForQR(ScanQR.java:138) at com.abc.smartpos.cash.ScanQR$4.handleMessage(ScanQR.java:127) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5254) 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:902) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697) 我的代码 ``` String orderresult; Handler handler = new Handler() { public void handleMessage(Message msg) { super.handleMessage(msg); orderresult=msg.getData().getString("msg"); //单独执行parseJSONWithGSONForQR()正常显示,继续执行查询操作这里报空指针 parseJSONWithGSONForQR(orderresult); responseinfo.setText(msg.getData().getString("JSON")); } }; //解析扫描得到的JSON数据后设置textview public void parseJSONWithGSONForQR(String jsonData) { String showorder; Gson gson = new Gson(); List<TransPack> transPackList = gson.fromJson(jsonData, new TypeToken<List<TransPack>>() { }.getType()); for (TransPack transPack : transPackList) { showorder="订单号:"+transPack.getId().toString()+"\n"+"意向金:"+transPack.getIntention().toString()+"\n"+"进度款:"+transPack.getProgress().toString()+"\n"+"设计费:"+transPack.getDesign().toString(); orderinfo.setText(showorder); } } //开启新线程 public void queryOrder(){ new Thread(){ public void run(){ postJson(); } }.start(); } //发送JSON并得到返回值,用handler发送 public String responseJSON; public static final String TAG="ScanQR"; public static final MediaType JSON=MediaType.parse("application/json; charset=utf-8"); public void postJson(){ OkHttpClient okHttpClient=new OkHttpClient(); RequestBody requestBody=RequestBody.create(JSON,orderresult); Request request=new Request.Builder() .url("http://api.jisuapi.com/iqa/query") .post(requestBody) .build(); try{ Response response=okHttpClient.newCall(request).execute(); if(response.isSuccessful()){ Log.i(TAG,response.body().string()); responseJSON=response.toString(); Message msg=new Message(); msg.getData().putString("JSON",responseJSON); handler.sendMessage(msg); } }catch (IOException e){ e.printStackTrace(); } } ``` ![图片说明](https://img-ask.csdn.net/upload/201712/31/1514704455_550345.jpg)

Android RecyclerView滑动出现空指针异常

ViewPager里面是Fragment然后Fragment里面是RecyclerV但是可以正常显示列表,一旦滑动就会出现异常,这个是垂直方向的 然后里面还嵌套了一个水平方向的网格式RecyclerView没有显示出来!TIME=1429828195000 FINGERPRINT=Xiaomi/cancro_wc_lte/cancro:4.4.4/KTU84P/5.4.24:user/release-keys HARDWARE=qcom UNKNOWN=unknown RADIO=unknown BOARD=MSM8974 versionCode=1 PRODUCT=cancro_wc_lte versionName=1.0 DISPLAY=KTU84P USER=builder HOST=qh-miui-ota-bd56 DEVICE=cancro TAGS=release-keys MODEL=MI 4LTE BOOTLOADER=unknown CPU_ABI=armeabi-v7a CPU_ABI2=armeabi IS_DEBUGGABLE=true ID=KTU84P SERIAL=895f2f74 MANUFACTURER=Xiaomi BRAND=Xiaomi TYPE=user java.lang.NullPointerException at android.support.v4.view.ViewCompat$ICSViewCompatImpl.setAccessibilityDelegate(ViewCompat.java:923) at android.support.v4.view.ViewCompat.setAccessibilityDelegate(ViewCompat.java:1343) at android.support.v7.widget.RecyclerView$Recycler.addViewHolderToRecycledViewPool(RecyclerView.java:3900) at android.support.v7.widget.RecyclerView$Recycler.recycleCachedViewAt(RecyclerView.java:3843) at android.support.v7.widget.RecyclerView$Recycler.recycleViewHolderInternal(RecyclerView.java:3880) at android.support.v7.widget.RecyclerView$Recycler.recycleView(RecyclerView.java:3804) at android.support.v7.widget.RecyclerView$LayoutManager.removeAndRecycleViewAt(RecyclerView.java:5529) at android.support.v7.widget.LinearLayoutManager.recycleChildren(LinearLayoutManager.java:1143) at android.support.v7.widget.LinearLayoutManager.recycleViewsFromEnd(LinearLayoutManager.java:1218) at android.support.v7.widget.LinearLayoutManager.recycleByLayoutState(LinearLayoutManager.java:1242) at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1268) at android.support.v7.widget.LinearLayoutManager.scrollBy(LinearLayoutManager.java:1102) at android.support.v7.widget.LinearLayoutManager.scrollVerticallyBy(LinearLayoutManager.java:959) at android.support.v7.widget.RecyclerView$ViewFlinger.run(RecyclerView.java:3062) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761) at android.view.Choreographer.doCallbacks(Choreographer.java:574) at android.view.Choreographer.doframe(Choreographer.java:543) at android.view.Choreographer$frameDisplayEventReceiver.run(Choreographer.java:747) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5047) 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:806) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622) at dalvik.system.NativeStart.main(Native Method)

android adapter 提示空指针异常

``` public class ContactInfoParser extends Activity { ListView mListView; List<String> contactList = new ArrayList<String>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mListView = (ListView) findViewById(R.id.list_contact); ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, contactList); mListView.setAdapter(adapter); readContacts(); } private void readContacts() { Cursor cursor = null; try{ cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null); while (cursor.moveToNext()) { String displayname = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)); String diplaynumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); contactList.add(displayname + "\n" + diplaynumber); } }catch (Exception e){ e.printStackTrace(); }finally { if (cursor != null) { cursor.close(); } } } } ``` 上面这段代码从其他activity跳转过来,执行到mListView.setAdapter(adapter);这句话的时候,提示一直报错空指针异常。 报错代码如下: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.liujing.shanzhaisafe/com.liujing.shanzhaisage.fangdaomokuai.dialog.ContactInfoParser}: 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:2325) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) at android.app.ActivityThread.access$800(ActivityThread.java:151) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5254) 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:903) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 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.liujing.shanzhaisage.fangdaomokuai.dialog.ContactInfoParser.onCreate(ContactInfoParser.java:24)

android adapter提示空指针异常情况

主要代码如下: package com.example.mydreamhero.ActivityManage; import android.app.Activity; import android.app.ActivityManager; import android.content.Context; import android.os.Bundle; import android.os.Debug; import android.widget.ListView; import com.example.mydreamhero.R; import java.util.ArrayList; import java.util.List; /** * Created by 刘 on 2017/3/5. */ public class AMProcessActivity extends Activity { private ListView listView; private List<AMProcessInfo> mAmprocessInfo = null; private ActivityManager manager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.am_main); listView = (ListView) findViewById(R.id.listview_am_process); manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); //提示下面这一行出错 listView.setAdapter(new AMProcessAdapter(this, getRunningprocess())); } private List<AMProcessInfo> getRunningprocess() { mAmprocessInfo = new ArrayList<AMProcessInfo>(); List<ActivityManager.RunningAppProcessInfo> appprocessInfo = manager.getRunningAppProcesses(); for (int i = 0; i < appprocessInfo.size(); i++) { ActivityManager.RunningAppProcessInfo info = appprocessInfo.get(i); int pid = info.pid; int uid = info.uid; String processName = info.processName; int[] memorypid = new int[]{pid}; Debug.MemoryInfo memoryInfo[] = manager.getProcessMemoryInfo(memorypid); int memorySize = memoryInfo[0].getTotalPss(); AMProcessInfo amProcessInfo = new AMProcessInfo(); amProcessInfo.setPid(""+pid); amProcessInfo.setUid(""+uid); amProcessInfo.setMemorySize(memorySize+"KB"); amProcessInfo.setProcessName(processName); mAmprocessInfo.add(amProcessInfo); } return mAmprocessInfo; } }** 出错一次如下: 03/05 23:17:17: Launching app $ adb push F:\androidforGoogle\MyDreamHero\app\build\outputs\apk\app-debug.apk /data/local/tmp/com.example.mydreamhero $ adb shell pm install -r "/data/local/tmp/com.example.mydreamhero" pkg: /data/local/tmp/com.example.mydreamhero Success $ adb shell am start -n "com.example.mydreamhero/com.example.mydreamhero.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER Client not ready yet..Waiting for process to come online Waiting for process to come online Connected to process 3275 on device genymotion-genymotion_vbox86p_6_0_160825_141918-192.168.196.101:5555 I/art: Background partial concurrent mark sweep GC freed 1613(300KB) AllocSpace objects, 0(0B) LOS objects, 39% free, 1587KB/2MB, paused 101us total 183.475ms D/AndroidRuntime: Shutting down VM E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.mydreamhero, PID: 3275 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mydreamhero/com.example.mydreamhero.ActivityManage.AMProcessActivity}: 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:2416) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 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.example.mydreamhero.ActivityManage.AMProcessActivity.onCreate(AMProcessActivity.java:29) at android.app.Activity.performCreate(Activity.java:6237) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)  at android.app.ActivityThread.-wrap11(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:148)  at android.app.ActivityThread.main(ActivityThread.java:5417)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)  我查了好多次都没有找到原因,求大神来不吝解答一下

ListView中遇到的空指针异常

以下代码段,异常在最下面: ``` package com.sweetstar86.myapplicationlistview; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import java.util.Vector; public class MainActivity6 extends AppCompatActivity { private ListView listView; private Vector<News> news = new Vector<>(); private MyAdapter myAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main6); listView = (ListView) findViewById(R.id.listView5); initData(); myAdapter = new MyAdapter(); listView.setAdapter(myAdapter); } private int index = 1; /** * Init Data */ private void initData() { for (int i = 0; i < 10; i++) { News n = new News(); n.title = "title--" + index; n.content = "content--" + index; index++; news.add(n); } } class MyAdapter extends BaseAdapter { @Override public int getCount() { return news.size(); } @Override public Object getItem(int position) { return news.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder vh; if(convertView==null){ convertView = getLayoutInflater().inflate(R.layout.list_item_6,null); vh = new ViewHolder(); vh.tv_title = (TextView) convertView.findViewById(R.id.textView_title); vh.tv_content = (TextView) convertView.findViewById(R.id.textView_content); convertView.setTag(vh); }else{ vh = (ViewHolder) convertView.getTag(); } News n = news.get(position); vh.tv_title.setText(n.title); vh.tv_content.setText(n.content); return convertView; } class ViewHolder { TextView tv_title; TextView tv_content; } } } ``` 异常: java.lang.NullPointerException at com.sweetstar86.myapplicationlistview.MainActivity6$MyAdapter.getView(MainActivity6.java:77) at android.widget.AbsListView.obtainView(AbsListView.java:2622) at android.widget.ListView.makeAndAddView(ListView.java:1838) at android.widget.ListView.fillDown(ListView.java:681) at android.widget.ListView.fillFromTop(ListView.java:742) at android.widget.ListView.layoutChildren(ListView.java:1659) at android.widget.AbsListView.onLayout(AbsListView.java:2440) at android.view.View.layout(View.java:14615) at android.view.ViewGroup.layout(ViewGroup.java:4491) at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1021) at android.view.View.layout(View.java:14615) at android.view.ViewGroup.layout(ViewGroup.java:4491) at android.widget.FrameLayout.onLayout(FrameLayout.java:448) at android.view.View.layout(View.java:14615) at android.view.ViewGroup.layout(ViewGroup.java:4491) at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:435) at android.view.View.layout(View.java:14615) at android.view.ViewGroup.layout(ViewGroup.java:4491) at android.widget.FrameLayout.onLayout(FrameLayout.java:448) at android.view.View.layout(View.java:14615) at android.view.ViewGroup.layout(ViewGroup.java:4491) at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1669) at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1527) at android.widget.LinearLayout.onLayout(LinearLayout.java:1440) at android.view.View.layout(View.java:14615) at android.view.ViewGroup.layout(ViewGroup.java:4491) at android.widget.FrameLayout.onLayout(FrameLayout.java:448) at android.view.View.layout(View.java:14615) at android.view.ViewGroup.layout(ViewGroup.java:4491) at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2191) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2005) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1218) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4999) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:791) at android.view.Choreographer.doCallbacks(Choreographer.java:591) at android.view.Choreographer.doFrame(Choreographer.java:561) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:777) at android.os.Handler.handleCallback(Handler.java:725) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:5308) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869) at dalvik.system.NativeStart.main(Native Method) 本人安卓新人,跟着教程学的,实在找不出来原因...

关于android app中接入图灵机器人的空指针异常

04-08 22:39:17.076: E/AndroidRuntime(24578): FATAL EXCEPTION: main 04-08 22:39:17.076: E/AndroidRuntime(24578): java.lang.NullPointerException 04-08 22:39:17.076: E/AndroidRuntime(24578): at com.example.godness.HttpUtils.doGet(HttpUtils.java:57) 04-08 22:39:17.076: E/AndroidRuntime(24578): at com.example.godness.ChatFragment$2.onClick(ChatFragment.java:100) 04-08 22:39:17.076: E/AndroidRuntime(24578): at android.view.View.performClick(View.java:4354) 04-08 22:39:17.076: E/AndroidRuntime(24578): at android.view.View$PerformClick.run(View.java:17948) 04-08 22:39:17.076: E/AndroidRuntime(24578): at android.os.Handler.handleCallback(Handler.java:725) 04-08 22:39:17.076: E/AndroidRuntime(24578): at android.os.Handler.dispatchMessage(Handler.java:92) 04-08 22:39:17.076: E/AndroidRuntime(24578): at android.os.Looper.loop(Looper.java:137) 04-08 22:39:17.076: E/AndroidRuntime(24578): at android.app.ActivityThread.main(ActivityThread.java:5293) 04-08 22:39:17.076: E/AndroidRuntime(24578): at java.lang.reflect.Method.invokeNative(Native Method) 04-08 22:39:17.076: E/AndroidRuntime(24578): at java.lang.reflect.Method.invoke(Method.java:511) 04-08 22:39:17.076: E/AndroidRuntime(24578): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102) 04-08 22:39:17.076: E/AndroidRuntime(24578): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869) 04-08 22:39:17.076: E/AndroidRuntime(24578): at dalvik.system.NativeStart.main(Native Method)

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) ```

android运行报错求教 空指针异常

报错日志 显示空指针异常 上日志 06-20 19:35:24.264 3122-3122/com.example.wangzhe.ssapp E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.wangzhe.ssapp, PID: 3122 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.wangzhe.ssapp/com.example.wangzhe.ssapp.Drawer.Device_managment}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.lidroid.xutils.DbUtils com.example.wangzhe.ssapp.My.getDb()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.lidroid.xutils.DbUtils com.example.wangzhe.ssapp.My.getDb()' on a null object reference at com.example.wangzhe.ssapp.Drawer.Device_managment.init(Device_managment.java:53) at com.example.wangzhe.ssapp.Drawer.Device_managment.onCreate(Device_managment.java:40) at android.app.Activity.performCreate(Activity.java:6237) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)  at android.app.ActivityThread.-wrap11(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:148)  at android.app.ActivityThread.main(ActivityThread.java:5417)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)  ![日志提示位置](https://img-ask.csdn.net/upload/201606/21/1466452017_434017.png) getDb(); package com.example.wangzhe.ssapp; import android.app.Application; import com.lidroid.xutils.DbUtils; import com.lidroid.xutils.DbUtils.DaoConfig; public class My extends Application { private static My mInstance; private DbUtils db; public static My getInstance() { return mInstance; } @Override public void onCreate() { super.onCreate(); mInstance = this; } public DbUtils getDb() { if (db == null) { DaoConfig daoConfig = new DaoConfig(this); daoConfig.setDbName("data.db"); daoConfig.setDbVersion(2); db = DbUtils.create(daoConfig); } return db; } }

android安卓开发 TextView空指针问题怎么解决

我的rmsg已经取到了 System.out.println打印输出也正常 那我设置textView22为什么就报了空指针呢 还是要把textView22放到别的地方去设置 我是点了一个按钮 开始刷卡 然后返回值通过handler发送 然后接收到以后设置成rmsg ``` private TextView textView22; private String rmsg; Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); rmsg=(String)msg.obj; System.out.println("我的卡号是******"+rmsg); textView22.setText(rmsg); } }; ```

从activity调用ViewPager里Fragment的方法传参出现空指针异常?

报错信息如下: FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{com.thefat.lingjunqi.enricher/com.thefat.lingjunqi.enricher.ActivityReading}: java.lang.NullPointerException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2308) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) at android.app.ActivityThread.access$600(ActivityThread.java:156) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1342) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:153) at android.app.ActivityThread.main(ActivityThread.java:5338) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600) at dalvik.system.NativeStart.main(Native Method) **Caused by: java.lang.NullPointerException** at com.thefat.lingjunqi.enricher.FragmentArticleEN.refresh(FragmentArticleEN.java:32) at com.thefat.lingjunqi.enricher.ActivityReading.onCreate(ActivityReading.java:103) at android.app.Activity.performCreate(Activity.java:5232) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2272) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)  at android.app.ActivityThread.access$600(ActivityThread.java:156)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1342)  at android.os.Handler.dispatchMessage(Handler.java:99)  at android.os.Looper.loop(Looper.java:153)  at android.app.ActivityThread.main(ActivityThread.java:5338)  at java.lang.reflect.Method.invokeNative(Native Method)  at java.lang.reflect.Method.invoke(Method.java:511)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)  at dalvik.system.NativeStart.main(Native Method) ActivityReading.class ``` package com.thefat.lingjunqi.enricher; import android.content.Context; import android.content.Intent; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.util.DisplayMetrics; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; public class ActivityReading extends FragmentActivity { private ViewPager mPager; private ArrayList<Fragment> fragmentsList; private ImageView bottomLine; private TextView textView1, textView2, textView3; private int currIndex = 0; private int bottomLineWidth; private int offset = 0; /*String [] articleTitle; String [] articleContent; String [] transTitle; String [] transContent; String wordsTitle; String [] wordsContent;*/ public static final String ITEM_ID = "item_id"; int color_current; int color_notCurrent; public static void actionStart(Context context, int id){ Intent intent=new Intent(context,ActivityReading.class); intent.putExtra(ActivityReading.ITEM_ID,id); context.startActivity(intent); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_reading); mPager = (ViewPager) findViewById(R.id.viewpager); getActionBar().setDisplayHomeAsUpEnabled(true); color_current=getResources().getColor(R.color.color_current); color_notCurrent =getResources().getColor(R.color.color_notcurrent); String [] articleTitle=getResources().getStringArray(R.array.lesson_name_list_en); String []articleContent=getResources().getStringArray(R.array.array_article); String []transTitle=getResources().getStringArray(R.array.lesson_name_list_cn); String []transContent=getResources().getStringArray(R.array.array_trans); String wordsTitle=getResources().getString(R.string.words_title); String []wordsContent=getResources().getStringArray(R.array.array_words); initImageView(); int index=getIntent().getIntExtra(ActivityReading.ITEM_ID,0); textView1 = (TextView) findViewById(R.id.text1); textView2 = (TextView) findViewById(R.id.text2); textView3 = (TextView) findViewById(R.id.text3); textView1.setOnClickListener(new MyOnClickListener(0)); textView2.setOnClickListener(new MyOnClickListener(1)); textView3.setOnClickListener(new MyOnClickListener(2)); final TextView[] titles = {textView1, textView2, textView3}; fragmentsList = new ArrayList<>(); FragmentArticleEN fragmentArticleEN = new FragmentArticleEN(); FragmentArticleCN fragmentArticleCN = new FragmentArticleCN(); FragmentWords fragmentWords = new FragmentWords(); fragmentsList.add(fragmentArticleEN); fragmentsList.add(fragmentArticleCN); fragmentsList.add(fragmentWords); MyFragmentPagerAdapter Pageradapter=new MyFragmentPagerAdapter(getSupportFragmentManager(), fragmentsList); mPager.setAdapter(Pageradapter); mPager.setCurrentItem(0); FragmentArticleEN fragmentArticleEN_ = (FragmentArticleEN) Pageradapter.instantiateItem(mPager,0); FragmentArticleCN fragmentArticleCN_ = (FragmentArticleCN) Pageradapter.instantiateItem(mPager,1); FragmentWords fragmentWords_= (FragmentWords) Pageradapter.instantiateItem(mPager,2); fragmentArticleEN_.refresh(articleTitle[index],articleContent[index]); fragmentArticleCN_.refresh(transTitle[index],transContent[index]); fragmentWords_.refresh(wordsTitle,wordsContent[index]); mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { int one=offset*2+bottomLineWidth;//页卡1->页卡2偏移量 @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { Animation animation=new TranslateAnimation(one*currIndex,one*position,0,0); animation.setFillAfter(true); animation.setDuration(250); bottomLine.startAnimation(animation); titles[currIndex].setTextColor(color_notCurrent); titles[position].setTextColor(color_current); currIndex=position; } @Override public void onPageScrollStateChanged(int state) { } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { //创建启动ActivityTitle的Intent Intent intent = new Intent(this, ActivityTitle.class); //添加额外的Flag,将Activity栈中处于FirstActivity之上的Activity弹出 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //启动intent对应的Activity startActivity(intent); return true; } return super.onOptionsItemSelected(item); } private void initImageView() { bottomLine = (ImageView)findViewById(R.id.cursor); bottomLineWidth = BitmapFactory.decodeResource(getResources(), R.drawable.cursor).getWidth(); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); int screenW_Phone = dm.widthPixels; offset = (screenW_Phone/3 - bottomLineWidth)/2; //imgageview设置平移,使下划线平移到初始位置(平移一个offset) Matrix matrix = new Matrix(); matrix.postTranslate(offset, 0); bottomLine.setImageMatrix(matrix); } public class MyOnClickListener implements View.OnClickListener { private int index = 0; public MyOnClickListener(int i) { index = i; } @Override public void onClick(View v) { mPager.setCurrentItem(index); } } } ``` FragmentArticleEN.class ``` package com.thefat.lingjunqi.enricher; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /** * Created by lingjunqi on 2015/12/2. */ public class FragmentArticleEN extends Fragment { private View view; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view=inflater.inflate(R.layout.fragment_fragment_article_en,container,false); return view; } public void refresh(String title, String content){ View visibilityLayout=view.findViewById(R.id.visibility_layout); visibilityLayout.setVisibility(View.VISIBLE); TextView articleTitleText=(TextView)view.findViewById(R.id.article_titile); TextView articleContentText=(TextView)view.findViewById(R.id.article_content); articleTitleText.setText(title); articleContentText.setText(content); } } ``` **如果我采用的方法错误,谁能告诉一下正确的从一个activity向另一个activity内的ViewPager里的fragment传参或者调用它的方法。**

Android的GLES20RecordingCanvas空指针的问题

错误是友盟统计提供的,只有这些,没法确定是哪段代码出了问题,所以只想问问大家有没有碰到过类似的问题,给我点提示就好啦,谢谢! 目前看都是出现在4.0以上的版本上,应该跟硬件加速有关。但不知道该怎么解决这个问题。不可能全局关闭硬件加速,代价太高 ``` java.lang.NullPointerException at android.view.GLES20RecordingCanvas.drawBitmap(GLES20RecordingCanvas.java:118) at android.graphics.drawable.BitmapDrawable.draw(BitmapDrawable.java:393) at android.widget.ImageView.onDraw(ImageView.java:892) at android.view.View.draw(View.java:11015) at android.view.ViewGroup.drawChild(ViewGroup.java:2971) at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2573) at android.view.ViewGroup.drawChild(ViewGroup.java:2969) at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2573) at android.view.View.draw(View.java:11018) at android.widget.FrameLayout.draw(FrameLayout.java:450) at android.widget.ScrollView.draw(ScrollView.java:1525) at android.view.ViewGroup.drawChild(ViewGroup.java:2971) at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2573) at android.view.ViewGroup.drawChild(ViewGroup.java:2969) at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2573) at android.view.View.draw(View.java:11018) at android.support.v4.view.ViewPager.draw(ViewPager.java:2092) at android.view.ViewGroup.drawChild(ViewGroup.java:2971) at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2573) at android.view.View.getDisplayList(View.java:10452) at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:2681) at android.view.View.getDisplayList(View.java:10417) at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:2681) at android.view.View.getDisplayList(View.java:10417) at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:2681) at android.view.View.getDisplayList(View.java:10417) at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:2681) at android.view.View.getDisplayList(View.java:10417) at android.view.HardwareRenderer$GlRenderer.draw(HardwareRenderer.java:851) at android.view.ViewRootImpl.draw(ViewRootImpl.java:2034) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1748) at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2583) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4503) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576) at dalvik.system.NativeStart.main(Native Method) ```

求大神指导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 ```

增加个context变量就报空指针异常

这个代码我是复制网上一位博客的,只不过在他的基础上增加个context,目的是想显示 Toast这个东西,但崩溃了,怎么改?新手不懂 ![图片说明](https://img-ask.csdn.net/upload/201702/17/1487280676_887989.png) ![图片说明](https://img-ask.csdn.net/upload/201702/17/1487280727_591317.jpg) EventHandler.java ``` package com.mytest.handlertest; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import android.widget.TextView; import android.widget.Toast; class EventHandler extends Handler { private NoLooperThread noLooperThread; private OwnLooperThread ownLooperThread; private TextView tv; private Context context; public EventHandler(Looper looper) { super(looper); } public EventHandler() { super(); } @Override public void handleMessage(Message msg) { super.handleMessage(msg); Log.e("EventHandler", "当前线程id:------+>"+Thread.currentThread().getId()); Toast.makeText(context, "当前线程id:------+>"+Thread.currentThread().getId(), Toast.LENGTH_SHORT).show(); //可以根据msg.what执行不同的处理,这里没有这么做 switch(msg.what){ case 1: tv.setText((String)msg.obj); break; case 2: tv.setText((String)msg.obj); noLooperThread.stop(); break; case 3: //不能在非主线程的线程里面更新UI,所以这里通过Log打印收到的消息 Log.e("EventHandler", (String)msg.obj); ownLooperThread.stop(); break; default: //不能在非主线程的线程里面更新UI,所以这里通过Log打印收到的消息 Log.e("EventHandler", (String)msg.obj); break; } } } ``` HandlerTest.java ``` package com.mytest.handlertest; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class HandlerTest extends Activity implements OnClickListener { private Button btn1,btn2,btn3,btn4,btn5,btn6; private boolean postRunnable; private EventHandler mHandler; private NoLooperThread noLooperThread; private OwnLooperThread ownLooperThread; private Handler mOtherThreadHandler; private TextView tv; private ReceiveMessageThread receiveMessageThread; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_handler_test); btn1=(Button)findViewById(R.id.b101); btn2=(Button)findViewById(R.id.b102); btn3=(Button)findViewById(R.id.b103); btn4=(Button)findViewById(R.id.b104); btn5=(Button)findViewById(R.id.b105); btn6=(Button)findViewById(R.id.b106); btn1.setOnClickListener(this); btn2.setOnClickListener(this); btn3.setOnClickListener(this); btn4.setOnClickListener(this); btn5.setOnClickListener(this); btn6.setOnClickListener(this); receiveMessageThread=new ReceiveMessageThread(); receiveMessageThread.start(); } @Override public void onClick(View v) { switch(v.getId()){ case R.id.b101: //主线程发送消息给自己 Looper looper; looper = Looper.myLooper(); //get the Main looper related with the main thread //如果不给任何参数的话会用当前线程对应的Looper(这里就是Main Looper)为Handler里面的成员mLooper赋值 mHandler = new EventHandler(looper); //mHandler = new EventHandler(); // 清除整个MessageQueue里的消息 mHandler.removeMessages(0); String obj = "This main thread's message and received by itself!"; //得到Message对象 Message m = mHandler.obtainMessage(1, 1, 1, obj); // 将Message对象送入到main thread的MessageQueue里面 mHandler.sendMessage(m); break; case R.id.b102: //other线程发送消息给主线程 postRunnable = false; noLooperThread = new NoLooperThread(); noLooperThread.start(); break; case R.id.b103: //other thread获取它自己发送的消息 tv.setText("please look at the error level log for other thread received message"); ownLooperThread = new OwnLooperThread(); ownLooperThread.start(); break; case R.id.b104: //other thread通过Post Runnable方式发送消息给主线程 postRunnable = true; noLooperThread = new NoLooperThread(); noLooperThread.start(); break; case R.id.b105: //主线程发送消息给other thread if(null!=mOtherThreadHandler){ tv.setText("please look at the error level log for other thread received message from main thread"); String msgObj = "message from mainThread"; Message mainThreadMsg = mOtherThreadHandler.obtainMessage(1, 1, 1, msgObj); mOtherThreadHandler.sendMessage(mainThreadMsg); } break; case R.id.b106: finish(); break; } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.handler_test, 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); } } ``` NoLooperThread.java ``` package com.mytest.handlertest; import android.content.Context; import android.os.Looper; import android.os.Message; import android.util.Log; import android.widget.TextView; import android.widget.Toast; class NoLooperThread extends Thread{ private Context context; private TextView tv; private boolean postRunnable; private EventHandler mNoLooperThreadHandler; public void run() { Looper myLooper, mainLooper; myLooper = Looper.myLooper(); mainLooper = Looper.getMainLooper(); //这是一个static函数 String obj; if(myLooper == null){ mNoLooperThreadHandler = new EventHandler(mainLooper); obj = "NoLooperThread has no looper and handleMessage function executed in main thread!"; } else { mNoLooperThreadHandler = new EventHandler(myLooper); obj = "This is from NoLooperThread self and handleMessage function executed in NoLooperThread!"; } Toast.makeText(context, obj, Toast.LENGTH_SHORT).show(); mNoLooperThreadHandler.removeMessages(0); if(false == postRunnable){ //send message to main thread Message m = mNoLooperThreadHandler.obtainMessage(2, 1, 1, obj); mNoLooperThreadHandler.sendMessage(m); Log.e("NoLooperThread", "NoLooperThread id:" + this.getId()); }else{ //下面new出来的实现了Runnable接口的对象中run函数是在Main Thread中执行,不是在NoLooperThread中执行 //注意Runnable是一个接口,它里面的run函数被执行时不会再新建一个线程 //您可以在run上加断点然后在eclipse调试中看它在哪个线程中执行 mNoLooperThreadHandler.post(new Runnable(){ @Override public void run() { tv.setText("update UI through handler post runnalbe mechanism!"); // noLooerThread.stop(); } }); } } } ``` OwnLooperThread.java ``` package com.mytest.handlertest; import android.content.Context; import android.os.Looper; import android.os.Message; import android.widget.Toast; class OwnLooperThread extends Thread{ private Context context; private EventHandler mOwnLooperThreadHandler; public void run() { Looper.prepare(); Looper myLooper, mainLooper; myLooper = Looper.myLooper(); mainLooper = Looper.getMainLooper(); //这是一个static函数 String obj; if(myLooper == null){ mOwnLooperThreadHandler = new EventHandler(mainLooper); obj = "OwnLooperThread has no looper and handleMessage function executed in main thread!"; } else { mOwnLooperThreadHandler = new EventHandler(myLooper); obj = "This is from OwnLooperThread self and handleMessage function executed in NoLooperThread!"; } Toast.makeText(context, obj, Toast.LENGTH_SHORT).show(); mOwnLooperThreadHandler.removeMessages(0); //给自己发送消息 Message m = mOwnLooperThreadHandler.obtainMessage(3, 1, 1, obj); mOwnLooperThreadHandler.sendMessage(m); Looper.loop(); } } ``` ReceiveMessageThread.java ``` package com.mytest.handlertest; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import android.widget.Toast; class ReceiveMessageThread extends Thread{ private Handler mOtherThreadHandler; private Context context; public void run() { Looper.prepare(); mOtherThreadHandler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); Log.e("ReceiveMessageThread", (String)msg.obj); Log.e("ReceiveMessageThread","当前线程id:----+>"+Thread.currentThread().getId()); Toast.makeText(context, "当前线程id:----+>"+Thread.currentThread().getId(), Toast.LENGTH_SHORT).show(); } }; Looper.loop(); } } ```

安卓Adapter空指针,一直解决不了

是这样的。我是在做一个相当于一个手机卫士,里面有通讯录和黑名单两个功能。这个代码是我做的黑名单里的。图片说明 想实现的功能是点黑名单按钮,可以出现这个黑名单的Activity。通讯录做了一个Listview,点通讯录按钮,可以导入系统通讯录,然后设置点击监听,长按item可以发短信,点击可以打电话。 现在的问题是,无论是通讯录还是黑名单,一点按钮就报错,报错的内容就是空指针。不知道怎么解决。哭唧唧。 ![图片说明](https://img-ask.csdn.net/upload/201706/18/1497753680_955031.png) 这个是代码。无论尝试什么方法,都报错空指针。 package com.jinwen.pengu.communication; import android.app.Activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class Stop extends Activity { private ListView iv_main; private BlackNumberAdapter adapter; private BlackNumberDao dao; private List data; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); iv_main = (ListView) findViewById(R.id.iv_main); adapter = new BlackNumberAdapter(); dao = new BlackNumberDao(this); data = dao.getAll(); iv_main.setAdapter(adapter); } public void add(View v){ } class BlackNumberAdapter extends BaseAdapter{ @Override public int getCount() { return data.size(); } @Override public Object getItem(int position) { return data.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView ==null){ convertView = View.inflate(Stop.this,android.R.layout.simple_list_item_1,null); } BlackNumber blackNumber = data.get(position); TextView textView = (TextView) convertView.findViewById(android.R.id.text1); textView.setText(blackNumber.getNumber()); return convertView; } } } 错误: 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.jinwen.pengu.communication.Stop.onCreate(Stop.java:31)

android空指针异常,求大神指教,已纠结好几天了。。。

package com.rong.shop.myshop.home; import android.content.Context; import android.support.v4.app.Fragment; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.GridView; import android.widget.ImageView; import android.widget.SimpleAdapter; import com.rong.shop.R; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** Created by Administrator on 2016/8/13. */ public class MyFragment_home extends Fragment { //ViewPager private ViewPager vpager_one; private ArrayList aList; private Adapter_homeViewPager mAdapter; //GridView private GridView gridview; private ImageView imageview; private Context mcontext = this.getActivity(); private List> listitem; private SimpleAdapter gAdapter; private int[] imgIds; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fg_home, container, false); //ViewPager vpager_one = (ViewPager) view.findViewById(R.id.vpager); aList = new ArrayList(); LayoutInflater li = getLayoutInflater(null); aList.add(li.inflate(R.layout.fg_home_viewpager_view_1, null, false)); aList.add(li.inflate(R.layout.fg_home_viewpager_view_2, null, false)); aList.add(li.inflate(R.layout.fg_home_viewpager_view_3, null, false)); aList.add(li.inflate(R.layout.fg_home_viewpager_view_4, null, false)); aList.add(li.inflate(R.layout.fg_home_viewpager_view_5, null, false)); mAdapter = new Adapter_homeViewPager(aList); vpager_one.setAdapter(mAdapter); //GridView gridview = (GridView)view.findViewById(R.id.gridview); listitem= new ArrayList<>(); imgIds = new int[]{ R.drawable.fg_home_gridview_1, R.drawable.fg_home_gridview_2, R.drawable.fg_home_gridview_3, R.drawable.fg_home_gridview_4, R.drawable.fg_home_gridview_5, R.drawable.fg_home_gridview_6, R.drawable.fg_home_gridview_7, R.drawable.fg_home_gridview_8, }; for (int i = 0; i < imgIds.length; i++) { Map showitem = new HashMap(); showitem.put("image", imgIds[i]); listitem.add(showitem); } gAdapter = new SimpleAdapter(mcontext, listitem, R.layout.fg_home_gridview_item, new String[] { "image" }, new int[]{R.id.gridview_image}); gridview.setAdapter(gAdapter);这里是第75行报错的代码 return view; } } 报错信息是: 09-01 08:49:51.260 22924-22924/? E/AndroidRuntime: FATAL EXCEPTION: main Process: com.rong.shop, PID: 22924 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rong.shop/com.rong.shop.myshop.home.MainActivity}: java.lang.NullPointerException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2212) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2271) at android.app.ActivityThread.access$800(ActivityThread.java:144) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5146) 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:732) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NullPointerException at android.widget.SimpleAdapter.(SimpleAdapter.java:85) at com.rong.shop.myshop.home.MyFragment_home.onCreateView(MyFragment_home.java:75) at android.support.v4.app.Fragment.performCreateView(Fragment.java:2074) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1286) at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:758) at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1671) at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:388) at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:619) at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1171) at android.app.Activity.performStart(Activity.java:5241) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2178) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2271) at android.app.ActivityThread.access$800(ActivityThread.java:144) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5146) 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:732) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566) at dalvik.system.NativeStart.main(Native Method)

求大神指导Android 空指针异常问题

代码如下: private OnPreferenceClickListener mPrefClickListener = new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { Intent intent = preference.getIntent(); try { startActivity(intent); } catch (ActivityNotFoundException e) { Toast.makeText(getActivity(), R.string.plugin_app_unavailable, Toast.LENGTH_LONG).show(); Log.w(TAG, preference.getKey() + " not available", e); } return true; } }; log 如下: 01-19 06:34:24.911 6327 6327 E AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.content.Intent.migrateExtraStreamToClipData()' on a null object reference 01-19 06:34:24.911 6327 6327 E AndroidRuntime: at android.app.Instrumentation.execStartActivity(Instrumentation.java:1622) 01-19 06:34:24.911 6327 6327 E AndroidRuntime: at android.app.Activity.startActivityFromFragment(Activity.java:4548) 01-19 06:34:24.911 6327 6327 E AndroidRuntime: at android.app.Activity.startActivityFromFragment(Activity.java:4510) 01-19 06:34:24.911 6327 6327 E AndroidRuntime: at android.app.Fragment.startActivity(Fragment.java:1086) 01-19 06:34:24.911 6327 6327 E AndroidRuntime: at android.app.Fragment.startActivity(Fragment.java:1065) 01-19 06:34:24.911 6327 6327 E AndroidRuntime: at com.lenovo.settings.CharSettings$2.onPreferenceClick(CharSettings.java:114) 01-19 06:34:24.911 6327 6327 E AndroidRuntime: at android.preference.Preference.performClick(Preference.java:1015) 01-19 06:34:24.911 6327 6327 E AndroidRuntime: at android.preference.PreferenceScreen.onItemClick(PreferenceScreen.java:214) 01-19 06:34:24.911 6327 6327 E AndroidRuntime: at android.widget.AdapterView.performItemClick(AdapterView.java:310) 01-19 06:34:24.911 6327 6327 E AndroidRuntime: at android.widget.AbsListView.performItemClick(AbsListView.java:1188) 01-19 06:34:24.911 6327 6327 E AndroidRuntime: at android.widget.AbsListView$PerformClick.run(AbsListView.java:3231) 01-19 06:34:24.911 6327 6327 E AndroidRuntime: at android.widget.AbsListView$3.run(AbsListView.java:4165) 01-19 06:34:24.911 6327 6327 E AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:815) 01-19 06:34:24.911 6327 6327 E AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:104) 01-19 06:34:24.911 6327 6327 E AndroidRuntime: at android.os.Looper.loop(Looper.java:194) 01-19 06:34:24.911 6327 6327 E AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5731) 01-19 06:34:24.911 6327 6327 E AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method) 01-19 06:34:24.911 6327 6327 E AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:372) 01-19 06:34:24.911 6327 6327 E AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959) 01-19 06:34:24.911 6327 6327 E AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754) 求大神指教,小白一枚,谢谢

安卓开发Fragment里面空指针问题求大神赐教

报错代码: 12-20 10:21:08.243 4780-4780/? E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.asus.accuntingapp, PID: 4780 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.asus.accuntingapp/com.example.asus.accuntingapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.LinkedList com.example.asus.accuntingapp.RecordDatabaseHelper.getAvaliableDate()' 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: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) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.LinkedList com.example.asus.accuntingapp.RecordDatabaseHelper.getAvaliableDate()' on a null object reference at com.example.asus.accuntingapp.MainViewPagerAdapter.initFragments(MainViewPagerAdapter.java:23) at com.example.asus.accuntingapp.MainViewPagerAdapter.<init>(MainViewPagerAdapter.java:19) at com.example.asus.accuntingapp.MainActivity.onCreate(MainActivity.java:28) at android.app.Activity.performCreate(Activity.java:5933) 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: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)  相关代码: public class MainViewPagerAdapter extends FragmentPagerAdapter { LinkedList<Mainfragment> fragments=new LinkedList<>(); LinkedList<String> dates=new LinkedList<>(); public MainViewPagerAdapter(FragmentManager fm) { super(fm); initFragments(); } private void initFragments(){ dates = GlobalUtil.getInstance().databaseHelper.getAvaliableDate(); if(!dates.contains(DateUtil.getFormattedDate())){ dates.addLast(DateUtil.getFormattedDate()); } for(String date:dates){ Mainfragment fragment=new Mainfragment(date); fragments.add(fragment); } } public void reload(){ for(Mainfragment fragment:fragments){ fragment.reload(); } } public int getLastIndex(){ return fragments.size()-1; } @Override public Fragment getItem(int position) { return fragments.get(position); } @Override public int getCount() { return fragments.size(); } } public class MainActivity extends AppCompatActivity { private TickerView tickerView; private ViewPager viewPager; private MainViewPagerAdapter pagerAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getSupportActionBar().setElevation(0); viewPager=(ViewPager)findViewById(R.id.view_pager); pagerAdapter=new MainViewPagerAdapter(getSupportFragmentManager()); pagerAdapter.notifyDataSetChanged(); viewPager.setAdapter(pagerAdapter); viewPager.setCurrentItem(pagerAdapter.getLastIndex()); findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent=new Intent(MainActivity.this,AddRecordActivity.class); startActivityForResult(intent,1); } }); GlobalUtil.getInstance().setContext(getApplicationContext()); LinkedList<String> dates=new LinkedList<>(); dates = GlobalUtil.getInstance().databaseHelper.getAvaliableDate(); Log.d("MainActivity","时间"+dates); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); pagerAdapter.reload(); } } 我在别的地方调用这个getAvaliableDate()方法没问题,在MainViewPagerAdapter类里面的initFragments()方法里面调用getAvaliableDate()就会报空指针。我不知道为什么,望大神赐教!

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.<init>(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<GroupTitle> Gp, Map<Integer,List<RssItem>> ChildMap) { mInflater = LayoutInflater.from(context); //是这里。。。。。 this.Gp = Gp; this.ChilderMap = ChildMap; list = new ArrayList<RssItem>(); } 我在碎片里面调用的时候是这样子的: adapter = new FragmentExpanableListViewAdapter(getActivity(), title, list); 能运行,数据的加载和显示也没问题,就是在页面切换的时候会偶尔报这个错。我想问一下 这会不会是和多个碎片共用一个适配器有关,因为碎片的布局的样式都一样,只是加载的数据类型不一样 adapter = new FragmentExpanableListViewAdapter(getActivity(), title, list); (就是像这行代码一样 这是里面的title 和list 不一样而已) 我就直接用多个碎片对应一个适配器了 这是怎么回事呢?/d:

listview加载好数据,点击同一项,有时会报空指针异常

05-30 08:54:03.107: E/AndroidRuntime(1270): java.lang.NullPointerException 05-30 08:54:03.107: E/AndroidRuntime(1270): at android.widget.TextView.onMeasure(TextView.java:6555) 05-30 08:54:03.107: E/AndroidRuntime(1270): at android.view.View.measure(View.java:12581) 05-30 08:54:03.107: E/AndroidRuntime(1270): at android.widget.TableRow.getColumnsWidths(TableRow.java:310) 05-30 08:54:03.107: E/AndroidRuntime(1270): at android.widget.TableLayout.findLargestCells(TableLayout.java:500) 05-30 08:54:03.107: E/AndroidRuntime(1270): at android.widget.TableLayout.measureVertical(TableLayout.java:465) 05-30 08:54:03.107: E/AndroidRuntime(1270): at android.widget.TableLayout.onMeasure(TableLayout.java:431) 05-30 08:54:03.107: E/AndroidRuntime(1270): at android.view.View.measure(View.java:12581) 05-30 08:54:03.107: E/AndroidRuntime(1270): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4671) 05-30 08:54:03.107: E/AndroidRuntime(1270): at android.widget.FrameLayout.onMeasure(FrameLayout.java:293) 05-30 08:54:03.107: E/AndroidRuntime(1270): at android.view.View.measure(View.java:12581) 05-30 08:54:03.107: E/AndroidRuntime(1270): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4671) 05-30 08:54:03.107: E/AndroidRuntime(1270): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1369) 05-30 08:54:03.107: E/AndroidRuntime(1270): at android.widget.LinearLayout.measureVertical(LinearLayout.java:660) 05-30 08:54:03.107: E/AndroidRuntime(1270): at android.widget.LinearLayout.onMeasure(LinearLayout.java:553) 05-30 08:54:03.107: E/AndroidRuntime(1270): at android.view.View.measure(View.java:12581) 05-30 08:54:03.107: E/AndroidRuntime(1270): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4671) 05-30 08:54:03.107: E/AndroidRuntime(1270): at android.widget.FrameLayout.onMeasure(FrameLayout.java:293) 05-30 08:54:03.107: E/AndroidRuntime(1270): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2062) 05-30 08:54:03.107: E/AndroidRuntime(1270): at android.view.View.measure(View.java:12581) 05-30 08:54:03.107: E/AndroidRuntime(1270): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1038) 05-30 08:54:03.107: E/AndroidRuntime(1270): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2382) 05-30 08:54:03.107: E/AndroidRuntime(1270): at android.os.Handler.dispatchMessage(Handler.java:99) 05-30 08:54:03.107: E/AndroidRuntime(1270): at android.os.Looper.loop(Looper.java:137) 05-30 08:54:03.107: E/AndroidRuntime(1270): at android.app.ActivityThread.main(ActivityThread.java:4340) 05-30 08:54:03.107: E/AndroidRuntime(1270): at java.lang.reflect.Method.invokeNative(Native Method) 05-30 08:54:03.107: E/AndroidRuntime(1270): at java.lang.reflect.Method.invoke(Method.java:511) 05-30 08:54:03.107: E/AndroidRuntime(1270): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 05-30 08:54:03.107: E/AndroidRuntime(1270): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 05-30 08:54:03.107: E/AndroidRuntime(1270): at dalvik.system.NativeStart.main(Native Method)

2019 AI开发者大会

2019 AI开发者大会(AI ProCon 2019)是由中国IT社区CSDN主办的AI技术与产业年度盛会。多年经验淬炼,如今蓄势待发:2019年9月6-7日,大会将有近百位中美顶尖AI专家、知名企业代表以及千余名AI开发者齐聚北京,进行技术解读和产业论证。我们不空谈口号,只谈技术,诚挚邀请AI业内人士一起共铸人工智能新篇章!

实现简单的文件系统

实验内容: 通过对具体的文件存储空间的管理、文件的物理结构、目录结构和文件操作的实现,加深对文件系统内部功能和实现过程的理解。 要求: 1.在内存中开辟一个虚拟磁盘空间作为文件存储器,在其上实现一个简

MIPS单周期CPU-组成原理实验-华中科技大学

使用logisim布线完成的MIPS单周期CPU,可支持28条指令。跑马灯的代码已经装入了寄存器,可以直接开启时钟运行。

2019数学建模A题高压油管的压力控制 省一论文即代码

2019数学建模A题高压油管的压力控制省一完整论文即详细C++和Matlab代码,希望对同学们有所帮助

基于QT和OpenCV的五子棋实现源码

一个简单的五子棋应用,基于QT和OpenCV的实现源码,通过相邻棋子判断是否获胜,不包含人工智能算法,适合新手入门

Git 实用技巧

这几年越来越多的开发团队使用了Git,掌握Git的使用已经越来越重要,已经是一个开发者必备的一项技能;但很多人在刚开始学习Git的时候会遇到很多疑问,比如之前使用过SVN的开发者想不通Git提交代码为什么需要先commit然后再去push,而不是一条命令一次性搞定; 更多的开发者对Git已经入门,不过在遇到一些代码冲突、需要恢复Git代码时候就不知所措,这个时候哪些对 Git掌握得比较好的少数人,就像团队中的神一样,在队友遇到 Git 相关的问题的时候用各种流利的操作来帮助队友于水火。 我去年刚加入新团队,发现一些同事对Git的常规操作没太大问题,但对Git的理解还是比较生疏,比如说分支和分支之间的关联关系、合并代码时候的冲突解决、提交代码前未拉取新代码导致冲突问题的处理等,我在协助处理这些问题的时候也记录各种问题的解决办法,希望整理后通过教程帮助到更多对Git操作进阶的开发者。 本期教程学习方法分为“掌握基础——稳步进阶——熟悉协作”三个层次。从掌握基础的 Git的推送和拉取开始,以案例进行演示,分析每一个步骤的操作方式和原理,从理解Git 工具的操作到学会代码存储结构、演示不同场景下Git遇到问题的不同处理方案。循序渐进让同学们掌握Git工具在团队协作中的整体协作流程。 在教程中会通过大量案例进行分析,案例会模拟在工作中遇到的问题,从最基础的代码提交和拉取、代码冲突解决、代码仓库的数据维护、Git服务端搭建等。为了让同学们容易理解,对Git简单易懂,文章中详细记录了详细的操作步骤,提供大量演示截图和解析。在教程的最后部分,会从提升团队整体效率的角度对Git工具进行讲解,包括规范操作、Gitlab的搭建、钩子事件的应用等。 为了让同学们可以利用碎片化时间来灵活学习,在教程文章中大程度降低了上下文的依赖,让大家可以在工作之余进行学习与实战,并同时掌握里面涉及的Git不常见操作的相关知识,理解Git工具在工作遇到的问题解决思路和方法,相信一定会对大家的前端技能进阶大有帮助。

实用主义学Python(小白也容易上手的Python实用案例)

原价169,限时立减100元! 系统掌握Python核心语法16点,轻松应对工作中80%以上的Python使用场景! 69元=72讲+源码+社群答疑+讲师社群分享会&nbsp; 【哪些人适合学习这门课程?】 1)大学生,平时只学习了Python理论,并未接触Python实战问题; 2)对Python实用技能掌握薄弱的人,自动化、爬虫、数据分析能让你快速提高工作效率; 3)想学习新技术,如:人工智能、机器学习、深度学习等,这门课程是你的必修课程; 4)想修炼更好的编程内功,优秀的工程师肯定不能只会一门语言,Python语言功能强大、使用高效、简单易学。 【超实用技能】 从零开始 自动生成工作周报 职场升级 豆瓣电影数据爬取 实用案例 奥运冠军数据分析 自动化办公:通过Python自动化分析Excel数据并自动操作Word文档,最终获得一份基于Excel表格的数据分析报告。 豆瓣电影爬虫:通过Python自动爬取豆瓣电影信息并将电影图片保存到本地。 奥运会数据分析实战 简介:通过Python分析120年间奥运会的数据,从不同角度入手分析,从而得出一些有趣的结论。 【超人气老师】 二两 中国人工智能协会高级会员 生成对抗神经网络研究者 《深入浅出生成对抗网络:原理剖析与TensorFlow实现》一书作者 阿里云大学云学院导师 前大型游戏公司后端工程师 【超丰富实用案例】 0)图片背景去除案例 1)自动生成工作周报案例 2)豆瓣电影数据爬取案例 3)奥运会数据分析案例 4)自动处理邮件案例 5)github信息爬取/更新提醒案例 6)B站百大UP信息爬取与分析案例 7)构建自己的论文网站案例

深度学习原理+项目实战+算法详解+主流框架(套餐)

深度学习系列课程从深度学习基础知识点开始讲解一步步进入神经网络的世界再到卷积和递归神经网络,详解各大经典网络架构。实战部分选择当下最火爆深度学习框架PyTorch与Tensorflow/Keras,全程实战演示框架核心使用与建模方法。项目实战部分选择计算机视觉与自然语言处理领域经典项目,从零开始详解算法原理,debug模式逐行代码解读。适合准备就业和转行的同学们加入学习! 建议按照下列课程顺序来进行学习 (1)掌握深度学习必备经典网络架构 (2)深度框架实战方法 (3)计算机视觉与自然语言处理项目实战。(按照课程排列顺序即可)

C/C++跨平台研发从基础到高阶实战系列套餐

一 专题从基础的C语言核心到c++ 和stl完成基础强化; 二 再到数据结构,设计模式完成专业计算机技能强化; 三 通过跨平台网络编程,linux编程,qt界面编程,mfc编程,windows编程,c++与lua联合编程来完成应用强化 四 最后通过基于ffmpeg的音视频播放器,直播推流,屏幕录像,

三个项目玩转深度学习(附1G源码)

从事大数据与人工智能开发与实践约十年,钱老师亲自见证了大数据行业的发展与人工智能的从冷到热。事实证明,计算机技术的发展,算力突破,海量数据,机器人技术等,开启了第四次工业革命的序章。深度学习图像分类一直是人工智能的经典任务,是智慧零售、安防、无人驾驶等机器视觉应用领域的核心技术之一,掌握图像分类技术是机器视觉学习的重中之重。针对现有线上学习的特点与实际需求,我们开发了人工智能案例实战系列课程。打造:以项目案例实践为驱动的课程学习方式,覆盖了智能零售,智慧交通等常见领域,通过基础学习、项目案例实践、社群答疑,三维立体的方式,打造最好的学习效果。

Java基础知识面试题(2020最新版)

文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...

Python界面版学生管理系统

前不久上传了一个控制台版本的学生管理系统,这个是Python界面版学生管理系统,这个是使用pycharm开发的一个有界面的学生管理系统,基本的增删改查,里面又演示视频和完整代码,有需要的伙伴可以自行下

Vue.js 2.0之全家桶系列视频课程

基于新的Vue.js 2.3版本, 目前新全的Vue.js教学视频,让你少走弯路,直达技术前沿! 1. 包含Vue.js全家桶(vue.js、vue-router、axios、vuex、vue-cli、webpack、ElementUI等) 2. 采用笔记+代码案例的形式讲解,通俗易懂

linux“开发工具三剑客”速成攻略

工欲善其事,必先利其器。Vim+Git+Makefile是Linux环境下嵌入式开发常用的工具。本专题主要面向初次接触Linux的新手,熟练掌握工作中常用的工具,在以后的学习和工作中提高效率。

JAVA初级工程师面试36问(完结)

第三十一问: 说一下线程中sleep()和wait()区别? 1 . sleep()是让正在执行的线程主动让出CPU,当时间到了,在回到自己的线程让程序运行。但是它并没有释放同步资源锁只是让出。 2.wait()是让当前线程暂时退让出同步资源锁,让其他线程来获取到这个同步资源在调用notify()方法,才会让其解除wait状态,再次参与抢资源。 3. sleep()方法可以在任何地方使用,而wait()只能在同步方法或同步块使用。 ...

java jdk 8 帮助文档 中文 文档 chm 谷歌翻译

JDK1.8 API 中文谷歌翻译版 java帮助文档 JDK API java 帮助文档 谷歌翻译 JDK1.8 API 中文 谷歌翻译版 java帮助文档 Java最新帮助文档 本帮助文档是使用谷

我以为我对Mysql事务很熟,直到我遇到了阿里面试官

太惨了,面试又被吊打

智鼎(附答案).zip

并不是完整题库,但是有智鼎在线2019年9、10、11三个月的试题,有十七套以上题目,普通的网申行测题足以对付,可以在做题时自己总结一些规律,都不是很难

Visual Assist X 破解补丁

vs a's'sixt插件 支持vs2008-vs2019 亲测可以破解,希望可以帮助到大家

150讲轻松搞定Python网络爬虫

【为什么学爬虫?】 &nbsp; &nbsp; &nbsp; &nbsp;1、爬虫入手容易,但是深入较难,如何写出高效率的爬虫,如何写出灵活性高可扩展的爬虫都是一项技术活。另外在爬虫过程中,经常容易遇到被反爬虫,比如字体反爬、IP识别、验证码等,如何层层攻克难点拿到想要的数据,这门课程,你都能学到! &nbsp; &nbsp; &nbsp; &nbsp;2、如果是作为一个其他行业的开发者,比如app开发,web开发,学习爬虫能让你加强对技术的认知,能够开发出更加安全的软件和网站 【课程设计】 一个完整的爬虫程序,无论大小,总体来说可以分成三个步骤,分别是: 网络请求:模拟浏览器的行为从网上抓取数据。 数据解析:将请求下来的数据进行过滤,提取我们想要的数据。 数据存储:将提取到的数据存储到硬盘或者内存中。比如用mysql数据库或者redis等。 那么本课程也是按照这几个步骤循序渐进的进行讲解,带领学生完整的掌握每个步骤的技术。另外,因为爬虫的多样性,在爬取的过程中可能会发生被反爬、效率低下等。因此我们又增加了两个章节用来提高爬虫程序的灵活性,分别是: 爬虫进阶:包括IP代理,多线程爬虫,图形验证码识别、JS加密解密、动态网页爬虫、字体反爬识别等。 Scrapy和分布式爬虫:Scrapy框架、Scrapy-redis组件、分布式爬虫等。 通过爬虫进阶的知识点我们能应付大量的反爬网站,而Scrapy框架作为一个专业的爬虫框架,使用他可以快速提高我们编写爬虫程序的效率和速度。另外如果一台机器不能满足你的需求,我们可以用分布式爬虫让多台机器帮助你快速爬取数据。 &nbsp; 从基础爬虫到商业化应用爬虫,本套课程满足您的所有需求! 【课程服务】 专属付费社群+每周三讨论会+1v1答疑

JavaWEB商城项目(包括数据库)

功能描述:包括用户的登录注册,以及个人资料的修改.商品的分类展示,详情,加入购物车,生成订单,到银行支付等!另外还有收货地址的和我的收藏等常用操作.环境(JDK 1.7 ,mysql 5.5,Ecli

Python数据挖掘简易入门

&nbsp; &nbsp; &nbsp; &nbsp; 本课程为Python数据挖掘方向的入门课程,课程主要以真实数据为基础,详细介绍数据挖掘入门的流程和使用Python实现pandas与numpy在数据挖掘方向的运用,并深入学习如何运用scikit-learn调用常用的数据挖掘算法解决数据挖掘问题,为进一步深入学习数据挖掘打下扎实的基础。

一学即懂的计算机视觉(第一季)

图像处理和计算机视觉的课程大家已经看过很多,但总有“听不透”,“用不了”的感觉。课程致力于创建人人都能听的懂的计算机视觉,通过生动、细腻的讲解配合实战演练,让学生真正学懂、用会。 【超实用课程内容】 课程内容分为三篇,包括视觉系统构成,图像处理基础,特征提取与描述,运动跟踪,位姿估计,三维重构等内容。课程理论与实战结合,注重教学内容的可视化和工程实践,为人工智能视觉研发及算法工程师等相关高薪职位就业打下坚实基础。 【课程如何观看?】 PC端:https://edu.csdn.net/course/detail/26281 移动端:CSDN 学院APP(注意不是CSDN APP哦) 本课程为录播课,课程2年有效观看时长,但是大家可以抓紧时间学习后一起讨论哦~ 【学员专享增值服务】 源码开放 课件、课程案例代码完全开放给你,你可以根据所学知识,自行修改、优化 下载方式:电脑登录https://edu.csdn.net/course/detail/26281,点击右下方课程资料、代码、课件等打包下载

软件测试2小时入门

本课程内容系统、全面、简洁、通俗易懂,通过2个多小时的介绍,让大家对软件测试有个系统的理解和认识,具备基本的软件测试理论基础。 主要内容分为5个部分: 1 软件测试概述,了解测试是什么、测试的对象、原则、流程、方法、模型;&nbsp; 2.常用的黑盒测试用例设计方法及示例演示;&nbsp; 3 常用白盒测试用例设计方法及示例演示;&nbsp; 4.自动化测试优缺点、使用范围及示例‘;&nbsp; 5.测试经验谈。

初级玩转Linux+Ubuntu(嵌入式开发基础课程)

课程主要面向嵌入式Linux初学者、工程师、学生 主要从一下几方面进行讲解: 1.linux学习路线、基本命令、高级命令 2.shell、vi及vim入门讲解 3.软件安装下载、NFS、Samba、FTP等服务器配置及使用

2019 Python开发者日-培训

本次活动将秉承“只讲技术,拒绝空谈”的理念,邀请十余位身处一线的Python技术专家,重点围绕Web开发、自动化运维、数据分析、人工智能等技术模块,分享真实生产环境中使用Python应对IT挑战的真知灼见。此外,针对不同层次的开发者,大会还安排了深度培训实操环节,为开发者们带来更多深度实战的机会。

快速入门Android开发 视频 教程 android studio

这是一门快速入门Android开发课程,顾名思义是让大家能快速入门Android开发。 学完能让你学会如下知识点: Android的发展历程 搭建Java开发环境 搭建Android开发环境 Android Studio基础使用方法 Android Studio创建项目 项目运行到模拟器 项目运行到真实手机 Android中常用控件 排查开发中的错误 Android中请求网络 常用Android开发命令 快速入门Gradle构建系统 项目实战:看美图 常用Android Studio使用技巧 项目签名打包 如何上架市场

机器学习初学者必会的案例精讲

通过六个实际的编码项目,带领同学入门人工智能。这些项目涉及机器学习(回归,分类,聚类),深度学习(神经网络),底层数学算法,Weka数据挖掘,利用Git开源项目实战等。

4小时玩转微信小程序——基础入门与微信支付实战

这是一个门针对零基础学员学习微信小程序开发的视频教学课程。课程采用腾讯官方文档作为教程的唯一技术资料来源。杜绝网络上质量良莠不齐的资料给学员学习带来的障碍。 视频课程按照开发工具的下载、安装、使用、程序结构、视图层、逻辑层、微信小程序等几个部分组织课程,详细讲解整个小程序的开发过程

相关热词 c#框体中的退出函数 c# 按钮透明背景 c# idl 混编出错 c#在位置0处没有任何行 c# 循环给数组插入数据 c# 多线程死锁的例子 c# 钉钉读取员工排班 c# label 不显示 c#裁剪影像 c#工作进程更新ui
立即提问