在MainActivity中:
private TextView log;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
log= (TextView) findViewById(R.id.log);
}
public void showMessage(final int messageType, final String msg){
runOnUiThread(new Runnable() {
@Override
public void run() {
log.setText(msg); // here is the problem
}
}
});
在logClass中:
private static MainActivity mainActivity;
public logClass() {
mainActivity = new MainActivity();
}
public void log() {
try {
mainActivity.showMessage(MessageTag.TIP, "Connecting...");
} catch(Exception el) {
el.printStackTrace();
}
}
在callFragment中:
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start:
new Thread(new Runnable() {
@Override
public void run() {
logClass.log();
}
}).start();
}
}
但是我遇到了这个问题:
FATAL EXCEPTION: main
Process: com.test.testing, PID: 7636
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:117)
at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:149)
at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:29)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:54)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:202)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:183)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
at com.test.testing.MainActivity$2.run(MainActivity.java:97)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
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)
答案 0 :(得分:0)
答案 1 :(得分:0)
如果callFragment
MainActivity
被@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start:
((MainActivity) getActivity()).showMessage(MessageTag.TIP, "Connecting...");
}
}
夸大,那么您可以这样做。
p4 verify
我也没有在你的代码中找到使用Thread。因为如果android默认运行在主线程上,可以改变你的观点。所以你可以在线程中删除多余的包装代码。