How to use a variable in a new activity? - java

I added a variable that pass form the first activity to the second one.
I want to use the info that has accepted from the first activity, at the new activity, and will save it on new double variable, display it as permanent on a textView.
Now, it appears only when I am clicking on the regular button that start the new activity.
As first step, I guess, I need to remove - "startActivity(intent1);".
How should I move on from here?
Java code:
First Activity (Name : settings.java)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
}
public void onClick (View v){
Intent intent = new Intent(settings.this, WaitressRecord.class);
startActivity(intent);
}
protected void onClickWait (View v) {
//--- Casting & Converting EditText "etSalaryWaitress" to Double "doubleSW".
btnWaitress =(Button)findViewById(R.id.btnWaitress);
etSalaryWaitress = (EditText) findViewById(R.id.etSalaryWaitress);
doubleSW = Double.parseDouble(etSalaryWaitress.getText().toString());
//---Casting Radio Button(s).
rbPercentage = (RadioButton)findViewById(R.id.rbPercentage);
rbShekel = (RadioButton)findViewById(R.id.rbShekel);
if (doubleSW < 100 ) {
if (rbPercentage.isChecked()) {
HafrashaP = 1 - (doubleSW / 100.0);
strHafPer = String.valueOf(HafrashaP);
Toast.makeText(settings.this, strHafPer, Toast.LENGTH_SHORT).show();
// start the SecondActivity
Intent intent1 = new Intent(this, WaitressRecord.class);
intent1.putExtra(Intent.EXTRA_TEXT, strHafPer);
startActivity(intent1);
} else if (rbShekel.isChecked()) {
HafrashaS = -doubleSW;
strHafShek = String.valueOf(HafrashaS);
Toast.makeText(settings.this, strHafShek, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(settings.this, "לא הוזנה סוג ההפרשה", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(settings.this, "מספר שגוי", Toast.LENGTH_SHORT).show();
}
}
New Activity: (Name : WaitressRecord.java)
public class WaitressRecord extends AppCompatActivity {
String strHafPer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_waitress_record);
// get the text from MainActivity
Intent intent1 = getIntent();
strHafPer = intent1.getStringExtra(Intent.EXTRA_TEXT);
// use the text in a TextView
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(strHafPer);
}
}

//First Activity
Intent intent= new Intent(this, SecondActivity.class);
Bundle extra = new Bundle();
mBundle.putString(VARIABLE_KEY, value);
intent.putExtras(mBundle);
startActivity(intent);
//on the second Acitivty
intent intent = getIntent();
Bundle bundleExtra;
//Null Checking
if (intent != null ) {
bundleExtra = getIntent().getExtras();
// Be sure your check your "VARIABLE KEY SAME AS in THE FIRST ACTIVITY
String resultString = extras.getString("VARIABLE_KEY");
}

Related

Getting the String Value to proceed to the next (specific) Activity

What I am trying here is, I want to get the string value of flevel and then when I click the search button it will proceed to the next (specific) Activity.
Goal is:
if the flevel is "Beginner" the next activity will be for the "Beginner", and if the flevel is "Experienced" the next activity will be for the "Experienced", and so on..
flevelfb = FilipinoBeginner
Bundle bnfb2 = getIntent().getExtras();
String flevelfb = bnfb2.getString("flevel");
flevel.setText(String.valueOf(flevelfb));
flevelfe = FilipinoExperienced
Bundle bnfe2 = getIntent().getExtras();
String flevelfe = bnfe2.getString("flevel");
flevel.setText(String.valueOf(flevelfe));
This part is for the search button:
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String flevels = flevel.getText().toString();
if (flevels.equals(flevelfb)){
Intent intent= new Intent(getApplicationContext(), FilipinoBeginner.class);
startActivity(intent);
}
else if (flevels.equals(flevelfe)){
Intent intent= new Intent(getApplicationContext(), FilipinoExperienced.class);
startActivity(intent);
}
}
});
you can change just search button click like this
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String flevels = flevel.getText().toString();
Intent intent = null;
if (flevels.equals("Beginner")){
intent = new Intent(getApplicationContext(), FilipinoBeginner.class);
}
else if (flevels.equals("Experienced")){
intent = new Intent(getApplicationContext(), FilipinoExperienced.class);
}
startActivity(intent);
}
});

Activity stack not working as it is supposed to

I have an app which has a MainActivity.
If its first launch, it launches an activity which displays a intro slider and if its not, it launches a MainWeatherActivity.
Here is the code from the MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean firstStart = PreferenceManager.getDefaultSharedPreferences(this)
.getBoolean(PREF_KEY_FIRST_START, true);
Log.i("MainActivity", "firstStart = " + Boolean.toString(firstStart));
if (firstStart) {
Intent i = new Intent(this, MainIntroActivity.class);
startActivityForResult(i, REQUEST_CODE_INTRO);
}
startActivity(new Intent(this, MainWeatherActivity.class));
finish();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_INTRO) {
if (resultCode == RESULT_OK) {
PreferenceManager.getDefaultSharedPreferences(this).edit()
.putBoolean(PREF_KEY_FIRST_START, false)
.apply();
} else {
PreferenceManager.getDefaultSharedPreferences(this).edit()
.putBoolean(PREF_KEY_FIRST_START, true)
.apply();
//User cancelled the intro so we'll finish this activity too.
finish();
}
}
}
When I open the app for the first time , user is supposed to see the MainIntroActivity and then the MainWeatherActivity.
But instead this code directly launches the MainWeatherActivity and when I press the back button it launches the MainIntroActivity.
Where have I gone wrong and How do I fix this?
MainIntroActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("MainIntroActivity","onCreate");
addSlide(new SlideFragmentBuilder()
.backgroundColor(R.color.colorPrimary)
.buttonsColor(R.color.colorAccent)
.neededPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
.image(agency.tango.materialintroscreen.R.drawable.ic_next)
.title("title 3")
.description("Description 3")
.build(),
new MessageButtonBehaviour(new View.OnClickListener() {
#Override
public void onClick(View v) {
showMessage("We provide solutions to make you love your work");
}
}, "Work with love"));
}
MainWeatherActivity
LocationManager mLocationManager;
double latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_weather);
Log.i("MainActivity","onCreate");
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(MainWeatherActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
latitude = location.getLatitude();
longitude = location.getLongitude();
Toast.makeText(MainWeatherActivity.this,"Successful. Latitude ="+Double.toString(latitude)+" Longitude = "+Double.toString(longitude),Toast.LENGTH_SHORT).show();
Log.i("MainActivity","Lat = "+latitude+", lon = "+ longitude);
}else{
Toast.makeText(MainWeatherActivity.this, "No Permission. Grant Permission to continue", Toast.LENGTH_SHORT).show();
}
}
EDIT :
I forgot to mention that both IntroActivity and MainActivity has a noHistory=true in the manifest file..
Hope the question is clear...
The call for starting activities is asynchronous. The behaviour you are seeing might be because of that.
Move the second call to the onActivityResult and to the else of the first if.
if (firstStart) {
Intent i = new Intent(this, MainIntroActivity.class);
startActivityForResult(i, REQUEST_CODE_INTRO);
} else {
startActivity(new Intent(this, MainWeatherActivity.class));
}
finish();
try replacing following code:
if (firstStart) {
Intent i = new Intent(this, MainIntroActivity.class);
startActivityForResult(i, REQUEST_CODE_INTRO);
}else{
startActivity(new Intent(this, MainWeatherActivity.class));
finish();
}

Variables losing data between activities and I don't know why?

I am currently creating an android app that scans a network and outputs results in a ListView but I am trying to make it to where I tap on the network and it saves the data in a database then sends you to a page to show you what you selected but when I click an item it substrings the values correctly and displays work fine on the main activity but when I try to use the variables on my display page activity there values are set null.
Here is the main activity in the click listener:
networklist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String grabItemInfo = wifis[position];
Network_Info info1 = new Network_Info();
info1.setMainBSSID( grabItemInfo.substring(grabItemInfo.indexOf('#') +1, grabItemInfo.lastIndexOf('#')));
info1.setMainSSID( grabItemInfo.substring(0,(grabItemInfo.indexOf('#'))));
info1.setMainCAP( grabItemInfo.substring(grabItemInfo.lastIndexOf('#')+1, grabItemInfo.length()));
Toast toastTest = Toast.makeText(getApplicationContext(), info1.getMainSSID(), Toast.LENGTH_SHORT);
Toast toastTest2 = Toast.makeText(getApplicationContext(), info1.getMainBSSID(), Toast.LENGTH_SHORT);
Toast toastTest3 = Toast.makeText(getApplicationContext(), info1.getMainCAP(), Toast.LENGTH_SHORT);
toastTest.show();
toastTest2.show();
toastTest3.show();
ContentValues dbv = new ContentValues();
dbv.put("SSID", info1.getMainSSID());
dbv.put("BSSID", info1.getMainBSSID());
dbv.put("CAPABILITIES", info1.getMainCAP());
netDataBase.insert("netDataTable", "NULL", dbv);
Intent intent = new Intent(getApplicationContext(), Attack_Page.class);
startActivity(intent);
}
});
Here is my display page:
public class Attack_Page extends Network_List {
protected void onCreate(Bundle SavedIS){
super.onCreate(SavedIS);
setContentView(R.layout.attack_page);
TextView SSIDview = (TextView) findViewById(R.id.SSIDView);
TextView BSSIDview = (TextView) findViewById(R.id.BSSIDView);
TextView CAPview = (TextView) findViewById(R.id.CAPView);
Button backButton = (Button) findViewById(R.id.backbutton);
Intent intent = getIntent();
//String MainSSIDP = intent.getStringExtra(getMainSSID());
Network_Info info1 = new Network_Info();
Toast testToast = Toast.makeText(getApplicationContext(), info1.getMainSSID(), Toast.LENGTH_SHORT);
testToast.show();
//Cursor IDselect = netDataBase.rawQuery("SELECT SSID FROM netDataTable WHERE SSID = "+getMainSSID()+"", wifis);
//SSIDview.setText(IDselect.toString());
backButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent bintent = new Intent(getApplicationContext(), Network_List.class);
startActivity(bintent);
}
});
}
}
Here is my setters and getters class:
public class Network_Info {
private String mainCAP;
private String mainSSID;
private String mainBSSID;
public void setMainSSID(String newMainSSID){
mainSSID = newMainSSID;
}
public void setMainBSSID(String newMainBSSID){
mainBSSID = newMainBSSID;
}
public void setMainCAP(String newMainCAP){
mainCAP = newMainCAP;
}
public String getMainSSID(){
return mainSSID;
}
public String getMainBSSID(){
return mainBSSID;
}
public String getMainCAP(){
return mainCAP;
}
}
Figured out you have to pass the variable with the intent:
Intent intent = new Intent(getApplicationContext(), Attack_Page.class);
intent.putExtra("EXTRA_SSID", info1.getMainSSID());
intent.putExtra("EXTRA_BSSID", info1.getMainBSSID());
intent.putExtra("EXTRA_CAP", info1.getMainCAP());
startActivity(intent);
Then use the key that you set in putExtra()
String MainSSIDP = intent.getStringExtra("EXTRA_SSID");
Thanks for the help though!

Button setText() wouldn't actually setText

I am trying to setText() to
Button btnFloor, btnTable;
Which isn't working ATM, actually I'm trying to send data from
FloorsActivity -> TablesActivity -> NewOrdersActivity
So how I pass Data from a activity to another?
FloorsActivity.java
#Override
public void onFloorItemClicked(int id) {
Intent intent = new Intent(this, TablesActivity.class);
intent.putExtra("FloorId", id);
startActivity(intent);
Toast.makeText(this, "Floor id : " + String.valueOf(id), Toast.LENGTH_SHORT).show();
}
TablesActivity.java
int floorId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_floors_tables);
initViews();
Intent intent = getIntent();
floorId = intent.getIntExtra("FloorId", 1);
}
#Override
public void onTableItemClicked(String name) {
String floorName = "F" + floorId;
Intent intent = new Intent(this, NewOrderActivity.class);
intent.putExtra("FloorId", floorId);
intent.putExtra("TableName", name);
intent.putExtra("FloorName", floorName);
startActivity(intent);
Toast.makeText(this, "Table Name : " + String.valueOf(name), Toast.LENGTH_SHORT).show();
}
NewOrderActivity.java
String floorName;
String tableName;
int floorId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_order);
initViews();
Intent intent = getIntent();
floorName = intent.getStringExtra("FloorName");
tableName = intent.getStringExtra("TableName");
floorId = intent.getIntExtra("FloorId", 1);
}
public void initViews() {
// Fetch view
btnFloor = (Button) findViewById(R.id.btn_floor);
btnTable = (Button) findViewById(R.id.btn_table);
//Set Views
btnFloor.setText(floorName);
btnTable.setText(tableName);
btnFloor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(NewOrderActivity.this, FloorsActivity.class);
startActivity(intent);
}
});
btnTable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(NewOrderActivity.this, TablesActivity.class);
intent.putExtra("FloorId", floorId);
startActivity(intent);
}
});
NewOrdersActivity is where I'm trying to set text
Here is my commit on Github for this full change
Here is the link to this project
You call initViews() before you've overloaded the intent extra's.
Fixed NewOrderActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_order);
Intent intent = getIntent();
floorName = intent.getStringExtra("FloorName");
tableName = intent.getStringExtra("TableName");
floorId = intent.getIntExtra("FloorId", 1);
initViews();
}

Activity called outside the tab

I am developing an app with 5 tabs and my last tab displays a list of menus. The problem appears when I click a menu tab, the menu activity appears nicely below my tab but when I click any of the menus (which it will call LoginActivity), the new Activity appears full screen not under the tab. How can I handle this? Below is my code.
TabActivity
package com.smartag.smarttreasure;
public class NfcSurveyActivity extends TabActivity {
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters,
mTechLists);
int profileCount = db.getContactsCount();
if (profileCount <= 0) {
Intent intent = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(intent);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
int profileCount = db.getContactsCount();
if (profileCount <= 0) {
Intent intent1 = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(intent1);
}
Bundle extras = getIntent().getExtras();
if (extras != null) {
tabToDisplay = extras.getString("tab");
if (tabToDisplay.equals("CAMERA")) {
barcodeData = extras.getString("barcodeData");
}
extras.clear();
}
TabHost tabHost = getTabHost();
// Home
TabSpec tbspecHome = tabHost.newTabSpec("Home");
tbspecHome.setIndicator("",
getResources().getDrawable(R.drawable.tab_account_style));
Intent iHome = new Intent(this, HomeActivity.class);
tbspecHome.setContent(iHome);
tabHost.addTab(tbspecHome);
// History
tabHost.addTab(tabHost
.newTabSpec("Fun")
.setIndicator("",
getResources().getDrawable(R.drawable.tab_fun_style))
.setContent(
new Intent(this, NfcSurveyActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)));
if (tabToDisplay != null && tabToDisplay.equals("REDEEM")) {
if (barcodeData != null && barcodeData.length() > 0) {
tabHost.addTab(tabHost
.newTabSpec("Camera")
.setIndicator(
"",
getResources().getDrawable(
R.drawable.tab_redeem_style))
.setContent(
new Intent(this, NfcSurveyActivity.class)
.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP)
.putExtra("autoLoadBarcodeData",
barcodeData)));
}
else {
tabHost.addTab(tabHost
.newTabSpec("Camera")
.setIndicator(
"",
getResources().getDrawable(
R.drawable.tab_redeem_style))
.setContent(
new Intent(this, NfcSurveyActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)));
}
} else {
tabHost.addTab(tabHost
.newTabSpec("Camera")
.setIndicator(
"",
getResources().getDrawable(
R.drawable.tab_redeem_style))
.setContent(
new Intent(this, NfcSurveyActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)));
}
// tabHost.setCurrentTab(2);
tabHost.getTabWidget().getChildAt(2).getLayoutParams().height = tabHost
.getTabWidget().getChildAt(2).getLayoutParams().height + 19;
// Search
TabSpec tbspecSearch = tabHost.newTabSpec("Finder");
tbspecSearch.setIndicator("",
getResources().getDrawable(R.drawable.tab_finder_style));
Intent iSearch = new Intent(this, NfcSurveyActivity.class);
tbspecSearch.setContent(iSearch);
tabHost.addTab(tbspecSearch);
// Profile
TabSpec tbspecProfile = tabHost.newTabSpec("Quit");
tbspecProfile.setIndicator("",
getResources().getDrawable(R.drawable.tab_quit_style));
Intent iProfile = new Intent(this, NfcSurveyActivity.class);
tbspecProfile.setContent(iProfile);
tabHost.addTab(tbspecProfile);
for (int i = 0; i <= 4; i++) {
tabHost.getTabWidget()
.getChildTabViewAt(i)
.setBackgroundColor(
getResources()
.getColor(android.R.color.transparent));
if (i == 2) {
tabHost.getTabWidget()
.getChildTabViewAt(i)
.setPadding(
tabHost.getTabWidget().getChildTabViewAt(i)
.getPaddingLeft(),
tabHost.getTabWidget().getChildTabViewAt(i)
.getPaddingTop(),
tabHost.getTabWidget().getChildTabViewAt(i)
.getPaddingRight(), 20);
}
}
if (tabToDisplay != null && tabToDisplay.length() > 0) {
if (tabToDisplay.equals("CAMERA")) {
tabHost.setCurrentTab(2);
} else if (tabToDisplay.equals("HISTORY")) {
tabHost.setCurrentTab(1);
}
}
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
public void onTabChanged(String tabId) {
NfcSurveyConfiguration.SelectedTab = tabId;
}
});
}
}
MenuActivity
public class HomeActivity extends ListActivity {
static final String[] Account = new String[] { "Point History", "Scan History",
"Reward/Coupon History", "Share/Transfer History", "Personalise" };
String tabToDisplay = "";
String barcodeData = "";
SharedPreferences nfcSurveyConfiguration;
String profileId;
String pleaseWait = "";
protected boolean _taken;
protected File _directory;
protected String _filename;
protected String _fileExtension;
String profileName = "";
String profileEmail = "";
String profileStatus = "";
String profileLanguage = "";
String profileType = "";
DatabaseHandler db = new DatabaseHandler(this);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,
R.layout.listview_item_row, Account));
ListView listView = getListView();
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
//Toast.makeText(getApplicationContext(),
// ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
Intent intent1 = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(intent1); // This activity appears not in the tab
}
});
}
#Override
public void onPause() {
super.onPause();
NfcSurveyConfiguration.CurrentActiveTab = 0;
}
}
Any suggestion or advice is highly appreciated.
this code inside setOnItemClickListener help me to solve the problem.
View view1 = getLocalActivityManager().startActivity(
"ReferenceName",
new Intent(getApplicationContext(),
YourActivityClass.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
setContentView(view1);

Categories

Resources