ERROR in sms sending - java

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().

Related

how can i unregister receiver in android?

i got this error thing Leaked Intent Receiver that was originally registered here, but the apps is still up and running even with that error kind of thing, what causes that error ? and does this affects the apps ?
here's what im trying to do :
private void sendSMS(String phoneNumber, String message) {
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
ArrayList<PendingIntent> sentPendingIntents = new ArrayList<PendingIntent>();
ArrayList<PendingIntent> deliveredPendingIntents = new ArrayList<PendingIntent>();
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(
SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED), 0);
try {
SmsManager sms = SmsManager.getDefault();
ArrayList<String> mSMSMessage = sms.divideMessage(message);
for (int i = 0; i < mSMSMessage.size(); i++) {
sentPendingIntents.add(i, sentPI);
deliveredPendingIntents.add(i, deliveredPI);
}
sms.sendMultipartTextMessage(phoneNumber, null, mSMSMessage,
sentPendingIntents, deliveredPendingIntents);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "SMS sending failed...", Toast.LENGTH_SHORT)
.show();
}
// ---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));
}
tnx in advance..
If you have registered the receiver in the onCreate then unregister it in it's onDestroy method.
If you have registered the receiver in the onResume then unregister it in it's onPause method.
If you have registered the receiver in the onStart then unregister it in it's onStop method.
The problem is likely because the Activity you are calling sendSMS from has exited, but that is the context in which you have registered your receivers as anonymous inner classes. You'll need to pull those receivers out, or retain references to them and unregister them in your onPause().
Since the receiver is being registered inside an activity and not on the manifest, you need to unregister it onPause or onStop
public void onStop() {
super.onStop();
if (myReceiver != null) {
unregisterReceiver(myReceiver);
}
I forgot to mention that you should created the BroadcastReceiver inside an inner class such as
private class myReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
//Add your code here
}
}
Hope it helps.

The method onClick(View, String) from the type new View.OnClickListener(){} is never used locally

These codes below are used to encrypt SMS using PRINCE algorithm and sends the SMS to the receiver. Currently I am facing a problem where public void onClick(View v,String args) gives an error message of "The method onClick(View, String) from the type new View.OnClickListener(){} is never used locally". I have also referred to The method onClick(View) from the type new Thread(){} is never used locally but the solutions given does not help me. Is there any other solution for this problem?
btnSendSMS.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String phoneNo = txtPhoneNo.getText().toString();
String message = txtMessage.getText().toString();
if (phoneNo.length()>0 && message.length()>0)
{
LongBuffer messageBuf = TooLong.messageToLongBuffer(message);
messageBuf.flip();
long[] messageData = new long[messageBuf.remaining()];
LongBuffer i = messageBuf.get(messageData);
String v1=prince.Encrypt(i, k0, kop, k1, t);
sendSMS(phoneNo, v1);
}
else
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
}
});
}
//---sends a SMS message to another device---
private void sendSMS(String phoneNumber, String v1)
{
/*
PendingIntent pi = PendingIntent.getActivity(this, 0,
new Intent(this, test.class), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, pi, null);
*/
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, v1, sentPI, deliveredPI);
}
}
The signature for an onClick() method is onClick(View), not onClick(View,String). The latter declares a new method that is never called and does not override the method in OnClickListener interface.
Remove the String argument from your method, and remove the other stub onClick(View).
public void `onClick(View v,String args)`
This method is never used locally because this method is an method written by you. OnButtonclick your method never get called. On click the onClick(View) method get invoked. Write your code inside onClick(View)
btnSendSMS.setOnClickListener(new View.OnClickListener()
{
// why have you written this method it not called from anywhere remove this
method put code in public void onClick(View v) method
public void onClick(View v,String args)
{
}
#Override
public void onClick(View v) {
String phoneNo = txtPhoneNo.getText().toString();
String message = txtMessage.getText().toString();
if (phoneNo.length()>0 && message.length()>0)
{
LongBuffer messageBuf = TooLong.messageToLongBuffer(message);
messageBuf.flip();
long[] messageData = new long[messageBuf.remaining()];
LongBuffer i = messageBuf.get(messageData);
String v1=prince.Encrypt(i, k0, kop, k1, t);
sendSMS(phoneNo, v1);
}
else
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
}
});
}
if you require this method (onClick(View v,String args) )then comment.

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.

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

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();
}

Categories

Resources