2015-11-07 151 views
0

我正在使用Async的天氣應用程序。它適用於MainActivity,現在我試圖爲它開發一個小部件,但我得到一個異常。執行doInBackground()時發生錯誤 - Android Widget

對於SO的其他答案,關於此問題的一般共識是停止在doInBackground中使用UI線程。所以我保持最小。

package ali.projecto; 

import android.app.PendingIntent; 
import android.appwidget.AppWidgetManager; 
import android.appwidget.AppWidgetProvider; 
import android.content.ComponentName; 
import android.content.Context; 
import android.content.Intent; 
import android.location.Criteria; 
import android.location.Location; 
import android.location.LocationManager; 
import android.os.AsyncTask; 
import android.widget.RemoteViews; 
import org.w3c.dom.Document; 
import org.w3c.dom.Element; 
import org.w3c.dom.Node; 
import java.io.InputStream; 
import java.net.URL; 

import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 

public class Widget extends AppWidgetProvider { 
    String xtemp; 
    Location loc; 
    Context context; 
    //======================================= OnUpdate Method 
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { 
     try { 
      RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget); 

      Intent intent = new Intent(context, Widget.class); 
      intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[0]); 
      intent.setAction("update"); 

      PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 
      remoteViews.setOnClickPendingIntent(R.id.rButton, pi); 

      new MyAsyncTask2().execute(context); 

      appWidgetManager.updateAppWidget(appWidgetIds, remoteViews); 
     }catch (Exception e){ 
      e.printStackTrace(); 
     } 
    } 
    //======================================= OnReceive Method 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     super.onReceive(context, intent); 
     try { 
     if (intent.getAction().equals("update")) { 
      new MyAsyncTask2().execute(); 
     } 
     } catch (Exception e){ 
      e.printStackTrace(); 
     } 
    } 
    //======================================= AsyncTask 
    public class MyAsyncTask2 extends AsyncTask<Context, Void, String> { 
     private RemoteViews views; 
     private Context context; 

     @Override 
     protected void onPreExecute() { 
      //getLocation(); 
     } 
     @Override 
     protected String doInBackground(Context... params) { 
      context = params[0]; 
      return loadXML2(); 
     } 
     @Override 
     protected void onPostExecute(String result) { 
      try { 
       AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); 
       views = new RemoteViews(context.getPackageName(), R.layout.widget); 
       if (result != null && result.length() >= 1) { 
        views.setTextViewText(R.id.widtemp, result); 
       } 
       appWidgetManager.updateAppWidget(new ComponentName(context, Widget.class), views); 
      } catch (Exception e){ 
       e.printStackTrace(); 
      } 
     } 
    } 
    //======================================= Load XML 
    public String loadXML2() { 
     try { 
      //=============================== Getting Data 
      URL xmlUrl = new URL("http://api.openweathermap.org/data/2.5/weather?q=dallas%20ga&units=metric&mode=xml&MYIDGOESHERE&units=metric&mode=xml"); 
      InputStream in = xmlUrl.openStream(); 
      Document doc = parse(in); 
      doc.getDocumentElement().normalize(); 
      //================================ Getting Temperature 
      Node nNode = doc.getElementsByTagName("temperature").item(0); 
      Element eElement = (Element) nNode; 
      double d = Math.round(Double.parseDouble(eElement.getAttribute("value"))); 
      int dx = (int) d; 
      xtemp = Integer.toString(dx) + "°"; 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return xtemp; 
    } 
    //======================================= Document Parsing 
    public static Document parse (InputStream is) { 
     Document ret = null; 
     DocumentBuilderFactory domFactory; 
     DocumentBuilder builder; 

     try { 
      domFactory = DocumentBuilderFactory.newInstance(); 
      domFactory.setValidating(false); 
      domFactory.setNamespaceAware(false); 
      builder = domFactory.newDocumentBuilder(); 

      ret = builder.parse(is); 
     } 
     catch (Exception ex) { 
      System.err.println("unable to load XML: " + ex); 
     } 
     return ret; 
    } 
} 

步驟產生這種錯誤:

  1. 創建窗口小部件(它更新,並顯示溫度就好了)。
  2. 單擊該小部件並停止使用此異常。

錯誤:

11-06 22:54:09.869 2505-3375/ali.projecto E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #4 
11-06 22:54:09.869 2505-3375/ali.projecto E/AndroidRuntime: Process: ali.projecto, PID: 2505 
11-06 22:54:09.869 2505-3375/ali.projecto E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground() 
11-06 22:54:09.869 2505-3375/ali.projecto E/AndroidRuntime:  at android.os.AsyncTask$3.done(AsyncTask.java:300) 
11-06 22:54:09.869 2505-3375/ali.projecto E/AndroidRuntime:  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) 
11-06 22:54:09.869 2505-3375/ali.projecto E/AndroidRuntime:  at java.util.concurrent.FutureTask.setException(FutureTask.java:222) 
11-06 22:54:09.869 2505-3375/ali.projecto E/AndroidRuntime:  at java.util.concurrent.FutureTask.run(FutureTask.java:242) 
11-06 22:54:09.869 2505-3375/ali.projecto E/AndroidRuntime:  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
11-06 22:54:09.869 2505-3375/ali.projecto E/AndroidRuntime:  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
11-06 22:54:09.869 2505-3375/ali.projecto E/AndroidRuntime:  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
11-06 22:54:09.869 2505-3375/ali.projecto E/AndroidRuntime:  at java.lang.Thread.run(Thread.java:818) 
11-06 22:54:09.869 2505-3375/ali.projecto E/AndroidRuntime: Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0 
11-06 22:54:09.869 2505-3375/ali.projecto E/AndroidRuntime:  at ali.projecto.Widget$MyAsyncTask2.doInBackground(Widget.java:77) 
11-06 22:54:09.869 2505-3375/ali.projecto E/AndroidRuntime:  at ali.projecto.Widget$MyAsyncTask2.doInBackground(Widget.java:67) 
11-06 22:54:09.869 2505-3375/ali.projecto E/AndroidRuntime:  at android.os.AsyncTask$2.call(AsyncTask.java:288) 
11-06 22:54:09.869 2505-3375/ali.projecto E/AndroidRuntime:  at java.util.concurrent.FutureTask.run(FutureTask.java:237) 
11-06 22:54:09.869 2505-3375/ali.projecto E/AndroidRuntime:  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)  
11-06 22:54:09.869 2505-3375/ali.projecto E/AndroidRuntime:  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)  
11-06 22:54:09.869 2505-3375/ali.projecto E/AndroidRuntime:  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)  
11-06 22:54:09.869 2505-3375/ali.projecto E/AndroidRuntime:  at java.lang.Thread.run(Thread.java:818)  
+1

你不能傳遞一個'Context'到'新MyAsyncTask2()。在執行'的onReceive()'調用()'。 –

+0

它的工作原理!謝謝!自從你先回答以後,我怎麼能接受你的回答? –

+0

很酷。輕鬆修復。真高興你做到了。 –

回答

1
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0 

Array爲空。

這條線可能會導致錯誤:

context = params[0];

的解決方案是在執行它的參數傳遞給異步任務。

new MyAsyncTask2().execute(my_parameter); 
相關問題