我已经实现了一个Android应用程序。我想借助getSpreadSheetData()
和getSpreadSheetResponce()
方法从谷歌电子表格中获取数据,但我收到错误StringIndexOutofBoundException
。
MainActivity
public class SearchActivity extends 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";
/** 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();
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);
// remove the unnecessary parts from the response and construct a
// JSON
int start = result.indexOf("{", result.indexOf("{") + 1);
int end = result.lastIndexOf("}");
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;
}
}
此行有错误:
String jsonResponse = result.substring(start, end);
LogCat
08-13 15:55:18.802: E/AndroidRuntime(4157): FATAL EXCEPTION: main
08-13 15:55:18.802: E/AndroidRuntime(4157): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.agrawalassociation/com.example.agrawalassociation.SearchActivity}: java.lang.StringIndexOutOfBoundsException: length=0; regionStart=-1; regionLength=0
08-13 15:55:18.802: E/AndroidRuntime(4157): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
08-13 15:55:18.802: E/AndroidRuntime(4157): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2146)
08-13 15:55:18.802: E/AndroidRuntime(4157): at android.app.ActivityThread.access$700(ActivityThread.java:140)
08-13 15:55:18.802: E/AndroidRuntime(4157): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
08-13 15:55:18.802: E/AndroidRuntime(4157): at android.os.Handler.dispatchMessage(Handler.java:99)
08-13 15:55:18.802: E/AndroidRuntime(4157): at android.os.Looper.loop(Looper.java:177)
08-13 15:55:18.802: E/AndroidRuntime(4157): at android.app.ActivityThread.main(ActivityThread.java:4947)
08-13 15:55:18.802: E/AndroidRuntime(4157): at java.lang.reflect.Method.invokeNative(Native Method)
08-13 15:55:18.802: E/AndroidRuntime(4157): at java.lang.reflect.Method.invoke(Method.java:511)
08-13 15:55:18.802: E/AndroidRuntime(4157): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
08-13 15:55:18.802: E/AndroidRuntime(4157): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
08-13 15:55:18.802: E/AndroidRuntime(4157): at dalvik.system.NativeStart.main(Native Method)
08-13 15:55:18.802: E/AndroidRuntime(4157): Caused by: java.lang.StringIndexOutOfBoundsException: length=0; regionStart=-1; regionLength=0
08-13 15:55:18.802: E/AndroidRuntime(4157): at java.lang.String.startEndAndLength(String.java:593)
08-13 15:55:18.802: E/AndroidRuntime(4157): at java.lang.String.substring(String.java:1474)
08-13 15:55:18.802: E/AndroidRuntime(4157): at com.example.agrawalassociation.SearchActivity.getSpreadSheetData(SearchActivity.java:173)
08-13 15:55:18.802: E/AndroidRuntime(4157): at com.example.agrawalassociation.SearchActivity.onCreate(SearchActivity.java:114)
08-13 15:55:18.802: E/AndroidRuntime(4157): at android.app.Activity.performCreate(Activity.java:5207)
08-13 15:55:18.802: E/AndroidRuntime(4157): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
08-13 15:55:18.802: E/AndroidRuntime(4157): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2085)
08-13 15:55:18.802: E/AndroidRuntime(4157): ... 11 more
请在我错的地方帮助我。
答案 0 :(得分:0)
添加日志记录行,然后检查开头和结尾是否大于或小于结果长度。
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);
我认为结果长度= 0并且你试图访问位置-1,这可能是因为结果是空的,而indexOf(&#34; {&#34;)不存在所以它返回-1