I am developing an android game in which there are near about 50 levels and each level represents a single activity . E.g. Level1, Level2...Level50.
After completion of every level I am switching to LevelUpActivity where I am showing the current score and level of player along with Level Up message. On button click I am switching to next level of the game. Now my question is that how can I switch to next activity (level) when I am having the current level number?
E.g. Suppose I have cleared Level2 then I want to jump on Level3 from LevelUpActivity what are the efficient ways to do that? Currently I am getting success for this task by using Switch Case statements. But will it be working efficiently for 50 or more than that numbers to check and then switch activities accordingly?
Following code snippet shows the class definition of LevelUpActivity
public class LevelUpActivity extends Activity implements View.OnClickListener {
Button btn_continue;
TextView scoreview, levelview;
int score, level;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.level_up);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
score = bundle.getInt("score");
level = bundle.getInt("levelno");
System.out.println("Current Score = " + score);
levelview = (TextView) findViewById(R.id.levelView);
levelview.setText("Level " + level + " Completed");
scoreview = (TextView) findViewById(R.id.score);
scoreview.setText(score + "");
btn_continue = (Button) findViewById(R.id.levelbtn);
btn_continue.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.levelbtn) {
Intent i;
switch (level) {
case 1:
i = new Intent(this, Level2.class);
i.putExtra("score", score);
startActivity(i);
break;
case 2:
i = new Intent(this, Level3.class);
i.putExtra("score", score);
startActivity(i);
break;
case 3:
i = new Intent(this, Level3.class);
i.putExtra("score", score);
startActivity(i);
break;
}
}
}
}
The performance of the switch statement won't be significantly decrease with the number of statements. The switch statement will be incredibly long though.
Assuming that every level Activity is following the same interface, (i.e. they accept a "score" and nothing else), then you can instead just put all your levels in an array.
private static final Class<Activity>[] levels = [
Level1.class,
Level2.class,
Level3.class,
...
Level4.class
]
Then just retrieve them like so:
int levelNumber = someMethodToGetLevelNumber();
Class<Activity> levelClass = levels[levelNumber];
Intent i = new Intent(this, Level2.class);
i.putExtra("score", score);
startActivity(i);
Related
I have 10 cardview in a fragment, when user click on one it'll open a specific html file within the application. When I try to open this class, the apps always crash .
My MainActivity is here
2nd Activity is here
What you can do to solve your issues is, in your MainActivity's onclick method change like :
Intent i;
switch (v.getId()) {
case R.id.indonesia_card:
i = new Intent(this, Indonesia.class);
i.putExtra("isFrom", "Indonesia");
startaCtivity(i);
case R.id.mathematika_card:
i = new Intent(this, Indonesia.class);
i.putExtra("isFrom", "Mathematika");
startaCtivity(i);
case R.id.ipa_card:
i = new Intent(this, Indonesia.class);
i.putExtra("isFrom", "IPA");
startaCtivity(i);
}
Now, In your other Activity receive the intent and set data appropriately.
String from = getIntent.getStringExtra("isFrom");
if (isFrom != null) {
if (isFrom.equals("Indonesia") {
webview.loadUrl("file:///android_asset/yourfile.html");
} else if (isFrom.equals("Mathematika") {
webview.loadUrl("file:///android_asset/yourfile.html");
}else if (isFrom.equals("IPA") {
webview.loadUrl("file:///android_asset/yourfile.html");
}
}
Hope this will help you.
I'm currently doing an basic math app. The app is very basic, the player is given an easy equation to calculate. For any correct answer scores will be added to the player. If incorrect it will reset to 0. I have set 3 game difficulty-stages: Easy, Medium & Hard. To be able to play Medium-difficulty the player has to finish the Easy stage - example by setting a certain amount of points needed to be reached to open the next level.
Problem: One way I tried was to set a "lock" in the PlayActivity.java in this piece of code:
case R.id.mediumButton:
startActivity(new Intent(this, MediumActivity.class));
break;
this by simply trying to pass data of the Current Score from the EasyActivity.java and then set a limit of ex. 50p by using the if-statement. This would then prevent startActivity(new Intent(this, MediumActivity.class)); from getting executted until the points are achieved. But I couldn't get the codes correct so that I could pass Current Scores from the EasyActivity.java to Playactivity.java.
Since I got nowhere with the above I tried another approach to this problem. I tried instead to use the High Score data stored (check below). Of course this is not the full code, just showing for context to give you guys a hint of what I did. Any ideas?
case R.id.mediumButton:
int score = 50p
if (score > highscore)
startActivity(new Intent(this, MediumActivity.class));
break;
.
SOLUTION:
By using the shared preferences, which stores my highscore in the HighScoreActivity, I retrieved the data and used that with an if-statement to set a "lock" for Medium & Hard stage. This is the code I used (I also added a toast to inform the player about the conditions for the different stages):
case R.id.mediumButton:
if (storedEasyHighScore >= 150) {
startActivity(new Intent(this, MediumActivity.class));
} else {
Toast mediumButtonToast = Toast.makeText(getApplicationContext(), "LEVEL LOCKED!\nEASY-level: Min. 150p required!", Toast.LENGTH_LONG);
TextView toastMessage = (TextView) mediumButtonToast.getView().findViewById(android.R.id.message);
toastMessage.setTextColor(Color.WHITE);
toastMessage.setTextSize(20);
mediumButtonToast.show();
}
break;
case R.id.hardButton:
if ((storedEasyHighScore >= 150) && (storedMediumHighScore >= 300)) {
startActivity(new Intent(this, HardActivity.class));
}else{
Toast mediumButtonToast = Toast.makeText(getApplicationContext(), "LEVEL LOCKED!\nEASY-level: Min. 150p required.\nMEDIUM-level: Min. 300p required.", Toast.LENGTH_LONG);
TextView toastMessage = (TextView) mediumButtonToast.getView().findViewById(android.R.id.message);
toastMessage.setTextColor(Color.WHITE);
toastMessage.setTextSize(20);
mediumButtonToast.show();
}
break;
In easy activity whenever calling playActivity pass the current score.
Intent intent = new Intent(this, playActivity.class);
intent.putExtra("key",value);
startActivity(intent);
In PlayActivity.java get score and initialize it:
Intent intent = getIntent();
int score= intent.getIntExtra("key")
In PlayActivity.java, get highscore from sharedPref, set buttons Enabled(false) and set disabled button's color Color.RED:
#Override
protected void onCreate(Bundle savedInstanceState) {
....
...
SharedPreferences sharedPrefsHighScore = getSharedPreferences("Prefs_HighScore",MODE_PRIVATE);
SharedPreferences.Editor editorScore = sharedPrefsHighScore.edit();
int storedHighScore = sharedPrefsHighScore.getInt("highScore",0);
//fetching button id to work as button click
Button easyButton = (Button) findViewById(R.id.easyButton);
Button mediumButton = (Button) findViewById(R.id.mediumButton);
Button hardButton = (Button) findViewById(R.id.hardButton);
if(storedHighScore > 100) {
mediumButton.setEnabled(true);
hardButton.setEnabled(true);
} else if(storedHighScore > 50) {
mediumButton.setEnabled(true);
hardButton.setEnabled(false);
hardButton.setBackgroundColor(Color.RED);
} else {
mediumButton.setEnabled(false);
mediumButton.setBackgroundColor(Color.RED);
hardButton.setEnabled(false);
hardButton.setBackgroundColor(Color.RED);
}
....
...
.
But I think best way is making Buttons invisible in XML and then check highScore and set visibility of buttons:
if(storedHighScore > 100) {
hardButton.setVisibility(View.VISIBLE);
mediumButton.setVisibility(View.VISIBLE);
} else if(storedHighScore > 50) {
mediumButton.setVisibility(View.VISIBLE);
}
I have problems with a menu systems that I made. four buttons the all work correctly but for one button that i have made it loads the wrong activity when I click on it, but when I click on the emulator's back button then it loads the correct activity and don't want this i want it to load the correct activity
This is the code that I have write for the menu
the check_view loads the question_view where it should load the check_view
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
appointment_image_view=(ImageView)findViewById(R.id.appointment_image_view);
check_view=(ImageView)findViewById(R.id.check_view);
questions_view=(ImageView)findViewById(R.id.questions_view);
survey_view =(ImageView)findViewById(R.id.survey_view);
appointment_image_view.setOnClickListener(this);
check_view.setOnClickListener(this);
questions_view.setOnClickListener(this);
survey_view.setOnClickListener(this);
}
public void onClick(View view){
switch (view.getId())
{
case R.id.appointment_image_view:
// open
Intent appointment_intent = new Intent(this,apppointmentactivity.class);
this.startActivity(appointment_intent);
break;
case R.id.check_view:
// open
Intent Health_intent1 = new Intent(this,HealthActivity.class);
this.startActivity(Health_intent1);
case R.id.questions_view:
//open
Intent Question_Intent = new Intent(this,QuestionsActivity.class);
this.startActivity(Question_Intent);
break;
case R.id.survey_view:
Intent Survery_intent = new Intent(this,SurveyActivity.class);
this.startActivity(Survery_intent);
break;
}
}
Try to add break; at your case R.id.check_view.
You are lacking a break; after this:
case R.id.check_view:
// open
Intent Health_intent1 = new Intent(this,HealthActivity.class);
this.startActivity(Health_intent1);
I am building a login system in android and i need to accomplish the following:
save userdata on the local storage
when a user is created and i press on the button it needs to dynamically create a radiobutton with the user name and short name in it.
I have already managed to accomplish these things, but the only problem i have now is that i want to to have 2 classes, one where you register your account and the other where the radiobuttons with the user data is displayed. So my question: how can i program the calss in such a way that when i press on the register button that it creates the radiobuttons in a different class.
beneath is the code of the classes:
enter code here
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.Save:
Intent I = new Intent();
I.putExtra(
I.setClass(this, ShowUsers.class);
startActivity(I);
break;
}
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Start other Activity
switch (v.getId()) {
case R.id.create:
Intent intent = new Intent();
intent.setClass(Main.this, Register.class);
startActivity(intent);
break;
}
Bundle extras = getIntent().getExtras();
String userName;
if (extras != null) {
userName = extras.getString("editTextName,editTextPassword,editTextshortname");
// and get whatever type user account id is
}
}
}
when i click the save button it needs to create the radio button in the main class, now the question is how can i accomplish this?
If the second class is an Activity, then one solution is to send it an Intent with the data it needs to create the radio buttons. You do this by creating an Intent object, calling any of its setExtra() methods, then calling startActivity() with the Intent. Check out the Android API docs for more details.
I created a listview with diff. activity to each items. When the user click on "clock in" I would like to grab the current time/date and send that data to the webserver in quickest way possible (without going through 2 step process to confirm). This will be for secondActivity class.
UPDATE* I am planning to add a password to the time/date within the phone so the user cant change them. I prefer current time/date within the phone instead of server time because if theres no signal/reception theres no way to clock in. How can I be able to grab the current time/date within the phone?
Customer.java
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class Customer extends ListActivity
{
TextView selection;
String[] items = { "Start Trip", "Clock in", "Customer Svc",
"Independent Inspection", "Pick Up", "Log Out" };
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, items));
selection = (TextView) findViewById(R.id.selection);
}
private static final int ACTIVITY_0 = 0;
private static final int ACTIVITY_1 = 1;
private static final int ACTIVITY_2 = 2;
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
final Intent intent = new Intent();
// Set up different intents based on the item clicked:
switch (position)
{
case ACTIVITY_0:
intent.setClass(this, com.company.merrill.IntentIntegrator.class);
break;
case ACTIVITY_1:
intent.setClass(this, com.company.merrill.SecondActivity.class);
break;
case ACTIVITY_2:
intent.setClass(this, com.company.merrill.ThirdActivity.class);
break;
default:
break;
}
// Pass the item position as the requestCode parameter, so on the `Activity`'s
// return you can examine it, and determine which activity were you in prior.
startActivityForResult(intent, position);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK)
{
// Perform different actions based on from which activity is
// the application returning:
switch (requestCode)
{
case ACTIVITY_0:
// contents contains whatever the code was
String contents = intent.getStringExtra("SCAN_RESULT");
// Format contains the type of code i.e. UPC, EAN, QRCode etc...
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
// Handle successful scan. In this example
// I just put the results into the TextView
resultsTxt.setText(format + "\n" + contents);
break;
case ACTIVITY_1:
// TODO: handle the return of the SecondActivity
break;
case ACTIVITY_2:
// TODO: handle the return of the ThirdActivity
break;
default:
break;
}
}
else if (resultCode == RESULT_CANCELED)
{
// Handle cancel. If the user presses 'back'
// before a code is scanned.
resultsTxt.setText("Canceled");
}
}
the quickest way would be creating a new thread and opening a connection to the server.
Take a look to the code:
new Thread(new Runnable() {
public void run() {
URL url = new URL("http://www.example.com/?data="+System.currentTimeMillis());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//if there is no need to read the content then we close the connection
urlConnection.disconnect();
}
}).start();
Then on your server-side you've to read the $_GET['data'] variable if you're working with php.
Please consider that this solution is not ok for different timezones. I would probably rely on server-side date.
How about using Time:
Time timeToday = new Time();
timeToday.setToNow();
today = timeToday.year+"-"+ timeToday.MONTH+"-"+timeToday.monthDay;
Why rely on the time from a users device? What if I changed the time on my handset then clocked in? How are you going to handle different timezones?
Why not simply rely on server time of the webserver since you know you can depend on this and you're already making a call to the webserver?
use this to get current date and time:
private String getDateandTime() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = df.format(c.getTime());
Log.e("Activity name", "time date "+formattedDate);
return formattedDate;
}
And call this function when user clicks to button and send this to server using networking library like Volley or Retrofit.