我想運行一個服務,它將連接到一個網站,並從網站獲取特定數據到android設備sqlite數據庫。它工作正常。但正如我所做的那樣,它有時會給出這個錯誤。但是當服務再次運行時,它再次運行良好。我根本找不到錯誤。此外,這是我第一次寫這麼複雜的服務,請讓我知道是否有任何有效的方法來做到這一點。Android服務java.lang.IndexOutOfBoundsException
public class Serviceclass extends Service {
protected static final String MyPREFERENCES = null;
private boolean isRunning;
private Context context;
private Thread backgroundThread;
private float n;
private ArrayList<String> xx = new ArrayList<String>();
private Document doc;
private String checkdate;
DatabaseHandler db = new DatabaseHandler(this);
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
this.context = this;
this.isRunning = false;
this.backgroundThread = new Thread(myTask);
}
private Runnable myTask = new Runnable() {
public void run() {
SharedPreferences myPrefs = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String date = myPrefs.getString("Date", null);
if (date != null) {
System.out.println("its not empty");
// check if the dates are a match
match(date);
} else {
System.out.println("its empty");
update();
}
stopSelf();
}
};
@Override
public void onDestroy() {
this.isRunning = false;
}
protected void match(String date) {
check();
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
checkdate = sharedpreferences.getString("Date", null);
System.out.println(checkdate);
if (date.contentEquals(checkdate)) {
System.out.println("Dates are the same");
db.addDaily(new Daily(xx.get(0), xx.get(7), xx.get(8)));
} else {
System.out.println("Dates are not the same");
update();
}
}
private void check() {
// TODO Auto-generated method stub
try {
doc = Jsoup.connect("http://www.xoxoxoxoxox.com/index.php").get();
Log.i("tag", "post");
Elements myin = doc.getElementsByClass("rates_text_home");
for (Element element : myin) {
String a = element.text();
xx.add(a);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void update() {
check();
Log.i("tag", xx.get(0));
System.out.println("Loading Data");
db.addDaily(new Daily(xx.get(0), xx.get(7), xx.get(8)));
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putString("Date", xx.get(0));
editor.commit();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!this.isRunning) {
this.isRunning = true;
this.backgroundThread.start();
}
return START_STICKY;
}
}
以下是錯誤的logcat輸出。
FATAL EXCEPTION: Thread-13
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
at java.util.ArrayList.get(ArrayList.java:311)
at com.example.marketapp.Serviceclass.match(Serviceclass.java:82)
at com.example.marketapp.Serviceclass$1.run(Serviceclass.java:53)
at java.lang.Thread.run(Thread.java:1019)