Android 3.0 Галерея и веб-просмотр NullPointerException - PullRequest
1 голос
/ 12 января 2012

Я сейчас экспериментирую с галереей Android.Вместо imageViews я использовал webviews.Эти веб-просмотры не кликабельны, поэтому галерею можно проводить влево или вправо.Но при длинном щелчке веб-просмотры должны стать кликабельными.Мой код работал отлично до версии 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;

    }


}

}

1 Ответ

0 голосов
/ 12 января 2012

Я подозреваю, что ваш метод onItemLongClick() вызывается с пустым (нулевым) представлением v. Я не знаю, почему это происходит в Android 3.0, а не в 2.x, поэтому не могу вам помочь. Единственный указатель, который я могу вам дать, это то, что это плохая практика программирования - использовать try / catch, только чтобы перехватить исключение nullpointer. Вам лучше изменить код на

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

Вы должны ловить исключения только для обработки непредвиденных обстоятельств (как своего рода крайняя мера), потому что создание и обработка исключений относительно дороги, и намного эффективнее проверить, является ли объект нулевым, и действовать соответствующим образом.

...