我收到一条错误消息,指出“FATAL EXCEPTION: AsyncTask #2 java.lang.RuntimeException: An error occurred while execution doInBackground() IndexOutOfBoundsException: Invalid index 1, size is 1”,我不知道为什么。我的 logcat 和源代码如下。如果需要任何其他信息,请告诉我......我只需要知道如何避免这种情况。
提前致谢!
日志猫:
08-01 09:21:38.019: E/AndroidRuntime(8421): FATAL EXCEPTION: AsyncTask #2
08-01 09:21:38.019: E/AndroidRuntime(8421): java.lang.RuntimeException: An error occured while executing doInBackground()
08-01 09:21:38.019: E/AndroidRuntime(8421): at android.os.AsyncTask$3.done(AsyncTask.java:200)
08-01 09:21:38.019: E/AndroidRuntime(8421): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
08-01 09:21:38.019: E/AndroidRuntime(8421): at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
08-01 09:21:38.019: E/AndroidRuntime(8421): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
08-01 09:21:38.019: E/AndroidRuntime(8421): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
08-01 09:21:38.019: E/AndroidRuntime(8421): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
08-01 09:21:38.019: E/AndroidRuntime(8421): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
08-01 09:21:38.019: E/AndroidRuntime(8421): at java.lang.Thread.run(Thread.java:1019)
08-01 09:21:38.019: E/AndroidRuntime(8421): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
08-01 09:21:38.019: E/AndroidRuntime(8421): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
08-01 09:21:38.019: E/AndroidRuntime(8421): at java.util.ArrayList.get(ArrayList.java:311)
08-01 09:21:38.019: E/AndroidRuntime(8421): at com.project.example.datasettings.ConfigFinalActivity.getValues(ConfigFinalActivity.java:366)
08-01 09:21:38.019: E/AndroidRuntime(8421): at com.project.example.datasettings.ConfigFinalActivity.InsertAPN(ConfigFinalActivity.java:334)
08-01 09:21:38.019: E/AndroidRuntime(8421): at com.project.example.datasettings.ConfigFinalActivity.updateTable(ConfigFinalActivity.java:689)
08-01 09:21:38.019: E/AndroidRuntime(8421): at com.project.example.datasettings.ConfigFinalActivity.access$0(ConfigFinalActivity.java:656)
08-01 09:21:38.019: E/AndroidRuntime(8421): at com.project.example.datasettings.ConfigFinalActivity$TableUpdateRequestTask.doInBackground(ConfigFinalActivity.java:560)
08-01 09:21:38.019: E/AndroidRuntime(8421): at com.project.example.datasettings.ConfigFinalActivity$TableUpdateRequestTask.doInBackground(ConfigFinalActivity.java:1)
08-01 09:21:38.019: E/AndroidRuntime(8421): at android.os.AsyncTask$2.call(AsyncTask.java:185)
08-01 09:21:38.019: E/AndroidRuntime(8421): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
08-01 09:21:38.019: E/AndroidRuntime(8421): ... 4 more
源代码段:
(错误发生在这里)
public ContentValues getValues() {
ContentValues values = new ContentValues();
values.put("name", nameArr.get(i));
values.put("apn", ApnArr.get(i));
values.put("mmsc", mmscArr.get(i));
values.put("mmsproxy", mmsproxyArr.get(i));
values.put("mmsport", mmsportArr.get(i));
values.put("proxy", proxyArr.get(i));
values.put("port", portArr.get(i));
if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))) {
values.put("numeric", getString(R.string.numeric_tmo));
values.put("mnc", (getString(R.string.mnc_tmo)));
} else if ((tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
values.put("numeric", getString(R.string.numeric_att));
values.put("mnc", (getString(R.string.mnc_att)));
}
return values;
}
/*
* Delete APN data where the indicated field has the values Entire table is
* deleted if both field and value are null
*/
private void DeleteAPNs(String field, String[] values)
throws SecurityException {
int c = 0;
c = getContentResolver().delete(APN_TABLE_URI, null, null);
if (c != 0) {
String s = "APNs Deleted:\n";
Log.d(TAG, s);
}
}
/*
* Return all column names stored in the string array
*/
private String getAllColumnNames(String[] columnNames) {
String s = "Column Names:\n";
for (String t : columnNames) {
s += t + ":\t";
}
return s + "\n";
}
完整来源:
public class ConfigFinalActivity extends Activity implements OnClickListener {
private static final String TAG = "ConfigActivity";
TelephonyManager tm;
AlertDialog mErrorAlert = null;
private Notification mNotification = null;
private Button mXButton = null;
// Progress
private ImageView mProgressImageview1;
private ImageView mProgressImageview2;
private ImageView mProgressImageview3;
private ImageView mProgressImageview4;
private ImageView mProgressImageview5;
private ImageView mLoadingCircle;
public static ArrayList<String> NameArr = new ArrayList<String>();
public static ArrayList<String> ValueArr = new ArrayList<String>();
public static ArrayList<String> nameArr = new ArrayList<String>();
public static ArrayList<String> ApnArr = new ArrayList<String>();
public static ArrayList<String> mmscArr = new ArrayList<String>();
public static ArrayList<String> mmsportArr = new ArrayList<String>();
public static ArrayList<String> mmsproxyArr = new ArrayList<String>();
public static ArrayList<String> portArr = new ArrayList<String>();
public static ArrayList<String> proxyArr = new ArrayList<String>();
public static int count;
int i, g = 0;
public static ContentValues Values = new ContentValues();
XmlParserHandlerFinal handler;
public static BigInteger id1, id2;
BigInteger[] id;
public static Integer mdn1, mdn2;
public static String car;
public static final Uri APN_TABLE_URI = Uri
.parse("content://telephony/carriers");
public static String Base_URL = "https://www.settings.com/";
NetworkTask task = new NetworkTask();
NetworkTask tasks = new NetworkTask();
InputStream stream = null;
private AnimationDrawable loadingAnimation;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int version = android.os.Build.VERSION.SDK_INT;
tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
handler = new XmlParserHandlerFinal();
handler.setContext(this.getBaseContext());
getImpVariablesForQuery();
if (version < VERSION_CODES.ICE_CREAM_SANDWICH) {
try {
// updating layout initially has updating text with 1 dot in the
// xml
setContentView(R.layout.updating);
// This image view has the updating text to be progressively
// updated
// with dots addition
ImageView loading = (ImageView) findViewById(R.id.loading_empty1);
// Button goButton = (Button) findViewById(R.id.loading_empty);
// Set updating button to drawable animation
loading.setBackgroundResource(R.drawable.updating1);
loadingAnimation = (AnimationDrawable) loading.getBackground();
ImageView loading2 = (ImageView) findViewById(R.id.loading_empty2);
// Button goButton = (Button) findViewById(R.id.loading_empty);
// Set updating button to drawable animation
loading2.setBackgroundResource(R.drawable.updating2);
loadingAnimation = (AnimationDrawable) loading2.getBackground();
// mProgressImageview = (ImageView)
// findViewById(R.id.updating_text);
// mLoadingCircle = (ImageView)
// findViewById(R.id.updating_hand);
tasks.execute("https://dl.dropboxusercontent.com/u/317242424276/GetPhoneSettings-rsp-eng.xml");
if (tasks.get() != null) {
stream = tasks.getInputStream();
Log.v("CfA", "here");
} else if (tasks.get() == null) {
setContentView(R.layout.error);
// finish();
// finish();
}
handler.getQueryResponse(stream);
Values = getContentValues();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Update APN table in separate thread
new TableUpdateRequestTask().execute("");
} else {// ICS and later versions
startActivity(new Intent(Settings.ACTION_APN_SETTINGS));
try {
task.execute("https://dl.dropboxusercontent.com/u/2342324234/GetPhoneSettings-rsp-eng.xml");
if (task.get() == null) {
setContentView(R.layout.error);
} else if (task.get() != null) {
stream = task.getInputStream();
Log.v("CfA", "here");
}
/*
* DataInputStream in = new DataInputStream(stream);
* BufferedReader br = new BufferedReader(new
* InputStreamReader(in)); String strLine; while ((strLine =
* br.readLine()) != null) { // Print the content on the console
* System.out.println (strLine); in.close(); }
*/
handler.getQueryResponse(stream);
Values = getContentValues();
showNotification();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finish();
}
}
private ContentValues getContentValues() {
ContentValues values = new ContentValues();
nameArr = handler.getnameArr();
ApnArr = handler.getApnArr();
mmscArr = handler.getMMSCArr();
mmsproxyArr = handler.getMmscProxyArr();
mmsportArr = handler.getMmsPortArr();
proxyArr = handler.getMmscProxyArr();
portArr = handler.getMmsPortArr();
count = handler.getCount();
System.out.println("count" + count);
values.put("name", nameArr.get(i));
values.put("apn", ApnArr.get(i));
values.put("mmsc", mmscArr.get(i));
values.put("mmsproxy", mmsproxyArr.get(i));
values.put("mmsport", mmsportArr.get(i));
values.put("proxy", proxyArr.get(i));
values.put("port", portArr.get(i));
if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))) {
values.put("numeric", getString(R.string.numeric_tmo));
values.put("mnc", (getString(R.string.mnc_tmo)));
} else if ((tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
values.put("numeric", getString(R.string.numeric_att));
values.put("mnc", (getString(R.string.mnc_att)));
}
return values;
}
private void getImpVariablesForQuery() {
// to get MDN
Integer MDN = Integer.parseInt(tm.getSimOperator());
Log.d("MDN", MDN.toString());
mdn1 = MDN % 1234;
Log.d("mdn1", mdn1.toString());
mdn2 = MDN / 1234;
Log.d("mdn2", mdn2.toString());
// to retrieve ICCID number of the SIM
String ICCID = tm.getSimSerialNumber();
Log.d("ICCID", ICCID);
long d = 1234;
BigInteger divisor = BigInteger.valueOf(d);
BigInteger bInteger = new BigInteger(ICCID);
id = bInteger.divideAndRemainder(divisor);
id1 = id[1];
System.out.println("ICCID%1234 = " + id1);
id2 = id[0];
System.out.println("ICCID/1234 = " + id2);
// Check for the Carrier Type
if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))) {
car = "TMO";
} else if ((tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
car = "ATT";
}
}
@SuppressWarnings("unused")
public ContentValues generateTFConfig() throws IOException, SAXException,
ParserConfigurationException {
// Extract the IMSI from the TelephonyManager instance
// String imsi = tm.getSubscriberId();
String operator = tm.getSimOperator();
ContentValues values = new ContentValues();
// Query the carrier table for the current data settings
Cursor c = getContentResolver().query(APN_TABLE_URI, null, "current=?",
new String[] { "1" }, null);
values = copyRecordFields(c);
// Copy the Simple Mobile settings into values
/*
* query the server for the data settings put the returned data settings
* into values
*/
/*
* String charset = "UTF-8"; String Append_URL = "settingsquery?";
* String param1 = "mdn1="; String param2 = "&mdn2="; String param3 =
* "&car="; String param4 = "&id1="; String param5 = "&id2="; String URL
* = ""; String parameters = param1 + mdn1 + param2 + mdn2 + param3 +
* car + param4 + id1 + param5 + id2; URL = Base_URL + Append_URL +
* parameters; Log.i("url...", URL); new NetworkTask().execute(URL);
*/
/*
* if (handler.getQueryResult().equals("success")) { values.put("name",
* handler.getName()); values.put("apn", handler.getApn());
* values.put("mmsc", handler.getMMSC());
*
* values.put("proxy", handler.getProxyAddress()); values.put("port",
* handler.getProxyPort()); values.put("mmsproxy",
* handler.getMMSCProxyAddress()); values.put("mmsport",
* handler.getMMSCProxyPort()); values.put("mcc",
* getString(R.string.mcc)); if
* ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))) {
* values.put("numeric", getString(R.string.numeric_tmo));
* values.put("mnc", (getString(R.string.mnc_tmo))); } else if
* ((tm.getSimOperator()) .equals(getString(R.string.numeric_att))) {
* values.put("numeric", getString(R.string.numeric_att));
* values.put("mnc", (getString(R.string.mnc_att))); }
*
* } else if (handler.getQueryResult().equals("no match")) {
* showAlert("no match"); } else if
* (handler.getQueryResult().equals("no plan")) { showAlert("no plan");
* }
*/
return values;
}
/*
* Insert a new APN entry into the system APN table Require an apn name, and
* the apn address. More can be added. Return an id (_id) that is
* automatically generated for the new apn entry.
*/
public int InsertAPN() throws SecurityException {
int id = -1;
for (i = 0; i <= 1; i++) {
ContentValues values2 = new ContentValues();
// values2 = values1;
values2 = getValues();
ContentResolver resolver = getContentResolver();
Cursor c = null;
try {
Uri newRow = resolver.insert(APN_TABLE_URI, values2);
// System.out.println("values in insertAPN" + values1);
if (newRow != null) {
c = resolver.query(newRow, null, null, null, null);
Log.d(TAG, "Newly added APN:");
// TF Settings have been inserted
// Obtain the apn id
int idindex = c.getColumnIndex("_id");
c.moveToFirst();
id = c.getShort(idindex);
Log.d(TAG, "New ID: " + id
+ ": Inserting new APN succeeded!");
}
} catch (SQLException e) {
Log.d(TAG, e.getMessage());
}
if (c != null)
c.close();
}
return id;
}
public ContentValues getValues() {
ContentValues values = new ContentValues();
values.put("name", nameArr.get(i));
values.put("apn", ApnArr.get(i));
values.put("mmsc", mmscArr.get(i));
values.put("mmsproxy", mmsproxyArr.get(i));
values.put("mmsport", mmsportArr.get(i));
values.put("proxy", proxyArr.get(i));
values.put("port", portArr.get(i));
if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))) {
values.put("numeric", getString(R.string.numeric_tmo));
values.put("mnc", (getString(R.string.mnc_tmo)));
} else if ((tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
values.put("numeric", getString(R.string.numeric_att));
values.put("mnc", (getString(R.string.mnc_att)));
}
return values;
}
/*
* Delete APN data where the indicated field has the values Entire table is
* deleted if both field and value are null
*/
private void DeleteAPNs(String field, String[] values)
throws SecurityException {
int c = 0;
c = getContentResolver().delete(APN_TABLE_URI, null, null);
if (c != 0) {
String s = "APNs Deleted:\n";
Log.d(TAG, s);
}
}
/*
* Return all column names stored in the string array
*/
private String getAllColumnNames(String[] columnNames) {
String s = "Column Names:\n";
for (String t : columnNames) {
s += t + ":\t";
}
return s + "\n";
}
/*
* Copy all data associated with the 1st record Cursor c. Return a
* ContentValues that contains all record data.
*/
private ContentValues copyRecordFields(Cursor c) {
if (c == null)
return null;
int row_cnt = c.getCount();
Log.d(TAG, "Total # of records: " + row_cnt);
ContentValues values = new ContentValues();//
if (c.moveToFirst()) {
String[] columnNames = c.getColumnNames();
Log.d(TAG, getAllColumnNames(columnNames));
String row = "";
for (String columnIndex : columnNames) {
int i = c.getColumnIndex(columnIndex);
row += c.getString(i) + ":\t";
// if (i>0)//Avoid copying the id field
// id to be auto-generated upon record insertion
values.put(columnIndex, c.getString(i));
}
row += "\n";
Log.d(TAG, row);
Log.d(TAG, "End Of Records");
}
return values;
}
// showAlert displays the text contained in message as an alert
public void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ConfigFinalActivity.this.finish();
}
});
mErrorAlert = builder.create();
mErrorAlert.show();
}
// showErrorAlert displays an alert with layout and a title
private void showErrorAlert(int layoutRes, String title) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Get the layout inflater
LayoutInflater inflater = ConfigFinalActivity.this.getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setTitle(title)
.setView(inflater.inflate(layoutRes, null))
.setPositiveButton(getString(R.string.assisted_button),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(
Settings.ACTION_APN_SETTINGS));
try {
showNotification();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
mErrorAlert = builder.create();
mErrorAlert.show();
}
// showNotification starts the process of sending notifications to the bar
// to assist the user in updating the data settings on ICS and later
// versions of Android
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
void showNotification() throws SAXException, ParserConfigurationException {
// handler.getQueryResponse();
/*
* String charset = "UTF-8"; String Append_URL = "settingsquery?";
* String param1 = "mdn1="; String param2 = "&mdn2="; String param3 =
* "&car="; String param4 = "&id1="; String param5 = "&id2="; String URL
* = ""; String parameters = param1 + mdn1 + param2 + mdn2 + param3 +
* car + param4 + id1 + param5 + id2; URL = Base_URL + Append_URL +
* parameters; Log.i("url...", URL); new NetworkTask().execute(URL);
*/
String field = getString(R.string.config_name_label);
String value = Values.get("name").toString();
int mId = 1;
String title = "1 of " + UpdateActivity.TotalSteps + " (Update "
+ field + ":)";
Notification.Builder mBuilder = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_launcher).setContentTitle(title)
.setContentText(value);
Intent resultIntent = new Intent(this,
NotificationActivityForMultiProf.class);
resultIntent.putExtra(field, value);
PendingIntent resultPendingIntent = PendingIntent.getActivity(
getApplicationContext(), 0, resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotification = mBuilder.getNotification();
mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(mId, mNotification);
finish();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
if (mNotification != null) {
outState.putString("NOTIFICATIONB", mNotification.toString());
}
}
@Override
protected void onRestart() {
super.onRestart();
if (mErrorAlert != null)
mErrorAlert.dismiss();
}
public void onClick(View v) {
if (v == mXButton) {
finish();
}
}
// This thread performs the setting update and shows pseudo progress update
private class TableUpdateRequestTask extends
AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
//
}
@Override
protected String doInBackground(String... params) {
int result = 0;
try {
result = updateTable();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}// Settings updated with this atomic call
catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// The code below plays a Simple Promo animation
// prior to displaying update success or failure message
for (int incr = 0; incr < 2; incr++) {
// Sleep for 1/2 second
// Invoke UI to change updating text to show 1 dot
// And Increasing the level to reduce the amount of clipping and
// slowly reveals the hand image
publishProgress(R.drawable.loading_full,
R.drawable.loading_empty, R.drawable.loading_empty,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_empty,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full);
// Sleep for 1/2 second
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
}
if (result != -1)
return "success";
else
return "failure";
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// Show updated screen if table was successfully updated
// Or alert indicating settings are not updated
if (result.equals("success")) {
completeUpdate();
} else
setContentView(R.layout.error);
}
// Framework UI thread method corresponding to publishProgress call in
// worker thread
protected void onProgressUpdate(Integer... progress) {
// Call function to update image view
setProgressImgView(progress[0], progress[1], progress[2],
progress[3], progress[4]);
}
}