Android 3.0 画廊 & Webview 空指针异常

发布于 2024-12-26 17:00:05 字数 5868 浏览 1 评论 0原文

我目前正在尝试 Android Gallery。我使用了 webviews,而不是 imageViews。这些网络视图不可点击,因此可以向左或向右滑动图库。但长按时,网络视图应该变得可点击。我的代码在 2.2 版本之前都可以完美运行。现在我有一个 3.0 设备要测试,代码在长按时失败...代码如下。

这里出了问题

    customGallery g = (customGallery) findViewById(R.id.gallery);
    g.setAdapter(new ImageAdapter(this));


    // ZOOM FUNCTION !
    //Detect longclicks on the gallery if the user preforms a longclick we check if view is clickable (clickable means we can zoom in on the webview)

    g.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView parent, View v, int position, long id) {
            //IT GOES WRONG RIGHT HERE 


            try{
        if(v.isClickable()){
                    Toast.makeText(ImageGalleryActivity.this, "Zoom disabled", Toast.LENGTH_SHORT).show();
                    v.setClickable(false);
                }else{
                    v.setClickable(true);
                    Toast.makeText(ImageGalleryActivity.this, "Zoom enabled", Toast.LENGTH_SHORT).show();
                }
            }catch (Exception e){
                Log.i("Exception", String.format("%s", e));
                Toast.makeText(ImageGalleryActivity.this, "NULLPNTR", Toast.LENGTH_SHORT).show();

            }
            return true;
            }

    });

}

这是该活动的完整代码...

public class ImageGalleryActivity extends Activity {

private WebView web;
public int screenWidth;
public int screenHeight;’

public View vx;
//ArrayList needed to quickly store the images we get from the AssetManager
ArrayList <String> imgID = new ArrayList <String>();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //Asset Manager needed to collect all the files in specific folders of assets
    final AssetManager assetManager = getAssets();
    Display display = getWindowManager().getDefaultDisplay();

    screenWidth = display.getWidth();
    screenHeight = display.getHeight();

    Log.i("Intial Height", String.format("%d", screenHeight));
    Log.i("Intial Width", String.format("%d", screenWidth));


    //Try collecting all the images
    try{
        String [] filelist = assetManager.list("book1");
        if (filelist == null){
            //TODO errorCatching 
        }else{
            for (int i = 0; i<filelist.length; i++){
            String fileName = filelist[i];
            Log.i("THE FILENAMES", fileName);
            //Add the images to the ArrayList (stringtype)
            imgID.add(fileName);

            }

        }
    }catch (IOException e){


    }

    setContentView(R.layout.main);

    customGallery g = (customGallery) findViewById(R.id.gallery);
    g.setAdapter(new ImageAdapter(this));


    // ZOOM FUNCTION !
    //Detect longclicks on the gallery if the user preforms a longclick we check if view is clickable (clickable means we can zoom in on the webview)

    g.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView parent, View v, int position, long id) {
            //IT GOES WRONG RIGHT HERE 


            try{
        if(v.isClickable()){
                    Toast.makeText(ImageGalleryActivity.this, "Zoom disabled", Toast.LENGTH_SHORT).show();
                    v.setClickable(false);
                }else{
                    v.setClickable(true);
                    Toast.makeText(ImageGalleryActivity.this, "Zoom enabled", Toast.LENGTH_SHORT).show();
                }
            }catch (Exception e){
                Log.i("Exception", String.format("%s", e));
                Toast.makeText(ImageGalleryActivity.this, "NULLPNTR", Toast.LENGTH_SHORT).show();

            }
            return true;
            }

    });

}



//Create imageAdapter class...

public class ImageAdapter extends BaseAdapter{
    int imagebackground;
    private Context mContext;

    public ImageAdapter(Context c){
        mContext = c;
        TypedArray a = obtainStyledAttributes(R.styleable.gallery);
        imagebackground = a.getResourceId(R.styleable.gallery_android_galleryItemBackground, 0);
        a.recycle();
    }

    public int getCount(){
        return imgID.size();

    }

    public Object getItem(int position){
        return position;
    }

    public long getItemId(int position){
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent){
        web = new WebView(mContext);
        String currImg = imgID.get(position);
        Log.i("Drawable", String.format("%s", imgID.get(position)));



        String stringScreenWidth = String.format("%d", screenWidth-200);
        Log.i("Current ScreenWidth", String.format("%d", screenWidth));
        Log.i("Should be", stringScreenWidth);
        web.loadDataWithBaseURL("file:///android_asset/book1/", "<html><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=10  minimum-scale=1\"><body style='width:"+screenWidth+"px;margin:0;padding:0;min-width:100%;'><image style='width:"+screenWidth+"px;' src='"+currImg+"'/><body></html>", "text/html", "UTF-8", null);
        //web.getSettings().setBuiltInZoomControls(true);
        web.setVerticalScrollBarEnabled(false);
        web.setHorizontalScrollBarEnabled(false);
        web.setMinimumHeight(1024);
        web.getSettings().setSupportZoom( true ); //Modify this
        web.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);//
        web.setLayoutParams( new customGallery.LayoutParams(WindowManager.LayoutParams.FILL_PARENT, WindowManager.LayoutParams.FILL_PARENT));


        web.setClickable(false);
        web.setFocusable(false);
        web.setLongClickable(true);
        return web;

    }


}

}

I'm currently experimenting with the Android Gallery. Instead of imageViews I used webviews. These webviews are not clickable so the gallery can be swiped left or right. But on a longclick the webviews should become clickable. My code worked perfectly until version 2.2. Now I have a 3.0 device to test on and the code fails at the longclick... Code is below.

It goes wrong here

    customGallery g = (customGallery) findViewById(R.id.gallery);
    g.setAdapter(new ImageAdapter(this));


    // ZOOM FUNCTION !
    //Detect longclicks on the gallery if the user preforms a longclick we check if view is clickable (clickable means we can zoom in on the webview)

    g.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView parent, View v, int position, long id) {
            //IT GOES WRONG RIGHT HERE 


            try{
        if(v.isClickable()){
                    Toast.makeText(ImageGalleryActivity.this, "Zoom disabled", Toast.LENGTH_SHORT).show();
                    v.setClickable(false);
                }else{
                    v.setClickable(true);
                    Toast.makeText(ImageGalleryActivity.this, "Zoom enabled", Toast.LENGTH_SHORT).show();
                }
            }catch (Exception e){
                Log.i("Exception", String.format("%s", e));
                Toast.makeText(ImageGalleryActivity.this, "NULLPNTR", Toast.LENGTH_SHORT).show();

            }
            return true;
            }

    });

}

Here is the full code of the activity...

public class ImageGalleryActivity extends Activity {

private WebView web;
public int screenWidth;
public int screenHeight;’

public View vx;
//ArrayList needed to quickly store the images we get from the AssetManager
ArrayList <String> imgID = new ArrayList <String>();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //Asset Manager needed to collect all the files in specific folders of assets
    final AssetManager assetManager = getAssets();
    Display display = getWindowManager().getDefaultDisplay();

    screenWidth = display.getWidth();
    screenHeight = display.getHeight();

    Log.i("Intial Height", String.format("%d", screenHeight));
    Log.i("Intial Width", String.format("%d", screenWidth));


    //Try collecting all the images
    try{
        String [] filelist = assetManager.list("book1");
        if (filelist == null){
            //TODO errorCatching 
        }else{
            for (int i = 0; i<filelist.length; i++){
            String fileName = filelist[i];
            Log.i("THE FILENAMES", fileName);
            //Add the images to the ArrayList (stringtype)
            imgID.add(fileName);

            }

        }
    }catch (IOException e){


    }

    setContentView(R.layout.main);

    customGallery g = (customGallery) findViewById(R.id.gallery);
    g.setAdapter(new ImageAdapter(this));


    // ZOOM FUNCTION !
    //Detect longclicks on the gallery if the user preforms a longclick we check if view is clickable (clickable means we can zoom in on the webview)

    g.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView parent, View v, int position, long id) {
            //IT GOES WRONG RIGHT HERE 


            try{
        if(v.isClickable()){
                    Toast.makeText(ImageGalleryActivity.this, "Zoom disabled", Toast.LENGTH_SHORT).show();
                    v.setClickable(false);
                }else{
                    v.setClickable(true);
                    Toast.makeText(ImageGalleryActivity.this, "Zoom enabled", Toast.LENGTH_SHORT).show();
                }
            }catch (Exception e){
                Log.i("Exception", String.format("%s", e));
                Toast.makeText(ImageGalleryActivity.this, "NULLPNTR", Toast.LENGTH_SHORT).show();

            }
            return true;
            }

    });

}



//Create imageAdapter class...

public class ImageAdapter extends BaseAdapter{
    int imagebackground;
    private Context mContext;

    public ImageAdapter(Context c){
        mContext = c;
        TypedArray a = obtainStyledAttributes(R.styleable.gallery);
        imagebackground = a.getResourceId(R.styleable.gallery_android_galleryItemBackground, 0);
        a.recycle();
    }

    public int getCount(){
        return imgID.size();

    }

    public Object getItem(int position){
        return position;
    }

    public long getItemId(int position){
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent){
        web = new WebView(mContext);
        String currImg = imgID.get(position);
        Log.i("Drawable", String.format("%s", imgID.get(position)));



        String stringScreenWidth = String.format("%d", screenWidth-200);
        Log.i("Current ScreenWidth", String.format("%d", screenWidth));
        Log.i("Should be", stringScreenWidth);
        web.loadDataWithBaseURL("file:///android_asset/book1/", "<html><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=10  minimum-scale=1\"><body style='width:"+screenWidth+"px;margin:0;padding:0;min-width:100%;'><image style='width:"+screenWidth+"px;' src='"+currImg+"'/><body></html>", "text/html", "UTF-8", null);
        //web.getSettings().setBuiltInZoomControls(true);
        web.setVerticalScrollBarEnabled(false);
        web.setHorizontalScrollBarEnabled(false);
        web.setMinimumHeight(1024);
        web.getSettings().setSupportZoom( true ); //Modify this
        web.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);//
        web.setLayoutParams( new customGallery.LayoutParams(WindowManager.LayoutParams.FILL_PARENT, WindowManager.LayoutParams.FILL_PARENT));


        web.setClickable(false);
        web.setFocusable(false);
        web.setLongClickable(true);
        return web;

    }


}

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

睡美人的小仙女 2025-01-02 17:00:05

我怀疑您的 onItemLongClick() 方法是用空(null)视图调用的。我不知道为什么这种情况发生在 Android 3.0 而不是 2.x 中,所以无法帮助您。我可以给您的唯一提示是,仅使用 try/catch 来捕获空指针异常是不好的编程习惯。您最好将代码更改为“

if (v != null && v.isClickable()) { 
   ....  
}

您应该只捕获异常来处理不可预见的情况”(作为一种最后的手段),因为抛出和处理异常的成本相对较高,并且检查对象是否为 null 并采取适当的行动会更有效。

I suspect that your onItemLongClick() method is called with an empty (null) View v. I don't know why this happens in Android 3.0 and not in 2.x so can't help you there. The only pointer I can give you is that it's bad programming practice to use try/catch, only to catch a nullpointer exception. You'd better change your code to

if (v != null && v.isClickable()) { 
   ....  
}

You should only catch exceptions to handle unforeseen circumstances (as a sort of last resort measure) because throwing and handling exceptions is relatively costly and it's much more efficient to check if an object is null and act appropriately.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文