onActivityResult() is not calling from Activity - java

I'm able to edit & save data from one Activity(EditActivity.java), but the updated data doesn't display(or carried over) to the next Activity(ViewActivity.java) when click Save button. I can see the changes on the EditText fields if go back to the EditActivity page.
EditActivity.java
btnSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// starting background task to update request
new SaveRequestDetails().execute();
}
});
class SaveRequestDetails extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String request_title = txtTitle.getText().toString();
String request_date = txtSdate.getText().toString();
String reqEndDate = txtEdate.getText().toString();
String hours = txtHours.getText().toString();
String reason = txtReason.getText().toString();
String explanation = txtExp.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_ID, request_id));
params.add(new BasicNameValuePair(TAG_TITLE, request_title));
params.add(new BasicNameValuePair(TAG_SDATE, request_date));
params.add(new BasicNameValuePair(TAG_EDATE, reqEndDate));
params.add(new BasicNameValuePair(TAG_HOURS, hours));
params.add(new BasicNameValuePair(TAG_REASON, reason));
params.add(new BasicNameValuePair(TAG_EXP, explanation));
JSONObject json = jsonParser.makeHttpRequest(url_update_request,
"POST", params);
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Intent i = getIntent();
// send result code 100 to notify about request update
setResult(100, i);
finish();
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
ViewActivity.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_request);
Intent i = getIntent();
// getting request id (rid) from intent
request_id = i.getStringExtra(TAG_ID);
// Getting complete request details in background thread
new GetRequestDetails().execute();
btnEdit = (Button) findViewById(R.id.btnEdit);
btnEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Starting new intent
Intent in = new Intent(getApplicationContext(), EditActivity.class);
// sending rid to next activity
in.putExtra(TAG_ID, request_id);
startActivity(in);
}
});
}
// Response from Edit 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 request
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}

Your headline says that, that onActivityResult() does not get called.
Use startActivityForResult(in, 55) instead of startActivity(in)
//EDIT:
By the way, checking the result code should by done using the RESULT_OK / RESULT_CANCELED constants. You might also consider checking the request code (in my example code it would be 55)

Related

android - Google places opens the map on closes after 1 sec

Im creating an intent to an activity by clicking on a button which should open google places, but it closes again really fast and says no location selected, and returns to the main activity, and then nothing happens if i click again.
My api should be fine, I have checked that it's the correct SHA1-fingerprint thats connected to the api key.
The result code is 2
It worked earlier in the activity before this one, but I needed it to open when i click on a button instead, and now when I try to open this new activity as an intent it wont work.
public class MapActivity extends AppCompatActivity {
int PLACE_PICKER_REQUEST = 1;
int status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_events);
status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (status != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(status)) {
GooglePlayServicesUtil.getErrorDialog(status, this,
100).show();
}
}
if (status == ConnectionResult.SUCCESS) {
int PLACE_PICKER_REQUEST = 199;
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
Context context = this;
try {
startActivityForResult(builder.build(context), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println("Result code: " + resultCode);
System.out.println("Request code: " + requestCode);
if (requestCode == 100) {
status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
}
if (requestCode == 199) {
//process Intent......
if (data != null) {
Place place = PlacePicker.getPlace(data, this);
String toastMsg = String.format("Place: %s", place.getName());
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
} else {
String toastMsg = ("No location selected.");
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
}
}
}
}
This is from the intent which create the new intent to maps
public void onClick(View view) {
Intent i = new Intent(this, MapActivity.class);
startActivity(i);
}
I think its happening because of you are using old method of getPlace
try to swap the arguments, by changing it from:
Place place = PlacePicker.getPlace(data, this);
to
Place place = PlacePicker.getPlace(getContext(), data);
Update #2
Enable Google places API in the developer console and add these lines to AndroidManifest
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="ADD_YOUR_API_KEY_HERE" />
Update #3
after some search, it looks like there is others having same issue. Look at these links:
https://github.com/zhangtaii/react-native-google-place-picker/issues/21
https://stackoverflow.com/a/32751164/
https://github.com/googlesamples/android-play-places/issues/13

Activity leaked :android.view.WindowLeakedActivity com.example.androidhive.AllProductsActivity has leaked window DecorView#bf6bd49[]

This is my MainScreenActivity.java code:
public class MainScreenActivity extends Activity{
Button btnViewProducts;
Button btnNewProduct;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_screen);
// Buttons
btnViewProducts = (Button) findViewById(R.id.btnViewProducts);
btnNewProduct = (Button) findViewById(R.id.btnCreateProduct);
// view products click event
btnViewProducts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launching All products Activity
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
}
});
// view products click event
btnNewProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launching create new product activity
Intent i = new Intent(getApplicationContext(), NewProductActivity.class);
startActivity(i);
}
});
}
My AllProductsActivity.java:
public class AllProductsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://127.0.0.1/android_connect2/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 response
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);
}
});
}
}
}
Below is my logcat:
11-25 13:59:59.941 10468-10468/com.example.androidhive E/WindowManager: android.view.WindowLeaked: Activity com.example.androidhive.AllProductsActivity has leaked window DecorView#bf6bd49[] that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:417)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:331)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
at android.app.Dialog.show(Dialog.java:316)
at com.example.androidhive.AllProductsActivity$LoadAllProducts.onPreExecute(AllProductsActivity.java:117)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:613)
at android.os.AsyncTask.execute(AsyncTask.java:560)
at com.example.androidhive.AllProductsActivity.onCreate(AllProductsActivity.java:57)
at android.app.Activity.performCreate(Activity.java:6664)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
I'm just a beginner and I have no idea what is causing the error. I have searched the site for solutions but it seems that this error is code specific. Any help is appreciated.
This happen because you have not initialize your ProgressDialog properly or you do not close your progress dialog properly. Make sure that in onPause() you call pDialog.dismiss(); And also initialize in this way.
Make object of Context and initialize it in onCreate(); as mContext=YourActivity.this
pDialog= ProgressDialog.show(mContext);
Problem is in do in background, check your else condition you are starting another activity from there so just put pDialog.dismiss(); before you start another activity
Reason behind this crash is you dialog is still showing and you are changing Activity so its showing WindowLeaked error
As you doInBackground will not allow to hide dialog you can hide it in onPause() method it will also work

Android app hangs after subsequent call to startActivityForResult

Not sure if this is know behavior or what, but here's the logical flow:
User opens app
Pulls nav drawer out, clicks profile pic to change it
Gallery intent pops up, user picks image, everything works fine
Subsequent attempt to open gallery works fine, upon choosing picture, application hangs
onResume() is not called, neither is onActivityResult(). I even commented out all the code in onActivityResult and it still happens. Any ideas what would cause this?
Here is code from onCreate() in the main activity
ImageButton profilePictureButton = (ImageButton) findViewById(R.id.change_profile_picture);
profilePictureButton.requestFocus();
profilePictureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 1);
}
});
And here's the handler:
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
if(resultCode == RESULT_OK) {
if(requestCode == 1) {
ImageView view = ((ImageView) findViewById(R.id.nav_profile_picture));
if(data != null) {
/*Picasso.with(this).load(data.getData()).into(view);
UsersCache.getInstance().GetUser("", new Response.Listener<UserItem>() {
#Override
public void onResponse(UserItem response) {
String pictureName = response.username + UUID.randomUUID().toString();
String url = "<redacted>";
JSONObject requestBody = new JSONObject();
try {
requestBody.put("profilePicture", "<redacted>/media/profile_pictures/" + pictureName);
} catch(JSONException e) {
e.printStackTrace();
return;
}
FlareJsonObjectRequest request = new FlareJsonObjectRequest(Method.POST, url, requestBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String tet = null;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String tet = null;
}
});
new AmazonS3Uploader(data.getData(), "profile_pictures/" + pictureName);
VolleyQueue.getInstance().getQueue().add(request);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String tet = null;
}
});*/
}
}
I think you are missing the read access permission in Manifest -
android:name="android.permission.READ_EXTERNAL_STORAGE" />

Android app login and and Signin issue

I am developing an android app in which , a sigin , and signup option is there . when a new user enters to the application for first time he needs to signup.. when he presses the sigin option he is directed to the account creation page.where he needs to gve the username,password and mobile number. all these three values are stored in sqlite ( applications memory ) and a passcode is created and send to the mobile number provided by user. and next page is registration page, where users username and password is checked along with the passcode which he recieved. This process I did to verify the mobile number. So my problem is if once the user created the account and go back to signin option and enter the username and password .. he is directing to the applications first page... because when account creation process is done his details are saved in the applications databse for verification. so user dont need to verify the passcode.. so is there any way to make the signin button view only after a registration process.. or something like that ... I am posting here the siginactivity, signupactivity and register activity.. pls check it and if found any error pls help me...
Signup Activity
public class SignUpActivity extends Activity
{
EditText editTextUserName,editTextPassword,editTextConfirmPassword, editMobileNumber;
Button btnCreateAccount;
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
Random r = new Random();
int number =r.nextInt(9999 - 1000) + 1000;
LoginDataBaseAdapter loginDataBaseAdapter;
private static String url_create_data = "http://iascpl.com/app/create_data1.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup_xm);
// get Instance of Database Adapter
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
// Get References of Views
editTextUserName=(EditText)findViewById(R.id.editTextUserName);
editTextPassword=(EditText)findViewById(R.id.editTextPassword);
editTextConfirmPassword=(EditText)findViewById(R.id.editTextConfirmPassword);
editMobileNumber = (EditText)findViewById(R.id.mobileNumber);
btnCreateAccount=(Button)findViewById(R.id.buttonCreateAccount);
btnCreateAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
String confirmPassword=editTextConfirmPassword.getText().toString();
String phoneNo = editMobileNumber.getText().toString();
String sms = Integer.toString(number);
//Intent intent = new Intent(SignUpActivity.this, RegisterActivity.class);
//intent.putExtra("number", sms + "");
//startActivity(intent);
//new CreateNewProduct().execute();
StringTokenizer st=new StringTokenizer(phoneNo,",");
while (st.hasMoreElements())
{
String tempMobileNumber = (String)st.nextElement();
if(tempMobileNumber.length()>0 && sms.trim().length()>0)
{
sendSMS(tempMobileNumber, sms);
}
else
{
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
}
}
// check if any of the fields are vacant
if(name.equals("")||password.equals("")||confirmPassword.equals(""))
{
Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if(!password.equals(confirmPassword))
{
Toast.makeText(getApplicationContext(), "Password does not match", Toast.LENGTH_LONG).show();
return;
}
else
{
// Save the Data in Database
loginDataBaseAdapter.insertEntry(name, password);
Toast.makeText(getApplicationContext(), "Passcode is sent to the mobile number you provided. ", Toast.LENGTH_LONG).show();
new CreateNewProduct().execute();
// Intent intent = new Intent(SignUpActivity.this, RegisterActivity.class);
// intent.putExtra("number", sms + "");
// startActivity(intent);
}
}
});
}
private void sendSMS(String phoneNumber, String message)
{
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED), 0);
//---when the SMS has been sent---
registerReceiver(new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
},new IntentFilter(SENT));
//---when the SMS has been delivered---
registerReceiver(new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
loginDataBaseAdapter.close();
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SignUpActivity.this);
pDialog.setMessage("Creating a new account..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = editTextUserName.getText().toString();
String password = editTextPassword.getText().toString();
String mobile = editMobileNumber.getText().toString();
String sms = Integer.toString(number);
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("mobile", mobile));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_data,
"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
Intent i = new Intent(SignUpActivity.this, RegisterActivity.class);
i.putExtra("number", sms + "");
startActivity(i);
//closing this screen
//finish();
} else {
// failed to create product
return "false";
}
} 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();
}*/
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
if (result == "false")
Toast.makeText(SignUpActivity.this, "User Name already exists. Please choose another user name ", Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
}
}
Register Activity
public class RegisterActivity extends Activity {
LoginDataBaseAdapter loginDataBaseAdapter;
Button btnReg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_xm);
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
btnReg = (Button) findViewById (R.id.buttonRegister);
final EditText editTextUserName=(EditText)findViewById(R.id.editTextUserNameToLogin);
final EditText editTextPassword=(EditText)findViewById(R.id.editTextPasswordToLogin);
final EditText editTextMobileNumber = (EditText)findViewById(R.id.editText1);
btnReg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String userName=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
String mobileNumber = editTextMobileNumber.getText().toString();
// fetch the Password form database for respective user name
String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName);
String sd = getIntent().getStringExtra("number");
String name = editTextUserName.getText().toString();
// check if the Stored password matches with Password entered by user
if(password.equals(storedPassword) && (mobileNumber.equals(sd)))
{
Toast.makeText(RegisterActivity.this, "Congrats: Registration Successfull", Toast.LENGTH_LONG).show();
Intent in = new Intent(RegisterActivity.this,HomePageActivity.class);
startActivity(in);
}
else
{
Toast.makeText(RegisterActivity.this, "User Name, Passcode or Password does not match", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onDestroy()
{
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}
}
Signin activity
public class SignInActivity extends Activity
{
/*LoginDataBaseAdapter loginDataBaseAdapter;*/
Button btnsignin;
EditText username,userpassword;
TextView txtName;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static String url_get_name = "http://iascpl.com/app/get_name_details.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String TAG_PASSWORD = "password";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.signin_xm);
/*loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();*/
btnsignin = (Button) findViewById ( R.id.button401);
username=(EditText)findViewById(R.id.editText401);
userpassword=(EditText)findViewById(R.id.editText402);
btnsignin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new GetProductDetails().execute();
/* String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName);*/
// check if the Stored password matches with Password entered by user
/*if(password.equals(storedPassword))
{
Toast.makeText(SignInActivity.this, "Login Successfull", Toast.LENGTH_LONG).show();
Intent i = new Intent(SignInActivity.this,HomePageActivity.class);
startActivity(i);
}
else
{
Toast.makeText(SignInActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show();
}*/
}
});
}
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SignInActivity.this);
pDialog.setMessage("Loading the result... Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... args)
{
String pid=username.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_get_name, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
final JSONObject product = productObj.getJSONObject(0);
txtName = (TextView) findViewById(R.id.textView1);
// product with this pid found
// Edit Text
runOnUiThread(new Runnable() {
#Override
public void run()
{
// TODO Auto-generated method stub
try {
txtName.setText(product.getString(TAG_PASSWORD));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}else{
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/*
#Override
protected void onDestroy()
{
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}*/
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String result)
{
// dismiss the dialog once got all details
/*super.onPostExecute(result);
if (result == "false")
Toast.makeText(SignInActivity.this, "User Name already exists. Please choose another user name ", Toast.LENGTH_LONG).show();*/
pDialog.dismiss();
}
}
}
I understood your problem ... You are saving your signup details in sqlite so when user entering username and password it is saved in sqlite and next step is registration process where user has to enter the secret code.. But as as username and password is saved in sqlite user can press back button and go back and login with username and password and avoid registration process...
Here you can do something like this. use shared preference
for ex:In registration page after successful registration give value l.
SharedPreferences set = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor ed = set.edit();
ed.putString("l", "l");
ed.commit();
and check in your home page whether the value is l or not if value is l only then make your signin button visible. You can use something like this for making the button invisible.
btn3.setVisibility(View.INVISIBLE);
btn4.setVisibility(View.INVISIBLE);

How to call notifyDataSetChanged() on ArrayList view?

This is the ArrayList page that opens as a result page after update and save. I guess I would need to somehow refresh so that it reflects the changes on the UI. I've tried to call notifyDataSetChanged() but no luck with my level of experience. Could someone kindly show how to implement it please?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_requests);
requestsList = new ArrayList<HashMap<String, String>>();
new LoadAllRequests().execute();
ListView list = getListView();
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String request_id = ((TextView) view.findViewById(R.id.request_id)).getText().toString();
Intent in = new Intent(getApplicationContext(),
ViewRequestActivity.class);
in.putExtra(TAG_ID, request_id);
startActivityForResult(in, 100);
}
});
}
// Response from ViewRequestActivity when delete a request reload this page again
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class LoadAllRequests extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_all_requests, "GET", params);
Log.d("All Requests: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
requests = json.getJSONArray(TAG_REQUESTS);
for (int i = 0; i < requests.length(); i++) {
JSONObject c = requests.getJSONObject(i);
String request_id = c.getString(TAG_ID);
String request_title = c.getString(TAG_TITLE);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, request_id);
map.put(TAG_TITLE, request_title);
requestsList.add(map);
}
} else {
Intent i = new Intent(getApplicationContext(),
NewRequestActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
You need to create an adapter for your ListView. The adapter is what feeds data to it for displaying. I would recommend you reading through this tutorial:
http://www.vogella.com/articles/AndroidListView/article.html
So once you have created your adapter and then called lv.setAdapter(<adapter>), you can then call <adapter>.notifyDataSetChanged(). This will tell the adapter that it needs to refresh itself.
You can use notifyDataSetChanged() method for your adapter.Wherever you want to update your listview you can use in following manner.
adapter.notifyDataSetChanged();

Categories

Resources