My EditText keeps coming out as null - android

I've been working on this app that collects information, then sends it in email form. All of my other EditTexts are working with the exception of the very first one, pilot (the hint is name, as in the name of the pilot). I've gone through this thoroughly for multiple hours but I just cant seem to find what is the problem. The only reason I know its null is because when it goes into the email format all it says is null
public class InfoSheet extends AppCompatActivity {
private double VesselUnits;
private EditText pilot, ship, to, from, LOA, MBDTH, CUSD, zone1, zone2, CallSign;
private Spinner agent_spinner;
private Button btnSubmit;
private String date, agent, Spilot, Sship, Sto, Sfrom, Szone1, Szone2, SCallSign, SVesselUnits;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info_sheet);
date=getTodaysDate();
addListenerOnButton();
}
public void collectNCalc(){
//grab all of our info
agent_spinner = (Spinner) findViewById(R.id.agent_spinner);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
pilot = (EditText) findViewById(R.id.Pilot);
ship = (EditText) findViewById(R.id.ship);
to = (EditText) findViewById(R.id.to);
from = (EditText) findViewById(R.id.from);
LOA = (EditText) findViewById(R.id.LOA);
MBDTH = (EditText) findViewById(R.id.MBDTH);
CUSD = (EditText) findViewById(R.id.CUSD);
zone1 = (EditText) findViewById(R.id.zone1);
zone2 = (EditText) findViewById(R.id.zone2);
CallSign = (EditText) findViewById(R.id.CallSign);
//convert what we need to int to do equations
String sLOA = LOA.getText().toString();
double intLOA = Integer.valueOf(sLOA);
intLOA = intLOA*3.281;
String sMBDTH = MBDTH.getText().toString();
double intMBDTH = Integer.valueOf(sMBDTH);
intMBDTH = intMBDTH*3.281;
String sCUSD = CUSD.getText().toString();
double intCUSD = Integer.valueOf(sCUSD);
intCUSD = intCUSD*3.281;
VesselUnits = intLOA*intMBDTH*intCUSD;
VesselUnits = VesselUnits/10000;
Spilot=pilot.getText().toString();
Sship=ship.getText().toString();
Sto=to.getText().toString();
Sfrom=from.getText().toString();
Szone1=zone1.getText().toString();
Szone2=zone2.getText().toString();
SCallSign=CallSign.getText().toString();
agent=agent_spinner.getSelectedItem().toString();
//SVesselUnits=String.valueOf(VesselUnits);
}
public void addListenerOnButton() {
final Context context2 = this;
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i2 = new Intent(context2, DigitalSignature.class);
//do the Calc
collectNCalc();
//pass to next activity
i2.putExtra("Pilot",Spilot);
i2.putExtra("ship",Sship);
i2.putExtra("to",Sto);
i2.putExtra("from",Sfrom);
i2.putExtra("zone1",Szone1);
i2.putExtra("zone2",Szone2);
i2.putExtra("callsign",SCallSign);
i2.putExtra("agent",agent);
i2.putExtra("vessleunits",VesselUnits);
i2.putExtra("date",date);
startActivity(i2);
}
});
}
its sent to the next and final activity:
public class DigitalSignature extends AppCompatActivity {
String pilot, ship, to, from, zone1, zone2, CallSign, agent, date;
Toolbar toolbar;
Button btn_get_sign, mClear, mGetSign, mCancel, btn_send;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_digital_signature);
Bundle extras = getIntent().getExtras();
if (extras != null) {
pilot = extras.getString("pilot");
ship = extras.getString("ship");
to = extras.getString("to");
from = extras.getString("from");
zone1 = extras.getString("zone1");
zone2 = extras.getString("zone2");
CallSign = extras.getString("callsign");
agent = extras.getString("agent");
vesselUnit = extras.getDouble("vesselunits");
date = extras.getString("date");
}
btn_send.setOnClickListener(new OnClickListener() {
public void onClick(View v){
Uri path = Uri.parse("file://" + file);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_TEXT, pilot+"\n"+ship+"\n"+to+"\n"+from+"\n"+zone1+"\n"+zone2+"\n"+CallSign+"\n"+agent+"\n"+vesselUnit);
// set the type to 'email'
emailIntent.setType("image/png");
String to[] = {"metropilottickets#gmail.com"};
emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
// the attachment
emailIntent.putExtra(Intent.EXTRA_STREAM, path);
// the mail subject
emailIntent.putExtra(Intent.EXTRA_SUBJECT, pilot+"'s Ticket for "+ship);
startActivity(Intent.createChooser(emailIntent , "Send email..."));
}
});
}
I left out a lot of the other code that's irrelevant to my question, but if anyone can point out why I'm getting null you'd be a life saver!

You need to use extras.getString("Pilot");
insteadof extras.getString("pilot");

Related

Sending integers via Intent method

I have seen a decent amount of methods to add a numerical value to an int integer value using intent(). Mine however is not working so well. Does anyone have any advice? I am sending an integer value, via a button, from a separate activity using theintent() method. This value should add 1 to the activity when the button is pressed. Here is what I have so far:
public class GameEmulator extends Activity{
//Creating two static values to pass strings from SelectPlayer classes
public final static String value = "EMPTY_VALUE";
public final static String value2 = "EMPTY_VALUE2";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
//Button created to go back to AddPlayer activity
Button addplayer1 = findViewById(R.id.button9);
addplayer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(GameEmulator.this, AddPlayer.class);
startActivity(i);
}
});
Button viewScores = findViewById(R.id.viewScore);
viewScores.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(GameEmulator.this, MainActivity.class);
startActivity(intent);
}
});
//Button for player one winning
Button winButtonOne = findViewById(R.id.button7);
winButtonOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int scored = 1;
Intent intent = new Intent(GameEmulator.this, Scoreboard.class);
intent.putExtra("MY_KEY", scored);
startActivity(intent);
}
});
TextView textView = findViewById(R.id.name1);
TextView textview2 = findViewById(R.id.name2);
//setting value retrieved from SleectPlayer and Displaying it in textView
Intent intent = getIntent();
String extra = intent.getStringExtra(value);
textView.setText(extra);
//setting value retrieved from SleectPlayer2 and Displaying it in textView2
Intent in = getIntent();
String extra1 = in.getStringExtra(value2);
textview2.setText(extra1);
}
}
public class Scoreboard extends Activity{
public static ArrayAdapter<String> adapter2;
public static ArrayAdapter<String> adapter3;
public static ArrayList<String> list2 = new ArrayList<>();
public static ArrayList<String> list3 = new ArrayList<>();
ListView selectView3;
ListView selectView4;
public static int losses1 = 0;
public static int ties1 = 0;
public static int losses2 = 0;
public static int ties2 = 0;
public final static String value2 = "EMPTY_VALUE2";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scoreboard);
selectView3 = findViewById(R.id.selectview3);
selectView3.setVisibility(View.VISIBLE);
selectView4 = findViewById(R.id.selectview4);
selectView4.setVisibility(View.VISIBLE);
//Using adapter for ListView menu
adapter2 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list2);
selectView3.setAdapter(adapter2);
//Using intent to retrieve string from AddPlayer Activity
Intent i = getIntent();
int score = getIntent().getIntExtra("MY_KEY", 1);
String data = i.getStringExtra("text_key");
if(data != null){
list2.add("Player 1"+"\n"+"Name: "+data+"\n"+"Wins: "+ score +"\n"+"Losses: "+ losses1+"\n"+"Ties: "+ ties1);
}
if(data != ""){
changeList();
}
adapter3 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list3);
selectView4.setAdapter(adapter3);
Intent intent = getIntent();
String extra= intent.getStringExtra(value2);
if(extra != null) {
list3.add("Player 2" + "\n" + "Name: " + extra + "\n" + "Wins: " + score + "\n" + "Losses: " + losses2 + "\n" + "Ties: " + ties2);
}
if(data != ""){
changeList();
}
}
public void changeList()
{
adapter2.notifyDataSetChanged();
}
}
This line:
String data = i.getStringExtra("text_key");
makes data = null because you did not put in the original intent an extra value with key "text_key"
So this code:
list2.add("Player 1"+"\n"+"Name: "+data+"\n"+"Wins: "+ score +"\n"+"Losses: "+ losses1+"\n"+"Ties: "+ ties1);
is never executed

Android Application stopped suddenly

I'm preety new on android and trying to write an application but I wrote some code and run on android device till here there is no any problem but when I try to launch query window "sorgulama.xml" application stopped my xml file like this
and my java scource file ( java code ) like this
public class Sorgulama extends Activity implements OnClickListener {
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.btnSorgula:
String sorgu = txtSorgu.getText().toString();
Sorgula(sorgu);
break;
case R.id.btnKisaYollar:
KisaYollar();
break;
case R.id.btnTablo:
Tablolar();
break;
}
}
Button btnSorgula, btnKisaYollar, btnTablo;
EditText txtSorgu;
TableLayout tbl;
ResultSetMetaData metaData;
TableRow renkTableRow;
int kolonSayisi = 0, tvId = 0, otoId = 1;
String url,driver,userName ,password;
ArrayList<String> arrayTablolar = new ArrayList<String>();
ArrayList<String> arrayResults = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.sorgulama);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setTitle("MSSQL Uygulaması v1.0");
Kontroller();
Ayarlar();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE);
}
private void Ayarlar()
{
DB db = new DB(this);
db.open();
Cursor c = db.Query();
String ipAdresi = null, veriTabaniAdi = null, kullaniciAdi = null, sifre = null;
while(c.moveToNext())
{
ipAdresi = c.getString(c.getColumnIndex("IpAdresi"));
veriTabaniAdi = c.getString(c.getColumnIndex("VeriTabaniAdi"));
kullaniciAdi = c.getString(c.getColumnIndex("KullaniciAdi"));
sifre = c.getString(c.getColumnIndex("Sifre"));
}
url = "jdbc:jtds:sqlserver://" + ipAdresi +";databaseName=" +veriTabaniAdi+"";
driver = "net.sourceforge.jtds.jtbc.Driver";
userName = kullaniciAdi;
password = sifre;
db.close();
}
private void Kontroller()
{
btnSorgula = (Button) findViewById(R.id.btnSorgula);
btnKisaYollar = (Button) findViewById(R.id.btnKisaYollar);
btnTablo = (Button) findViewById(R.id.btnTablo);
txtSorgu = (EditText) findViewById(R.id.txtSorgu);
tbl = (TableLayout) findViewById(R.id.tblSonuc);
btnSorgula.setOnClickListener(this);
btnKisaYollar.setOnClickListener(this);
btnTablo.setOnClickListener(this);
}
private void KisaYollar(){
final CharSequence cs[];
cs = new String[5];
cs[0] = "select";
cs[1] = "*";
cs[2] = "from";
cs[3] = "where";
cs[4] = "and";
cs[5] = "or";
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Kısa Yollar").setIcon(R.drawable.logo).setItems(cs, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String sorgu = txtSorgu.getText().toString();
txtSorgu.setText(sorgu+cs[item]);
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void Tablolar(){
}
private void Sorgula(String sorgu)
{
}
}
Can anyone help me about this issue pls?
you missed super.onCreate(savedInstanceState). Also
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
must be called before setContentView

onCreate() method with if-else condition

I am calling an activity namely LoginActivity.java in which i am getting values using Intent, storing data to SQLite, fetching data from SQLite and given a small condition, condition looks like this:
if(txtEvent.getText().toString().equals("") && txtOperative.getText().toString().equals(""))
{
Intent intentCall = new Intent(LoginActivity.this, LicenseListActivity.class);
startActivity(intentCall);
}
Now, how App works:-
Splash Screen > LoginActivity (if txtEvent and txtOperative equals to null) then calling > LicenseListActivity > GetEventsActivity > GetOperativesActivity (passing some values mainly EVENT & OPERATIVE name) to LoginActivity (also storing to database - checked using SQLite DB Viewer)
So issue is, instead of calling LoginActivity.java its calling LicenseListActivity.java again, after GetOperativesActivity.java ?
GetOperativesActivity.java:-
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
firstName = contactList.get(position).get(TAG_NAME);
Intent intent = new Intent(GetOperativesActivity.this, LoginActivity.class);
intent.putExtra("name", name);
intent.putExtra("deviceID", deviceID);
intent.putExtra("emailID", emailID);
intent.putExtra("firstName", firstName);
startActivity(intent);
}
});
LoginActivity.java:-
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_login);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnCamera = (Button) findViewById(R.id.btnCamera);
btnGallery = (Button) findViewById(R.id.btnGallery);
txtDeviceID = (TextView) findViewById(R.id.txtDeviceID);
txtEmailID = (TextView) findViewById(R.id.txtEmailID);
txtEvent = (TextView) findViewById(R.id.txtEvent);
txtOperative = (TextView) findViewById(R.id.txtOperative);
txtEventOperator = (TextView) findViewById(R.id.txtEventOperator);
Intent intent = getIntent();
deviceID = intent.getStringExtra("deviceID");
emailID = intent.getStringExtra("emailID");
event = intent.getStringExtra("name");
operative = intent.getStringExtra("firstName");
txtDeviceID.setText(deviceID);
txtEmailID.setText(emailID);
txtEvent.setText(event);
txtOperative.setText(operative);
txtEventOperator.setText(event + " " + operative);
strEvent = txtEvent.getText().toString();
strOperative = txtOperative.getText().toString();
// Dialog
final AlertDialog.Builder adb = new AlertDialog.Builder(this);
AlertDialog ad = adb.create();
// new Class DB
final myDBClass myDb = new myDBClass(this);
// Save Data
long saveStatus = myDb.InsertData(
txtDeviceID.getText().toString(),
txtEmailID.getText().toString(),
txtEvent.getText().toString(),
txtOperative.getText().toString(),
txtEventOperator.getText().toString()
);
if(saveStatus <= 0)
{
ad.setMessage("Error!! ");
ad.show();
return;
}
// Show Data
String arrData[] = myDb.SelectData();
if(arrData != null)
{
txtDeviceID.setText(arrData[1]);
txtEmailID.setText(arrData[2]);
txtEvent.setText(arrData[3]);
txtOperative.setText(arrData[4]);
txtEventOperator.setText(arrData[5]);
}
if(txtEvent.getText().toString().equals("") && txtOperative.getText().toString().equals(""))
{
Intent intentCall = new Intent(LoginActivity.this, LicenseListActivity.class);
startActivity(intentCall);
}
}
If you have any question in your mind, please let me know ...
public class LoginActivity extends Activity{
static int counter = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_login);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnCamera = (Button) findViewById(R.id.btnCamera);
btnGallery = (Button) findViewById(R.id.btnGallery);
txtDeviceID = (TextView) findViewById(R.id.txtDeviceID);
txtEmailID = (TextView) findViewById(R.id.txtEmailID);
txtEvent = (TextView) findViewById(R.id.txtEvent);
txtOperative = (TextView) findViewById(R.id.txtOperative);
txtEventOperator = (TextView) findViewById(R.id.txtEventOperator);
Intent intent = getIntent();
deviceID = intent.getStringExtra("deviceID");
emailID = intent.getStringExtra("emailID");
event = intent.getStringExtra("name");
operative = intent.getStringExtra("firstName");
txtDeviceID.setText(deviceID);
txtEmailID.setText(emailID);
txtEvent.setText(event);
txtOperative.setText(operative);
txtEventOperator.setText(event + " " + operative);
strEvent = txtEvent.getText().toString();
strOperative = txtOperative.getText().toString();
// Dialog
final AlertDialog.Builder adb = new AlertDialog.Builder(this);
AlertDialog ad = adb.create();
// new Class DB
final myDBClass myDb = new myDBClass(this);
// Save Data
long saveStatus = myDb.InsertData(
txtDeviceID.getText().toString(),
txtEmailID.getText().toString(),
txtEvent.getText().toString(),
txtOperative.getText().toString(),
txtEventOperator.getText().toString()
);
if(saveStatus <= 0)
{
ad.setMessage("Error!! ");
ad.show();
return;
}
// Show Data
String arrData[] = myDb.SelectData();
if(arrData != null)
{
txtDeviceID.setText(arrData[1]);
txtEmailID.setText(arrData[2]);
txtEvent.setText(arrData[3]);
txtOperative.setText(arrData[4]);
txtEventOperator.setText(arrData[5]);
}
if(counter==0&&txtEvent.getText().toString().equals("") && txtOperative.getText().toString().equals(""))
{
counter++;
Intent intentCall = new Intent(LoginActivity.this, LicenseListActivity.class);
startActivity(intentCall);
}
}//end onCreate
}//end class

Number format exception

What is wrong with this code? I've got NumberFormatException. Invalid int: ""
Everything looks correctly but I don't know am I doing my EditTexts correctly. Any help is welcome.
public class Wyslij extends Activity {
EditText et_nazwa;
EditText et_nip;
EditText et_adres;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.wyslij);
et_nazwa = (EditText) findViewById(R.id.et_nazwa);
et_nip = (EditText) findViewById(R.id.et_nip);
et_adres = (EditText) findViewById(R.id.et_adres);
ib_wyslij = (ImageButton) findViewById(R.id.ib_wyslij);
String nazwa_firmy = et_nazwa.getText().toString();
String nip_firmowy = et_nip.getText().toString();
int nip_firmy = Integer.valueOf(nip_firmowy);
String adres_firmy = et_adres.getText().toString();
final Zamowienie zam = new Zamowienie();
zam.klient.nazwa = nazwa_firmy;
zam.klient.nip = nip_firmy;
zam.klient.adres = adres_firmy;
String suma_zamowienia = podaj_sume(TowarZamowienie.towary_zamowione);
int suma_zam = Integer.valueOf(suma_zamowienia);
zam.suma=suma_zam;
}
}
public class Wyslij extends Activity {
EditText et_nazwa;
EditText et_nip;
EditText et_adres;
int suma_zam;
int nip_firmy;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.wyslij);
et_nazwa = (EditText) findViewById(R.id.et_nazwa);
et_nip = (EditText) findViewById(R.id.et_nip);
et_adres = (EditText) findViewById(R.id.et_adres);
ib_wyslij = (ImageButton) findViewById(R.id.ib_wyslij);
String nazwa_firmy = et_nazwa.getText().toString();
String nip_firmowy = et_nip.getText().toString();
if(nip_firmowy != null && !nip_firmowy.equalsIgnoreCase(""){
nip_firmy = Integer.parseInt(nip_firmowy);
String adres_firmy = et_adres.getText().toString();
final Zamowienie zam = new Zamowienie();
zam.klient.nazwa = nazwa_firmy;
if(nip_firmy != null){
zam.klient.nip = nip_firmy;
}
if(adres_firmy != null){
zam.klient.adres = adres_firmy;
}
}
String suma_zamowienia = podaj_sume(TowarZamowienie.towary_zamowione);
if(suma_zamowienia != null && !suma_zamowienia.equalsIgnoreCase(""){
suma_zam = Integer.parseInt(suma_zamowienia);
zam.suma=suma_zam;}
}
}
I believe there is a white space when you are fetching value from EditText. So before you convert the string value to integer you need to trim the white space like below,
String nip_firmowy = et_nip.getText().toString().trim(); // use trim here
int nip_firmy = Integer.parseInt(nip_firmowy); // use parseInt() method

How to bring contacts up to send a text

I have an application that defines a word and then sends the definition via SMS. The problem is that the user has to type in a phone number. I was thinking that perhaps the app should bring up the contacts list, so the user can select a contact which the user can then send the message to that contact. Here is my code for the SMSActivity:
public class SMSActivity extends Activity
{
String APPTAG = "SMSTransmit";
//Private static strings:
private final static String SENT = "SMS_SENT";
private final static String DELIVERED = "SMS_DELIVERED";
private Button btnSend;
private Button btnExit;
private Button btnClear;
private EditText etPhoneNumber;
private EditText etUserMessage;
//Private BroadcastReceiver member variables:
private SMSDispatchReceiver sendReceiver = null;
private SMSReceiptReceiver receiptReceiver = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms);
Bundle extras = getIntent().getExtras();
String definiedWord = null;
if (extras != null)
{
definiedWord = extras.getString("DEFINITION");
}
else
{
definiedWord = "None";
}
Log.d("recievedAGAIN", definiedWord);
Log.v(APPTAG, "MainActivity: onCreate() called");
//Create a new broadcast receiver for sending the SMS
sendReceiver = new SMSDispatchReceiver();
//Create a new broadcast receiver for receipt of the send SMS
receiptReceiver = new SMSReceiptReceiver();
//Register the new receivers (as new IntentFiler() objects):
registerReceiver(sendReceiver, new IntentFilter(SENT));
registerReceiver(receiptReceiver, new IntentFilter(DELIVERED));
//Get the view objects:
btnSend = (Button) findViewById(R.id.btnSend);
btnClear = (Button) findViewById(R.id.btnClear);
btnExit = (Button) findViewById(R.id.btnExit);
etPhoneNumber = (EditText) findViewById(R.id.etNumber);
etUserMessage = (EditText) findViewById(R.id.etMessage);
//Disable the soft keyboard (this is only in general):
InputMethodManager inMethodMgr = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inMethodMgr.hideSoftInputFromInputMethod(etPhoneNumber.getWindowToken(), 0);
inMethodMgr.hideSoftInputFromInputMethod(etUserMessage.getWindowToken(), 0);
//Set the hint for the EditText boxes:
etPhoneNumber.setHint("Enter phone number (Default = 5556)");
etUserMessage.setHint(definiedWord);
//Create an click event listener for the Send button (OnClickListener):
btnSend.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
String strMessage = null;
String strNumber = null;
//Get the phone number from the EditText box:
strNumber = etPhoneNumber.getText().toString();
//Check the phone number:
if (strNumber.length() <= 0)
{
//No phone number, then get the default (5556):
strNumber = SMSProperties.getPhoneNumber();
}
//Get the message from the EditText box:
strMessage = etUserMessage.getText().toString();
//Check the message contains some content:
if (strMessage.length() > 0)
{
//Sent the SMS to the phone number
sendSMS(strNumber, strMessage);
} else
{
//Warn the user and reset the focus / hint:
Toast.makeText(getBaseContext(), "No message text! Please enter some text for the SMS!!", Toast.LENGTH_SHORT).show();
etUserMessage.setHint("Enter message text here . . . ");
etUserMessage.requestFocus();
}
}
});
//Create an click event listener for the Clear button (OnClickListener):
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Clear the appropriate EditText box:
if (etUserMessage.isFocused()) {
//Clear the text in the user message EditText box:
etUserMessage.setText("");
//Set the hint in the user message EditText box:
etUserMessage.setHint("Enter message text here . . . ");
} else if (etPhoneNumber.isFocused()) {
//Clear the text in the phone number EditText box:
etPhoneNumber.setText("");
//Set the hint in the phone number EditText box:
etPhoneNumber.setHint("Enter phone number (Default = 5556)");
}
}
});
//Create an click event listener for the Exit button (OnClickListener):
btnExit.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Finish the activity:
//NOTE: As this is the main activity it will cause onDestroy() to be called!
finish();
}
});
}
//Method to send an SMS message to another device:
private void sendSMS(String strNum, String strMsg)
{
//TODO: Create a pending intent for the SMSDistatchReceiver (SENT):
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent("SENT"), 0);
//TODO: Create a pending intent for the SMSReceiptReceiver (DELIVERED):
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent("DELIVERED"), 0);
//Get a default SmsManager object:
SmsManager smsMgr = SmsManager.getDefault();
//TODO: Send the SMS using the SmsManager:
smsMgr.sendTextMessage(strNum, null, strMsg, sentPI, deliveredPI);
}
consider contact is a button to bring up the contact list
contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View g) {
Intent q = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(q, 1001);
}
});
and to handle the result (which is referenced by 1001) use this:
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
// getting the URI from result for further working
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String id =c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String hasPhone =c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone.equalsIgnoreCase("1")) {
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,
null, null);
phones.moveToFirst();
//this string will hold the contact number
String cNumber = phones.getString(phones.getColumnIndex("data1"));
//this string will hold the contact name
String cName = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
}
}}
}

Categories

Resources