How to sending email from android like "mailto:" in PHP? - java

has everyone know how to sending an email from android device like mailto: in PHP?? i really need that for my lockscreen application.. it will send a email (email must be registered before) to the client when his/her forgot his/her password. what should i do?? any idea?? thanks..
package com.application.outgoingemail;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class EmailService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
//Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startid) {
//Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
sendEmail();
}
#Override
public void onDestroy() {
}
public void sendEmail()
{
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"myEmail#example.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
i.putExtra(Intent.EXTRA_TEXT , "body of email");
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(EmailService.this,ex.getMessage(), Toast.LENGTH_SHORT).show();
Toast.makeText(EmailService.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
/*try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (Exception ex) {
Toast.makeText(EmailService.this,ex.getMessage(), 10).show();
//Toast.makeText(EmailService.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}*/
}
}
and on the mainForm :
package com.application.outgoingemail;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class main extends Activity implements OnClickListener{
/** Called when the activity is first created. */
Button Button1,Button2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button1=(Button)findViewById(R.id.button1);
Button1.setOnClickListener(this);
Button2=(Button)findViewById(R.id.button2);
Button2.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
startService(new Intent(main.this, EmailService.class));
break;
case R.id.button2:
stopService(new Intent(main.this, EmailService.class));
break;
default:
break;
}
}
}

you can do by this way ::
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"recipient#example.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
i.putExtra(Intent.EXTRA_TEXT , "body of email");
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MyActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}

Related

Can't dismiss dialog in Android

I don't know why my dialog can not be dismissed. Actually, I see in my database, the data we take successfully gets saved in that database. Just the dialog dismiss code is not working.
This is my code:
package com.app.kfstore.EmailLoginRegister;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.app.kfstore.MainActivity;
import com.app.kfstore.OperationRetrofitApi.ApiClient;
import com.app.kfstore.OperationRetrofitApi.ApiInterface;
import com.app.kfstore.OperationRetrofitApi.Users;
import com.app.kfstore.R;
import com.blogspot.atifsoftwares.animatoolib.Animatoo;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class EmailRegisterActivity extends AppCompatActivity {
private EditText name,email,password;
private Button regBtn;
public static ApiInterface apiInterface;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_email_register);
//////hide status bar code//////
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
//////end code for hide status bar//////
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
init();
}
private void init() {
name = (EditText) findViewById(R.id.name);
email = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.password);
regBtn = (Button) findViewById(R.id.button2);
regBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Registration();
}
});
}
private void Registration() {
String user_name = name.getText().toString().trim();
String user_email = email.getText().toString().trim();
String user_password = password.getText().toString().trim();
if(TextUtils.isEmpty(user_name)){
name.setError("Name is required!");
}
else if(TextUtils.isEmpty(user_email)){
email.setError("Email is required!");
}
else if(TextUtils.isEmpty(user_password)){
password.setError("Password is required!");
}
else {
ProgressDialog dialog = new ProgressDialog(this);
dialog.setTitle("Registering...");
dialog.setMessage("Please wait while we adding your credentials");
dialog.show();
dialog.setCanceledOnTouchOutside(false);
Call<Users> call = apiInterface.performEmailRegistration(user_name,user_email,user_password);
call.enqueue(new Callback<Users>() {
#Override
public void onResponse(Call<Users> call, Response<Users> response) {
if(response.body().getResponse().equals("ok")){
Toast.makeText(EmailRegisterActivity.this, "Your account has been created", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
else if(response.body().getResponse().equals("failed!")){
Toast.makeText(EmailRegisterActivity.this, "Something went wrong, Please try again!", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
else if(response.body().getResponse().equals("already")){
Toast.makeText(EmailRegisterActivity.this, "This email is already exists, Please try another email", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}
#Override
public void onFailure(Call<Users> call, Throwable t) {
}
});
}
}
//////link code for text go to login page//////
public void goToLogin(View view) {
Intent intent = new Intent(EmailRegisterActivity.this, EmailLoginActivity.class);
startActivity(intent);
Animatoo.animateSlideRight(this);
finish();
}
///////end of code//////
//////link code for back button go to main page//////
public void goToMainPage(View view) {
Intent intent = new Intent(EmailRegisterActivity.this, MainActivity.class);
startActivity(intent);
Animatoo.animateSlideRight(this);
finish();
}
//////end of code//////
}
This for easy code to see( just same code but i just cut the top and bottom code)
else {
ProgressDialog dialog = new ProgressDialog(this);
dialog.setTitle("Registering...");
dialog.setMessage("Please wait while we adding your credentials");
dialog.show();
dialog.setCanceledOnTouchOutside(false);
Call<Users> call = apiInterface.performEmailRegistration(user_name,user_email,user_password);
call.enqueue(new Callback<Users>() {
#Override
public void onResponse(Call<Users> call, Response<Users> response) {
if(response.body().getResponse().equals("ok")){
Toast.makeText(EmailRegisterActivity.this, "Your account has been created", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
else if(response.body().getResponse().equals("failed!")){
Toast.makeText(EmailRegisterActivity.this, "Something went wrong, Please try again!", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
else if(response.body().getResponse().equals("already")){
Toast.makeText(EmailRegisterActivity.this, "This email is already exists, Please try another email", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}
#Override
public void onFailure(Call<Users> call, Throwable t) {
}
});
}
}
Result just run dialog without dismiss dialog:
If you have any ideas or advice, I realy apreciate it.
Thanks
Just tried your code, and it works perfectly.
Make sure you have an 'else' clause in your onResponse, and dismiss the dialog in onFailure as well
#Override
public void onResponse(Call<Users> call, Response<Users> response) {
if(response.body().getResponse().equals("ok")){}
else if(response.body().getResponse().equals("failed!")){}
else if(response.body().getResponse().equals("already")){}
else {
Toast.makeText(EmailRegisterActivity.this, "Do'h, I forgot to put and 'else' clause", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}
#Override
public void onFailure(Call<Users> call, Throwable t) {
Toast.makeText(EmailRegisterActivity.this, "Do'h, Failure :(", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}

Start Application from inside Service

I have a service that have to start an application and count every 15 second.
I create AlarmManager and call the service every 15 second.The problem is when i push the start button program start service class and open application and start to count, but when i push stop button the application get error
"Unfortunately, Program has stopped."
After that the program automatically start to counting and opening the application
and i can't stop that.
I can't figure out. any help or something new can do this. thanks.
Myservice.java
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class Myservice extends Service{
int counter=0;
public IBinder onBind(Intent arg0)
{
return null;
}
public void onCreate() {
Toast.makeText(getApplicationContext(), "Service Created", Toast.LENGTH_SHORT).show();
}
#SuppressWarnings("deprecation")
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
Startapp();
counter++;
Toast.makeText(getApplicationContext(), "Service Start : " + counter,Toast.LENGTH_SHORT).show();
}
public void onDestroy()
{
Toast.makeText(getApplicationContext(), "Service Destroy", Toast.LENGTH_SHORT).show();
super.onDestroy();
}
public void Startapp()
{
Intent in = getPackageManager().getLaunchIntentForPackage("com.example.application");
startActivity(in);
Toast.makeText(getApplicationContext(), "Counter : " + counter, Toast.LENGTH_SHORT).show();
}
}
MainActivity.java
import java.util.Calendar;
import java.util.List;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Intent myIntent;
PendingIntent pendingIntent;
AlarmManager alarmManager;
Button btn1;
Button btn2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button)findViewById(R.id.button1);
btn2 =(Button)findViewById(R.id.button2);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
myIntent = new Intent(MainActivity.this, Clash.class);
pendingIntent = PendingIntent.getService(MainActivity.this, 7778, myIntent, 0);
alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),15000, pendingIntent);
Toast.makeText(MainActivity.this, "Start Alarm", Toast.LENGTH_LONG).show();
}
});
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
alarmManager.cancel(pendingIntent);
pendingIntent.cancel();
Toast.makeText(MainActivity.this, "Cancel!", Toast.LENGTH_LONG).show();
}
});
}
Try this its working....set in stop button...always cancel pending intent after creating it
alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
myIntent = new Intent(MainActivity.this, MyService.class);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
pendingIntent = PendingIntent.getService(MainActivity.this, 7778, myIntent, 0);
try {
alarmManager.cancel(pendingIntent);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("ex....."+e);
}
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),10000, pendingIntent);
Toast.makeText(MainActivity.this, "Start Alarm", Toast.LENGTH_LONG).show();
}
});
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
pendingIntent = PendingIntent.getService(MainActivity.this, 7778, myIntent, 0);
try {
alarmManager.cancel(pendingIntent);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("ex....."+e);
}
MainActivity.this.stopService(myIntent);
Toast.makeText(MainActivity.this, "Cancel!", Toast.LENGTH_LONG).show();
}
});
You need to set this flag:
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
So your Startapp method will look like this:
public void Startapp()
{
Intent in = getPackageManager().getLaunchIntentForPackage("com.example.application");
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(in);
Toast.makeText(getApplicationContext(), "Counter : " + counter, Toast.LENGTH_SHORT).show();
}

ERROR in sms sending

THIS IS THE ERROR:
The method getBroadcast(Context, int, Intent, int) in the type PendingIntent is not applicable for the arguments (new View.OnClickListener(){}, int, Intent, int) error
here's the code from MainActivity.java:
import android.app.Activity;
import android.os.Bundle;
import android.provider.Telephony.Sms;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
public class MainActivity extends Activity
{
Button btnSendSMS;
EditText txtPhoneNo;
EditText txtMessage;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
txtMessage = (EditText) findViewById(R.id.txtMessage);
btnSendSMS.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String phoneNo = txtPhoneNo.getText().toString();
String message = txtMessage.getText().toString();
if (phoneNo.length()>0 && message.length()>0)
sendSMS(phoneNo, message);
else
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
}
private void sendSMS(String phoneNo, String message) {
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0); // <--- THIS IS WHERE I GET THE ERROR
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0); // <--- THIS IS WHERE I GET THE ERROR
// ---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(phoneNo, null, message, sentPI, deliveredPI);
}
});
}
}
I'm trying to make a Scheduled Auto sms sending, but i won't go far with this errors. PLEAS help.
You have a problem with your context being passed in as the error says. Replace this with getApplicationContext()
PendingIntent sentPI = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(DELIVERED), 0);
Just replace those 2 lines !
Update :
I just tried that and it worked !
package com.sm.mrecruit.activity;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity
{
Button btnSendSMS;
EditText txtPhoneNo;
EditText txtMessage;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
txtMessage = (EditText) findViewById(R.id.txtMessage);
btnSendSMS.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String phoneNo = txtPhoneNo.getText().toString();
String message = txtMessage.getText().toString();
if (phoneNo.length()>0 && message.length()>0)
sendSMS(phoneNo, message);
else
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
}
private void sendSMS(String phoneNo, String message) {
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(SENT), 0); // <--- THIS IS WHERE I GET THE ERROR
PendingIntent deliveredPI = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(DELIVERED), 0); // <--- THIS IS WHERE I GET THE ERROR
// ---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(phoneNo, null, message, sentPI, deliveredPI);
}
});
}
Thats it ! Try that !
The problem is the same for both lines. The method getBroadcast() is expecting a context as it's first argument. When you call this method you are inside of an anonymous inner class, in this case an onClickListener class. When you provided the this keyword as the first argument, this refers to that onClickListener class. What you need instead is to grab the context of the application which you are currently in and provide that to the method. You can achieve that by changing the error causing lines like this.
PendingIntent sentPI = PendingIntent.getBroadcast(MainActivity.getApplication(), 0, new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(MainAcitivty.getApplication(), 0, new Intent(DELIVERED), 0);
Replace this with MainActivity.getApplication().

Android Limiting signup for one user

I developed an android application ... It is an applications first page... two buttons it have ... signup and sign in .. when user enter for first time he needs to signup and when sign up is pressed registration process will start ... user has to give an username, password and a mobile number .. once he give all this a passcode will be generated annd will be send to the mobile number provided user has to enter this passcode recieved along with the username and password to register... once he got register .. he can signin with the username and password.
Al these part is working fine ... My requirement is to limit the registration for only 1 username.... so for one download one username is allowed .. after one registartion the signup option must deactivated... so what I have to do for that .. I am giving the code ..below...
MainActivity
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
public class MainActivity extends Activity {
Button btnSignIn,btnSignUp;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
btnSignIn=(Button)findViewById(R.id.buttonSignIn);
btnSignUp=(Button)findViewById(R.id.buttonSignUP);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intentSignUP=new Intent(getApplicationContext(),SignUPActivity.class);
startActivity(intentSignUP);
}
});
}
public void signIn(View V)
{
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
// get the References of views
final EditText editTextUserName=(EditText)dialog.findViewById(R.id.editTextUserNameToLogin);
final EditText editTextPassword=(EditText)dialog.findViewById(R.id.editTextPasswordToLogin);
final EditText editTextMobileNumber = (EditText)dialog.findViewById(R.id.editText1);
Button btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIn);
btnSignIn.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");
// check if the Stored password matches with Password entered by user
if(password.equals(storedPassword) && (mobileNumber.equals(sd)))
{
Toast.makeText(MainActivity.this, "Congrats: Login Successfull", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
else
{
Toast.makeText(MainActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
#Override
protected void onDestroy() {
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}
}
Signup Activity
import java.util.Random;
import java.util.StringTokenizer;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SignUPActivity extends Activity
{
EditText editTextUserName,editTextPassword,editTextConfirmPassword, editMobileNumber;
Button btnCreateAccount;
Random r = new Random();
int number =r.nextInt(9999 - 1000) + 1000;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
// 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() {
public void onClick(View v) {
// TODO Auto-generated method stub
String userName=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, MainActivity.class);
intent.putExtra("number", sms + "");
startActivity(intent);
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(userName.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(userName, password);
Toast.makeText(getApplicationContext(), "Account Successfully Created and the passcode is sent to the mobile number you provided. ", Toast.LENGTH_LONG).show();
}
}
});
}
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();
}
}
LoginDataBaseAdapter.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class LoginDataBaseAdapter {
static final String DATABASE_NAME = "login.db";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
static final String DATABASE_CREATE = "create table "+"LOGIN"+
"( " +"ID"+" integer primary key autoincrement,"+ "USERNAME text,PASSWORD text); ";
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper dbHelper;
public LoginDataBaseAdapter(Context _context)
{
context = _context;
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public LoginDataBaseAdapter open() throws SQLException
{
db = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
db.close();
}
public SQLiteDatabase getDatabaseInstance()
{
return db;
}
public void insertEntry(String userName,String password)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("USERNAME", userName);
newValues.put("PASSWORD",password);
// Insert the row into your table
db.insert("LOGIN", null, newValues);
///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
public int deleteEntry(String UserName)
{
//String id=String.valueOf(ID);
String where="USERNAME=?";
int numberOFEntriesDeleted= db.delete("LOGIN", where, new String[]{UserName}) ;
// Toast.makeText(context, "Number for Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
return numberOFEntriesDeleted;
}
public String getSinlgeEntry(String userName)
{
Cursor cursor=db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
if(cursor.getCount()<1) // UserName Not Exist
{
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
cursor.close();
return password;
}
public void updateEntry(String userName,String password)
{
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put("USERNAME", userName);
updatedValues.put("PASSWORD",password);
String where="USERNAME = ?";
db.update("LOGIN",updatedValues, where, new String[]{userName});
}
}
To make it simple
Just get the count of the LOGIN Table. If it returns 1 then hide the SignUp button otherwise show the SignUP button. Use the following line of code to get the total count of the table.
In Activity
if(loginDataBaseAdapter.getUsercount()==1){
btnSignUp.setVisibility(View.INVISIBLE);
}
In Database
public long getUsercount() {
return DatabaseUtils.queryNumEntries(db, "LOGIN");
}
It should work.
A quick simple approach would be to use a "marker" that carries a value indicating if they created an account or not. You can use a boolean or an int.
So your programming logic would go as such:
Main Activity
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
public class MainActivity extends Activity {
Button btnSignIn,btnSignUp;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
btnSignIn=(Button)findViewById(R.id.buttonSignIn);
btnSignUp=(Button)findViewById(R.id.buttonSignUP);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(getValue("registrationComplete"==1){
Toast.makeText(getApplicationContext(), "You already have registered.",
Toast.LENGTH_LONG).show(); }
else{
Intent intentSignUP = new
Intent(getApplicationContext(),SignUPActivity.class);
startActivity(intentSignUP);
}
}
});
}
public void signIn(View V)
{
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
// get the References of views
final EditText editTextUserName=(EditText)dialog.findViewById(R.id.editTextUserNameToLogin);
final EditText editTextPassword=(EditText)dialog.findViewById(R.id.editTextPasswordToLogin);
final EditText editTextMobileNumber = (EditText)dialog.findViewById(R.id.editText1);
Button btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIn);
btnSignIn.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");
// check if the Stored password matches with Password entered by user
if(password.equals(storedPassword) && (mobileNumber.equals(sd)))
{
Toast.makeText(MainActivity.this, "Congrats: Login Successfull", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
else
{
Toast.makeText(MainActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
public int getValue(String name) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
return prefs.getInt(name, 0);
}
#Override
protected void onDestroy() {
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}
}
SingUp Activity
import android.content.SharedPreferences;
import java.util.Random;
import java.util.StringTokenizer;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SignUPActivity extends Activity
{
EditText editTextUserName,editTextPassword,editTextConfirmPassword, editMobileNumber;
Button btnCreateAccount;
Random r = new Random();
int number =r.nextInt(9999 - 1000) + 1000;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
// 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() {
public void onClick(View v) {
// TODO Auto-generated method stub
String userName=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, MainActivity.class);
intent.putExtra("number", sms + "");
startActivity(intent);
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(userName.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(userName, password);
// Set value of registrationComplete to 1 to indicate its done.
setValue("registrationComplete",1);
Toast.makeText(getApplicationContext(), "Account Successfully Created and the passcode is sent to the mobile number you provided. ", Toast.LENGTH_LONG).show();
}
}
});
}
public void setValue(String name, int newValue) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(name, newValue);
editor.commit();
}
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();
}

Android service called data from list multiple times

1.hello, I have created service for Schedule message but the problem is i have set the loop in my service method but it send the message all the message that is set on list.
2.I want to set the loop like, send message on list will be send at least ones time.
3.And the message has been sent is not send again.
//Here is my code.
//MyService class
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.telephony.gsm.SmsManager;
import android.util.Log;
import android.widget.Toast;
public class SchedulerMsgService extends Service {
private static final String TAG = "MyService";
private DatabaseHelper mDbHelper;
private ArrayList<schedulerDetails> myschedule = new ArrayList<schedulerDetails>();
private String phoneNo, message, sDate, curTime;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
#Override
public void onStart(Intent intent, int startId) {
Log.d(TAG, "oNsTART IS rEADY ");
mDbHelper = new DatabaseHelper(this);
final List<schedulerDetails> ScheduleList = mDbHelper.selectAllNumbers();
for (int j = 0; j < ScheduleList.size(); j++) {
myschedule.add(ScheduleList.get(j));
phoneNo = myschedule.get(j).num;
message = myschedule.get(j).textMessage;
sDate = myschedule.get(j).date;
curTime = myschedule.get(j).time;
sendSMS(phoneNo, message, sDate, curTime);
}
Toast.makeText(this, "condition Matched", Toast.LENGTH_LONG).show();
// Toast.makeText(this, "condition Not Matched",
// Toast.LENGTH_LONG).show();
}
public void sendSMS(String phoneNo, String message, String sDate,
String curTime) {
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);
registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
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(), "Null 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));
registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
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(phoneNo, null, message, sentPI, deliveredPI);
}
}
If the message has been sent, then remove the number from your database or add some information in the database that the message has been sent. Then mDbHelper.selectAllNumbers() can return only the numbers that need to receive the message.

Categories

Resources