Dialog Box not working [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have been trying to implement this dialog box for the past 3 hours and I can't figure out why it's not popping up, I think it's best to show my entire class to understand my issue:
Registration.java
public class Registration extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
}
//on submit press
public void SubmitRegistration(View view) {
// start an asynch request
class RequestTask extends AsyncTask<String, String, String>{
#Override
public String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Do anything with response..
}
}
// assign text in fields to string values
EditText first = (EditText)findViewById(R.id.first);
String first2 = first.getText().toString();
EditText last = (EditText)findViewById(R.id.last);
String last2 = last.getText().toString();
EditText display = (EditText)findViewById(R.id.display);
String display2 = display.getText().toString();
//calculates the number of characters in the display field
int length2 = display2.length();
EditText email = (EditText)findViewById(R.id.email);
String email2 = email.getText().toString();
EditText password = (EditText)findViewById(R.id.password);
String password2 = password.getText().toString();
EditText vpassword = (EditText)findViewById(R.id.vpassword);
String vpassword2 = vpassword.getText().toString();
//calculates the number of characters in the password field
int length = vpassword2.length();
// verifying the following in order: Passwords match? A Password field is empty?
//Password and Display Name less than 6 characters long? Email contains an # sign and a period?
if(!vpassword2.equals(password2)) {
Toast.makeText(getApplicationContext(), "Passwords do not match!", Toast.LENGTH_SHORT).show();
}
else if (password2.isEmpty() || vpassword2.isEmpty()){
Toast.makeText(getApplicationContext(), "Password field is empty", Toast.LENGTH_SHORT).show();
}
else if (length < 6 || length2 < 6 ) {
Toast.makeText(getApplicationContext(), "Password and Display Name must be at least 6 characters long", Toast.LENGTH_LONG).show();
}
else if (!email2.contains("#") || !email2.contains(".")){
Toast.makeText(getApplicationContext(), "Must enter valid email address.", Toast.LENGTH_SHORT).show();
}
//start else
else {
//send php with all the data to server for validation and insertion into table
String output = null;
try {
output = new RequestTask()
.execute("http://www.alkouri.com/android/registercheck.php?first=" + first2 + "&last=" + last2 + "&display=" + display2 + "&email=" + email2 + "&password=" + password2)
.get();
//example: www.alkouri.com/android/registercheck.php?first=Adam&last=Alkouri&display=arugala&email=arugala#blackbaud.com&password=123
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//if the response from website contains "duplicate" (which means there is a duplicate email address in the DB) then it will display toast.
if (output.contains("Duplicate")) {
Toast.makeText(getApplicationContext(), "Email address already in system, press back button if you forgot password and click on Forgot Password ", Toast.LENGTH_LONG).show();
}
//if the response from website contains "You have registered successfully" then it will send popup message and go to login screen
else if (output.contains("You have")){
//start dialogue
AlertDialog.Builder alertbox = new AlertDialog.Builder(Registration.this);
alertbox.setMessage("You have succesfully registered. Please check your email for further instructions."); // Please Restart Application // "Please restart the app and download your purchase again".
alertbox.setPositiveButton("YES", new DialogInterface.OnClickListener() {
//create button in dialogue
public void onClick(DialogInterface arg0, int arg1)
{
//on clicking "ok" in the dialogue box, current activity will close and return to last activity (login screen).
finish();
}
});
alertbox.show();
}
}//end else
} //end button click task
}//end class
So, at the very bottom, directly under the very last toast, I would like a dialogue box to pop up.
It's to let the user know they have registered and they should check their email for further instructions.
The toast is showing up just fine, but when I implement ANY of the following examples, nothing pops up.
I don't get any errors in the LogCat, it's just that nothing pops up....
I have tried the following examples that I Have seen online:
public class FireMissilesDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_fire_missiles)
.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES!
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
http://stackoverflow.com/questions/2115758/how-to-display-alert-dialog-in-android
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("Write your message here.");
builder1.setCancelable(true);
builder1.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder1.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
What am I doing wrong?

AlertDialog.Builder alertbox = new AlertDialog.Builder(MainMenuActivity.this);
alertbox.setMessage("Please restart the app and download your data again."); // Please Restart Application // "Please restart the app and download your purchase again".
alertbox.setPositiveButton("YES", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
//code
}
});
alertbox.setNegativeButton("NO", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
//code
}
});
alertbox.show();

You need to put an OnclickListener for your submit button in onCreate() method and call your other functions from there.
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Call your submitregistration function function here
}
});
}

output = new RequestTask()
.execute("http://www.mywebsite.com/android/registercheck.php?first=" + first2 + "&last=" + last2 + "&display=" + display2 + "&email=" + email2 + "&password=" + password2)
.get();
Calling get does not make it asynchronous anymore. It blocks the ui thread waiting for the result.
Move the AsyncTask out of onClick
class RequestTask extends AsyncTask<String, String, String>{
http://developer.android.com/reference/android/os/AsyncTask.html#get()
public final Result get ()
Added in API level 3
Waits if necessary for the computation to complete, and then retrieves its result.
Also Declare your variables a instance variables and initialize your views in onCreate.
EditText first ;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
first = (EditText)findViewById(R.id.first);
On Button click get the text from editText
Invoke asynctask
new RequestTask().execute(params); // no get
The result of doInbackground computation is a param to onPostExecute. Based on the result you can display dialog in onPostExecute.

Related

Android Studio - Using Volley to get JSON data from the server

This is my first attempt to create a login system in Android Studio and already got myself into trouble with my code.
My PHP script always returns something as JSON and I'm trying to parse that JSON in my LoginActivity, inside the login -method, but I'm getting
the following error after creditentials were forwarded to the server and the login button was clicked:
I/qtaguid﹕ Failed write_ctrl(u 43) res=-1 errno=22
I/qtaguid﹕ Untagging socket 43 failed errno=-22
W/NetworkManagementSocketTagger﹕ untagSocket(43) failed with errno -22
It did work earlier, when I was doing a stringRequest instead of jsonRequest, so everything should be fine on the server side. Since I'm very new to Android development, I'm unable to figure this one out by myself and need desperately your help.
Here's my LoginActivity without the imports:
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
// Define Views
private EditText editTextEmail, editTextPassword;
private Button buttonLogin;
private ProgressBar progress;
private UserLocalStore userLocalStore;
private boolean loggedIn = false;
private final String TAG = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide(); // Hides the Action Bar for Login Activity
setContentView(R.layout.activity_login); // Sets the Content View
// Initializing Views
// EditText fields
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
// Buttons
buttonLogin = (Button) findViewById(R.id.buttonLogin);
// Other
progress = (ProgressBar) findViewById(R.id.progressBar);
// This method will set watcher for the EditTextFields
// The method will watch the value set to the EditTextFields.
// If there is nothing inputted in the EditTextField, "Login" button is disabled.
// Correspondingly, if there are text in the field, "Login" button is enabled.
watcher(editTextEmail, editTextPassword, buttonLogin);
// On-Click listeners
buttonLogin.setOnClickListener(this);
}
// Watcher method to check the value of EditText field
public void watcher(final EditText editText, final EditText editPassword, final Button button)
{
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if (editText.length() == 0 && editPassword.length() == 0) // If length of the text field is equal to 0
button.setEnabled(false); // Disable the "Send" button
else
button.setEnabled(true); // Otherwise enable
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
if(editText.length() == 0 && editPassword.length() == 0)
button.setEnabled(false); //disable at app start
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
// If the value of loggedIn variable is true
if(!loggedIn) {
// We will start the Courses activity
Intent intent = new Intent(LoginActivity.this, CourseActivity.class);
startActivity(intent);
}
}
private void login() {
// Get the values from the edit texts
final String email = editTextEmail.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
// Creating a JSON Object request
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Config.LOGIN_URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
// This line will not print out
System.out.println(response);
try {
String json_status = response.getString("status");
String message = response.getString("message");
if(json_status.equalsIgnoreCase(Config.LOGIN_SUCCESS)) {
System.out.println(message);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// You can handle the error here if you want
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
// Adding parameters to request
params.put(Config.KEY_EMAIL, email);
params.put(Config.KEY_PASSWORD, password);
// Return parameters
return params;
}
};
// Adding the string request to the queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjectRequest);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
// If button Login was clicked
case R.id.buttonLogin:
login(); // Start login method after "Login" button is clicked
// startActivity(new Intent(this, MainActivity.class));
break;
}
}
}
And here's my PHP:
<?php
require_once("dbconnect.php");
// POST Variables
$post_email = $_POST['email'];
$post_password = $_POST['password'];
// Prepare the SQL query
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute(array(
':email' => $post_email,
));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0 && password_verify($post_password, $row['password']) && $row['role'] != 'staff') {
$user = array(); // Create an array for the user information
$user['id'] = $row['id'];
$user['name'] = $row['name'];
$user['email'] = $row['email'];
$user['password'] = $row['password'];
$user['role'] = $row['role'];
// echo json_encode(["message" => "success"]);
echo json_encode(["status" => "success", "message" => "Successfully logged in"]); // Format the array to JSON
} else {
echo json_encode(["status" => "error", "message" => "Incorrect creditentials"]);
}
You might not be passing the params, I usually use this syntax:
// Get the values from the edit texts
final String email = editTextEmail.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
Map<String, Object> params = new ArrayMap<>(2);
// Adding parameters to request
params.put(Config.KEY_EMAIL, email);
params.put(Config.KEY_PASSWORD, password);
// Creating a JSON Object request
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(params),
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
Log.d(TAG, response.toString());
// other stuff ...
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
// You can handle the error here if you want
}
});
// Adding the string request to the queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjectRequest);
Also, you might want to handle all the volley requests in a Singleton class, have a look at this SO question.
Hope this helps in any way :)

ProgressDialog from other Activity

i have 2 Activitys. In the first Updater Activity i want to create a ProgressDialog,
which I want to show in the other Activity(TopRatedFragment). How can i do this?
public class Updater extends Activity {
String pid = "1";
JSONObject x;
int success;
ProgressDialog pDialog;
int y;
private String result;
String Url = "domain.com";
JSONArray products = null;
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checker);
}
public int getResult(JSONObject json) {
try {
Log.d("Request: ", json.toString());
// Getting JSON Array
success = json.getInt(TAG_SUCCESS);
Log.i("Status 2 z", "Status z: "+ success);
} catch (JSONException e) {
e.printStackTrace();
}
return success;
}
public final int updaten(String site) {
Update task = new Update();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", site));
x = task.execute(params).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
y = getResult(x);
return y;
}
class Update extends AsyncTask<List<NameValuePair>, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Updater.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected JSONObject doInBackground(List<NameValuePair>... params) {
// Getting JSON from URL
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(Url, params[0]);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
Log.d("Updater ", json.toString());
}
}
public class TopRatedFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
return rootView;
}
This method is called after an OnClickListener.
public void Updatequest(final String site) {
ConnectivityManager connMgr = (ConnectivityManager) getActivity()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
ado = new Updater();
Log.i("Status 2 z", "Status z: " + z);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
getActivity());
// set title
alertDialogBuilder.setTitle("Do you really want to report?");
// set dialog message
alertDialogBuilder
.setMessage("Press Yes to submit your report")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// if this button is clicked, close
// current activity
int z = ado.updaten(site); //call the method in the other Activity
Log.i("Status 1 z", "Status z: " + z);
if (z == 1) {
Toast.makeText(
getActivity(),
"Thanks, your report was successfull",
Toast.LENGTH_LONG).show();
z = 0;
} else {
Toast.makeText(
getActivity(),
"Please check your Internet connection!",
Toast.LENGTH_LONG).show();
}
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
else {
Toast.makeText(getActivity(),
"An error has occured please check your Internet Connection again", Toast.LENGTH_LONG)
.show();
}
If i click on the Button, a lot of errors are shown. The first is the FATAL EXCEPTION: main
and a java.lang.NullPointerException.
How can I fix that ?
If you look into the logcat, you will find the full exception backtrace. It tells you the line, where the NullPointerException was thrown. Please check, if that button really exists. Maybe, it is caused by a wrong ID or something else.
If you have a very loooong backtrace, read through the trace and look for "Caused by...." lines. It often happened to me, that the exception was encapsulated and wasn't obvious shown in the logcat.

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 can i put alert dialog box in loop specially in for loop Android

I want to add different dialog box for different contacts ..!! and i want create in following for loop and here is my code ..!!
public class CallActivity extends Activity{
sqlAdapter adapter;
Context mContext;
String Birthdate, CurrentDate, ctName = "Unknown", phNumber = "Unknown";
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.reminder);
Calendar cal = Calendar.getInstance();
int date = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH)+1;
/* For geting Current Date */
if(date<10 && month<10){
CurrentDate = "0"+month+"-0"+date;
Toast.makeText(getBaseContext(), "CurrentDate : " + CurrentDate, Toast.LENGTH_LONG).show();
}else if(month<10 && date>10){
CurrentDate = "0"+month+"-"+date;
Toast.makeText(getBaseContext(), "CurrentDate : " + CurrentDate, Toast.LENGTH_LONG).show();
}else if(month>9 && date<10){
CurrentDate = month+"-0"+date;
Toast.makeText(getBaseContext(), "CurrentDate : " + CurrentDate, Toast.LENGTH_LONG).show();
}else {
CurrentDate = month+"-"+date;
Toast.makeText(getBaseContext(), "CurrentDate : " + CurrentDate, Toast.LENGTH_LONG).show();
}
adapter = new sqlAdapter(getBaseContext());
adapter.openToRead();
ArrayList<ContactDetails> cDetails = adapter.getContactDetails(CurrentDate);
adapter.close();
/* this is for loop where i want to generate alert dialog box for different contacts */
for (int i = 0; i < cDetails.size(); i++) {
ctName = cDetails.get(i).Name;
adapter.openToRead();
phNumber = adapter.getcNumber(ctName);
adapter.close();
alertforcall(getBaseContext(),ctName,phNumber);
}
}
public void alertforcall(Context context, String Name, final String ctNumber){
mContext = context;
AlertDialog alert = new AlertDialog.Builder(CallActivity.this).create();
alert.setIcon(R.drawable.ic_launcher);
alert.setTitle("");
alert.setMessage("Are you sure want to call " + Name +"? " );
alert.setButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
alert.setButton2("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String phoneNumber = "tel:" + ctNumber;
Intent intent = new Intent(Intent.ACTION_CALL, Uri
.parse(phoneNumber));
startActivity(intent);
finish();
}
});
alert.show();
}
Bad Practice, Creating a Dialog in for-loop is not a Good Programming practice.
Just pass, a ArrayList of Contact to alertforcall() method, and When you want to show the dialog on condition base set the Name and Contact in that AlertDialog..
For example,
Now, when you want to show alert dialog for particular contact, I assume you are clicking on Contact List, So by getting Name and Number for particular List Item and passing it to alertforcall() method You can show particular Alert Dialog.

problem setting progress bar before alert dialog which has a spinner

public class classified extends Activity
{
private ArrayAdapter<String> aaagency ;
String strdata="";
String strerrormess="";
public void onCreate(Bundle savedInstanceState)
{
setTitle("Classified Ad. Booking");
super.onCreate(savedInstanceState);
this.setContentView(R.layout.classified);
}
public void srcAgency(View view) throws IOException
{
Log.i("Classified Ad","srcAgency");
new srcAgency().execute();
srcAgency srcagen = new srcAgency();
strdata = srcagen.strtempdata;
Log.i("AgencyData2", strdata);
Log.i("AgencyData3", strerrmess);
if(strerrmess.equals(""))
{
strarr= fun1.split(strdata, "^");
aaagency = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item , strarr);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Agency");
builder.setAdapter(aaagency, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
txtAgency.setText(strarr[item]);
}
});
builder.show();
}
}
class srcAgency extends AsyncTask<Void, String, Void>
{
String strtempdata="";
ProgressDialog dialog;
#Override
protected void onPreExecute()
{
strerrmess="";
super.onPreExecute();
dialog = ProgressDialog.show(classified.this, "", "Please wait...", true);
dialog.show();
}
#Override
protected Void doInBackground(Void... unused)
{
try
{
stragency = txtAgency.getText().toString().trim();
intagencyBrac1= stragency.lastIndexOf('(');
intagencyBrac2= stragency.lastIndexOf(')');
if (stragency.length() < 3)
{strerrmess="Please Enter atleast 3 Characters for Agency Searching";}
else if(intagencyBrac1>=0||intagencyBrac2>=0)
{strerrmess="Please Enter Characters for Agency Searching";}
else
{
if(stragency.indexOf(' ')!=-1)
{stragency = stragency.replace(' ', '!');}
Log.i("AgencyUrl",strurl);
strdata = "Client1^Client2^Client3^Client4^Client5^Client6^Client1";
Log.i("AgencyData",strdata);
strtempdata = strdata;
if(!strdata.equals(""))
{
}
else
{strerrmess ="No Data Available";}
}
}
catch(Exception e)
{
}
return null;
}
#Override
protected void onPostExecute(Void unused)
{
dialog.dismiss();
if (strerrmess.equals("Please Enter atleast 3 Characters for Agency Searching"))
{Toast(strerrmess);intflag=1;}
else if(strerrmess.equals("Please Enter Characters for Agency Searching"))
{Toast(strerrmess);intflag=1;}
else if(strerrmess.equals("Your Session Got Expired. Please login again."))
{
Intent intent = new Intent(classified.this, loginscreen.class);
startActivity(intent);
Toast(strerrmess);
intflag=1;
}
else
{intflag=0;}
}
}
}
I am unable to get the value of strdata which i have initialized in asynctask function in the srcagency function. What should I do? Even though strdata is a global variable.
I have also tried this but I think you can't initialize array adapter in onpostexecute function...
#Override
protected void onPostExecute(Void unused)
{
dialog.dismiss();
if (strerrmess.equals("Please Enter atleast 3 Characters for Agency Searching"))
{Toast(strerrmess);intflag=1;}
else if(strerrmess.equals("Please Enter Characters for Agency Searching"))
{Toast(strerrmess);intflag=1;}
else if(strerrmess.equals("Your Session Got Expired. Please login again."))
{
Intent intent = new Intent(classified.this, loginscreen.class);
startActivity(intent);
Toast(strerrmess);
intflag=1;
}
else
{strarr= fun1.split(strdata, "^");
aaagency = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item , strarr);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Agency");
builder.setAdapter(aaagency, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
txtAgency.setText(strarr[item]);
}
});
builder.show();}
}
Any help or comments would be appreciated.
Thanks
Log.i("Classified Ad","srcAgency");
new srcAgency().execute();
srcAgency srcagen = new srcAgency();
strdata = srcagen.strtempdata;
This does not work. You are saying, start an AsyncTask that will set your strdata at some point in the future but also immediately return and after creating a new AsyncTask have it know what the last AsyncTask did.
Try this:
void srcAgency(View v){
//We only want to start the AsyncTask here, nothing else.
// Whatever you did before and whatever triggered the srcAgency(View) method
srcAgency srcagen = new srcAgency();
srcagen.execute();
return;
}
public void realSrcAgency(View v) {
... // The rest of original srcAgency(View)
}
// Inside of asyncTask srcAgency ...
public void postExecute() {
// Call the new method we just had, but after our asyncTask is done.
realSrcAgency(null);
}
Basically you can't expect all these things to happen simultaneously. It would be easy to help you if you trimmed down the specifics of your code. It looks like you just want a button or some click to start an async task that fills a strings. However after that string is filled do something else with it. Also I don't believe you need an async task for any of this.

Categories

Resources