How to call a new thread from button click

Posted by Lynnooi on Stack Overflow See other posts from Stack Overflow or by Lynnooi
Published on 2010-04-15T08:34:27Z Indexed on 2010/04/19 4:43 UTC
Read the original article Hit count: 415

Filed under:
|

Hi,

I'm trying to call a thread on a button click (btn_more) but i cant get it right. The thread is to get some data and update the images. The problem i have is if i only update 4 or 5 images then it works fine. But if i load more than 5 images i will get a force close. At times when the internet is slow I will face the same problem too. Can please help me to solve this problem or provide me some guidance? Here is the error i got from LogCat:

04-19 18:51:44.907: ERROR/AndroidRuntime(1034): Uncaught handler: thread main exiting due to uncaught exception 04-19 18:51:44.927: ERROR/AndroidRuntime(1034): java.lang.NullPointerException 04-19 18:51:44.927: ERROR/AndroidRuntime(1034): at mobile9.android.gallery.GalleryWallpapers.setWallpaperThumb(GalleryWallpapers.java:383) 04-19 18:51:44.927: ERROR/AndroidRuntime(1034): at mobile9.android.gallery.GalleryWallpapers.access$4(GalleryWallpapers.java:320) 04-19 18:51:44.927: ERROR/AndroidRuntime(1034): at mobile9.android.gallery.GalleryWallpapers$1.handleMessage(GalleryWallpapers.java:266) 04-19 18:51:44.927: ERROR/AndroidRuntime(1034): at android.os.Handler.dispatchMessage(Handler.java:99) 04-19 18:51:44.927: ERROR/AndroidRuntime(1034): at android.os.Looper.loop(Looper.java:123) 04-19 18:51:44.927: ERROR/AndroidRuntime(1034): at android.app.ActivityThread.main(ActivityThread.java:4310) 04-19 18:51:44.927: ERROR/AndroidRuntime(1034): at java.lang.reflect.Method.invokeNative(Native Method) 04-19 18:51:44.927: ERROR/AndroidRuntime(1034): at java.lang.reflect.Method.invoke(Method.java:521) 04-19 18:51:44.927: ERROR/AndroidRuntime(1034): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860) 04-19 18:51:44.927: ERROR/AndroidRuntime(1034): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 04-19 18:51:44.927: ERROR/AndroidRuntime(1034): at dalvik.system.NativeStart.main(Native Method)

My Code:

public class GalleryWallpapers extends Activity implements 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;
            }
     }

  }

© Stack Overflow or respective owner

Related posts about android

Related posts about thread