How can I transfer integer value from one activity to another? - java

i'm trying to compile 4 integers from 4 different activities. the first activity is one of the 4 integer. the second activity is where i compile them.. I don't know what's the best way to send a value from different activites. Most of the intent methods i saw uses startActivity but still won't work.
public class QuizSecond extends AppCompatActivity implements View.OnClickListener{
TextView totalQuestionsTextView2;
TextView questionTextView2;
Button ansA2, ansB2, ansC2, ansD2;
Button submitBtn2;
int score= 0;
int totalQuestion2 = QuestionAnswer2.question2.length;
int currentQuestionIndex2 = 0;
String selectedAnswer2 = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_second);
totalQuestionsTextView2 = findViewById(R.id.total_question2);
questionTextView2 = findViewById(R.id.question_preview);
ansA2 = findViewById(R.id.ans_A2);
ansB2 = findViewById(R.id.ans_B2);
ansC2 = findViewById(R.id.ans_C2);
ansD2 = findViewById(R.id.ans_D2);
submitBtn2 = findViewById(R.id.submit_btn2);
ansA2.setOnClickListener(this);
ansB2.setOnClickListener(this);
ansC2.setOnClickListener(this);
ansD2.setOnClickListener(this);
submitBtn2.setOnClickListener(this);
totalQuestionsTextView2.setText("Total questions : "+totalQuestion2);
loadNewQuestion();
}
#Override
public void onClick(View view) {
ansA2.setBackgroundColor(Color.WHITE);
ansB2.setBackgroundColor(Color.WHITE);
ansC2.setBackgroundColor(Color.WHITE);
ansD2.setBackgroundColor(Color.WHITE);
Button clickedButton = (Button) view;
if(clickedButton.getId()==R.id.submit_btn2){
if(selectedAnswer2.equals(QuestionAnswer2.correctAnswers2[currentQuestionIndex2])) {
score++;
}
currentQuestionIndex2++;
loadNewQuestion();
Intent quizIntent = new Intent(QuizSecond.this,ComputeActivity.class);
quizIntent.putExtra("EXTRA_NUMBER",score);
}
else{
//choices button clicked
selectedAnswer2 = clickedButton.getText().toString();
clickedButton.setBackgroundColor(Color.MAGENTA);
}
}
void loadNewQuestion(){
if(currentQuestionIndex2 == totalQuestion2 ){
startActivity(new Intent(QuizSecond.this, ComputeActivity.class));
return;
}
questionTextView2.setText(QuestionAnswer2.question2[currentQuestionIndex2]);
ansA2.setText(QuestionAnswer2.choices2[currentQuestionIndex2][0]);
ansB2.setText(QuestionAnswer2.choices2[currentQuestionIndex2][1]);
ansC2.setText(QuestionAnswer2.choices2[currentQuestionIndex2][2]);
ansD2.setText(QuestionAnswer2.choices2[currentQuestionIndex2][3]);
}
}
second activity:
int number = getIntent().getIntExtra("EXTRA_NUMBER",0); if (number > 3){ Toast.makeText(ComputeActivity.this, "Your Message", Toast.LENGHT_LONG).show();}

Update this
Intent quizIntent = new Intent(QuizSecond.this, ComputeActivity.class);
quizIntent.putExtra("TRANSFER_NUMBER", score);
startActivity(quizIntent);

Related

Attempt to write to null Array error when passing data to main activity

I am still a beginner and this is my first post here on the forum, sorry if the format of the question is not the right one.
I have an array of Resources in a class called DatabaseTagWalk that I use to find the id of a button in the MainActivity class.
This is the class where I store the id (in the activity_main.xml file i have created 6 buttons and assigned to them the same names as down here
public class DatabaseTagWalk {
int[] iconWalkId;
public DatabaseTagWalk(){
iconWalkId = new int[6];
iconWalkId[0] = R.id.topsightswalk;
iconWalkId[1] = R.id.literarypariswalk;
iconWalkId[2] = R.id.secretpassageswalk;
iconWalkId[3] = R.id.picnictimewalk;
iconWalkId[4] = R.id.joggitwalk;
iconWalkId[5] = R.id.deluxegardenswalk;
}
}
And this is the main activity class where I look for the id of the button to set a specific text and to specify the parameters used when the button is clicked
public class MainActivity extends AppCompatActivity {
DatabaseWalks listofwalks;
DatabaseTagWalk tagWalk;
Button[] buttons;
int buttonClicked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listofwalks = new DatabaseWalks();
tagWalk = new DatabaseTagWalk();
for (int i = 0; i < listofwalks.walkList.length; i++) {
buttons[i] = (Button) findViewById(tagWalk.iconWalkId[i]);
buttons[i].setText(listofwalks.walkList[i].returnWalk());
setOnClick(buttons[i], tagWalk.iconWalkId[i]);
}
}
public void setOnClick(Button button, final int buttonTag ){
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonClicked = buttonTag;
Intent startingGame = new Intent("android.intent.action.SECONDACTIVITY");
startingGame.putExtra("buttonTag", buttonClicked);
startActivity(startingGame);
}
});
}
}
When i run the app I get the error:
"Attempt to write to null array" in the MainActivity at the line:
buttons[i] = (Button) findViewById(tagWalk.iconWalkId[i]);
You did not initialize your buttons list. You told that this variable exist, but you did not assign any value.
Change your line:
Button[] buttons;
to (if you know size - e.g. 10):
Button[] buttons = new Button[10];
or if wyou would like base on walkList size:
// After this line
listofwalks = new DatabaseWalks();
// Add new line, because here you know the list size
buttons = new Button[listofwalks.walkList.length];

Opening another activity based on number of filled editTexts

The app has a MainActivity with 6 editText fields, and a button. There are 5 more activities, named Activity2, Activity3, etc. Now, When a user enters names in editText fields, and press a button, the app should find out how many editText fields are filled, and open the activity with a corresponding number in it's name.
Example:
If only one field is filled, a toast should appear, saying More players.
If two fields are filled, app opens Activity2.
If three fields are filled, app opens Activity3, etc.
Now, to the problem. I am missing something out, and can't find out what. Here is MainActivity.java
public class MainActivity extends AppCompatActivity {
private EditText editText1,editText2,editText3,editText4,editText5,editText6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.btn);
editText1 = findViewById(R.id.editText1);
editText2 = findViewById(R.id.editText2);
editText3 = findViewById(R.id.editText3);
editText4 = findViewById(R.id.editText4);
editText5 = findViewById(R.id.editText5);
editText6 = findViewById(R.id.editText6);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int filledFileds = countFilledFields();
Log.d("filled", String.valueOf(filledFileds));
Class newClass = MainActivity.class;
switch (filledFileds){
case 1:
Context context = getApplicationContext();
CharSequence text = "You need more players!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
break;
case 2:
newClass = Activity2.class;
System.out.println("Activity2");
break;
case 3:
newClass = Activity3.class;
System.out.println("Activity3");
break;
case 4:
newClass = Activity4.class;
System.out.println("Activity4");
break;
case 5:
newClass = Activity5.class;
System.out.println("Activity5");
break;
case 6:
newClass = Activity6.class;
System.out.println("Activity6");
break;
default:
}
Intent intent = new Intent(MainActivity.this, newClass);
}
});
}
private int countFilledFields() {
ArrayList<EditText> editTexts = new ArrayList<>();
editTexts.add(editText1);
editTexts.add(editText2);
editTexts.add(editText3);
editTexts.add(editText4);
editTexts.add(editText5);
editTexts.add(editText6);
int filledNumber = 0;
for(int i = 0;i < editTexts.size() ;i++){
if(editTexts.get(i).getText()!=null && !editTexts.get(i).getText().toString().matches("")){
filledNumber += 1;
}
}
return filledNumber;
}
}
The log shows the exact number, something is not working...
Here is your click listener, with the switch omitted for brevity:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int filledFileds = countFilledFields();
Log.d("filled", String.valueOf(filledFileds));
Class newClass = MainActivity.class;
switch (filledFileds){
...
}
Intent intent = new Intent(MainActivity.this, newClass);
}
The problem is at the very end: you've created an Intent object ... but you're not doing anything with it. Probably you have just forgotten a startActivity() call:
Intent intent = new Intent(MainActivity.this, newClass);
startActivity(intent);
Also, looking this over, you have a problem with the case where the user only enters one EditText. As written, you'll still try to start a new activity (you'll just start a new copy of the same MainActivity, which is probably a bad idea). A better idea would be to only start the new activity if the user fills out enough EditTexts:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int filledFileds = countFilledFields();
Log.d("filled", String.valueOf(filledFileds));
Class newClass = null;
switch (filledFileds){
...
}
if (newClass != null) {
Intent intent = new Intent(MainActivity.this, newClass);
startActivity(intent);
}
}
You're missing one thing:
startActivity(intent);

Adding two values from two different activities and displaying the total in a different activity

I Have 3 Activities : 1- ItemMenu , 2- Snooker , 3- Billiards
When i press the button in the ItemMenu Activity to calculate the total of Snooker & Billiards Activity , it just gives me the total of the last activity I've been to , i need it to give me the total of the 2 Activities combined
Here is the code of Billiards Activity :
public class Billiards extends AppCompatActivity {
EditText ebgames;
Button bsave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_billiards);
ebgames = (EditText)findViewById(R.id.ebgames);
bsave = ( Button )findViewById(R.id. bsave);
}
public void bsave (View v)
{
Double dbgames = Double.parseDouble(ebgames.getText().toString());
Double calcbgames = (dbgames)*0.50;
Double btotal = (calcbgames);
Intent btoim = new Intent(getApplicationContext(),ItemMenu.class);
btoim.putExtra("btot",btotal);
startActivity(btoim);
}
Here is the code of Snooker Activity :
public class Snooker extends AppCompatActivity {
EditText esgames;
Button ssave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snooker);
esgames = (EditText)findViewById(R.id.esgames);
ssave = ( Button )findViewById(R.id. ssave);
}
public void ssave (View v)
{
Double dsgames = Double.parseDouble(esgames.getText().toString());
Double calcsgames = (dsgames)*1.00;
Double stotal = (calcsgames);
Intent stoim = new Intent(getApplicationContext(),ItemMenu.class);
stoim.putExtra("stot",stotal);
startActivity(stoim);
}
And Here is the code of ItemMenu Activity :
public class ItemMenu extends AppCompatActivity {
Button snooker;
Button billiards;
TextView total;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_menu);
snooker = ( Button ) findViewById ( R.id. snooker ) ;
billiards = ( Button ) findViewById ( R.id. billiards ) ;
}
public void billiards (View v)
{
Intent billiards = new Intent(getApplicationContext(),Billiards.class);
startActivity(billiards);
}
public void snooker (View v)
{
Intent snooker = new Intent(getApplicationContext(),Snooker.class);
startActivity(snooker);
}
public void totcalc (View v)
{
Intent gettot = getIntent();
Double imfromb = gettot.getDoubleExtra("btot",0);
Double imfroms = gettot.getDoubleExtra("stot",0);
Double gtotal = imfromb + imfroms;
total.setText(String.valueOf(gtotal));
}
In your current version, you should get the most recent score in onCreate() each time ItemMenu starts. Then you can add it to a list or keep a running total.
Alternatively, you could start Snooker or Billiards using startActivityForResult(). Similar to my previous suggestion, you get the score in onActivityResult() and then save a list of scores, keep a running total, or whatever you wish.
For more details about returning a result from an activity, see Getting a Result from an Activity and Starting Activities and Getting Results
You can save btotal and stotal value in SharedPreferences and access it from ItemMenu Activity.

Displaying list values with each button click

How can i display list items on each button click. Lets say there are 4 names in the list. When I press next it displays the first name. Then when you press next it displays the second name and so on.
The only way I think is using the list.get() method. however I dont know how to use the method so that it knows how many values there are in the list and displaying then on each button hit. I think i need to use for method however I hadnt had any luck with it.
public class ZaidimasActivity extends ZaidejaiActivity {
public TextView mPlayer;
public TextView mKlausimas;
public Button mNext;
public Button mBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zaidimas);
/** //get the player list from ZaidejaiActivity
Bundle recdData = getIntent().getExtras();
String myVal = recdData.getString("playerList"); */
Intent zaidejuInfo = getIntent();
Bundle extrasBundle = zaidejuInfo.getExtras();
final ArrayList<String> players = extrasBundle.getStringArrayList("playerList");
//show the first players name
mPlayer = (TextView)findViewById(R.id.ZaidejoVardas);
players.size();
mPlayer.setText(players.get(0));
mNext = (Button)findViewById(R.id.KitasBtn);
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPlayer.setText(players.get(1));
}
});
mBack = (Button)findViewById(R.id.GryztiMeniuBtn);
mBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent gryztiMeniu = new Intent(ZaidimasActivity.this, ZaidejaiActivity.class);
startActivity(gryztiMeniu);
}
});
}
Here you go, maintain a variable for storing the global array index and increment it every time the button is clicked.
private int count = 0; // Global array index. Make it as class field
final ArrayList<String> players = extrasBundle.getStringArrayList("playerList");
mPlayer = (TextView)findViewById(R.id.ZaidejoVardas);
players.size();
mPlayer.setText(players.get(0));
mNext = (Button)findViewById(R.id.KitasBtn);
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
mPlayer.setText(players.get((count)%players.size())); //Incrementing global count and making sure it never exceeds the players list size
}
});

Text view if statement not working

Can anyone help me work out where I'm going wrong here. On the button click the media player plays one of the mfiles at random and I'm trying to set a textview depending on which file was played. Currently the setText if statements only match the audio playing half the time. Really not sure where I'm going wrong here.
private final int SOUND_CLIPS = 3;
private int mfile[] = new int[SOUND_CLIPS];
private Random rnd = new Random();
MediaPlayer mpButtonOne;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mfile[0] = R.raw.one;
mfile[1] = R.raw.two;
mfile[2] = R.raw.three;
//Button setup
Button bOne = (Button) findViewById(R.id.button1);
bOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final TextView textOne = (TextView)findViewById(R.id.textView1);
mpButtonOne = MediaPlayer.create(MainActivity.this, mfile[rnd.nextInt(SOUND_CLIPS)]);
if (mpButtonOne==null){
//display a Toast message here
return;
}
mpButtonOne.start();
if (mfile[rnd.nextInt(SOUND_CLIPS)] == mfile[0]){
textOne.setText("one");
}
if (mfile[rnd.nextInt(SOUND_CLIPS)] == mfile[1]){
textOne.setText("two");
}
if (mfile[rnd.nextInt(SOUND_CLIPS)] == mfile[2]){
textOne.setText("three");
}
mpButtonOne.setOnCompletionListener(new soundListener1());
{
}
So just to clarify the problem I am having is that the setText only matches the audio occasionally, not on every click. The rest of the time it displays the wrong text for the wrong audio.
You are choosing another random file
mfile[rnd.nextInt(SOUND_CLIPS)]
set that to a variable in onClick() then check against that variable in your if statement
public void onClick(View v) {
int song = mfile[rnd.nextInt(SOUND_CLIPS)];
final TextView textOne = (TextView)findViewById(R.id.textView1);
mpButtonOne = MediaPlayer.create(MainActivity.this, song);
if (song == mfile[0]){
textOne.setText("one");
}
Edit
To make it a member variable so you can use it anywhere in the class, just declare it outside of a method. Usually do this before onCreate() just so all member variables are in the same place and it makes your code more readable/manageable.
public class SomeClass extends Activity
{
int song;
public void onCreate()
{
// your code
}
then you can just initialize it in your onClick()
public void onClick(View v) {
song = mfile[rnd.nextInt(SOUND_CLIPS)];
final TextView textOne = (TextView)findViewById(R.id.textView1);
mpButtonOne = MediaPlayer.create(MainActivity.this, song);

Categories

Resources