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);
Related
I have declared strings string1, string2, string3, string4.. string7 in public class. and I am getting values from MySQL database using JSON in onCreate method and storing in String variables st1 , st2, st3...., st7.
Now I need to pass these st1 ,st2,st3,...,st7 values to the string1, string2, string3... string7 respectively.
public class MainActivity extends AppCompatActivity {
private Context mContext;
private Activity mActivity;
private CoordinatorLayout mCLayout;
private Button mButtonDo;
private TextView mTextView;
private String mJSONURLString = "http://paolo.....";
String string1, string2, string3, string4, string4, string5, string6, string7;
String seats = string1 + "" + string2 + "" + string3 + "" + string4 + "" + string5 + "" + string6 + "" + string7;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = getApplicationContext();
mActivity = MainActivity.this;
mCLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
mTextView = (TextView) findViewById(R.id.tv);
mTextView.setText("");
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, mJSONURLString, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray seat) {
try {
// Loop through the array elements
for (int i = 0; i < seat.length(); i++) {
// Get current json object
JSONObject student = seat.getJSONObject(i);
String st1 = student.getString("st1");
String st2 = student.getString("st2");
String st3 = student.getString("st3");
String st4 = student.getString("st4");
String st5 = student.getString("st5");
String st6 = student.getString("st6");
String st7 = student.getString("st7");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonArrayRequest);
}
}
If you are getting the elements in the for loop as you are doing :
String st1 = student.getString("st1");
String st2 = student.getString("st2");
String st3 = student.getString("st3");
String st4 = student.getString("st4");
String st5 = student.getString("st5");
String st6 = student.getString("st6");
String st7 = student.getString("st7");
You should change it to :
string1 = student.getString("st1");
string2 = student.getString("st2");
string3 = student.getString("st3");
string4 = student.getString("st4");
string5 = student.getString("st5");
string6 = student.getString("st6");
string7 = student.getString("st7");
And if you want to update UI or something just add the method inside the onResponse() I mean if you want to display that text you can create a
private void showText(){
your_text_view1.setText(string1);
(....)
}
And then in the end of onResponse() just put this method.
I made two classes(DataBase, and addItem to database class) and one activiy. I dont know how to pass Activity class into method. AndroidStudio throws error.
I tried to use getApplicationContext(), but didnt work. Here is code:
DataBase file
public DataBase(Context context) {
super(context, DATABASE_NAME, null, TABLE_VERSION); }
DodajNadgranieClass (fragment) file
btZapisz.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String radiobutton = "", bruttoValue ="", data, tytul;
SharedPreferences pref = getSharedPreferences("prefs", MODE_PRIVATE);
data = edPodajDate.getText().toString();
tytul = edPodajTytul.getText().toString();
if (edPodajDate.getText().toString().isEmpty() || edPodajTytul.getText().toString().isEmpty() || radioGroup.getCheckedRadioButtonId() == -1) {
Toast.makeText(DodajNadgranieActivity.this, "Musisz podać wszystkie dane", Toast.LENGTH_SHORT).show();
} else {
if (rbOperetka.isChecked()) {
radiobutton = "1";
bruttoValue = pref.getString("operetka", "");
} else if (rbMusical.isChecked()) {
radiobutton = "2";
bruttoValue = pref.getString("musical", "");
} else if (rbKoncert.isChecked()) {
radiobutton = "3";
bruttoValue = pref.getString("koncert", "");
} else if (rbBajka.isChecked()) {
radiobutton = "4";
bruttoValue = pref.getString("bajka", "");
} else if (rbOpera.isChecked()) {
radiobutton = "5";
bruttoValue = pref.getString("opera", "");
} else if (rbInne.isChecked()) {
radiobutton = "6";
bruttoValue = pref.getString("inne", "");
}
ObliczPodatki obliczPodatki = new ObliczPodatki();
obliczPodatki.obliczPodatki(bruttoValue, data, tytul, radiobutton);
Toast.makeText(DodajNadgranieActivity.this, "DODANO", Toast.LENGTH_SHORT).show();
radioGroup.clearCheck();
edPodajTytul.setText(null);
edPodajDate.setText(null);
and Activity file
public class ObliczPodatki extends Application {
public void obliczPodatki (String brutto, String data, String tytul, String radiobutton) {
kwota_brutto = Double.parseDouble(brutto);
kwota_netto = kwota_brutto * KWOTA_NETTO;
kwota_ubezpieczenie_emerytalne = kwota_brutto * UBEZPIECZENIE_EMERYTALNE;
kwota_ubezpieczenie_rentowe = kwota_brutto * UBEZPIECZENIE_RENTOWE;
kwota_ubezpieczenie_zdrowotne = kwota_brutto * UBEZPIECZENIE_ZDROWOTNE;
kwota_ubezpieczenie_chorobowe = kwota_brutto * UBEZPIECZENIE_CHOROBOWE;
kwota_zaliczka_pit = kwota_brutto * ZALICZKA_PIT;
sBrutto = "" + kwota_brutto;
sNetto = "" + kwota_netto;
sEmerytalne = "" + kwota_ubezpieczenie_emerytalne;
sRentowe = "" + kwota_ubezpieczenie_rentowe;
sZdrowotne = "" + kwota_ubezpieczenie_zdrowotne;
sChorobowe = "" + kwota_ubezpieczenie_chorobowe;
sPit = "" + kwota_zaliczka_pit;
DataBase myDb = new DataBase(this);
myDb.addNewNadgranie(data, tytul, radiobutton, sBrutto, sNetto, sEmerytalne, sRentowe, sZdrowotne, sChorobowe, sPit);
}
}
you are using Application and not Activity class . please change it to this :
public class ObliczPodatki extends AppCompatActivity
You could change the function of obliczPodatki to :
public void obliczPodatki (Activity activity, String brutto, String data, String tytul, String radiobutton) {
Call it using :
obliczPodatki.obliczPodatki((DodajNadgranieActivity)v.getContext(),bruttoValue, data, tytul, radiobutton);
I have an app that uses a foreign key when updating a table. I want to be able to put their email down instead of using their number.
Here is the Database methods:
private int getIdFromName(String email) {
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<Integer> refs = new ArrayList<>();
Cursor cursor;
cursor = db.rawQuery("select " + REFEREE_EMAIL_COL + " from " +
REF_TABLE + " where " + REFEREE_EMAIL_COL + "='" + email + "'", null);
while (cursor.moveToNext()){
refs.add(cursor.getInt(0));
}
return refs.get(0);
}
public boolean updateRef(String email)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
int ref_id = getIdFromName(email);
values.put(REFEREE_ID_COL, ref_id);
db.insert(MATCH_TABLE, null, values);
return true;
}
Here is where I call it:
public class UpdateMatchActivity extends AppCompatActivity {
private static final String TAG = "EditDataActivity";
private Button btnSave,btnDelete;
private EditText homeTeamEdit, awayTeamEdit, typeOfMatchEdit, redCardsEdit, bookingsEdit, groundEdit, refEdit, dateEdit, timeEdit,
awayScoreEdit, homeScoreEdit;
DBHandler mDatabaseHelper;
private String homeTeam, awayTeam, homeScore, awayScore;
private String typeOfMatch;
private String ref;
private String redCards, bookings;
private String date, time;
private String ground;
private int selectedID;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_match);
btnSave = (Button) findViewById(R.id.UpdateMatchButton);
homeTeamEdit = (EditText) findViewById(R.id.HomeTeamUpdate);
homeScoreEdit = (EditText) findViewById(R.id.updateHomeScore);
awayTeamEdit = (EditText) findViewById(R.id.AwayTeamUpdate);
awayScoreEdit = (EditText) findViewById(R.id.updateAwayScore);
typeOfMatchEdit = (EditText) findViewById(R.id.updateTypeOfMatch);
refEdit = (EditText) findViewById(R.id.updateRef);
groundEdit = (EditText) findViewById(R.id.updateGround);
refEdit = (EditText) findViewById(R.id.updateRef);
ref = refEdit.getText().toString();
mDatabaseHelper = new DBHandler(this);
//get the intent extra from the ListDataActivity
Intent receivedIntent = getIntent();
//now get the itemID we passed as an extra
selectedID = receivedIntent.getIntExtra("MatchId", -1); //NOTE: -1 is just the default value
//now get the name we passed as an extra
homeTeam = receivedIntent.getStringExtra("homeTeam");
homeScore = receivedIntent.getStringExtra("homeScore");
awayTeam = receivedIntent.getStringExtra("awayTeam");
awayScore = receivedIntent.getStringExtra("awayScore");
ground = receivedIntent.getStringExtra("ground");
typeOfMatch = receivedIntent.getStringExtra("typeOfMatch");
//set the text to show the current selected name
homeTeamEdit.setText(homeTeam);
awayTeamEdit.setText(awayTeam);
typeOfMatchEdit.setText(typeOfMatch);
groundEdit.setText(ground);
homeScoreEdit.setText(homeScore);
awayScoreEdit.setText(awayScore);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String item = refEdit.getText().toString();
if(!mDatabaseHelper.checkIfRefExists(ref)) {
mDatabaseHelper.updateRef(ref);
toastMessage("Ref Updated");
}
else
{
toastMessage("No ref with that email");
}
}
});
}
/**
* customizable toast
* #param message
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
I tried using the getIdFromName method when creating for the first time and it works but when I try update it, it gives me "java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)"
Totally lost here so any guidance would be appreciated.
I have been doing an app that needs a profile page. the login is an activity and the profile page is fragment. whenever I do the passing, it always returns null.
here is my MainActivity.java
public class MainActivity extends Activity {
ConnectionClass connectionClass;
EditText edtuserid,edtpass;
Button btnlogin;
ProgressBar pbbar;
public int test2;
public String test3 = "";
String user_fname;
String user_lname;
int dept_id;
String test;
String user_email;
String user_password;
String user_username;
Bundle profileBundle;
String userid;
String password;
int userIDD;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectionClass = new ConnectionClass();
edtuserid = (EditText) findViewById(R.id.edtuserid);
edtpass = (EditText) findViewById(R.id.edtpass);
btnlogin = (Button) findViewById(R.id.btnlogin);
pbbar = (ProgressBar) findViewById(R.id.pbbar);
pbbar.setVisibility(View.GONE);
edtuserid.setText(test3);
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userid = edtuserid.getText().toString();
password = edtpass.getText().toString();
DoLogin doLogin = new DoLogin();
doLogin.execute("");
}
});
}
public class DoLogin extends AsyncTask<String,String,String>
{
int b;
String z = "";
Boolean isSuccess = false;
#Override
public void onPreExecute() {
pbbar.setVisibility(View.VISIBLE);
}
#Override
public void onPostExecute(String r) {
pbbar.setVisibility(View.GONE);
if(isSuccess) {
//DITO ANG REDIRECTION
Intent base = new Intent(MainActivity.this, OtherActivity.class);
startActivity(base);
finish();
}
}
#Override
public String doInBackground(String... params) {
if(userid.trim().equals("")|| password.trim().equals(""))
z = "Please enter User Id and Password";
else
{
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "select user_id, user_fname, user_lname, department_id, user_email, user_password, user_username from users where user_id='" + userid + "' and user_password='" + password + "'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
userIDD = rs.getInt(1);
Bundle profileBundle = new Bundle();
profileBundle.putInt("userID", userIDD);
PathfinderAdd fragobj = new PathfinderAdd();
fragobj.setArguments(profileBundle);
z = "The ID is " + userIDD;
isSuccess=true;
}
else
{
z = "Invalid Credentials";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
z = "Error Somewhere";
Log.e("MYAPP", "exception", ex);
}
}
return z;
}
}
public String getMyData() {
String test4 = test3;
return test4;
}
}
And in the fragment, I retrieve the data as:
PathfinderAdd.java
public class PathfinderAdd extends Fragment {
ConnectionClass connectionClass;
EditText edtideaname, edtbenefit,edtobservation,edtquickwin,targetdate;
Button btnadd;
TextView targettv;
Spinner spinner1, spinner2;
ProgressBar pbbar;
String proid;
CalendarView calendar;
String realDate;
String DAY;
Date targ = null;
String finalDate;
SimpleDateFormat timeFormat;
java.sql.Date sql;
Date date2;
int userID = 0;
int user = 0;
public PathfinderAdd(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.addpathfinder, container, false);
connectionClass = new ConnectionClass();
edtideaname = (EditText) rootView.findViewById(R.id.edtideaname);
edtbenefit = (EditText) rootView.findViewById(R.id.edtbenefit);
edtobservation = (EditText) rootView.findViewById(R.id.edyobservation);
edtquickwin = (EditText) rootView.findViewById(R.id.edtquickwin);
targetdate = (EditText) rootView.findViewById(R.id.target);
spinner1 = (Spinner) rootView.findViewById(R.id.spinner1);
spinner2 = (Spinner) rootView.findViewById(R.id.spinner2);
btnadd = (Button) rootView.findViewById(R.id.btnadd);
pbbar = (ProgressBar) rootView.findViewById(R.id.pbbar);
targettv = (TextView) rootView.findViewById(R.id.tvtarget);
pbbar.setVisibility(View.GONE);
calendar = (CalendarView) rootView.findViewById(R.id.calendar1);
proid = "";
//String userId = ((MainActivity)getActivity()).IDD;
MainActivity getID = new MainActivity();
String IDD = getID.getMyData();
Toast.makeText(PathfinderAdd.this.getActivity(), IDD, Toast.LENGTH_SHORT).show();
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddPro addPro = new AddPro();
addPro.execute("");
}
});
calendar.setOnDateChangeListener(new OnDateChangeListener() {
public void onSelectedDayChange(CalendarView view, int year_date, int month_date,
int dayOfMonth) {
int day = dayOfMonth;
int month = month_date;
int year = year_date;
DAY=String.valueOf(year)+String.valueOf(month)+String.valueOf(day);
}
});
return rootView;
}
public class AddPro extends AsyncTask<String, String, String> {
String z = "";
Boolean isSuccess = false;
String observation = edtobservation.getText().toString();
String quickwin = edtquickwin.getText().toString();
String ideaname = edtideaname.getText().toString();
String benefit = edtbenefit.getText().toString();
String target_date = targetdate.getText().toString();
String process = spinner1.getSelectedItem().toString();
String benefitType = spinner2.getSelectedItem().toString();
String lol = "2015-11-28";
Integer benefit_type = spinner2.getSelectedItemPosition();
Integer idea_type = spinner1.getSelectedItemPosition();
Integer idea_id;
Integer benefit_id;
Integer pathfinder_id = 1;
Integer pathfinder_status = 9;
Integer pathfinder_prog = 0;
#Override
protected void onPreExecute() {
pbbar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r) {
pbbar.setVisibility(View.GONE);
Toast.makeText(PathfinderAdd.this.getActivity(), r, Toast.LENGTH_SHORT).show();
if(isSuccess==true) {
edtideaname.setText(null);
edtbenefit.setText(null);
edtobservation.setText(null);
edtquickwin.setText(null);
targetdate.setText(null);
}
}
#Override
protected String doInBackground(String... params) {
if (ideaname.trim().equals("") || benefit.isEmpty() || observation.trim().equals("") || quickwin.trim().equals(""))
z = "Please fill all the fields";
else {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
//timeFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);
//finalDate = timeFormat.format(targ);
//sql = new java.sql.Date(targ.getTime());
int lol=1;
double benefitInt = Double.parseDouble(benefit);
date2 = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH).parse(DAY);
String newDateString = new SimpleDateFormat("yyyy/MM/dd",Locale.ENGLISH).format(date2);
DateFormat format2 = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH);
Date date3 = format2.parse(newDateString);
String dates = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH)
.format(Calendar.getInstance().getTime());
//String date = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH)
//.format(calendar.getDate());
switch (idea_type)
{
case 0:
idea_id = 1;
break;
case 1:
idea_id = 2;
break;
case 2:
idea_id = 3;
break;
case 3:
idea_id = 4;
break;
case 4:
idea_id = 5;
break;
default:
idea_id = 1;
break;
}
switch(benefit_type)
{
case 0:
benefit_id = 1;
break;
case 1:
benefit_id = 2;
break;
default:
benefit_id = 1;
break;
}
String query = "insert into pathfinder (pathfinder_id,pathfinder_name,idea_id,benefit_id,pathfinder_potential_eqv,pathfinder_observation,pathfinder_quickwin,pathfinder_target_closure,pathfinder_status,pathfinder_progress,patfinder_actual_closure,pathfinder_date_raised,user_id)" +
"values ('" +pathfinder_id+ "','" +ideaname+ "','" +idea_id+ "','" +benefit_id+ "','" +benefitInt+ "','" +observation+ "','" +quickwin+ "','" +dates+ "','" +pathfinder_status+ "','" +pathfinder_prog+ "','" +dates+ "','" +dates+ "','" + user+"')";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.executeUpdate();
z = "Added Successfully";
isSuccess = true;
}
} catch (Exception ex) {
isSuccess = false;
z = "Exceptions";
Log.e("MYAPP", "exception", ex);
}
}
return z;
}
}
}
the problem is that whenever this code executes, i get a null value. I have also tried assigning it to a method but it still returns null.
you must use same object for going to fragment. i think you used another object of fragment for transaction that's why it is showing null.
it have to be somewhat like this
PathfinderAdd fragobj = new PathfinderAdd();
fragobj.setArguments(profileBundle);
getSupportFragmentManager().beginTransaction().add(R.id.container , fragobj).commit();
You can also do this without passing data to fragment. You can directly get data from your main Activity like this. In your main Activity just do this.
if(rs.next())
{
userIDD = rs.getInt(1);
user_fname = rs.getString(2);
user_lname = rs.getString(3);
dept_id = rs.getInt(4);
user_email = rs.getString(5);
user_password = rs.getString(6);
user_username = rs.getString(7);
}
Then in your Fragment get values like this:
userId = ((YourActivity)getActivity()).userIDD;
Make sure your veriables are activity global.
If you are using a static fragment, setArguments() simply won't work. You need to set arguments for a transaction before you do a beginTransaction() in your fragmentManager. If you do it after that, then also setArguments() won't work
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.