我是android的新手,我想使用JSON向服务器发送editText值。我收到此错误“StringIndexOutOfBoundsException”,我不知道如何解决它。这是我的代码:
JSONParser.java
package com.example.bookstore;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method.equals("POST")){
HttpClient httpclient = getNewHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpclient.execute(httpPost);
if(httpResponse != null){
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
}else if(method.equals("GET")){
// request method is GET
HttpClient httpclient = getNewHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpclient.execute(httpGet);
if(httpResponse != null){
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
if(reader != null){
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
public HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
}
Sale.java
package com.example.bookstore;
public class Sale extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText BookName;
EditText AuthorName;
EditText Publication;
EditText Price;
EditText BookGenre;
// url to create new product
private static String url_create_product = "https://5.144.130.36/android/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.sale);
BookName = (EditText) findViewById(R.id.BookName);
AuthorName = (EditText) findViewById(R.id.AuthorName);
Publication = (EditText) findViewById(R.id.Publication);
Price = (EditText) findViewById(R.id.Price);
BookGenre = (EditText) findViewById(R.id.BookGenre);
Button confirm = (Button) findViewById(R.id.Confirm);
confirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewBook().execute();
}
});
}
class CreateNewBook extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Sale.this);
pDialog.setMessage("Book Submition");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
runOnUiThread(new Runnable() {
public void run() {
String B_Name = BookName.getText().toString();
String Au_Name = AuthorName.getText().toString();
String Pub = Publication.getText().toString();
String Pr = Price.getText().toString();
String B_Genre = BookGenre.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("B_Name", B_Name));
params.add(new BasicNameValuePair("Au_Name", Au_Name));
params.add(new BasicNameValuePair("Pub", Pub));
params.add(new BasicNameValuePair("Pr", Pr));
params.add(new BasicNameValuePair("B_Genre", B_Genre));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String result) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
public void onDestroy() {
super.onDestroy();
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
logcat的
04-29 11:13:59.536: E/AndroidRuntime(784):
java.lang.StringIndexOutOfBoundsException: length=58; regionStart=-1;
regionLength=1
04-29 11:13:59.536: E/AndroidRuntime(784): at
java.lang.String.startEndAndLength(String.java:583)
04-29 11:13:59.536: E/AndroidRuntime(784): at
java.lang.String.substring(String.java:1464)
04-29 11:13:59.536: E/AndroidRuntime(784): at
com.example.bookstore.JSONParser.makeHttpRequest(JSONParser.java:109)
我有认证的MySSLSocketFactory类,我认为不存在任何问题。
答案 0 :(得分:0)
我会在您粘贴日志后编辑我的答案,但我认为问题出在:
jObj = new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
或带有字符串操作的类似片段。 将此行更改为:
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("{");
stringBuilder.append(StringUtils.substringBeforeLast(StringUtils.substringAfter(json, "{"), "}"));
stringBuilder.append("}");
jObj = new JSONObject(stringBuilder.toString());
这篇文章完全是StringOutOfBoundsException,NullPointerException是安全的。