I'm trying to display text that is input by the user if it is not null but I'm having some trouble (I'm a Java noob). Here is the flow of my app:
Starts at Main.java with a button:
-Button: Profile
If you click profile, the app goes to the profile page Display.java that also has a button:
-Button: Edit Profile
-This view also displays the information (name, phone number, zip code, etc)
When a user clicks Edit Profile, the program goes to a form at EditProfile.java, which has a form where users enter the information and then there is a button to submit.
-Button: Submit
This submit button takes the user back to the previous view (Display.java) and displays the information that was previously entered in the form with the string resultText.
I'm not sure how to make this work. If anyone has any suggestions, I'd really appreciate the help!
Edit: One thing to note is that I'm getting a "Dead Code" error on the if expression in Display.java
Display.java:
public class Display extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
String newline = System.getProperty("line.separator");
TextView resultText = (TextView) findViewById(R.id.resultText);
Bundle bundle = getIntent().getExtras();
String firstName = null;
String lastName;
String phoneNumber;
String city;
String zipCode;
if(firstName != null) {
firstName = bundle.getString("EditTextFirstName");
lastName = bundle.getString("EditTextLastName");
phoneNumber = bundle.getString("EditTextPhoneNumber");
city = bundle.getString("EditTextCity");
zipCode = bundle.getString("EditTextZipCode");
resultText.setText("Name: " + firstName + " " + lastName + newline + "Phone Number: " + phoneNumber +
newline + "City: " + city + newline + "Zip Code: " + zipCode + newline);
}
Button profile = (Button) findViewById(R.id.button1);
profile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Display.this, EditProfile.class));
}
});
}
}
EditProfile.java:
public class EditProfile extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
}
public void sendFeedback(View button) {
final EditText firstnameField = (EditText)this.findViewById(R.id.EditTextFirstName);
String firstname = firstnameField.getText().toString();
final EditText lastnameField = (EditText) findViewById(R.id.EditTextLastName);
String lastname = lastnameField.getText().toString();
final EditText phoneNumberField = (EditText) findViewById(R.id.EditTextPhoneNumber);
String phoneNumber = phoneNumberField.getText().toString();
final EditText cityField = (EditText) findViewById(R.id.EditTextCity);
String city = cityField.getText().toString();
final EditText zipCodeField = (EditText) findViewById(R.id.EditTextZipCode);
String zipcode = zipCodeField.getText().toString();
int count = 0;
int fnlen=firstname.length();
int lnlen=lastname.length();
int phlen=phoneNumber.length();
int citylen=city.length();
int zclen=zipcode.length();
if (fnlen<=0){
firstnameField.setError("Enter your first name");
}
else {
count += 1;
}
if (lnlen<=0){
lastnameField.setError("Enter your last name");
}
else {
count += 1;
}
if (phlen<=0){
phoneNumberField.setError("Enter your ten digit phone number");
}
else if (phlen!=10){
phoneNumberField.setError("Phone number must be ten digits");
}
else {
count += 1;
}
if (citylen<=0){
cityField.setError("Enter your city");
}
else {
count += 1;
}
if (zclen<=0){
zipCodeField.setError("Enter your Zip Code");
}
else if (zclen!=5){
zipCodeField.setError("Enter a five digit zip code");
}
else {
count += 1;
}
if (count == 5) {
Intent intent = new Intent();
intent.setClass(this,Display.class);
intent.putExtra("EditTextFirstName",firstnameField.getText().toString());
intent.putExtra("EditTextLastName",lastnameField.getText().toString());
intent.putExtra("EditTextPhoneNumber",phoneNumberField.getText().toString());
intent.putExtra("EditTextCity",cityField.getText().toString());
intent.putExtra("EditTextZipCode",zipCodeField.getText().toString());
startActivity(intent);
}
else {
count = 0;
}
}
}
try with `Intent i= getIntent();
if(i.getExtras()!=null){
firstName = bundle.getString("EditTextFirstName");
lastName = bundle.getString("EditTextLastName");
phoneNumber = bundle.getString("EditTextPhoneNumber");
city = bundle.getString("EditTextCity");
zipCode = bundle.getString("EditTextZipCode");
resultText.setText("Name: " + firstName + " " + lastName + newline + "Phone Number: " + phoneNumber +
newline + "City: " + city + newline + "Zip Code: " + zipCode + newline);
}`in your Display Class instead of firstName != null) { ...} and let me know if any queries.
Related
I am making an app and I'm stuck with one problem. I want to know what can I do to make this happen:
I want to check if the edit text is empty or not and if it is not, then perform a particular piece of the task and if it is empty then make a toast which says please enter the names.
Here is my code: `
final TextView percentage = (TextView) findViewById(R.id.percentage_text);
Button calculateButton = (Button) findViewById(R.id.calculate_button);
calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Random noGen = new Random();
int number = noGen.nextInt(101);
EditText firestName = (EditText) findViewById(R.id.first_name);
String firstNameString = firestName.getEditableText().toString();
EditText secName = (EditText) findViewById(R.id.sec_name);
String secNameString = secName.getEditableText().toString();
percentage.setText(Integer.toString(number));
Toast.makeText(getApplicationContext(), "The love score between " + firstNameString +" & " + secNameString + " is " + number + "%", Toast.LENGTH_SHORT ).show();
}
});
`
I know I can easily do this with if else statement but I am not able to do it
Thanks in advance!!!
Try this:
if(firestName.getText()!=null &&
!firestName.getText().equals("") && secName.getText()!=null &&
!secName.getText().equals("")){
// do your task
}else{
// show msg
}
You can check String variable that whether is empty or not. You can refer below code. You can find more String operation on Internet.
Button calculateButton = (Button) findViewById(R.id.calculate_button);
EditText firestName = (EditText) findViewById(R.id.first_name);
EditText secName = (EditText) findViewById(R.id.sec_name);
calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Random noGen = new Random();
int number = noGen.nextInt(101);
String firstNameString = firestName.getEditableText().toString();
String secNameString = secName.getEditableText().toString();
if(!firstNameString.isEmpty() && !secNameString.isEmpty()){
//Perform your task
}
percentage.setText(Integer.toString(number));
Toast.makeText(getApplicationContext(), "The love score between " + firstNameString +" & " + secNameString + " is " + number + "%", Toast.LENGTH_SHORT ).show();
}
});
Try below code;
EditText firestName = (EditText) findViewById(R.id.first_name);
String firstNameString = firestName.getEditableText().toString();
EditText secName = (EditText) findViewById(R.id.sec_name);
String secNameString = secName.getEditableText().toString();
if(firstNameString.matches("") && secNameString.matches("")){
//Do your code here
}
if(firestName.getText().toString().equals("")){
//do some stuff
}else{
Toast.makeText(getApplicationContext(), "Please enter", Toast.LENGTH_SHORT ).show();
}
I want to display the String number from mySpinner only inside my Toast but I can't find out to do just that thing. Any help is welcome!
if(cursor.moveToFirst())
{
do
{
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
if(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",new String[]{ id }, null);
while (pCur.moveToNext())
{
String name = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
list.add(name + "\n" + number);
break;
}
pCur.close();
}
} while (cursor.moveToNext()) ;
}
adapter stuff of no importance
spinnerClickListener();
}
Onclick method for imagebutton to display the selected contact phone number in a toast.
public void spinnerClickListener(){
//spinner item button onclick listener
callBTN = (ImageButton)findViewById(R.id.call);
mySpinner = (Spinner)findViewById(R.id.contacts);
callBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Selected number :" + "\n" + mySpinner.getSelectedItem(), Toast.LENGTH_LONG).show();
}
});
}
thanks in advance!
you should use this
mySpinner.getSelectedItem().toString()
instead of
mySpinner.getSelectedItem()
I have a program that will retrieve some data from database, and show it on the screen as some buttons. How can I give an Id to every button created and make button.OnClickListener to every button with the correct id?
Here is my codes :
private void selectAllGroup() {
// TODO Auto-generated method stub
MyGroup = (TextView) findViewById(R.id.tvListGroup);
Database allGroup = new Database(MyGroupActivity.this);
allGroup.open();
listGroup = allGroup.countHowManyGroups(username);
layout = (LinearLayout) findViewById(R.id.LLMyGroup);
String groupName[] = allGroup.fetchGroupName(username);
for (int i = 0; i < listGroup; i++) {
newBt = new Button(this);
newBt.setText(groupName[i]);
layout.addView(newBt);
}
allGroup.close();
}
And here is my database code (if needed) :
public int countHowManyGroups(String username) {
// TODO Auto-generated method stub
String Query = "SELECT " + GROUP_NAME + " From " + MS_GROUP
+ " a INNER JOIN " + MS_GROUP_DETAIL + " b ON a." + GROUP_ID
+ "=b." + GROUP_ID + " WHERE " + MEMBER_USERNAME + "=?";
Cursor c = ourDatabase.rawQuery(Query, new String[] { username });
int cnt = c.getCount();
c.close();
return cnt;
}
public String[] fetchGroupName(String username){
int i=0;
String Query = "SELECT " + GROUP_NAME + " From " + MS_GROUP
+ " a INNER JOIN " + MS_GROUP_DETAIL + " b ON a." + GROUP_ID
+ "=b." + GROUP_ID + " WHERE " + MEMBER_USERNAME + "=?";
Cursor c = ourDatabase.rawQuery(Query, new String[] { username });
String groupName[] = new String [c.getCount()];
int iGroupName = c.getColumnIndex(GROUP_NAME);
c.moveToFirst();
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
groupName[i] = c.getString(iGroupName);
i++;
}
c.close();
return groupName;
}
Regarding to your question "How can I give an Id to every button created and make button.OnClickListener to every button with the correct id?"
Simply use inside your for-loop:
newBt.setId(id to set) // Should be positive, doesn't have to be unique
newBt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//The View carries the Id
v.getId();
//Then you can simply set up a fast Switch-case for example
switch (v.getid()) {
case 1:
break;
default:
break;
}
});
Update
No Problem just cast Button to the View in the onClick-Method and get the String:
newBt.setId(id to set) // Should be positive, doesn't have to be unique
newBt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Button myClickedButton = (Button) v;
String buttonText = myClickedButton.getText();
//Do something with your logic here.
//You can also Switch-case on a String ! But AFAIK
//it's only possible on Java Compiler 1.7 or above.
//But Eclipse will guide you if you want to Switch on String
});
You can setTag for each button inside the for loop as
newBt.setTag(i);
newBt.setOnClickListener(this);
and inside your OnClick method get the tag as the position like
#Override
public void onClick(View view){
int buttonClicked = (int) view.getTag();
// Do your code here according to the position of the button clicked
}
for (int i = 0; i < listGroup; i++) {
newBt = new Button(this);
newBt.setText(groupName[i]);
newBt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//write your logic to do the work you need when button is clicked.You do not need id for this.
}
});
layout.addView(newBt);
}
You don't need id for listening to button click event.
In my application I have three edit text and I am using shared preference to store those number. I want to fetch the numbers from shared preference and display in edit text and i want to edit the text also. When i run the below code i am getting NullPointerException. Can somebody help me?
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.change_cell_number);
init();
/*SharedPreferences sharedPref=this.getSharedPreferences("MY_PREF_2",MODE_WORLD_READABLE);
SharedPreferences.Editor shredPref_Editor=sharedPref.edit();
shredPref_Editor.putString(MY_ACTIVITY,"changeSMSnumber");
shredPref_Editor.commit();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(ChangeSmsNumber_Activity.this);
String servername = settings.getString("sharedPreferencesKey", "defaultValue");
//server.setText(servername);
*/
btnSubmit.setOnClickListener(new OnClickListener()
{
#SuppressWarnings("unused")
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
String numberISD=edtxt_ISD_Code1.getText().toString();
if(edtxt_ISD_Code1.getText().toString().isEmpty())
{
Toast.makeText(getApplicationContext(),"Enter ISD 1st Number * ", Toast.LENGTH_SHORT).show();
}
else if(edtxt_Cell_Number1.getText().toString().isEmpty())
{
Toast.makeText(getApplicationContext(),"Enter 1st Number *", Toast.LENGTH_SHORT).show();
}
else
{
String strSign1 = edtxt_PlusSign1.getText().toString();
String strSign2 = edtxt_PlusSign2.getText().toString();
String strSign3 = edtxt_PlusSign3.getText().toString();
String strSign4 = edtxt_PlusSign4.getText().toString();
String strSign5 = edtxt_PlusSign5.getText().toString();
String strIsd1 = edtxt_ISD_Code1.getText().toString();
String strIsd2 = edtxt_ISD_Code2.getText().toString();
String strIsd3 = edtxt_ISD_Code3.getText().toString();
String strIsd4 = edtxt_ISD_Code4.getText().toString();
String strIsd5 = edtxt_ISD_Code5.getText().toString();
String strNum1 = edtxt_Cell_Number1.getText().toString();
String strNum2 = edtxt_Cell_Number2.getText().toString();
String strNum3 = edtxt_Cell_Number3.getText().toString();
String strNum4 = edtxt_Cell_Number4.getText().toString();
String strNum5 = edtxt_Cell_Number5.getText().toString();
String final_Num_1 = strSign1 + strIsd1 + strNum1;
String final_Num_2 = strSign2 + strIsd2 + strNum2;
String final_Num_3 = strSign3 + strIsd3 + strNum3;
String final_Num_4 = strSign4 + strIsd4 + strNum4;
String final_Num_5 = strSign5 + strIsd5 + strNum5;
SharedPreferences settings = ChangeSmsNumber_Activity.this.getSharedPreferences("MyPref_CellNumber",0);
strGetCellNum = settings.getString("num1", "n/a");
final_Num_1=strGetCellNum;
}
}
});
}
Please guide me.
sharedPref=this.getSharedPreferences("MY_PREF_2",MODE_PRIVATE);
String number= sharedPref.getString("KeyValue","defaultValue")//you can use defaultValue=""
For setting in Edittext
editText.setText(number);
Please go through the code below.
String[] Info contains 2 values like this:
shiftDirection & 1 or
currGear & 5 and similar pairs.
If I receive shiftDirection & 0, I should display the previously received value of currGear.
So I create PresentGear as a global variable and when currGearis received, I store it's value in PresentGear.
Then when I receive shiftDirection & 0, I try to display PresentGear but nothing gets displayed.
PresentGear is assigned no value. It would be very helpful if someone could suggest why this is happening or if my approach is wrong, kindly suggest an alternative way.
Cheers,
Madhu
public class Images extends Activity {
/** Called when the activity is first created. */
//LinearLayout mLinearLayout;
//ImageView showImage;
String PresentGear = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
String[] Info = extras.getStringArray("MsgInfo");
Log.d("TCP","in DA Images. Message name: " + Info[0] + ", value: " + Info[1]);
if (Info[0].equals("currGear")) {
PresentGear = Info[1];
setContentView(R.layout.image);
TextView text_bottom = (TextView) findViewById(R.id.textView2);
text_bottom.setText(Info[1]);
}
Log.d("TCP","in DA Images. Present gear1: " + PresentGear);
DataAction(Info[0], Info[1]);
}
public void DataAction (String mName, String mVal) {
String _mName = mName;
String _mVal = mVal;
if (_mName.equals("shiftDirection") && _mVal.equals("1")) {
setContentView(R.layout.image);
//TextView text_top = (TextView) findViewById(R.id.textView1);
ImageView showImage = (ImageView) findViewById(R.id.imageView1);
//text_bottom.setText(Info[1]);
showImage.setImageResource(R.drawable.shift_up);
} else if (_mName.equals("shiftDirection") && _mVal.equals("-1")) {
setContentView(R.layout.image);
//TextView text_bottom = (TextView) findViewById(R.id.textView2);
ImageView showImage = (ImageView) findViewById(R.id.imageView1);
//text_bottom.setText(Info[1]);
showImage.setImageResource(R.drawable.shift_down);
} else if (_mName.equals("recomGear") && _mVal != null) {
Integer msgValue = Integer.parseInt(_mVal);
Integer CurrentGear = (msgValue) - 1;
Log.d("TCP","in DA Images. Current gear: " + CurrentGear);
String Gear = Integer.toString(CurrentGear);
setContentView(R.layout.image);
TextView text_top = (TextView) findViewById(R.id.textView1);
TextView text_bottom = (TextView) findViewById(R.id.textView2);
ImageView showImage = (ImageView) findViewById(R.id.imageView1);
showImage.setImageResource(R.drawable.shift_up);
text_bottom.setText(Gear);
text_top.setText(_mVal);
//} //else if (_mName.equals("currGear") && _mVal != null) {
//PresentGear = _mVal;
//Log.d("TCP","in DA Images. Present gear1: " + PresentGear);
//setContentView(R.layout.image);
//TextView text_bottom = (TextView) findViewById(R.id.textView2);
//text_bottom.setText(_mVal);
} else if (_mName.equals("shiftDirection") && _mVal.equals("0")) {
Log.d("TCP","in DA Images. Present gear: " + PresentGear);
setContentView(R.layout.image);
TextView text_bottom = (TextView) findViewById(R.id.textView2);
TextView text_top = (TextView) findViewById(R.id.textView1);
text_top.setText("Go on");
text_bottom.setText(PresentGear);
}
}
}
Update:
Thank you all for the response. I will post the part where I am getting the string array from. It may not be the best designed code. Would be happy if any changes are suggested.
public class TCPListen extends Activity implements TCPListener {
private TextView mTitle;
public String data[] = new String[2];
public String PGear;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
// Set up the window layout
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
// Set up the custom title
mTitle = (TextView) findViewById(R.id.title_left_text);
mTitle.setText(R.string.app_name);
mTitle = (TextView) findViewById(R.id.title_right_text);
//TcpServiceHandler handler=new TcpServiceHandler(this);
//handler.execute("192.168.62.23");
TcpServiceHandler handler = new TcpServiceHandler(this,this);
Thread th = new Thread(handler);
th.start();
}
public String[] callCompleted(String source){
Log.d("TCP", "Std parser " + source);
//mTitle.setText(source);
//String data[] = new String[2];
//if (source.matches("<MSG><N>.*</N><V>.*</V></MSG>")) {
Document doc = null;
try{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = (Document) db.parse(new ByteArrayInputStream(source.getBytes()));
NodeList n = doc.getElementsByTagName("N");
Node nd = n.item(0);
String msgName = nd.getFirstChild().getNodeValue();
NodeList n1 = doc.getElementsByTagName("V");
Node nd1 = n1.item(0);
String tmpVal = nd1.getFirstChild().getNodeValue();
data[0] = msgName;
data[1] = tmpVal;
Log.d("TCP", "Inside Std parser " + data[0] + " " + data[1]);
actionOnData(data[0], data[1]);
}
catch(Exception e){
e.printStackTrace();
}
Log.d("TCP", "Just outside Std parser " + data[0] + " " + data[1]);
return data;
//} else Log.d("TCP", "Message in wrong format " + source);
//mTitle.setText("Message in wrong format " + source);
//return data;
}
//Function to display driver messages/images based on individual messages
public void actionOnData(String name, String value) {
String tempName = name;
String tempVal = value;
if(tempName.equals("shiftDirection") && tempVal.equals("1")) {
Log.d("TCP","in actionOnData " + data[0] + " " + data[1]);
//mTitle.setText("Change to next higher gear");
Intent myIntent = new Intent();
myIntent.setClassName("com.example.android.TCPListen", "com.example.android.TCPListen.Images");
myIntent.putExtra("MsgInfo", data); // key/value pair, where key needs current package prefix.
startActivity(myIntent);
finish();
} else if(tempName.equals("recomGear")) {
Log.d("TCP","in actionOnData " + data[0] + " " + data[1]);
//mTitle.setText("Drive like a man");
Intent myIntent = new Intent();
myIntent.setClassName("com.example.android.TCPListen", "com.example.android.TCPListen.Images");
myIntent.putExtra("MsgInfo", data); // key/value pair, where key needs current package prefix.
startActivity(myIntent);
finish();
} else if(tempName.equals("shiftDirection") && tempVal.equals("-1")) {
Log.d("TCP","in actionOnData " + data[0] + " " + data[1]);
//mTitle.setText("Change to next higher gear");
Intent myIntent = new Intent();
myIntent.setClassName("com.example.android.TCPListen", "com.example.android.TCPListen.Images");
myIntent.putExtra("MsgInfo", data); // key/value pair, where key needs current package prefix.
startActivity(myIntent);
finish();
} else if(tempName.equals("currGear")) {
Log.d("TCP","in actionOnData " + data[0] + " " + data[1]);
//mTitle.setText("Change to next higher gear");
PGear = data[1];
Intent myIntent = new Intent();
myIntent.setClassName("com.example.android.TCPListen", "com.example.android.TCPListen.Images");
myIntent.putExtra("MsgInfo", data); // key/value pair, where key needs current package prefix.
startActivity(myIntent);
//finish();
} else if(tempName.equals("shiftDirection") && tempVal.equals("0")) {
Log.d("TCP","in actionOnData " + data[0] + " " + data[1]);
//mTitle.setText("Change to next higher gear");
data[1] = PGear;
Intent myIntent = new Intent();
myIntent.setClassName("com.example.android.TCPListen", "com.example.android.TCPListen.Images");
myIntent.putExtra("MsgInfo", data); // key/value pair, where key needs current package prefix.
startActivity(myIntent);
finish();
} else mTitle.setText("Just show something");
//Log.d("TCP", "Just show an image");
//}
}
}
In fact, in the above code, I have temporarily solved the issue of storing value of currGear and using it in shiftDirection, 0.
The value of PresentGear will only persist for the lifetime of your Activity. If the OS kills your Activity then the value will be lost. You should put some logging in onPause(), onStop() and onDestroy() and check how the lifecycle of your app is working. You may have to write out the value of PresentGear to SharedPreferences in onPause() and read the result in your onCreate(). Check out this link for the lifecycle:
Application fundamentals
Sounds like you should step through this code in the debugger and examine what values are being delivered to this activity. How are you constructing the Intent that gets delivered? (I suspect that either Info[0] isn't "currGear" or Info[1] is "", but something else could be going on.)