Android onClickListener NullPointerException

我怕爱的太早我们不能终老 提交于 2019-12-13 11:28:31

问题


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]  

回答1:


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

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




回答2:


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



来源:https://stackoverflow.com/questions/24990500/android-onclicklistener-nullpointerexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!