如何从按钮单击调用新线程

时间:2010-04-15 08:34:28

标签: android multithreading

我正在尝试按下按钮(btn_more)来调用线程,但我无法正确使用它。线程是获取一些数据并更新图像。我遇到的问题是,如果我只更新4或5个图像,那么它工作正常。但如果我加载超过5张图像,我将获得一个力量关闭。在互联网速度慢的时候,我也会遇到同样的问题。请帮我解决这个问题或者给我一些指导?这是我从LogCat得到的错误:

  

04-19 18:51:44.907:ERROR / AndroidRuntime(1034):未捕获   handler:thread main由于退出   未被捕的例外04-19 18:51:44.927:   ERROR / AndroidRuntime(1034):   java.lang.NullPointerException 04-19   18:51:44.927:   错误/ AndroidRuntime(1034):at   mobile9.android.gallery.GalleryWallpapers.setWallpaperThumb(GalleryWallpapers.java:383)   04-19 18:51:44.927:   错误/ AndroidRuntime(1034):at   mobile9.android.gallery.GalleryWallpapers.access $ 4(GalleryWallpapers.java:320)   04-19 18:51:44.927:   错误/ AndroidRuntime(1034):at   mobile9.android.gallery.GalleryWallpapers $ 1.handleMessage(GalleryWallpapers.java:266)   04-19 18:51:44.927:   错误/ AndroidRuntime(1034):at   android.os.Handler.dispatchMessage(Handler.java:99)   04-19 18:51:44.927:   错误/ AndroidRuntime(1034):at   android.os.Looper.loop(Looper.java:123)   04-19 18:51:44.927:   错误/ AndroidRuntime(1034):at   android.app.ActivityThread.main(ActivityThread.java:4310)   04-19 18:51:44.927:   错误/ AndroidRuntime(1034):at   java.lang.reflect.Method.invokeNative(母语   方法)04-19 18:51:44.927:   错误/ AndroidRuntime(1034):at   java.lang.reflect.Method.invoke(Method.java:521)   04-19 18:51:44.927:   错误/ AndroidRuntime(1034):at   com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:860)   04-19 18:51:44.927:   错误/ AndroidRuntime(1034):at   com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)   04-19 18:51:44.927:   错误/ AndroidRuntime(1034):at   dalvik.system.NativeStart.main(母语   方法)

我的代码:

  

公共类GalleryWallpapers扩展Activity实现Runnable {

  public static String MODEL = android.os.Build.MODEL ;
    private static final String rootURL = "http://www.uploadhub.com/mobile9/gallery/c/";

    private int wallpapers_count = 0;

    private int ringtones_count = 0;

    private int index = 0;

    private int folder_id;

    private int page;

    private int page_counter = 1;

    private String family;

    private String keyword;

    private String xmlURL = "";

    private String thread_op = "xml";

    private ImageButton btn_back;

    private ImageButton btn_home;

    private ImageButton btn_filter;

    private ImageButton btn_search;

    private TextView btn_more;

    private ProgressDialog pd;

    GalleryExampleHandler myExampleHandler = new GalleryExampleHandler();


    Context context = GalleryWallpapers.this.getBaseContext();

    Drawable image;


    @Override

    public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            MODEL = "HTC Legend";  // **needs to be remove after testing**

            try {

                 MODEL = URLEncoder.encode(MODEL,"UTF-8");

            } catch (UnsupportedEncodingException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

            }
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            setContentView(R.layout.gallerywallpapers);
            Bundle b = this.getIntent().getExtras();
            family = b.getString("fm").trim();
            folder_id = Integer.parseInt(b.getString("fi"));
            keyword = b.getString("kw").trim();
            page = Integer.parseInt(b.getString("page").trim());
            WindowManager w = getWindowManager();
            Display d = w.getDefaultDisplay();
            final int width = d.getWidth();
            final int height = d.getHeight();
            xmlURL = rootURL + "wallpapers/1/?output=rss&afm=wallpapers&mdl=" + MODEL + "&awd=" + width + "&aht=" + height;
            if (folder_id > 0) {
                  xmlURL = xmlURL + "&fi=" + folder_id;
            }

            pd = ProgressDialog.show(GalleryWallpapers.this, "",
            "Loading...", true, false);
            Thread thread = new Thread(GalleryWallpapers.this);
            thread.start();

            btn_more = (TextView) findViewById(R.id.btn_more);

            btn_more.setOnClickListener(new View.OnClickListener() {
                  public void onClick(View view) {
                            myExampleHandler.filenames.clear();
                            myExampleHandler.authors.clear();
                            myExampleHandler.duration.clear();
                            myExampleHandler.fileid.clear();

                            btn_more.setBackgroundResource(R.drawable.btn_more_click);
                            page = page + 1;
                            thread_op = "xml";
                            xmlURL = rootURL + "wallpapers/1/?output=rss&afm=wallpapers&mdl=" + MODEL + "&awd=" + width + "&aht=" + height;
                            xmlURL = xmlURL + "&pg2=" + page;
                            index = 0;
                            pd = ProgressDialog.show(GalleryWallpapers.this, "",
                    "Loading...", true, false);
                            Thread thread = new Thread(GalleryWallpapers.this);
                            thread.start();
                       }
                 });

   }


        public void run() {
            if(thread_op.equalsIgnoreCase("xml")){
                     readXML();
            }
            else if(thread_op.equalsIgnoreCase("getImg")){
                     getWallpaperThumb();
            }
            handler.sendEmptyMessage(0);
         }

         private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        int count = 0;
        if (!myExampleHandler.filenames.isEmpty()){
            count = myExampleHandler.filenames.size();
        }
        count = 6;
        if(thread_op.equalsIgnoreCase("xml")){
            pd.dismiss();
            thread_op = "getImg";
            btn_more.setBackgroundResource(R.drawable.btn_more);
        }
        else if(thread_op.equalsIgnoreCase("getImg")){
            setWallpaperThumb();
            index++;
            if (index < count){
                Thread thread = new Thread(GalleryWallpapers.this);
                thread.start();

            }
        }
    }
};

    private void readXML(){
    if (xmlURL.length() != 0) {
        try {
            /* Create a URL we want to load some xml-data from. */
            URL url = new URL(xmlURL);
            /* Get a SAXParser from the SAXPArserFactory. */
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();

            /* Get the XMLReader of the SAXParser we created. */
            XMLReader xr = sp.getXMLReader();
            /*
             * Create a new ContentHandler and apply it to the
             * XML-Reader
             */
            xr.setContentHandler(myExampleHandler);

            /* Parse the xml-data from our URL. */
            xr.parse(new InputSource(url.openStream()));
            /* Parsing has finished. */

            /*
             * Our ExampleHandler now provides the parsed data to
             * us.
             */
            ParsedExampleDataSet parsedExampleDataSet = myExampleHandler
                    .getParsedData();

        } catch (Exception e) {
            //showDialog(DIALOG_SEND_LOG);
        }
    }
}

    private void getWallpaperThumb(){
           int i = this.index;
           if (!myExampleHandler.filenames.elementAt(i).toString().equalsIgnoreCase("")){
                     image = ImageOperations(context,
                myExampleHandler.thumbs.elementAt(i).toString(), "image.jpg");
           }
     }

      private void setWallpaperThumb(){
            int i = this.index;
            if (myExampleHandler.filenames.elementAt(i).toString() != null) {
                    String file_info = myExampleHandler.filenames.elementAt(i).toString();
                    String author = "\nby " + myExampleHandler.authors.elementAt(i).toString();
                    final String folder = myExampleHandler.folder_id.elementAt(folder_id).toString();
                    final String fid = myExampleHandler.fileid.elementAt(i).toString();
                    ImageView imgView = new ImageView(context);
                    TextView tv_filename = null;
                    TextView tv_author = null;

                    switch (i + 1) {
                            case 1:
                                  imgView = (ImageView) findViewById(R.id.image1);
                                  tv_filename = (TextView) findViewById(R.id.filename1);
                                  tv_author = (TextView) findViewById(R.id.author1);
                                  break;
                            case 2:
                                  imgView = (ImageView) findViewById(R.id.image2);
                                  tv_filename = (TextView) findViewById(R.id.filename2);
                                  tv_author = (TextView) findViewById(R.id.author2);
                                  break;
                            case 3:
                                  imgView = (ImageView) findViewById(R.id.image3);
                                  tv_filename = (TextView) findViewById(R.id.filename3);
                                  tv_author = (TextView) findViewById(R.id.author3);
                                  break;
            case 4:
                .
                                    .
                                    .
                                    .
                                    .
            case 10:
                                  imgView = (ImageView) findViewById(R.id.image10);
                                  tv_filename = (TextView) findViewById(R.id.filename10);
                                  tv_author = (TextView) findViewById(R.id.author10);
                                  break;
                    }
                    if (image.getIntrinsicHeight() > 0) {
                         imgView.setImageDrawable(image);
                    } else {
                         imgView.setImageResource(R.drawable.default_wallpaper);
                    }
                    tv_filename.setText(file_info);
                    tv_author.setText(author);
                    imgView.setOnClickListener(new View.OnClickListener() {
                           public void onClick(View view) {
                // Perform action on click
            }
        });
    }
}

    private Drawable ImageOperations(Context ctx, String url,
            String saveFilename) {
            try {
                    InputStream is = (InputStream) this.fetch(url);
                    Drawable d = Drawable.createFromStream(is, "src");
                    return d;
            } catch (MalformedURLException e) {
                    e.printStackTrace();
                    return null;
            } catch (IOException e) {
                    e.printStackTrace();
                    return null;
            }
     }

  }

1 个答案:

答案 0 :(得分:0)

在代码中使用try catch块,Eclipse IDE将发出警告,您必须解决此问题。问题是因为你的数组索引超出了初学者的范围,Java会抛出一个你可以捕获的异常。我希望这会有所帮助。