Получить объект из метода (работоспособного) таймера - PullRequest
1 голос
/ 11 августа 2010

Я реализовал таймер, который анализирует URL каждые 15 минут (задача Timer). Объект с именем ParsedExampleDataSet получает эти данные.

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

Как я могу получить его? Есть ли другая реализация, которую я мог бы попробовать? Почему getBaseContext() не работает внутри работоспособного?

Вот большая часть моего кода, где у меня проблема. Я также добавил два комментария, где моя проблема возникает.

 @Override
    public void onCreate(Bundle icicle) {
            super.onCreate(icicle)
           final  TextView tv = new TextView(this);
            TimerTask scanTask;
            final Handler handler = new Handler();
            Timer t = new Timer();                  
                scanTask = new TimerTask() {
                    public void run() {
                            handler.post(new Runnable() {
                                    public void run() {
                                        URL url = null;
                                        try {
                                            url = new URL("http://www.eurosport.fr/");
                                        } catch (MalformedURLException e3) {

                                            e3.printStackTrace();
                                        }

                                        /* Get a SAXParser from the SAXPArserFactory. */
                                        SAXParserFactory spf = SAXParserFactory.newInstance();
                                        SAXParser sp;
                                        try {
                                            sp = spf.newSAXParser();
                                        } catch (ParserConfigurationException e2) {

                                            e2.printStackTrace();
                                        } catch (SAXException e2) {

                                            e2.printStackTrace();
                                        }

                                        /* Get the XMLReader of the SAXParser we created. */
                                        XMLReader xr = null;
                                        try {
                                            sp = spf.newSAXParser();
                                            xr = sp.getXMLReader();
                                        } catch (SAXException e1) {

                                            e1.printStackTrace();
                                        } catch (ParserConfigurationException e) {

                                            e.printStackTrace();
                                        }
                                        /* Create a new ContentHandler and apply it to the XML-Reader*/
                                        ExampleHandler myExampleHandler = new ExampleHandler();
                                        try {
                                            sp = spf.newSAXParser();
                                        } catch (ParserConfigurationException e1) {
                                            // TODO Auto-generated catch block
                                            e1.printStackTrace();
                                        } catch (SAXException e1) {
                                            // TODO Auto-generated catch block
                                            e1.printStackTrace();
                                        }
                                        xr.setContentHandler(myExampleHandler);

                                        /* Parse the xml-data from our URL. */
                                        try {
                                            xr.parse(new InputSource(url.openStream()));
                                        } catch (IOException e) {

                                            e.printStackTrace();
                                        } catch (SAXException e) {

                                            e.printStackTrace();
                                        }
                                        /* Parsing has finished. */

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

                                       System.out.println(parsedExampleDataSet.toString());

                                        tv.setText(parsedExampleDataSet.toString());


                                     Context context = this.getBaseContext(); 

 // I dont understand why inside the runnable getBaseContext() does not exist ???

    Bitmap mBitmap = BitmapFactory.decodeResource(getResources(),
            R.raw.nature1)
        context.setWallpaper(mBitmap);


                                    }


                           });

                    }  };
                    // I want to retrieve ParsedExampleDataSEt here in order to use it  is it Possible ????



                    this.setContentView(tv);



                   long temps=1*15*1000;

                t.scheduleAtFixedRate(scanTask, 300,temps ); 

1 Ответ

1 голос
/ 21 октября 2010

Я думаю, это потому, что когда вы делаете: Context context = this.getBaseContext() внутри класса TimerTask(), вы ссылаетесь на переменную, которая находится вне области действия класса.Поскольку TimerTask() не имеет подкласса от ContextWrapper, он не получает контекст напрямую.Чтобы получить контекст действия (надеюсь, а не контекст Application), вы должны сделать: Context context = ParsedExampleDataSet.this.getBaseContext(); Таким образом, вы, вероятно, не должны получать никаких исключений нулевого указателя.

...