我在向服务器发送数据时遇到问题,不幸的是关闭了我的应用程序。我不知道为什么会这样。我试过但无法解决。请有人帮助我。 它总是在新CreateUser()中显示错误.execute(); ,类CreateUser扩展AsyncTask {, pDialog.show(); , int success = json.getInt(TAG_SUCCESS); if(success == 1) {。这些线我得到错误。我也有JSON解析器类
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
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.setHeader("Content-type", "application/json");
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;
}
/*public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Try to 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 the JSON Object.
return jObj;
}*/
}
这是我的代码:
public class ConsentActivity extends ActionBarActivity {
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
SharedPreferences sharedpref_user;
SharedPreferences.Editor editor;
String result;
private static String url_new_user = "http://192.167.1.123:8080/pharmacy/services/user/createUser";
private static final String TAG_SUCCESS = "success";
@InjectView(R.id.btn_next5) protected Button next_Edit;
@InjectView(R.id.checkBox_consent) protected CheckBox checkbox_consent;
@InjectView(R.id.close_icon5) protected TextView close_text_consent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.consent_info);
sharedpref_user = getSharedPreferences("UserMgmt", 0);
editor = sharedpref_user.edit();
//text justification
String htmlText = "<html><body style=\"text-align:justify\" \"> %s </body></Html>";
String myData = "<font color='#035e85'>"+"All copyright, trade marks, design rights, patents and other intellectual property rights (registered and unregistered) in and on YGT Online Services and YGT Content belong to the YGT and/or third parties (which may include you or other users). The YGT reserves all of its rights in YGT Content and YGT Online Services. Nothing in the Terms grants you a right or licence to use any trade mark, design right or copyright owned or controlled by the YGT or any other third party except as expressly provided in the Terms.\n"+"</font>";
WebView webView = (WebView) findViewById(R.id.webView_consent_txt_justify);
webView.loadData(String.format(htmlText, myData), "text/html", "utf-8");
webView.setBackgroundColor(0);
webView.setBackgroundColor(0x00000000);
ButterKnife.inject(this);
next_Edit.setEnabled(false);
checkbox_consent.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if ( isChecked )
{
next_Edit.setEnabled(true);
result="true";
}
else{
next_Edit.setEnabled(false);
result="false";
}
}
});
Typeface font_close5 = Typeface.createFromAsset( getAssets(), "fontawesome-webfont.ttf" );
TextView personal_close=(TextView)findViewById(R.id.close_icon5);
personal_close.setTypeface(font_close5);
close_text_consent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
});
Boolean consent_check = checkbox_consent.isChecked();
//Toast.makeText(TermsConditions.this, "result:" + tc_check, Toast.LENGTH_SHORT).show();
editor.putBoolean("ChkBoxConsent", consent_check);
editor.commit();
//next button1
next_Edit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new CreateUser().execute();
}
});
}
@Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
class CreateUser extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ConsentActivity.this);
pDialog.setMessage("Registering New User..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
SharedPreferences pref = getSharedPreferences("UserMgmt", Context.MODE_PRIVATE);
String Firstname = pref.getString("FName", "");
String Lastname = pref.getString("LName", "");
String Userid = pref.getString("UserId", "");
String Password = pref.getString("Password", "");
String Repassword = pref.getString("RePassword", "");
String Idproof_typ=pref.getString("IdType","");
String Idproof_number=pref.getString("IdNumber","");
String Dob=pref.getString("DOB","");
String Gender=pref.getString("Gender","");
String Email=pref.getString("Email","");
String Mobile_number=pref.getString("Mobile","");
String Country_code=pref.getString("CountryCode","");
String Landline=pref.getString("LandLine","");
String Country=pref.getString("Country","");
String State=pref.getString("State","");
String Address=pref.getString("Address","");
String Pincod=pref.getString("Pincode","");
boolean Tc_chk_state = pref.getBoolean("ChkBoxTC", true);
boolean Consent_chk_state = pref.getBoolean("ChkBoxConsent", true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
// params.add(new BasicNameValuePair("userId", Userid));
params.add(new BasicNameValuePair("firstName", Firstname));
params.add(new BasicNameValuePair("lastName", Lastname));
params.add(new BasicNameValuePair("password", Password));
params.add(new BasicNameValuePair("newPassword", Repassword));
params.add(new BasicNameValuePair("identityType", Idproof_typ));
params.add(new BasicNameValuePair("identityNumber", Idproof_number));
params.add(new BasicNameValuePair("dob", Dob));
params.add(new BasicNameValuePair("gender", Gender));
params.add(new BasicNameValuePair("emailId", Email));
params.add(new BasicNameValuePair("mobileNumber", Mobile_number));
params.add(new BasicNameValuePair("stdCode", Country_code));
params.add(new BasicNameValuePair("landlineNumber", Landline));
params.add(new BasicNameValuePair("countryCode", Country));
params.add(new BasicNameValuePair("stateCode", State));
params.add(new BasicNameValuePair("addr", Address));
params.add(new BasicNameValuePair("zipcode", Pincod));
JSONObject json = jsonParser.makeHttpRequest(url_new_user,
"POST", params);
// Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created a user
Intent i = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create user
Log.d("failed to create user", json.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
请检查我的错误logcat
Caused by: java.lang.NullPointerException
at ***mtest.you.com.pharmacy.ConsentActivity$CreateUser.doInBackground(ConsentActivity.java:191)
at mtest.you.com.pharmacy.ConsentActivity$CreateUser.doInBackground(ConsentActivity.java:123)***
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
04-08 17:27:52.933 3873-3873/mtest.tag.com.pharmacy E/WindowManager﹕ android.view.WindowLeaked: Activity mtest.yougo.com.pharmatnt.ConsentActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{421a9280 V.E..... R......D 0,0-684,192} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:422)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:250)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at mtest.yougo.com.pharmatnt.ConsentActivity$CreateUser.onPreExecute(ConsentActivity.java:132)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at mtest.you.com.pharmacy.ConsentActivity$3.onClick(ConsentActivity.java:112)
at mtest.you.com.pharmacy.ConsentActivity$CreateUser.onPreExecute(ConsentActivity.java:132)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at mtest.you.com.pharmacy.ConsentActivity$3.onClick(ConsentActivity.java:112)
答案 0 :(得分:0)
我认为问题是您尝试从后台线程退出活动。一种解决方案就是这样。
在CreateUser类的开头声明您的JSONObject:
JSONObject json;
在doInBackground()中替换:
JSONObject json = jsonParser.makeHttpRequest(url_new_user,
"POST", params);
使用:
json = jsonParser.makeHttpRequest(url_new_user,
"POST", params);
将此代码移入onPostExecute:
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created a user
Intent i = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create user
Log.d("failed to create user", json.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
最后,您应该在CreateUser类中使用它:
class CreateUser extends AsyncTask<String, String, String> {
JSONObject json;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ConsentActivity.this);
pDialog.setMessage("Registering New User..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
SharedPreferences pref = getSharedPreferences("UserMgmt", Context.MODE_PRIVATE);
String Firstname = pref.getString("FName", "");
String Lastname = pref.getString("LName", "");
String Userid = pref.getString("UserId", "");
String Password = pref.getString("Password", "");
String Repassword = pref.getString("RePassword", "");
String Idproof_typ=pref.getString("IdType","");
String Idproof_number=pref.getString("IdNumber","");
String Dob=pref.getString("DOB","");
String Gender=pref.getString("Gender","");
String Email=pref.getString("Email","");
String Mobile_number=pref.getString("Mobile","");
String Country_code=pref.getString("CountryCode","");
String Landline=pref.getString("LandLine","");
String Country=pref.getString("Country","");
String State=pref.getString("State","");
String Address=pref.getString("Address","");
String Pincod=pref.getString("Pincode","");
boolean Tc_chk_state = pref.getBoolean("ChkBoxTC", true);
boolean Consent_chk_state = pref.getBoolean("ChkBoxConsent", true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
// params.add(new BasicNameValuePair("userId", Userid));
params.add(new BasicNameValuePair("firstName", Firstname));
params.add(new BasicNameValuePair("lastName", Lastname));
params.add(new BasicNameValuePair("password", Password));
params.add(new BasicNameValuePair("newPassword", Repassword));
params.add(new BasicNameValuePair("identityType", Idproof_typ));
params.add(new BasicNameValuePair("identityNumber", Idproof_number));
params.add(new BasicNameValuePair("dob", Dob));
params.add(new BasicNameValuePair("gender", Gender));
params.add(new BasicNameValuePair("emailId", Email));
params.add(new BasicNameValuePair("mobileNumber", Mobile_number));
params.add(new BasicNameValuePair("stdCode", Country_code));
params.add(new BasicNameValuePair("landlineNumber", Landline));
params.add(new BasicNameValuePair("countryCode", Country));
params.add(new BasicNameValuePair("stateCode", State));
params.add(new BasicNameValuePair("addr", Address));
params.add(new BasicNameValuePair("zipcode", Pincod));
json = jsonParser.makeHttpRequest(url_new_user,
"POST", params);
// Log.d("Create Response", json.toString());
return null;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created a user
Intent i = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create user
Log.d("failed to create user", json.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
答案 1 :(得分:0)
class CreateUser extends AsyncTask<String, String, String> {
int success=0;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ConsentActivity.this);
pDialog.setMessage("Registering New User..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
SharedPreferences pref = getSharedPreferences("UserMgmt", Context.MODE_PRIVATE);
String Firstname = pref.getString("FName", "");
String Lastname = pref.getString("LName", "");
String Userid = pref.getString("UserId", "");
String Password = pref.getString("Password", "");
String Repassword = pref.getString("RePassword", "");
String Idproof_typ=pref.getString("IdType","");
String Idproof_number=pref.getString("IdNumber","");
String Dob=pref.getString("DOB","");
String Gender=pref.getString("Gender","");
String Email=pref.getString("Email","");
String Mobile_number=pref.getString("Mobile","");
String Country_code=pref.getString("CountryCode","");
String Landline=pref.getString("LandLine","");
String Country=pref.getString("Country","");
String State=pref.getString("State","");
String Address=pref.getString("Address","");
String Pincod=pref.getString("Pincode","");
boolean Tc_chk_state = pref.getBoolean("ChkBoxTC", true);
boolean Consent_chk_state = pref.getBoolean("ChkBoxConsent", true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
// params.add(new BasicNameValuePair("userId", Userid));
params.add(new BasicNameValuePair("firstName", Firstname));
params.add(new BasicNameValuePair("lastName", Lastname));
params.add(new BasicNameValuePair("password", Password));
params.add(new BasicNameValuePair("newPassword", Repassword));
params.add(new BasicNameValuePair("identityType", Idproof_typ));
params.add(new BasicNameValuePair("identityNumber", Idproof_number));
params.add(new BasicNameValuePair("dob", Dob));
params.add(new BasicNameValuePair("gender", Gender));
params.add(new BasicNameValuePair("emailId", Email));
params.add(new BasicNameValuePair("mobileNumber", Mobile_number));
params.add(new BasicNameValuePair("stdCode", Country_code));
params.add(new BasicNameValuePair("landlineNumber", Landline));
params.add(new BasicNameValuePair("countryCode", Country));
params.add(new BasicNameValuePair("stateCode", State));
params.add(new BasicNameValuePair("addr", Address));
params.add(new BasicNameValuePair("zipcode", Pincod));
JSONObject json = jsonParser.makeHttpRequest(url_new_user,
"POST", params);
Log.d("Create Response", json.toString());
try {
success = json.getInt(TAG_SUCCESS);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
if (success == 1) {
// successfully created a user
Intent i = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create user
Log.d("failed to create user", json.toString());
}
}
}
}
检查&#34;创建响应&#34;在日志中发布帖子以追溯你的json响应。