我正在实施Android应用。我有一个包含大约100行数据的Google电子表格(包含2列)。我正在将此电子表格中的数据提取到我的应用中
This is my spreadsheet
但是,我得到了这个例外StringIndexOutofBoundsException.
Main Activity
// action bar
private ActionBar actionBar;
private ListView listView;
ListAdapter adapter;
DatabaseHelper databaseHelper;
DBHelper dbHelper;
Utility utility;
ArrayList<Personinfo> list;
ArrayAdapter<Personinfo> arrayAdapter;
AdapterFilter adapterfilter;
LinearLayout linearLayout;
Personinfo personinfo;
Boolean isInternetPresent = false;
Intent intent;
// private static final String FETCH_DATA_FROM_SPREADSHEET =
// "https://docs.google.com/spreadsheets/d/1FJBt8ZHAcnfwLhx0rYjC4ELImLInYxkOTTauw8PL6W4/gviz/tq";
private static final String FETCH_DATA_FROM_SPREADSHEET = "https://spreadsheets.google.com/tq?tq&key=1n_VjwHm8qIU5YRMM-wMkJIap2KZa5vOfxWI5dpYT1PE&gid=1262286779";
/** The pref name. */
final String PREF_NAME = "pref";
/** The hash map. */
public static HashMap<Integer, List<String>> hashMap = null;
/** The info array list. */
public static ArrayList<String> infoArrayList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color
.parseColor("#03A9F4")));
actionBar.setTitle("Agarwal Association");
list = new ArrayList<Personinfo>();
dbHelper = new DBHelper(this);
dbHelper.openDataBase();
Cursor cursor = dbHelper.Get_ContactDetails();
cursor.moveToFirst();
do {
String name = cursor.getString(0);
String phoneno = cursor.getString(1);
Personinfo personinfo = new Personinfo(name, phoneno);
list.add(personinfo);
} while (cursor.moveToNext());
cursor.close();
dbHelper.close();
listView = (ListView) findViewById(R.id.listView);
adapterfilter = new AdapterFilter(this, R.layout.child_listview, list);
Log.i("List", "" + list.get(0).getPhoneno());
listView.setAdapter(adapterfilter);
listView.setTextFilterEnabled(true);
getSpreadSheetData();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
.getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextChange(String newText) {
adapterfilter.getFilter().filter(newText);
adapterfilter.notifyDataSetChanged();
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
// this is your adapter that will be filtered
adapterfilter.getFilter().filter(query);
adapterfilter.notifyDataSetChanged();
return false;
}
};
searchView.setOnQueryTextListener(textChangeListener);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_search:
// search action
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void getSpreadSheetData() {
// TODO Auto-generated method stub
hashMap = new HashMap<Integer, List<String>>();
// hashMap = new HashMap<Integer, String>();
String result = getSpreadSheetResponce();
Log.i("jsonResponse:", result);
System.out.print(result);
// remove the unnecessary parts from the response and construct a
// JSON
int start = result.indexOf("{", result.indexOf("{") + 1);
int end = result.lastIndexOf("}");
System.out.println("Start: " + start + " End: " + end
+ " results length: " + result.length());
String jsonResponse = result.substring(start, end);
try {
JSONObject mainObj = new JSONObject(jsonResponse);
// String value = null;
List<String> arraylist = new ArrayList<String>();
if (mainObj != null) {
JSONArray list = mainObj.getJSONArray("rows");
if (list != null) {
for (int i = 0; i < list.length(); i++) {
JSONObject innerJsonObject = list.getJSONObject(i);
if (innerJsonObject != null) {
JSONArray valuesJsonArray = innerJsonObject
.getJSONArray("c");
if (valuesJsonArray != null) {
for (int j = 0; j < valuesJsonArray.length(); j++) {
JSONObject innerElem = valuesJsonArray
.getJSONObject(j);
if (innerElem != null) {
String name = innerElem.getString("v");
String phoneno = innerElem
.getString("f");
arraylist.add(name);
arraylist.add(phoneno);
hashMap.put(j, arraylist);
}
}
}
}
}
}
}
Log.i("hashMap.get(0)", "" + hashMap.get(0));
infoArrayList = new ArrayList<String>();
infoArrayList.addAll(hashMap.get(0));
} catch (JSONException e) {
e.printStackTrace();
}
}
private String getSpreadSheetResponce() {
URL url;
String responce = null;
try {
url = new URL(FETCH_DATA_FROM_SPREADSHEET);
BufferedReader in = new BufferedReader(new InputStreamReader(
url.openStream()));
while ((responce = in.readLine()) != null) {
in.close();
}
Log.i("Responce:", "" + in);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return responce;
}
LogCat
08-24 12:52:18.747: E/AndroidRuntime(14543): FATAL EXCEPTION: main
08-24 12:52:18.747: E/AndroidRuntime(14543): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.agrawalassociation/com.example.agrawalassociation.SearchActivity}: java.lang.StringIndexOutOfBoundsException: length=7; regionStart=-1; regionLength=0
08-24 12:52:18.747: E/AndroidRuntime(14543): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
08-24 12:52:18.747: E/AndroidRuntime(14543): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2146)
08-24 12:52:18.747: E/AndroidRuntime(14543): at android.app.ActivityThread.access$700(ActivityThread.java:140)
08-24 12:52:18.747: E/AndroidRuntime(14543): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
08-24 12:52:18.747: E/AndroidRuntime(14543): at android.os.Handler.dispatchMessage(Handler.java:99)
08-24 12:52:18.747: E/AndroidRuntime(14543): at android.os.Looper.loop(Looper.java:177)
08-24 12:52:18.747: E/AndroidRuntime(14543): at android.app.ActivityThread.main(ActivityThread.java:4947)
08-24 12:52:18.747: E/AndroidRuntime(14543): at java.lang.reflect.Method.invokeNative(Native Method)
08-24 12:52:18.747: E/AndroidRuntime(14543): at java.lang.reflect.Method.invoke(Method.java:511)
08-24 12:52:18.747: E/AndroidRuntime(14543): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
08-24 12:52:18.747: E/AndroidRuntime(14543): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
08-24 12:52:18.747: E/AndroidRuntime(14543): at dalvik.system.NativeStart.main(Native Method)
08-24 12:52:18.747: E/AndroidRuntime(14543): Caused by: java.lang.StringIndexOutOfBoundsException: length=7; regionStart=-1; regionLength=0
08-24 12:52:18.747: E/AndroidRuntime(14543): at java.lang.String.startEndAndLength(String.java:593)
08-24 12:52:18.747: E/AndroidRuntime(14543): at java.lang.String.substring(String.java:1474)
08-24 12:52:18.747: E/AndroidRuntime(14543): at com.example.agrawalassociation.SearchActivity.getSpreadSheetData(SearchActivity.java:179)
08-24 12:52:18.747: E/AndroidRuntime(14543): at com.example.agrawalassociation.SearchActivity.onCreate(SearchActivity.java:117)
08-24 12:52:18.747: E/AndroidRuntime(14543): at android.app.Activity.performCreate(Activity.java:5207)
08-24 12:52:18.747: E/AndroidRuntime(14543): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
08-24 12:52:18.747: E/AndroidRuntime(14543): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2085)
08-24 12:52:18.747: E/AndroidRuntime(14543): ... 11 more
答案 0 :(得分:0)
StringIndexOutOfBoundsException: length=7; regionStart=-1; regionLength=0
您尝试从位置-1开始获取子字符串。换句话说, start 变量的值为-1。
-1是indexOf()在找不到您要查找的内容时返回的内容。它可能失败了,因为你的结果字符串看起来不像你期望的那样(或者你的double-indexOf()调用逻辑是错误的。)
编辑:您关联的电子表格&#34; (&#34; json.txt&#34;)从这一行开始:/*O_o*/
。七个字符,没有大括号......这可能是歪曲你的代码的那个。
答案 1 :(得分:-1)
我认为问题发生在CityList
应该使用String jsonResponse = result.substring(start, end);
来避免异常