Android onClickListener NullPointerException

2019-09-30 21:58发布

all. I've searched, but can't find anything that helps me fix this problem.

My app quits almost immediately on launch due to a NullPointerException. I suspect maybe the problem is that I'm using a drawable image (ImageView) rather than a button (View) as the thing you click on.

Thanks for any help. This has been driving me bonkers for hours!

Code is as follows:

package com.example.imageswitchermk2;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;

public class MainActivity extends Activity implements OnClickListener{
ImageView blankTile;    

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);
    blankTile = (ImageView) findViewById(R.drawable.blank); 
    blankTile.setOnClickListener(this); //LINE 19
}
    public void onClick(View v) {
        blankTile.setId(R.drawable.zero);
    }
}

and stack is as follows:

Thread [<1> main] (Suspended (exception NullPointerException))  
<VM does not provide monitor information>   
MainActivity.onCreate(Bundle) line: 19  
MainActivity(Activity).performCreate(Bundle) line: 5231 
Instrumentation.callActivityOnCreate(Activity, Bundle) line: 1087   
ActivityThread.performLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 2148    
ActivityThread.handleLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 2233 
ActivityThread.access$800(ActivityThread, ActivityThread$ActivityClientRecord, Intent) line: 135    
ActivityThread$H.handleMessage(Message) line: 1196  
ActivityThread$H(Handler).dispatchMessage(Message) line: 102    
Looper.loop() line: 136 
ActivityThread.main(String[]) line: 5001    
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]  
Method.invoke(Object, Object...) line: 515  
ZygoteInit$MethodAndArgsCaller.run() line: 785  
ZygoteInit.main(String[]) line: 601 
NativeStart.main(String[]) line: not available [native method]  

2条回答
一纸荒年 Trace。
2楼-- · 2019-09-30 22:45
blankTile = (ImageView) findViewById(R.drawable.blank); 

you can not use R.drawable to retrieve items. You have to use R.id

查看更多
看我几分像从前
3楼-- · 2019-09-30 22:52

To get Id of View,use R.id instead of R.drawable,So change

blankTile = (ImageView) findViewById(R.drawable.blank); 

to

blankTile = (ImageView) findViewById(R.id.blank); 

And set drawable using blankTile.setImageResource(R.drawable.zero);

查看更多
登录 后发表回答