Changing a Class - java

so I'm new to Android Studio and currently am coding an Othello board game app for my phone and in my first game class I open with:
public class gameClass extends AppCompatActivity implements View.OnClickListener{
private board b = new board();
And this works fine and runs the game but then I wanted to run the same code on another activity with a few alterations, so I copy and pasted the entire code from the 1st class onto the second class and then made a few modifications (including me changing the class name where appropriate) but for some reason the modifications come up on both activities when I run the program.
My question is how can I change 1 class so that it doesn't affect the other without making one of them a private class since I bring in subs from other classes and send data from class to class.
Edit: As more information is needed apparently, I'll show all the parts of code where there is the issue.
public class game2 extends AppCompatActivity implements View.OnClickListener{
private board b = new board();
....
....
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.play:
mysound.start();
b.playgame();
setboard();
current.setImageResource(R.drawable.blackothello3);
counterforWhites.setText("WHITE : " + b.count(Colour.White));
counterforBlacks.setText("BLACK : " + b.count(Colour.Black));
showPossibleMove(); // The main issue is that this subroutine works in the other activity where this is NOT called for.
break;
The code in the other class for the other activity is almost the exact same, the only exception is that the
showPossibleMove() command is not there yet when I run that activity it shows the runs this sub and it shows the possible moves in that screen when I dont want it to.

your question is not clear . If you are willing to get true answer please put your codes here to see what you have done .
Generally , if you extend one class from AppCompatActivity , you are creating an activity that must be declared in AndroidManifest.xml.However , for passing any data from one activity to another your first option is Intent.
If you asked me , I would create a new activity from wizard not copying and past.
Hope these suggestions would help you.

Related

How to get the context inside a mouse click listener

In Android Studio, developing in Java, I have the following (a somewhat minimized version of what I'm trying to do).
package com.example.japanesequiz;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
String[] hiragana = {"あ", "か"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button generate = findViewById(R.id.generate);
TextView questionText = findViewById(R.id.question_text);
RadioGroup radioGroup = new RadioGroup(this);
MainActivity ma_inst = this;
generate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Random rand = new Random();
int hir_index = rand.nextInt(2);
questionText.setText(hiragana[hir_index]);
RadioButton rb1 = new RadioButton(ma_inst);
rb1.setId(View.generateViewId());
rb1.setText("Ah");
radioGroup.addView(rb1);
RadioButton rb2 = new RadioButton(ma_inst);
rb2.setId(View.generateViewId());
rb2.setText("Ka");
radioGroup.addView(rb2);
}
});
}
}
The basic idea is that I want to have the main screen initially mostly blank, but with a button at the bottom. When tapped, it eventually show some text and a radio button group. (I haven't yet fully built out the rest, of course.)
But at this stage what I expect when I launch the app is to see the mostly blank screen, and maybe if I tap the button it will generate some text and options (that then do nothing, further implementation to come).
But the app never launches. Instead, Graddle finishes building, I get a terminal saying that it's launching the app, but it hangs and times out.
If I had to guess -- and this is a guess because I'm very new to Android development -- there is some issue with grabbing the this instance and then using it in the OnClickListener. I'm not certain what the issue is, but it's the only thing I see here that looks fishy. Also, I'm not sure how else one is supposed to add objects to the current activity from inside of the anonymous class passed into the OnClickListener since, there, a reference to this then refers to the anonymous inner class.
I know that it is possible to use a lambda instead, and that probably resolves the issue, but I want to really understand what's going on here, since it seems like it might be conceptually important for later development.
My question: If I have correctly understood this much, then how does a lambda get around this issue? If I've not correctly understood then I'd appreciate any insight, thanks!
There are many questions in one question. First, let me try to answer your title question: "How to get context inside a mouse click listener":
There are many ways, but you can consider this one (your click lisener's onClick has the signature void onClick(View view), hence you have access to view.
view.getContext()
Next, nothing wrong with these though you better migrate to view binding https://developer.android.com/topic/libraries/view-binding as butterknife is deprecated officially
Button generate = findViewById(R.id.generate);
TextView questionText = findViewById(R.id.question_text);
Next, you don't really need this trick in order to get activity in your lambda:
MainActivity ma_inst = this;
Instead and if really needed, you can always do Context context = MainActivity.this;
Lastly, I think the issue the app never launches roots into something else not related with title question you posted, unfortunately.

Changing from a non activity to an activity Android Studio

I'm currently developing a game app for my 2nd year project at uni, but i'm a little stuck on how i can move from a non-activity class to an activity. So my none activity class is a quit screen within the game (yes i know you shouldn't use quit in a game but its one of my requirements), when i click on a button i want it to take me to the activity. (which basically thanks the user for playing and then exits the app) using System.exit(0) is just going back to the last activity visited.
The screen extends my Game Screen Class which is a parent class i created, this is the code for what happens when the user touches the 'yes' button in the quit screen:
#Override
public void update(ElapsedTime elapsedTime) {
Input input = game.getInput();
List<GameTouchEvent> touchEvents = input.getTouchEvents();
if(touchEvents.size() > 0){
GameTouchEvent touchEvent = touchEvents.get(0);
if(yesButtonBound.contains((int) touchEvent.x, (int) touchEvent.y)){
System.exit(0);
}
I'm not looking for specific code answers as this is a project but any advice or hints would be very appreciated thanks!!

Which is the best way to use media player?

Just to be clear, because my question can be not so clear.
I develop Music Player app. The thing is I have MainActivity and 4 Fragments in this activity(it's not all).
In each fragment I have list of songs retrieved from device using CustomCursorAdapter(for example: first fragment - all songs, second fragment albums e.t.c.)
I already tried to use MediaPlayerSingleton
public class singletonMediaPlayer{
MediaPlayer mediaPlayer;
private static singletonMediaPlayer in = null;
private singletonMediaPlayer() { }
public static singletonMediaPlayergetInstance() {
if (in == null) {
synchronized (singletonMediaPlayer.class) {
if (in == null) {
in = new singletonMediaPlayer();
}
}
}
return instance;
}
}
But here the problem was that all playback controls I have in MainActivity(not in fragments) and have no idea how to handle previouse, next buttons. It is not a problem if media player is in fragment or activity together with ListView of songs but like this... have no idea. Plus when I tried to select item(song) from another activity it just didn't play until I press play button. Playbacks I can see it through all fragments so it's looks like this(just in case):
Plus I have 2 seperate Activities to show songs from albums and from playlists. Sooooooooooo... Finaly the question is:
How do you think it is better to build Media Player for such app (just in case, I don't need code from you). Is it better to use Music Service(which I already started to build) or maybe Singletone is better(in that case I just don't know how to perform the task with singletone for now) or maybe there is another way??? Will be great if somebody response with hint, link or just show me the way in which better to go.
Thank you in advance!
P.S.
Yep, by the way there are 3 ListViews with songs(for now) - 2 of them reusable.

Get text of textView from another activity

I am trying to get text from textview which is located in class 2 to use it in class 1 by pressing a button. I do this by sending an Intent, but i got the error of my content. That is what i am trying to send (from class 2 to class 1):
public static void intent_send(){
Intent i = new Intent();
i.putExtra("number",Integer.parseInt(text_view_current_page.getText().toString()));
class2.startActivity(i);
}
text_view_current_page is a static TextView, otherwise it has an error in this void. I call this void by pressing a button in class 1:
Class2.intent_send();
Intent i = getIntent();
Bundle b = i.getExtras();
PagerNumber = b.getInt("number");
I have an error in the line of the content definition:
i.putExtra("number",Integer.parseInt(text_view_current_page.getText().toString()));
What should i do with this textView to be able get it's text from another class by pressing a button? Should it be static or should i declare it in that class which receives an intent?
In Android activities are fully separated components and hence those cannot access each other's stuff directly. Those have their own window and view hierarchy which are private only to the owner activity itself.
Nevertheless there are a couple of ways for activities to interact with each other.
Sending data when you are starting second activity via Intent.
Utilizing Application object as a share object among all app's components.
Registering in-activity broadcast receivers by which you can send signals between activities.
My Recommendation for your case:
If in your case, the second activity should have a very close relation with the first one (e.g. accessing its view hierarchy), you could implement the second activity as a dialog or fragment not an activity.

Android Game Leader Board: Where to extends BaseGameActivity?

My activity_main_layout has 2 buttons:
//Start game on click
<Button android:id="#+id/btnStart"/>
//If not sign in Google Game play Service
//Sign in then show leader board on click
<Button android:id="#+id/btnLeader board" />
Click on btnStart to begin playing game:
btnStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Intent intent = new Intent(MainActivity.this, game_play.class);
startActivity(intent);
finish();
}
});
As you can see, class game_play is the place to play and update height score.
I'm wondering where to extends BaseGameActivity? Inside class MainActivity or game_play or both of them?
I try many times but it's not successfull.
I'm really an amateur, I expect that you give me some ideas.
Have you gone through the QuickStart Guide? This is a good place to start if you are new to developing games for Android. To answer you question, you need to access the Play Game Services from the activity that is going to handle signing in and calling game services APIs.
From your description it sounds like both your activities will need to make calls (the main activity is showing the leaderboard, and the game activity is most likely posting scores).
Extending your activity from BaseGameActivity really is not needed any longer (for an entertaining explanation watch: Death of BasegameActivity. What you do need to do is implement the two interfaces that handle initializing the GoogleAPIClient:
public class MainActivity extends Activity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
}
To implement these, refer to the samples and the doc: https://developers.google.com/games/services/android/init
You can do the same in your game activity. The application will maintain the login state between activities, so the player will not have to login twice.

Categories