无法从回调方法更新textview

时间:2018-04-27 09:32:59

标签: java android interface nullpointerexception callback

我在MainActivity中实现了一个接口,在回调方法中我想更新我的TextView但是我得到了nullpointer异常。

这是我的MainActivity类

public class MainActivity extends AppCompatActivity implements GenericCallback
{

    Context mcontext;
    TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mcontext = this;

        Button btn = findViewById(R.id.btn);
        tv = findViewById(R.id.tv);
        btn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                startActivity(new Intent(MainActivity.this,SecondActivity.class));
            }
        });

    }

    @Override
    public void doSomething(Context context, String... a)
    {
        Toast.makeText(context,"Calback"+a[0]+a[1],Toast.LENGTH_SHORT).show();
        tv = findViewById(R.id.tv);//Line 43
        tv.setText(a[0]+a[1]);
    }

我的界面看起来像这样

public interface GenericCallback
{
    void doSomething(Context context, String... a);
}

我的SecomdActivity

public class SecondActivity extends AppCompatActivity
{
    Context context;
    GenericCallback genericCallback = new MainActivity();

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        context = this;
        String a="Secomd",b = "Activity";
        genericCallback.doSomething(context,a,b);
        finish();
    }
}

栈跟踪

  

引起:java.lang.NullPointerException:尝试调用虚拟   方法'android.view.Window $ Callback   在null对象引用上的android.view.Window.getCallback()'           在android.support.v7.app.AppCompatDelegateImplBase。(AppCompatDelegateImplBase.java:117)           在android.support.v7.app.AppCompatDelegateImplV9。(AppCompatDelegateImplV9.java:149)           在android.support.v7.app.AppCompatDelegateImplV14。(AppCompatDelegateImplV14.java:56)           在android.support.v7.app.AppCompatDelegateImplV23。(AppCompatDelegateImplV23.java:31)           在android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:200)           在android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:183)           在android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519)           在android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)           在android.com.callback.MainActivity.doSomething(MainActivity.java:43)           在android.com.callback.SecondActivity.onCreate(SecondActivity.java:21)

我已经知道什么是nullpointer,我已经提到thisthis

4 个答案:

答案 0 :(得分:1)

您可以使用EventBus Library

安装

  

编译'org.greenrobot:eventbus:3.1.1'

首先,创建一个Java类

override func viewDidAppear(_ animated: Bool) {

        super.viewDidAppear(animated)

        let url = URL(string:"http://192.168.0.113/attendance/check_attend.php")

        let parameters = ["emp_id": self.att_emp_id]

        var request = URLRequest(url : url!)

        request.httpMethod = "POST"

        request.httpBody = try? JSONSerialization.data(withJSONObject:parameters, options: [])

        request.addValue("application/json", forHTTPHeaderField: "Content-Type")

        let session = URLSession.shared

        session.dataTask(with: request, completionHandler: { (data, response, error) in

            if let data = data {

                do {

                    let json = try? JSONSerialization.jsonObject(with: data, options: []) as! Dictionary<String, Any>

                    if let json = json {

                        print("HERE SHOULD BE YOUR JSON \(json)")

                        //var datas = [String:AnyObject]()

                        if let datas = json["data"] as? [String:AnyObject]  , let in_time_Str = datas["in_time"] as? String, let out_time_Str = datas["out_time"] as? String , let grace_Str = datas["grace"] as? String, let signal_Str = datas["signal"] as? String

                        {

                            print("here is attendance Data : \(datas)")

                            print("Here is attendance Signal : \(signal_Str)")

                            //datas = data

                            if in_time_Str != ""

                            {

                                self.server_in_time = in_time_Str

                                print("Here is attendance IN TIME : \(self.server_in_time)")

                            }

                            if out_time_Str != ""

                            {

                                self.server_out_time = out_time_Str

                                print("Here is attendance OUT TIME : \(self.server_out_time)")
                            }
                            if signal_Str == "10" {
                                self.grace_str_time = grace_Str
                                DispatchQueue.main.async {
                                    self.out_time_button.isEnabled = false
                                }
                            } else if signal_Str == "01" {
                                self.server_in_time = in_time_Str
                                DispatchQueue.main.async {
                                    self.inTimeTextField.text = self.server_in_time
                                    self.in_time_button.isEnabled = false
                                    self.out_time_button.isEnabled = true
                                }
                            } else if signal_Str == "00" {
                                self.server_out_time = out_time_Str   
                                DispatchQueue.main.async {   
                                    self.inTimeTextField.text = self.server_in_time   
                                    self.outTimeTextField.text = self.server_out_time    
                                    self.in_time_button.isEnabled = false    
                                    self.out_time_button.isEnabled = false    
                                }    
                            } else {    
                                print("Error : \(String(describing: error))")    
                            }    
                        }    
                    }    
                }    
            } else {    
                print("Error \(String(describing: error?.localizedDescription))")    
            }    
        }).resume()    
    }

然后在SecondActivity中

public class MsgEvent {
String oo;

public String getOo() {
    return oo;
}

public void setOo(String oo) {
    this.oo = oo;
}
}

然后在MainActivity中

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
    context = this;
    String a="Secomd",b = "Activity";
    MsgEvent msgEvent = new MsgEvnet();
    msgEvent.setOo(a);
    EventBus.getDefault().post(msgEvent);
    finish();
}

答案 1 :(得分:1)

您可以使用 BroadcastReceiver

检查以下示例

<强> MainActivity

public class MainActivity extends AppCompatActivity {


    TextView mTitle;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTitle = findViewById(R.id.toolbar_title);

        startActivity(new Intent(this, SecondActivity.class));

    }

    private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            mTitle.setText(intent.getStringExtra("DATA"));
            Toast.makeText(context, "recieved text : " + intent.getStringExtra("DATA"), Toast.LENGTH_SHORT).show();

        }
    };

    @Override
    protected void onResume() {
        IntentFilter filter = new IntentFilter();
        filter.addAction("MY_ACTION");
        registerReceiver(myBroadcastReceiver, filter);

        super.onResume();
    }

    @Override
    protected void onPause() {

        super.onPause();
    }

}

XML表格MainActivity

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbarIcon"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="vertical">


    <TextView
        android:id="@+id/toolbar_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:text="Nilesh"
        android:textStyle="bold" />


</LinearLayout>

<强> Second_activity

    public class SecondActivity extends AppCompatActivity {

    TextView tvText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        getSupportActionBar().setTitle("SECOND Activity");


        tvText = findViewById(R.id.tvText);

        tvText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendBroadcast();
            }
        });

    }

    public void sendBroadcast() {

        Intent broadcast = new Intent();
        broadcast.putExtra("DATA", "MY NAME IS NILESH");
        broadcast.setAction("MY_ACTION");
        sendBroadcast(broadcast);
    }
}

第二项活动的布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SecondActivity">

    <TextView
        android:layout_width="match_parent"
        android:id="@+id/tvText"
        android:text="Click to Send Broadcas"
        android:layout_height="wrap_content" />

</LinearLayout>

答案 2 :(得分:0)

您获得该null异常的原因是您的MainActivity视图不会膨胀,因为它没有被框架实例化。

您可以从第一个活动创建实例getter方法。

private static GenericCallback instance;

public static GenericCallback getHandler() {
    return instance;
}

@Override
protected void onCreate(Bundle savedInstanceState)
{
     ...
     instance = this;
     ...
}

然后在第二个活动中,获取该实例而不是实例化活动。

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
    context = this;
    String a="Secomd",b = "Activity";
    GenericCallback genericCallback = MainActivity.getHandler();
    genericCallback.doSomething(context,a,b);
    finish();
}

答案 3 :(得分:0)

GenericCallback genericCallback = new MainActivity();更改为 SecondActivity中的GenericCallback genericCallback;

在onCreate中声明genericCallback对象中的值,如genericCallback = this;