我做了一个应用程序,它将名称,联系号码和其他字段作为输入,并将该数据保存在mysql数据库的服务器上。这在Android应用程序中没有验证输入字段(EditText)时工作正常,但是当验证时它会出现致命错误。下面是我的验证和logcat代码。再次,如果我从活动中删除验证代码,那么数据已成功导入服务器并且我获得了Json响应以获得成功。但是通过验证它显示错误,我不知道为什么会发生这种情况?请帮帮我。
.....
public static SharedPreferences sellcro;
public static String name11;
public static String mobile11;
public static String weight11;
public static String name111 = "";
public static String mobile111 = "";
public static String weight111 = "";
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputMobile;
EditText inputWeight;
private static final String TAG_SUCCESS = "success";
.....
inputName = (EditText) findViewById(R.id.editText1);
inputMobile = (EditText) findViewById(R.id.editText2);
inputWeight = (EditText) findViewById(R.id.editText3);
.....
btnCreateProduct.setOnClickListener....
name11 = inputName.getText().toString();
if (!isValidName(name11)) {
inputName.setError("Please Enter Proper Name");
}
else{
name111 = "right";
}
mobile11 = inputMobile.getText().toString();
if (!isValidMobile(mobile11)) {
inputMobile.setError("Please Enter 10 Digit Mobile Number");
}
else{
mobile111 = "right";
}
weight11 = inputWeight.getText().toString();
if (!isValidWeight(weight11)) {
inputWeight.setError("Weight must be maximum of 9 character");
}
else{
weight111 = "right";
}
if(mobile111.equals("right") && weight111.equals("right") && name111.equals("right")){
new CreateNewProduct().execute();
}else{}
}
});}
private boolean isValidWeight(String weight11) {
// TODO Auto-generated method stub
if(weight11 != null && weight11.length()>0 && weight11.length()<10){
return true;
}
return false;
}
private boolean isValidMobile(String mobile11) {
// TODO Auto-generated method stub
if(mobile11 != null && mobile11.length()>0 && mobile11.length()==10){
return true;
}
return false;
}
private boolean isValidName(String name11) {
// TODO Auto-generated method stub
if(name11 != null && name11.length()<60){
String name_pattern = "[a-zA-z]+([ '-][a-zA-Z]+)*";
Pattern pattern = Pattern.compile(name_pattern);
Matcher matcher = pattern.matcher(name11);
return matcher.matches();
}
return false;
}
class CreateNewProduct extends AsyncTask<...............
.......
protected String doInBackground(String... args) {
..........
// 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) {
// successfully created product
// closing this screen
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
...........
logcat的:
02-25 05:28:04.103: D/OpenGLRenderer(2911): Render dirty regions requested: true
02-25 05:28:04.106: D/(2911): HostConnection::get() New Host Connection established 0xa5ce8ef0, tid 2911
02-25 05:28:04.114: D/Atlas(2911): Validating map...
02-25 05:28:04.153: D/libEGL(2911): loaded /system/lib/egl/libEGL_genymotion.so
02-25 05:28:04.153: D/(2911): HostConnection::get() New Host Connection established 0xa4d331e0, tid 2930
02-25 05:28:04.159: D/libEGL(2911): loaded /system/lib/egl/libGLESv1_CM_genymotion.so
02-25 05:28:04.171: D/libEGL(2911): loaded /system/lib/egl/libGLESv2_genymotion.so
02-25 05:28:04.178: I/OpenGLRenderer(2911): Initialized EGL, version 1.4
02-25 05:28:04.210: D/OpenGLRenderer(2911): Enabling debug mode 0
02-25 05:28:04.255: W/EGL_genymotion(2911): eglSurfaceAttrib not implemented
02-25 05:28:04.255: W/OpenGLRenderer(2911): Failed to set EGL_SWAP_BEHAVIOR on surface 0xb048c4e0, error=EGL_SUCCESS
02-25 05:28:07.584: W/EGL_genymotion(2911): eglSurfaceAttrib not implemented
02-25 05:28:07.584: W/OpenGLRenderer(2911): Failed to set EGL_SWAP_BEHAVIOR on surface 0xa4e56060, error=EGL_SUCCESS
02-25 05:28:24.934: W/EGL_genymotion(2911): eglSurfaceAttrib not implemented
02-25 05:28:24.934: W/OpenGLRenderer(2911): Failed to set EGL_SWAP_BEHAVIOR on surface 0xa4e352e0, error=EGL_SUCCESS
02-25 05:28:25.532: E/JSON Parser(2911): Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
02-25 05:28:25.544: E/AndroidRuntime(2911): FATAL EXCEPTION: AsyncTask #1
02-25 05:28:25.544: E/AndroidRuntime(2911): Process: com.creatorscorp.krushidhan, PID: 2911
02-25 05:28:25.544: E/AndroidRuntime(2911): java.lang.RuntimeException: An error occured while executing doInBackground()
02-25 05:28:25.544: E/AndroidRuntime(2911): at android.os.AsyncTask$3.done(AsyncTask.java:300)
02-25 05:28:25.544: E/AndroidRuntime(2911): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
02-25 05:28:25.544: E/AndroidRuntime(2911): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
02-25 05:28:25.544: E/AndroidRuntime(2911): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
02-25 05:28:25.544: E/AndroidRuntime(2911): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
02-25 05:28:25.544: E/AndroidRuntime(2911): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
02-25 05:28:25.544: E/AndroidRuntime(2911): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
02-25 05:28:25.544: E/AndroidRuntime(2911): at java.lang.Thread.run(Thread.java:818)
02-25 05:28:25.544: E/AndroidRuntime(2911): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
02-25 05:28:25.544: E/AndroidRuntime(2911): at com.creatorscorp.krushidhan.SellYourCrops$CreateNewProduct.doInBackground(SellYourCrops.java:307)
02-25 05:28:25.544: E/AndroidRuntime(2911): at com.creatorscorp.krushidhan.SellYourCrops$CreateNewProduct.doInBackground(SellYourCrops.java:1)
02-25 05:28:25.544: E/AndroidRuntime(2911): at android.os.AsyncTask$2.call(AsyncTask.java:288)
02-25 05:28:25.544: E/AndroidRuntime(2911): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
02-25 05:28:25.544: E/AndroidRuntime(2911): ... 4 more
02-25 05:28:25.840: W/EGL_genymotion(2911): eglSurfaceAttrib not implemented
02-25 05:28:25.841: W/OpenGLRenderer(2911): Failed to set EGL_SWAP_BEHAVIOR on surface 0xa1361360, error=EGL_SUCCESS
02-25 05:28:26.330: E/WindowManager(2911): android.view.WindowLeaked: Activity com.creatorscorp.krushidhan.SellYourCrops has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{110dbf2c V.E..... R......D 0,0-1026,348} that was originally added here
02-25 05:28:26.330: E/WindowManager(2911): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
02-25 05:28:26.330: E/WindowManager(2911): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
02-25 05:28:26.330: E/WindowManager(2911): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
02-25 05:28:26.330: E/WindowManager(2911): at android.app.Dialog.show(Dialog.java:298)
02-25 05:28:26.330: E/WindowManager(2911): at com.creatorscorp.krushidhan.SellYourCrops$CreateNewProduct.onPreExecute(SellYourCrops.java:280)
02-25 05:28:26.330: E/WindowManager(2911): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
02-25 05:28:26.330: E/WindowManager(2911): at android.os.AsyncTask.execute(AsyncTask.java:535)
02-25 05:28:26.330: E/WindowManager(2911): at com.creatorscorp.krushidhan.SellYourCrops$5.onClick(SellYourCrops.java:221)
02-25 05:28:26.330: E/WindowManager(2911): at android.view.View.performClick(View.java:4756)
02-25 05:28:26.330: E/WindowManager(2911): at android.view.View$PerformClick.run(View.java:19749)
02-25 05:28:26.330: E/WindowManager(2911): at android.os.Handler.handleCallback(Handler.java:739)
02-25 05:28:26.330: E/WindowManager(2911): at android.os.Handler.dispatchMessage(Handler.java:95)
02-25 05:28:26.330: E/WindowManager(2911): at android.os.Looper.loop(Looper.java:135)
02-25 05:28:26.330: E/WindowManager(2911): at android.app.ActivityThread.main(ActivityThread.java:5221)
02-25 05:28:26.330: E/WindowManager(2911): at java.lang.reflect.Method.invoke(Native Method)
02-25 05:28:26.330: E/WindowManager(2911): at java.lang.reflect.Method.invoke(Method.java:372)
02-25 05:28:26.330: E/WindowManager(2911): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
02-25 05:28:26.330: E/WindowManager(2911): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
02-25 05:28:27.336: I/Process(2911): Sending signal. PID: 2911 SIG: 9
JSonParser:
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 == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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;
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);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
答案 0 :(得分:0)
@EDIT 更改编码
//BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
BufferedReader reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8), 8);
也可能使用
在jsonParser类中删除一些不需要的字符return new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
答案 1 :(得分:0)
if(name.getText().toString().equals("")) {
Toast.makeText(BookAppointment.this,
"Enter Name", Toast.LENGTH_SHORT)
.show();
}else if(mobile.getText().toString().equals("")) {
Toast.makeText(BookAppointment.this,
"Enter mobile", Toast.LENGTH_SHORT)
.show();
}
else {
if (!txt_name.isEmpty() || !txt_mob.isEmpty()
if (!isValidEmail(email.getText().toString())) {
Toast.makeText(getApplicationContext(),
"Invalid Email", Toast.LENGTH_LONG).show();
}
else {
String values = null;
try {
values = "name=" + URLEncoder.encode(txt_name, "UTF-8")
+ "&mobile=" + URLEncoder.encode(txt_mob, "UTF-8");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
new BookAppointmentTask().execute(values);
}
}
}
}
});
}
private class BookAppointmentTask extends
AsyncTask<String, Integer, Double> {
ProgressDialog pd;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
pd = new ProgressDialog(BookAppointment.this);
pd.setIndeterminate(true);
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
super.onPreExecute();
}
@Override
protected Double doInBackground(String... arg0) {
// TODO Auto-generated method stub
postData(arg0[0]);
return null;
}
public void postData(String values) {
// TODO Auto-generated method stub
// Create a new HttpClient and Post Header
HttpClient httpClient = new DefaultHttpClient();
String BOOK_APPOINTMENT = APPOINTMENT_URL + values;
System.out.println("URL_BOOK_APPOINTMENT = " + BOOK_APPOINTMENT);
HttpPost httpPost = new HttpPost(BOOK_APPOINTMENT);
try {
// Execute HTTP Post Request
HttpResponse httpResponse = httpClient.execute(httpPost);
String json = EntityUtils.toString(httpResponse.getEntity());
JSONObject jsonObject = new JSONObject(json);
message = jsonObject.getString("message");
System.out.println("MESSAGE_STATUS = " + message);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
@Override
protected void onPostExecute(Double result) {
// TODO Auto-generated method stub
pd.dismiss();
super.onPostExecute(result);
Toast.makeText(BookAppointment.this, message, Toast.LENGTH_SHORT).show();
name.setText("");
mobile.setText("");
}
}
Try this and let me know if it works