У меня возникла исключительная ситуация ArrayIndexOutOfBoundsException в моем приложении для Android, когда я возвращаюсь из элемента сведений в список элементов.Он отлично работает, когда я щелкаю любой элемент в списке, чтобы просмотреть его детали, но когда я возвращаюсь к деталям, любой выбранный элемент выдает эту ошибку:
12-27 12:40:14.033: WARN/System.err(681): java.lang.ArrayIndexOutOfBoundsException
12-27 12:40:14.083: WARN/System.err(681): at com.salesforce.android.restsample.ContactListView$1.onItemClick(ContactListView.java:74)
12-27 12:40:14.083: WARN/System.err(681): at android.widget.AdapterView.performItemClick(AdapterView.java:284)
12-27 12:40:14.134: WARN/System.err(681): at android.widget.ListView.performItemClick(ListView.java:3513)
12-27 12:40:14.134: WARN/System.err(681): at android.widget.AbsListView$PerformClick.run(AbsListView.java:1812)
12-27 12:40:14.153: WARN/System.err(681): at android.os.Handler.handleCallback(Handler.java:587)
12-27 12:40:14.183: WARN/System.err(681): at android.os.Handler.dispatchMessage(Handler.java:92)
12-27 12:40:14.183: WARN/System.err(681): at android.os.Looper.loop(Looper.java:123)
12-27 12:40:14.193: WARN/System.err(681): at android.app.ActivityThread.main(ActivityThread.java:3683)
12-27 12:40:14.193: WARN/System.err(681): at java.lang.reflect.Method.invokeNative(Native Method)
12-27 12:40:14.213: WARN/System.err(681): at java.lang.reflect.Method.invoke(Method.java:507)
12-27 12:40:14.213: WARN/System.err(681): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-27 12:40:14.223: WARN/System.err(681): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-27 12:40:14.323: WARN/System.err(681): at dalvik.system.NativeStart.main(Native Method)
В моем коде возникает ошибка:
gs.setSelectedAccount(gs.getAccounts()[position]);
Здесь позиция дает правильное значение, но ошибка сохраняется.
Вот код:
public class ContactListView extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
GlobalState gs = (GlobalState) getApplication();
setContentView(R.layout.newlist);
getAccountData();
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, gs.getAccountNames()));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
final EditText et = (EditText) findViewById(R.id.editText);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
GlobalState gs = (GlobalState) getApplication();
try{
gs.setSelectedAccount(gs.getAccounts()[position]);
}catch(IndexOutOfBoundsException e)
{
e.printStackTrace();
}
JSONObject acct = gs.getSelectedAccount();
String str = null;
try {
str = acct.getString("AccountId")!= "null"?acct.getString("AccountId"):"";
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
launchAccountDetail(str);
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
}
});
final Button btnGo = (Button) findViewById(R.id.btnGo);
Button btnSearch = (Button) findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
et.setVisibility(View.VISIBLE);
btnGo.setVisibility(View.VISIBLE);
}
});
btnGo.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String txt = et.getText().toString();
launchPartularAccount(txt);
// getAccountData(txt);
// setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, gs.getAccountNames()));
}
});
Button newBtn = (Button)findViewById(R.id.btnFromDate);
newBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
GlobalState gs = (GlobalState) getApplication();
gs.setSelectedAccount(gs.getAccounts()[0]);
launchAddAccount();
}
});
}
protected void launchAddAccount() {
Intent i = new Intent(this, AddAccount.class);
startActivity(i);
}
protected void launchAccountDetail(String str) {
Intent i = new Intent(this, ContactDetail.class);
i.putExtra("Id", str);
startActivity(i);
}
private void getAccountData() {
GlobalState globalState = (GlobalState) getApplication();
OAuthTokens myTokens = globalState.getAccessTokens();
DefaultHttpClient client = new DefaultHttpClient();
String url = myTokens.get_instance_url() + "/services/data/v20.0/query/?q=";
String soqlQuery = "Select Id, Name, Birthdate, AssistantName, AssistantPhone, Department, Email, LastActivityDate, AccountId, Account.Name, Account.BillingState From Contact limit 20";
try
{
url += URLEncoder.encode(soqlQuery, "UTF-8");
}
catch(UnsupportedEncodingException e){}
HttpGet getRequest = new HttpGet(url);
getRequest.addHeader("Authorization", "OAuth " + myTokens.get_access_token());
try {
HttpResponse response = client.execute(getRequest);
String result = EntityUtils.toString(response.getEntity());
JSONObject object = (JSONObject) new JSONTokener(result).nextValue();
JSONArray records = object.getJSONArray("records");
globalState.setAccountNames(new String[records.length()]);
globalState.setAccounts(new JSONObject[records.length()]);
for (int i=0;i<records.length();i++) {
JSONObject record = (JSONObject) records.get(i);
String accountName = record.getString("Name");
globalState.getAccountNames()[i] = accountName;
globalState.getAccounts()[i] = record;
}
} catch (IOException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
}
private void launchPartularAccount(String txt) {
// TODO Auto-generated method stub
Intent i = new Intent(this, ParticularAccount.class);
i.putExtra("id", txt);
startActivity(i);
}
}