YXTS122 2017-02-16 21:44 采纳率: 100%
浏览 1617
已采纳

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

这个代码我是复制网上一位博客的,只不过在他的基础上增加个context,目的是想显示
Toast这个东西,但崩溃了,怎么改?新手不懂
图片说明
图片说明
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();   
       }   
    }   


  • 写回答

8条回答 默认 最新

  • bigname22 2017-02-17 04:03
    关注

    楼主也知道了是context没赋值的原因,解决的办法应该有很多,我提的一种:给这个类NoLooperThread创建一个构造函数,

     public NoLooperThread(Context context){
         this.context = context;
     }
    

    在创建这个线程的时候把他传进去应该问题就解决了吧

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥15 关于#单片机#的问题,请各位专家解答!
  • ¥15 博通raid 的写入速度很高也很低
  • ¥15 目标计数模型训练过程中的问题
  • ¥100 Acess连接SQL 数据库后 不能用中文筛选
  • ¥15 用友U9Cloud的webapi
  • ¥20 电脑拓展屏桌面被莫名遮挡
  • ¥20 ensp,用局域网解决
  • ¥15 Python语言实验
  • ¥15 我每周要在投影仪优酷上自动连续播放112场电影,我每一周遥控操作一次投影仪,并使得电影永远不重复播放,请问怎样操作好呢?有那么多电影看吗?
  • ¥20 电脑重启停留在grub界面,引导出错需修复