我已经创建了一个Android应用程序,其中有登录表单,更新详细信息表单等。
每当我输入错误的细节时,应用程序就会停止工作,并出现强制关闭对话框。
这是我的代码:
Login.java
public class AllProductsActivity extends ListActivity
{
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
private static String url_all_products = "http://192.168.1.4/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray products = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String>
{
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
UpdateDetails.java
public class UpdateDetails extends Activity
{
EditText inputName;
EditText inputAddress;
EditText inputPassword;
EditText confirmPassword;
EditText inputEmailId, inputMobileno;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// JSON Node names
private static final String resp = "success";
//private static final String Flag = "flag";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.updatedetails);
// Edit Text
inputName = (EditText) findViewById(R.id.editName);
inputAddress = (EditText) findViewById(R.id.editAddress);
inputPassword = (EditText) findViewById(R.id.editPassword);
confirmPassword=(EditText) findViewById(R.id.editConfirmPassword);
inputEmailId=(EditText) findViewById(R.id.editText2_emailid);
inputMobileno=(EditText) findViewById(R.id.editText1_mobile);
// Create button
Button update_details = (Button) findViewById(R.id.buttonUpdate);
// button click event
update_details.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (inputPassword == confirmPassword){
// updating user in background thread
new UpdateUserDetails().execute();
}
else {
//Some Sort Of Alert Box
Toast.makeText(getApplicationContext(), "Please Enter Valid Details", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Background Async Task to Create new product
* */
class UpdateUserDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UpdateDetails.this);
pDialog.setMessage("Updating User Details.. Please wait");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Updating User
* */
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String address = inputAddress.getText().toString();
String password = inputPassword.getText().toString();
String mobileno = inputMobileno.getText().toString();
String emailid = inputEmailId.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("address", address));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("mobile_no", mobileno));
params.add(new BasicNameValuePair("email_id",emailid));
final String url_user = "http://"+ Login.serve +"/catxam/android_update.php";
// getting JSON Object
JSONObject json = jsonParser.makeHttpRequest(url_user,"POST", params);
// check log cat from response
Log.d("Update Response", json.toString());
// check for success tag
try {
int success = json.getInt(resp);
if (success == 1) {
// successfully update user
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
Toast.makeText(getApplicationContext(), "Unsuccessful Updation", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
任何人都可以帮助我找出错误并帮助我纠正项目中的错误。
感谢您的帮助。提前致谢
这是logCat窗口!
02-13 19:32:10.096: E/AndroidRuntime(7328): FATAL EXCEPTION: AsyncTask #2
02-13 19:32:10.096: E/AndroidRuntime(7328): java.lang.RuntimeException: An error occured while executing doInBackground()
02-13 19:32:10.096: E/AndroidRuntime(7328): at android.os.AsyncTask$3.done(AsyncTask.java:299)
02-13 19:32:10.096: E/AndroidRuntime(7328): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
02-13 19:32:10.096: E/AndroidRuntime(7328): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
02-13 19:32:10.096: E/AndroidRuntime(7328): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
02-13 19:32:10.096: E/AndroidRuntime(7328): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
02-13 19:32:10.096: E/AndroidRuntime(7328): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-13 19:32:10.096: E/AndroidRuntime(7328): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
02-13 19:32:10.096: E/AndroidRuntime(7328): at java.lang.Thread.run(Thread.java:838)
02-13 19:32:10.096: E/AndroidRuntime(7328): Caused by: java.lang.NullPointerException
02-13 19:32:10.096: E/AndroidRuntime(7328): at
com.example.catxam.Login$CreateNewUser.doInBackground(Login.java:146)
02-13 19:32:10.096: E/AndroidRuntime(7328): at com.example.catxam.Login$CreateNewUser.doInBackground(Login.java:1)
02-13 19:32:10.096: E/AndroidRuntime(7328): at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-13 19:32:10.096: E/AndroidRuntime(7328): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
02-13 19:32:10.096: E/AndroidRuntime(7328): ... 4 more
抱歉无法发布图片:(
答案 0 :(得分:1)
在postExecute中执行此操作。要显示或传递给另一个活动,请在postExecute中使用。只有在doInBackground中执行的主要操作。
try {
int success = json.getInt(resp);
if (success == 1) {
// successfully update user
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
Toast.makeText(getApplicationContext(), "Unsuccessful Updation", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
答案 1 :(得分:1)
您无法从doInBackground方法调用Toast.makeText
,因为它需要在UI线程上完成。
在doInBackground结束时执行此操作:
// check for success tag
try {
int success = json.getInt(resp);
String success = success == 1 ? "success" : null;
return success;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
和onPostExecute:
protected void onPostExecute(String result) {
if (result!= null) {
// successfully update user
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
Toast.makeText(getApplicationContext(), "Unsuccessful Updation", Toast.LENGTH_SHORT).show();
}
pDialog.dismiss();
}
此外,您不应在LoadAllProducts
:
// updating UI from Background Thread
runOnUiThread(new Runnable()
onPostExecute
旨在让您在后台任务结束时更新UI,因此您无需创建额外的线程来执行该代码。
答案 2 :(得分:1)
和其他答案一样,你的错误(虽然没有logcat ....)是你打电话:
Toast.makeText(getApplicationContext(), "Unsuccessful Updation", Toast.LENGTH_SHORT).show();
<{1>}中的,仅在UI线程上允许UI操作。另一方面,你不需要:
doInBackground
<{1>}中的因为它已经在UI线程上执行,所以你应该使用runOnUiThread(new Runnable() {
作为你的toast消息。