The values are not being passed on the first click of editText - java

I need to take the values of a and b from the user via editText and pass it to the next activity.This is the first activity:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.content.Intent;
import android.widget.EditText;
public class activitysecond extends AppCompatActivity {
private String[] arraySpinner;
private String[] arraySpinner2;
int a=0,b=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
final EditText editText1=(EditText) findViewById(R.id.editText1);
final EditText editText2=(EditText) findViewById(R.id.editText2);
final Bundle bundle = new Bundle();
Button EnterButton=(Button) findViewById(R.id.Enterbutton);
this.arraySpinner = new String[]{
"None", "Lightly Active", "Moderately Active", "Very Active"
};
Spinner s = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<>
(this,
android.R.layout.simple_spinner_dropdown_item, arraySpinner
);
s.setAdapter(adapter);
this.arraySpinner2 = new String[]{
"Male", "Female"
};
Spinner s1 = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<String> adapter1 = new ArrayAdapter<>
(this,
android.R.layout.simple_spinner_dropdown_item, arraySpinner2
);
s1.setAdapter(adapter1);
editText1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a = Integer.valueOf(editText1.getText().toString());
bundle.putInt("one",a);
}
});
editText2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
b = Integer.valueOf(editText2.getText().toString());
bundle.putInt("two",b);
}
});
EnterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent z = new Intent(activitysecond.this, activitythird.class);
startActivity(z);
z.putExtras(bundle);
}
});
}
}
The next activity to which i want to pass the values is
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class activitythird extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thirdactivity);
}
public void thirdbutton(View view){
final TextView thirdtext=(TextView) findViewById(R.id.thirdtext);
Bundle seconddata=getIntent().getExtras();
int vala=seconddata.getInt("one");
int valb=seconddata.getInt("two");
thirdtext.setText(vala + " " +valb);
}
}
The values a and b are not passed and the thirdtext does not change
Please help!!

You start your activity before you add the bundle to your intent.
Try it like this:
Intent z = new Intent(activitysecond.this, activitythird.class);
z.putExtras(bundle);
startActivity(z);

Replace this
EnterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent z = new Intent(activitysecond.this, activitythird.class);
startActivity(z);
z.putExtras(bundle);
}
});
with
EnterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent z = new Intent(activitysecond.this, activitythird.class);
z.putExtras("one", Integer.parseInt(editText1.getText().toString()));
z.putExtras("two", Integer.parseInt(editText2.getText().toString()));
startActivity(z);
}
});

Remove ClickListener for the edit texts and add the following lines in onClick of EnterButton
a = Integer.valueOf(editText1.getText().toString());
bundle.putInt("one",a);
b = Integer.valueOf(editText2.getText().toString());
bundle.putInt("two",b);

At the below; putExtra comes before startActivity, that is the mistake.
EnterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent z = new Intent(activitysecond.this, activitythird.class);
startActivity(z);
z.putExtras(bundle);
}
});
try at below code;
EnterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent z = new Intent(activitysecond.this, activitythird.class);
z.putExtras(bundle); // first
startActivity(z); //second
}
});
Also editText onClickListeners should not be implemented for your case. You should get the variables via:
if (editText1.getText() != null) { // to avoid exception
a = Integer.valueOf(editText1.getText().toString());
bundle.putInt("one",a);
}
if (editText2.getText() != null) { to avoid exception
b = Integer.valueOf(editText2.getText().toString());
bundle.putInt("two",b);
}

Modify your code like this:
EnterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent z = new Intent(activitysecond.this, activitythird.class);
z.putExtras(bundle);
startActivity(z);
}
});
z.putExtras(bundle); must be higher that startActivity(z);

Related

How to Delete an Item from Arraylist in SharedPreferences with Android Studio

I was trying to save the array's data in shared prefrences and two problems occured.
The first one is that every time I open the activity that should have the array in it (mainPage activity) it doesn't show anything until I add use the foodAdding activity to add food and then it shows all the previous foods and shows the food that I have just added
The second one is that whenever I try to delete any of the elements it get deleted till I refresh the activity or go to another activity and come back so how could I delete elements properly in the shared prefrences ??
the code for the mainPage activity (the activity that should show all the foods):
package com.example.yourhealthapp;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class mainPage extends AppCompatActivity {
Button adding;
Button main;
Button profile;
public static ArrayList<Food> foods = new ArrayList<Food>();
FoodAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
adapter = new FoodAdapter(this, foods);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
Intent intent = getIntent();
int weight = intent.getIntExtra("weight", 404);
int height = intent.getIntExtra("height", 404);
int age = intent.getIntExtra("age", 404);
adding = findViewById(R.id.adding_main);
main = findViewById(R.id.main_main);
profile = findViewById(R.id.profile_main);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
final int item = position;
new AlertDialog.Builder(mainPage.this).setIcon(android.R.drawable.ic_delete).setTitle("Are you sure ?").setMessage("Do you want to delete this meal ?")
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
foods.remove(item);
adapter.notifyDataSetChanged();
}
})
.setNegativeButton("no", null).show();
return true;
}
});
adding.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_page = new Intent(mainPage.this, foodadding.class);
next_page.putExtra("weight", weight);
next_page.putExtra("height", height);
next_page.putExtra("age", age);
startActivity(next_page);
}
});
main.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_page = new Intent(mainPage.this, mainPage.class);
next_page.putExtra("weight", weight);
next_page.putExtra("height", height);
next_page.putExtra("age", age);
startActivity(next_page);
}
});
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_page = new Intent(mainPage.this, profile.class);
next_page.putExtra("weight", weight);
next_page.putExtra("height", height);
next_page.putExtra("age", age);
startActivity(next_page);
}
});
loadData();
adapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
super.onResume();
adapter.notifyDataSetChanged();
}
public void loadData()
{
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("meals list", null);
Type type = new TypeToken<ArrayList<Food>>() {}.getType();
foods = gson.fromJson(json, type);
if (foods == null)
{
foods = new ArrayList<>();
}
}
}
The code for the foodAdding activity (the activity that you add the foods from):
package com.example.yourhealthapp;
import androidx.appcompat.app.AppCompatActivity;
import android.app.SearchManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class foodadding extends AppCompatActivity {
Button adding;
Button main;
Button profile;
Button add;
Button dont;
EditText calories;
EditText servings;
EditText grams;
EditText name;
mainPage array = new mainPage();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_foodadding);
adding = findViewById(R.id.adding_food);
main = findViewById(R.id.main_food);
profile = findViewById(R.id.profile_food);
add = findViewById(R.id.add);
dont = findViewById(R.id.dont);
Intent i = getIntent();
int weight = i.getIntExtra("weight", 404);
int height = i.getIntExtra("height", 404);
int age = i.getIntExtra("age", 404);
grams = findViewById(R.id.grams);
calories = findViewById(R.id.calories);
servings = findViewById(R.id.servings);
name = findViewById(R.id.name);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Food w = new Food(name.getText().toString(), Integer.parseInt(calories.getText().toString()) , Integer.parseInt(servings.getText().toString()), Integer.parseInt(grams.getText().toString()));
array.foods.add(w);
saveData();
}
});
dont.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String q = name.getText().toString();
q = "How many calories there are in one serving of" + q;
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH );
intent.putExtra(SearchManager.QUERY, q);
startActivity(intent);
}
});
adding.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_page = new Intent(foodadding.this, foodadding.class);
next_page.putExtra("weight", weight);
next_page.putExtra("height", height);
next_page.putExtra("age", age);
startActivity(next_page);
}
});
main.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_page = new Intent(foodadding.this, mainPage.class);
next_page.putExtra("weight", weight);
next_page.putExtra("height", height);
next_page.putExtra("age", age);
startActivity(next_page);
}
});
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_page = new Intent(foodadding.this, profile.class);
next_page.putExtra("weight", weight);
next_page.putExtra("height", height);
next_page.putExtra("age", age);
startActivity(next_page);
}
});
}
public void saveData()
{
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(array.foods);
editor.putString("meals list", json);
editor.apply();
}
}
And I want as well to save the info that I created using the user's input in this activity (profile) so how could I do that ?
the code for the profile activity is :
package com.example.yourhealthapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import java.lang.Math;
import android.widget.Button;
import android.widget.TextView;
public class profile extends AppCompatActivity {
Button adding;
Button main;
Button profile;
Button edit;
int caleaten = 0 ;
MainActivity info = new MainActivity();
mainPage fo = new mainPage();
TextView gain;
TextView loose;
TextView maintain;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
adding = findViewById(R.id.adding_profile);
main = findViewById(R.id.main_profile);
maintain = findViewById(R.id.maintain);
edit = findViewById(R.id.edit);
loose = findViewById(R.id.loosing);
gain = findViewById(R.id.gaining);
profile = findViewById(R.id.profile_profile);
Intent intent = getIntent();
int weight = intent.getIntExtra("weight", 404);
int height = intent.getIntExtra("height", 404);
int age = intent.getIntExtra("age", 404);
double maintanancem = (10 * weight) + (6.25 * height) - (5 * age) + 5;
double maintainancew = (10 * weight) + (6.25 * height) - (5 * age) - 161;
if(info.active == "low physical activity")
{
maintainancew *= 1.375;
maintanancem *= 1.375;
}
else if(info.active == "average physical activity")
{
maintainancew *= 1.550;
maintanancem *= 1.550;
}
else
{
maintainancew *= 1.725;
maintanancem *= 1.725;
}
for (int i = 0 ; i < fo.foods.size(); i++)
{
caleaten += fo.foods.get(i).getmCalories() * fo.foods.get(i).getmServings();
}
maintanancem -= caleaten;
maintainancew -= caleaten;
if (info.g == "male" )
{
maintain.setText(Integer.toString((int)maintanancem));
gain.setText(Integer.toString((int)maintanancem + 500));
loose.setText(Integer.toString((int) (maintanancem - 500)));
}
else
{
maintain.setText(Integer.toString((int)maintainancew));
gain.setText(Integer.toString((int)maintainancew + 500));
loose.setText(Integer.toString((int)maintainancew - 500));
}
adding.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_page = new Intent(profile.this, foodadding.class);
next_page.putExtra("weight", weight);
next_page.putExtra("height", height);
next_page.putExtra("age", age);
startActivity(next_page);
}
});
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(profile.this , MainActivity.class);
startActivity(i);
}
});
main.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_page = new Intent(profile.this, mainPage.class);
next_page.putExtra("weight", weight);
next_page.putExtra("height", height);
next_page.putExtra("age", age);
startActivity(next_page);
}
});
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_page = new Intent(profile.this, profile.class);
next_page.putExtra("weight", weight);
next_page.putExtra("height", height);
next_page.putExtra("age", age);
startActivity(next_page);
}
});
}
}

Sound overlapping with multiple button clicks

package com.example.tobiadegoroye.pokemonsoundboard;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
public class PokemonSoundboard extends AppCompatActivity {
MediaPlayer psyduckplayer; //member variable
MediaPlayer pikachuplayer; //member variable
MediaPlayer diglettplayer; //member variable
ImageButton mpsyduckbutton;
ImageButton mpikachubutton;
ImageButton mdiglettbutton;
View.OnClickListener psyducklistner = new View.OnClickListener() {
#Override
public void onClick(View v) {
psyduckplayer.start();
}
};
View.OnClickListener pikachulistner = new View.OnClickListener() {
#Override
public void onClick(View v) {
pikachuplayer.start();
}
};
View.OnClickListener digletlistner = new View.OnClickListener() {
#Override
public void onClick(View v) {
diglettplayer.start();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pokemon_soundboard);
mpsyduckbutton = (ImageButton) findViewById(R.id.psyduckbutton);
mpikachubutton = (ImageButton) findViewById(R.id.pikachubutton);
mdiglettbutton = (ImageButton) findViewById(R.id.diglettbutton);
psyduckplayer = MediaPlayer.create(this,R.raw.psyduck);
pikachuplayer = MediaPlayer.create(this,R.raw.pikachu);
diglettplayer = MediaPlayer.create(this,R.raw.diglett);
mpsyduckbutton.setOnClickListener(psyducklistner);
mpikachubutton.setOnClickListener(pikachulistner);
mdiglettbutton.setOnClickListener(digletlistner);
}
}
Use the MediaPlayer.isPlaying() and MediaPlayer.stop() methods.
public void stopPlaying()
{
if(pikachuplayer != null && pikachuplayer.isPlaying())
{
pikachuplayer.stop();
}
if(digletplayer != null && digletplayer.isPlaying())
{
digletplayer.stop();
}
if(psyduckplayer != null && psyduckplayer.isPlaying())
{
psyduckplayer.stop();
}
}
View.OnClickListener psyducklistner = new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
psyduckplayer.start();
}
};
View.OnClickListener pikachulistner = new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
pikachuplayer.start();
}
};
View.OnClickListener digletlistner = new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
diglettplayer.start();
}
};
View.OnClickListener digletlistner = new View.OnClickListener() {
#Override
public void onClick(View v) {
diglettplayer.start();
}
};
The stopPlaying() method stops all Medias from playing, only if they're playing and not null (They probably aren't null, as they're member variables, but it's still a good practice).

Code doesn't work

I'm trying to make an APK that saves passwords with the site using two different ArrayLists. This way, I can get the right indexnumber of the site and get the password based on this indexnumber. In the beginning of MainActivity, I add two random Strings to the ArrayLists, so that I don't have to work with empty ArrayLists, but this is utterly useless I think.
The problem is I can only view the last site-password I have put in. Previous combinations are "lost."
code:
MainActivity.java
package com.example.prive.passwordsafe;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
public ArrayList<String> passwordList = new ArrayList<>();
public ArrayList<String> siteList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
passwordList.add("ejifjejfijeifjeijfiejifjeijfiejfijefie");
siteList.add("iejfijeifjiejfiejidvjijijeijivjiejvijeivjejv");
Button addButton = (Button) findViewById(R.id.addButton);
Button showButton = (Button) findViewById(R.id.showButton);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
firstIntent();
}
});
showButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
secondIntent();
}
});
}
#Override
public void onResume(){
super.onResume();
add();
}
private void firstIntent() {
Intent intent = new Intent(MainActivity.this, addActivity.class);
intent.putStringArrayListExtra("passwordList", passwordList);
intent.putStringArrayListExtra("siteList", siteList);
startActivity(intent);
}
private void secondIntent() {
Intent intent = new Intent(MainActivity.this, showActivity.class);
intent.putStringArrayListExtra("passwordList", passwordList);
intent.putStringArrayListExtra("siteList", siteList);
startActivity(intent);
}
public void add(){
Bundle pickupData = getIntent().getExtras();
if(pickupData == null){
return;
}
String receivedPassword = pickupData.getString("Password");
String receivedSite;
receivedSite = pickupData.getString("Site");
passwordList.add(receivedPassword);
siteList.add(receivedSite);
}
}
addActivity.java
package com.example.prive.passwordsafe;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class addActivity extends AppCompatActivity {
public EditText siteInsert, passwordInsert;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toevoeg);
siteInsert = (EditText) findViewById(R.id.siteInsert);
passwordInsert = (EditText) findViewById(R.id.passwordInsert);
siteInsert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast msg = Toast.makeText(getBaseContext(), "site", Toast.LENGTH_LONG);
msg.show();
}
});
passwordInsert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast msg = Toast.makeText(getBaseContext(), "password", Toast.LENGTH_LONG);
msg.show();
}
});
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String password = passwordInsert.getText().toString();
String site = siteInsert.getText().toString();
Intent intent = new Intent(addActivity.this, MainActivity.class);
intent.putExtra("Password", password);
intent.putExtra("Site", site);
startActivity(intent);
}
});
}
}
showActivity.java
package com.example.prive.passwordsafe;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class showActivity extends AppCompatActivity {
public EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toon);
Button showButton = (Button) findViewById(R.id.showButton);
Button backButton = (Button) findViewById(R.id.backButton);
editText = (EditText) findViewById(R.id.editText);
final TextView textView = (TextView) findViewById(R.id.textView);
Bundle pickupData = getIntent().getExtras();
final ArrayList<String> passwordList = pickupData.getStringArrayList("passwordList");
final ArrayList<String> siteList = pickupData.getStringArrayList("siteList");
editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast msg = Toast.makeText(getBaseContext(), "site", Toast.LENGTH_LONG);
msg.show();
}
});
if (passwordenList != null && siteList != null) {
showButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int numberOfPasswords = passwordenList.size();
for (int i = 0; i <= numberOfPasswords; i++) {
String password;
String temporary = editText.getText().toString();
if (temporary.equals(siteList.get(i))) {
password = passwordList.get(i);
textView.setText(password);
}else{
password = "wrong input";
textView.setText(password);
}
}
}
});
}else{
return;
}
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
When you exit an Activity, all the data on it is lost. You have to persist your ArrayList in SQLite or use SharedPreferences instead.
SharedPreferences: https://developer.android.com/reference/android/content/SharedPreferences.html
SQLite: https://developer.android.com/training/basics/data-storage/databases.html

Android studio use same integer in 2 activities

i was making an android app and i need to use one integer value in 2 activities. I tried using this code but it didn't work.
//Integer Sender
Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("MyIntNameGoesHere", intValue);
startActivity(myIntent);
//Integer receiver
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
It says Cannot resolve symbol intValue and Cannot resolve symbol A and the same for B.
Here's the whole code.
MainActivity:
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int balance;
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Hide notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//Click counter
final TextView text = (TextView) findViewById(R.id.balance_text);
assert text != null;
// to retreuve the values from the shared preference
preferences = PreferenceManager.getDefaultSharedPreferences(this);
balance = preferences.getInt("balance", 0);
text.setText(balance + " $");
final ImageButton button = (ImageButton) findViewById(R.id.click_button);
assert button != null;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
balance++;
text.setText("" + balance + " $");
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("balance", balance);
editor.apply();
}
});
final Button UpgradesButton = (Button) findViewById(R.id.upgrades_button);
assert UpgradesButton != null;
UpgradesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, UpgradesActivity.class));
}
});
//Balance Integer Sender
}
}
UpgradesActivity:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
public class UpgradesActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upgrades);
//Hide notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
final Button e2u_button = (Button) findViewById(R.id.e2u_button);
assert e2u_button != null;
e2u_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
final Button back_button = (Button) findViewById(R.id.back_button);
assert back_button != null;
back_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(UpgradesActivity.this, MainActivity.class));
}
});
//TODO: Pass balance integer from MainActivity to here.
}
}
Error code:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
public class UpgradesActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upgrades);
//Receive balance from MainActivity
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("key_int", 0);
//Hide notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
final Button e2u_button = (Button) findViewById(R.id.e2u_button);
assert e2u_button != null;
e2u_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(balance >= 300){ //ERROR ON THIS LINE
}
}
});
final Button back_button = (Button) findViewById(R.id.back_button);
assert back_button != null;
back_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(UpgradesActivity.this, MainActivity.class));
}
});
//TODO: Pass balance integer from MainActivity to here.
}
}
ALL ABOVE IS ANSWERED! ---------------------------------------------------------
Now i have problems with this part of the code:
#Override
public void onClick(View v) {
if(balance >= 300){
balance -= 300;
}
if(balance < 300){
final TextView text = (TextView) findViewById(R.id.not_enough_money_text);
assert text != null;
text.setText("You do not have enough money.");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
text.setText("");
}
}, 2000);
}
}
When i click the button it says i do not have enough money but i have over 300. Please help me.
I found out what the problem was but I'm not sure how to fix it. I need to send balance back to MainActivity. Can anyone help with that?
Send the data like this -
UpgradesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, UpgradesActivity.class);
intent.putExtra("key_int", balance);
startActivity(intent);
}
});
And fetch it in onCreate() of UpgradesActivity -
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("key_int", 0);
You're using different key when sending and receiving the Int.
Change this line:
int intValue = mIntent.getIntExtra("intVariableName", 0);
To this:
int intValue = mIntent.getIntExtra("MyIntNameGoesHere", 0);

Android Eclipse - Buttons only open one after the other

I'm having a rather strange issue that I just can't solve.
I'm teaching myself Android Eclipse and I've created a very simple looking app with three buttons, 1)Facebook 2)LinkedIn and 3)Favourite Band. However, when I open the app on my phone, I can only press the buttons in order 1) --> 2) --> 3). For example, I can't open 2) unless i've already opened 1) and I can't open 3) unless I've already opened 2) etc. How can I change it so that I can open 3) first for example?
I've posted my java script below, any ideas would be great!
package tabletop.app4asli;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
MediaPlayer thesong;
Button main;
Button main2;
Button main3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
main = (Button) findViewById(R.id.btn_go);
main.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = "https://www.facebook.com/asli.akidil?fref=ts";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
main2 = (Button) findViewById(R.id.button2);
main2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = "https://www.linkedin.com/pub/asli-akidil/8a/719/55a.";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
main3 = (Button) findViewById(R.id.button3);
main3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = "http://www.biffyclyro.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
It's because the code for the layout of button 2 is included in the onClick event of your button 1, and the layout of button 3 is included in the onClicked event of your button 2.
The code of onCreated() function should be looked like follows:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
main = (Button) findViewById(R.id.btn_go);
main.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = "https://www.facebook.com/asli.akidil?fref=ts";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
main2 = (Button) findViewById(R.id.button2);
main2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = "https://www.linkedin.com/pub/asliakidil/8a/719/55a.";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
main3 = (Button) findViewById(R.id.button3);
main3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = "http://www.biffyclyro.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
}
You are setting ClickListener for button 3 in the ClickListener of button 2 and ClickListener for button 2 in the ClickListener of button 1. So, button 2 and 3 won't initialize until button 1 and 2 are clicked respectively. You can set OnClickListener to all Buttons in a for loop like this:
ArrayList<Button> buttonList = new ArrayList<Button>();
buttonList.add((Button) findViewById(R.id.button1));
buttonList.add((Button) findViewById(R.id.button2));
buttonList.add((Button) findViewById(R.id.button3));
ArrayList<String> urlList = new ArrayList<String>();
urlList.add("https://www.facebook.com/asli.akidil?fref=ts");
urlList.add("https://www.linkedin.com/pub/asli-akidil/8a/719/55a.");
urlList.add("http://www.biffyclyro.com");
for (int i = 0; i < buttonList.size(); i++) {
final int index = i;
final Button button = buttonList.get(index);
final String url = urlList.get(index);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
}

Categories

Resources