I'm having problem in storing the intent.putExtra inside the android local database. I am creating a game like 4Pics1Word for my project. It has only 25 levels so I created 25 activities and I randomized it. After solving a particular activity, it will then be removed to the ArrayList of Classes, ArrayList<Class>. Now, I used intent.putExtra("ACTIVITY_LIST", activityList); to store the intent and to pass it to the next activity. My problem is I can't store it on local database. When I exit the game the progress is not saved, it starts again from the first level. Any suggestions? Thank you!
Here's my code in my Main Activity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
Button btnStart;
Context context;
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnStart = (Button) findViewById(R.id.btnStart);
btnStart.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// We are creating a list, which will store the activities that haven't been opened yet
ArrayList<Class> activityList = new ArrayList<>();
activityList.add(first.class);
activityList.add(second.class);
activityList.add(third.class);
activityList.add(fourth.class);
activityList.add(fifth.class);
Random generator = new Random();
int number = generator.nextInt(5) + 1;
Class activity = null;
switch(number) {
case 1:
activity = first.class;
activityList.remove(first.class);
break;
case 2:
activity = second.class;
activityList.remove(second.class);
break;
case 3:
activity = third.class;
activityList.remove(third.class);
break;
case 4:
activity = fourth.class;
activityList.remove(fourth.class);
break;
default:
activity = fifth.class;
activityList.remove(fifth.class);
break;
}
Intent intent = new Intent(getBaseContext(), activity);
intent.putExtra("ACTIVITY_LIST", activityList);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(activityList); // myObject - instance of MyObject
prefsEditor.putString("MyObject", json);
prefsEditor.commit();
startActivity(intent);
}
}
Here's my code in my first activity:
public class first extends AppCompatActivity implements View.OnClickListener{
EditText etAnswer;
Button btnGo;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
etAnswer = (EditText) findViewById(R.id.etAnswer);
btnGo = (Button) findViewById(R.id.btnGo);
btnGo.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnGo:
String answer = etAnswer.getText().toString();
if(answer.equals("Jose Rizal") || answer.equals("jose rizal") || answer.equals("Rizal") || answer.equals("rizal") ){
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("The famous Rizal monument in Luneta was not the work of a Filipino but a Swiss sculptor named Richard Kissling?" +
"\n" +
"\n" +
"Source: http://www.joserizal.ph/ta01.html");
dlgAlert.setTitle("Did you know that ...");
dlgAlert.setPositiveButton("Next",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ArrayList<Class> activityList = new ArrayList<>();
Bundle extras = getIntent().getExtras();
activityList = (ArrayList<Class>) extras.get("ACTIVITY_LIST");
if(activityList.size() == 0) {
Context context = getApplicationContext();
CharSequence last = "Congratulations! You just finished the game! Please wait for the next update!";
int durationFinal = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, last, durationFinal);
toast.show();
} else {
// Now, the random number is generated between 1 and however many
// activities we have remaining
Random generator = new Random();
int number = generator.nextInt(activityList.size()) + 1;
Class activity = null;
// Here, we are checking to see what the output of the random was
switch(number) {
case 1:
// We will open the first remaining activity of the list
activity = activityList.get(0);
// We will now remove that activity from the list
activityList.remove(0);
break;
case 2:
// We will open the second remaining activity of the list
activity = activityList.get(1);
activityList.remove(1);
break;
case 3:
// We will open the third remaining activity of the list
activity = activityList.get(2);
activityList.remove(2);
break;
case 4:
// We will open the fourth remaining activity of the list
activity = activityList.get(3);
activityList.remove(3);
break;
default:
// We will open the fifth remaining activity of the list
activity = activityList.get(4);
activityList.remove(4);
break;
}
// Note: in the above, we might not have 3 remaining activities, for example,
// but it doesn't matter because that case wouldn't be called anyway,
// as we have already decided that the number would be between 1 and the number of
// activities left.
// Starting the activity, and passing on the remaining number of activities
// to the next one that is opened
Intent intent = new Intent(getBaseContext(), activity);
intent.putExtra("ACTIVITY_LIST", activityList);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
});
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}else{
Context context = getApplicationContext();
CharSequence text = "Wrong! Try Again.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
break;
}
}
}
Everytime you come to MainActivity , you new an ArrayList and add all the activities rather than get the cache from your local SharedPreferences .
When you finish one game in an Activity , you did not save your progress in cache.
After updating the arrayList,save your arrayList like this :
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(activityList); // myObject - instance of MyObject
prefsEditor.putString("MyObject", json);
prefsEditor.commit();
And when you want to read the arrayList saved ,do like this:
String arrayStr = mPrefs.getString("myObject","defValue");
Gson gson = new Gson();
List<Class> array = gson.fromGson(arrayStr,new TypeToken<List<Class>>(){}.getType());
if(array==null){
array = new ArrayList<>();
array.add(...);
}
Related
there is one feature in my app which is 'message us on WhatsApp' and for that, I have added 10 different numbers on firebase Remote configuration and I fetch those numbers in-app. Whenever a user clicks on the message us button, I need that user device gets one WhatsApp number (among 10 different numbers) allot for a lifetime (until factory reset of the device) of that device and like that whenever new user install the application user has to get different number among those 10 or 20 numbers. Everyone should get a different number when he or she uses the feature 'message us'. Currently, I have added as when the user clicks on 'message us', the user gets a different number every time and this creates a duplicate entry at the admin end. Admin gets the same user on different WhatsApp numbers. I know I Can use a Unique Device id to solve this problem but I don't have any idea how to work with a unique device id.
anyone, please help
public class DashBoard extends AppCompatActivity implements View.OnClickListener {
public CardView wpicon, telicon, callicon, share;
//for firebase remote config
private FirebaseStorage storage = FirebaseStorage.getInstance();
private FirebaseRemoteConfig remoteConfig = FirebaseRemoteConfig.getInstance();
TextView textView;
//Store NUmber's
public String number1;
public String number2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//firebase remote config
remoteConfig = FirebaseRemoteConfig.getInstance();
FirebaseRemoteConfigSettings firebaseRemoteConfigSettings = new FirebaseRemoteConfigSettings.Builder()
.setMinimumFetchIntervalInSeconds(0)
.build();
remoteConfig.setConfigSettingsAsync(firebaseRemoteConfigSettings);
remoteConfig.setDefaultsAsync(R.xml.mobile_number_default);
getValuesFromFirebaseConfig();
String androidId = Settings.Secure.getString(getContentResolver(),Settings.Secure.ANDROID_ID);
setContentView(R.layout.activity_dash_board);
Util.blackIconStatusBar(DashBoard.this, R.color.white);
wpicon = (CardView) findViewById(R.id.cardview1);
telicon = (CardView) findViewById(R.id.cardview2);
callicon = (CardView) findViewById(R.id.cardview3);
textView = findViewById(R.id.dummytext);
textView.setText(androidId);
wpicon.setOnClickListener(this);
telicon.setOnClickListener(this);
callicon.setOnClickListener(this);
}
private void getValuesFromFirebaseConfig() {
remoteConfig.fetchAndActivate()
.addOnCompleteListener(new OnCompleteListener<Boolean>() {
#Override
public void onComplete(#NonNull Task<Boolean> task) {
if (task.isSuccessful()) {
Log.i("DashBoard", String.valueOf(task.getResult()));
String text = remoteConfig.getString("mobile_number");
String text2 = remoteConfig.getString("mobile_number_2");
// list.add(text);
// list.add(text2);
number1 = text;
number2 = text2;
} else {
Toast.makeText(DashBoard.this, "Fetch Failed", Toast.LENGTH_SHORT).show();
}
}
}); }
#Override
public void onClick(View v) {
Intent i;
String num;
String text;
text = "Hi! sir I Need Your Service";
ArrayList<String> list = new ArrayList<>();
list.add(number1);
list.add(number2);
// Random random = new Random();
// String rando = list.get(random.nextInt(list.size()));
Random random = new Random();
String rando = list.get(random.nextInt(list.size()));
switch (v.getId()) {
case R.id.cardview1:
Intent intent = new Intent(Intent.ACTION_VIEW);
i = intent.setData(Uri.parse("http://api.whatsapp.com/send?phone=" + rando + "&text=" + text));
startActivity(i);
break;
case R.id.cardview2:
Intent intentw = new Intent(Intent.ACTION_VIEW);
i = intentw.setData(Uri.parse("http://api.whatsapp.com/send?phone=" + rando + "&text=" + text));
startActivity(i);
break;
case R.id.cardview3:
Intent intentI = new Intent(Intent.ACTION_VIEW);
i = intentI.setData(Uri.parse("http://api.whatsapp.com/send?phone=" + rando + "&text=" + text));
startActivity(i);
break;
}
}
}
I have a problem, I want to click on the list, calling a new activity and rename the button to another name.
I tried several things, nothing worked, can someone please help me?
My class EditarTimes:
private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView arg0, View arg1, int pos, long id) {
t = times.get(pos);
CadastroTimes cad = new CadastroTimes();
CadastroTimes.salvar.setText("Alterar");
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
startActivity(intent);
}
};
public class CadastroTimes extends AppCompatActivity {
private Time t;
private timeDatabase db;
private EditText edID;
private EditText edNome;
public Button salvar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cadastro_times);
edID = (EditText) findViewById(R.id.edID);
edNome = (EditText) findViewById(R.id.edNome);
db = new timeDatabase(getApplicationContext());
salvar = (Button) findViewById(R.id.btnCadastrar);
salvar.setText("Cadastrar");
String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("Alterar");
}
} else {
newString= (String) savedInstanceState.getSerializable("Alterar");
}
//button in CadastroTimes activity to have that String as text
System.out.println(newString + " AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
salvar.setText(newString);
}
public void salvarTime(View v) {
t = new Time();
t.setNome(edNome.getText().toString());
if (salvar.getText().equals("Alterar")) {
db.atualizar(t);
exibirMensagem("Time atualizado com sucesso!");
} else {
db.salvar(t);
exibirMensagem("Time cadastrado com sucesso!");
}
Intent intent = new Intent(this, EditarTimes.class);
startActivity(intent);
}
private void limparDados() {
edID.setText("");
edNome.setText("");
edNome.requestFocus();
}
private void exibirMensagem(String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
}
public class EditarTimes extends AppCompatActivity {
private Time t;
private List<Time> times;
private timeDatabase db;
private ListView lvTimes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editar_times);
lvTimes = (ListView) findViewById(R.id.lvTimes);
lvTimes.setOnItemClickListener(selecionarTime);
lvTimes.setOnItemLongClickListener(excluirTime);
times = new ArrayList<Time>();
db = new timeDatabase(getApplicationContext());
atualizarLista();
}
private void excluirTime(final int idTime) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Excluir time?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage("Deseja excluir esse time?")
.setCancelable(false)
.setPositiveButton(getString(R.string.sim),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (db.deletar(idTime)) {
atualizarLista();
exibirMensagem(getString(R.string.msgExclusao));
} else {
exibirMensagem(getString(R.string.msgFalhaExclusao));
}
}
})
.setNegativeButton(getString(R.string.nao),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.create();
builder.show();
atualizarLista();
}
private void atualizarLista() {
times = db.listAll();
if (times != null) {
if (times.size() > 0) {
TimeListAdapter tla = new TimeListAdapter(
getApplicationContext(), times);
lvTimes.setAdapter(tla);
}
}
}
private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long id) {
t = times.get(pos);
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
String strName = "Alterar";
intent.putExtra("Alterar", strName);
startActivity(intent);
}
};
private AdapterView.OnItemLongClickListener excluirTime = new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
excluirTime(times.get(pos).getId());
return true;
}
};
private void exibirMensagem(String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
public void telaCadastrar(View view) {
Intent intent = new Intent(this, CadastroTimes.class);
startActivity(intent);
}
public void botaoSair(View view) {
Intent intent = new Intent(this, TelaInicial.class);
startActivity(intent);
}
}
You can pass the button caption to CadastroTimes with intent as
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
intent.putExtra("buttontxt","Changed Text");
startActivity(intent);
Then in CadastroTimes.java set the text of the button to the new value that you passed. The code will look like:
button = (Button)findViewById(R.id.button); // This is your reference from the xml. button is my name, you might have your own id given already.
Bundle extras = getIntent().getExtras();
String value = ""; // You can do it in better and cleaner way
if (extras != null) {
value = extras.getString("buttontxt");
}
button.setText(value);
Do remember to do it in onCreate after setContentView
//From Activity
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
intent.putExtra("change_tag", "text to change");
startActivity(intent);
//To Activity
public void onCreate(..){
Button changeButton = (Button)findViewById(R.id.your_button);
// Button to set received text
Intent intent = getIntent();
if(null != intent &&
!TextUtils.isEmpty(intent.getStringExtra("change_tag"))) {
String changeText = intent.getStringExtra("change_tag");
// Extracting sent text from intent
changeButton.setText(changeText);
// Setting received text on Button
}
}
1: Use intent.putExtra() to share a value from one activity another activity, as:
In ActivityOne.class :
startActivity(
Intent(
applicationContext,
ActivityTwo::class.java
).putExtra(
"key",
"value"
)
)
In ActivityTwo.class :
var value = ""
if (intent.hasExtra("key")
value = intent.getStringExtra("key")
2: Modify button text programatically as:
btn_object.text = value
Hope this will help you
For changing the button text:
Use a static method to call from the other activity to directly modify the button caption.
Use an intent functionality, which is preferable.
Use an Interface and implement it, which is used for communicating between activities or fragment in a manner of fire and forget principle.
Now, i got you:
Your EditarTimes activity with listview:
//set setOnItemClickListener
youtListView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Intent i = new Intent(EditarTimes.this, CadastroTimes.class);
//text which you want to display on the button to CadastroTimes activity
String strName = "hello button";
i.putExtra("STRING_I_NEED", strName);
}
});
In CadastroTimes activity,
under onCreate() method, get the text string as:-
String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("STRING_I_NEED");
}
} else {
newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
//button in CadastroTimes activity to have that String as text
yourButton.setText(newString);
Ok, so the first step would be to take the button you want and make it a public static object (and put it at the top of the class).
public static Button button;
Then you can manipulate that using this in another class:
ClassName.button.setText("My Button");
In your case it is
CadastroTimes.salvar.setText("Alterar");
if you want to change value from that do not do not go the activity via intent you can use file to save value to file or you have multiple values the use database and access
the value oncreate to set the value of text....
In my case, I had to send an EditText value from a Dialog styled Activity, which then got retrieved from a Service.. My Example is similar to some of the above answers, which are also viable.
TimerActivity.class
public void buttonClick_timerOK(View view) {
// Identify the (EditText) for reference:
EditText editText_timerValue;
editText_timerValue = (EditText) findViewById(R.id.et_timerValue);
// Required 'if' statement (to avoid NullPointerException):
if (editText_timerValue != null) {
// Continue with Button code..
// Convert value of the (EditText) to a (String)
String string_timerValue;
string_timerValue = editText_timerValue.getText().toString();
// Declare Intent for starting the Service
Intent intent = new Intent(this, TimerService.class);
// Add Intent-Extras as data from (EditText)
intent.putExtra("TIMER_VALUE", string_timerValue);
// Start Service
startService(intent);
// Close current Activity
finish();
} else {
Toast.makeText(TimerActivity.this, "Please enter a Value!", Toast.LENGTH_LONG).show();
}
}
And then inside my Service class, I retrieved the value, and use it inside onStartCommand.
TimerService.class
// Retrieve the user-data from (EditText) in TimerActivity
intent.getStringExtra("TIMER_VALUE"); // IS THIS NEEDED, SINCE ITS ASSIGNED TO A STRING BELOW TOO?
// Assign a String value to the (EditText) value you retrieved..
String timerValue;
timerValue = intent.getStringExtra("TIMER_VALUE");
// You can also convert the String to an int, if needed.
// Now you can reference "timerValue" for the value anywhere in the class you choose.
Hopefully my contribution helps!
Happy coding!
Accessing view reference of another Activity is a bad practice. Because there is no guarantee if the reference is still around by the time you access it (considering the null reference risk).
What you need to do is to make your other Activity read values (which you want to display) from a data source (e.g. persistence storage or shared preferences), and the other Activity manipulates these values. So it appears as if it changes the value of another activity, but in reality it takes values from a data source.
Using SharedPreferences:
Note: SharedPreferences saves data in the app if you close it but it will be lost when it has been deleted.
In EditarTimes.java:
private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView arg0, View arg1, int pos, long id) {
t = times.get(pos);
SharedPreferences.Editor editor = getSharedPreferences("DATA", MODE_PRIVATE).edit();
editor.putString("btnText", "Your desired text");
editor.apply();
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
startActivity(intent);
}
};
In CadastroTimes.java
public Button salvar;
salvar.setText(getSharedPreferences("DATA", MODE_PRIVATE).getString("btnText", ""));
//note that default value should be blank
As far as my thoughts go, I can realize that the problem is not with the code you provided as it seems to be implemented correctly. It is possible that you have saved the activityState somewhere in your actual code and because it is not implemented properly, the savedInstanceState found in the onCreate method is not null but the required information is missing or not correct. That's why newString is getting null and salvar textview is getting blank.
Here, I need to know which one is more useful to you - information from getIntent() or from savedInstanceState? The code you provided insists me to assume that savedInstanceState has got the preference.
If you prefer savedInstanceState, then you may use SharedPreferences like this to get the same value you want:
private SharedPreferences mPrefs;
private String newString;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
........
// try to get the value of alterarValue from preference
mPrefs = getSharedPreferences("MyData", MODE_PRIVATE);
newString = mPrefs.getString("alterarValue", "");
if (newString.equals("")){
// we have not received the value
// move forward to get it from bundle
newString = getIntent().getStringExtra("Alterar");
}
// now show it in salvar
salvar.setText(newString);
}
protected void onPause() {
super.onPause();
// you may save activity state or other info in this way
SharedPreferences.Editor ed = mPrefs.edit();
ed.putString("alterarValue", newString);
ed.commit();
}
Or if you don't need to get it from savedInstanceState, please use it:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
........
// try to get the value of alterarValue from bundle
String newString = getIntent().getStringExtra("Alterar");
// now show it in salvar
salvar.setText(newString);
}
That's all I know. Hope it will help. If anything goes wrong, please let me know.
I have a task to make a simple restaurant menu app in Android. So, the home page consist of Food button and Drink button. If Food button clicked, the food menu page will appear. If Drink button clicked, the drink menu page will appear.
MainActivity.java:
int x = 1;
public int value()
{
x = 1;
return x;
}
public void clickFood(View view)
{
value();
Intent intent = new Intent(MainActivity.this, MenuList.class);
startActivity(intent);
}
public int value2()
{
x = 2;
return x;
}
public void clickDrink(View view)
{
value2();
Intent intent = new Intent(MainActivity.this, MenuList.class);
startActivity(intent);
}
MenuList.java:
mainListView = (ListView) findViewById(R.id.mainListView );
int y = 1;
if(main.x == y)
{
// List of food
fooddrink = new String[]{"Fried Chicken", "Fried Rice"};
}
else
{
// List of drink
fooddrink = new String[]{"Ice Tea", "Ice Coffee"};
}
ArrayList<String> listFoodDrink = new ArrayList<String>();
listFoodDrink.addAll( Arrays.asList(fooddrink) );
listAdapter = new ArrayAdapter<String>(this, R.layout.menu_list_row, listFoodDrink);
mainListView.setAdapter( listAdapter );
The problem, the output of ListView is always display food menu, despite I click Drink button. I find that this is because x value in MainActivity.java doesn't return the value, so the int x value always = 1.
How am I doing wrong?
This is your problem:
MainActivity main = new MainActivity();
You create a new instance of MainActivity (not the one you've "come from") where x = 1.
Make x in MainActivity, for example, static like
static int x = 1;
and use it in MenuList.java as follows:
if(MainActivity.x == y)
{ ...
But!
That is NOT how you should go in Android taking into consideration its component's lifecycle (more on that). Once MainActivity has been destroyed by the system, x, as being static, is always = 1, unless another instance of MainActivity has changed it.
So, you may use several options, one of which would be to store x value somewhere, e.g. in SharedPreferences. Another one would be to pass the value within Intent's extra as per #VVJ's answer.
You have two activities MainActivity and MenuListActivity.In MainActivity there are two buttons Food and Restaurant. You have handle click event for each as follows:
foodButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MenuList.class);
intent.putExtra("type",1);//pass 1 for food
startActivity(intent);
}
});
restaurantButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MenuList.class);
intent.putExtra("type",2);//pass 2 for Restaurant
startActivity(intent);
}
});
Now in your MenuList activity you have to take value of key "type" and based on type value pass appropriate data source to adapter.You can do something like this(in onCreate of MenuList activity):
int type=getActivity().getIntent().getExtras().getInt("type");
i(type==1)
{
// List of food
fooddrink = new String[]{"Fried Chicken", "Fried Rice"};
}
else
{
// List of drink
fooddrink = new String[]{"Ice Tea", "Ice Coffee"};
}
ArrayList<String> listFoodDrink = new ArrayList<String>();
listFoodDrink.addAll( Arrays.asList(fooddrink) );
listAdapter = new ArrayAdapter<String>(this, R.layout.menu_list_row, listFoodDrink);
mainListView.setAdapter( listAdapter );
I have a few interesting question here about how to return to latest activity if the game was restart/re-open because I have a new game button and continue button.So when continue button clicked it will return to last activity that opened before and the condition is activity is random from activityone to activityfive
I will explain with my code
this is menu.class
public class menu extends Activity {
int level;
Button newgame, continues, continuelocked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.menu);
continuelocked=(Button)findViewById(R.id.buttoncontinuelocked);
continues=(Button)findViewById(R.id.buttoncontinue);
newgame=(Button)findViewById(R.id.buttonnewgame);
newgame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
Intent i =new Intent(menu.this, intro.class);
startActivity(i);
}
});
}
public void onResume() {
super.onResume();
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
level = pref.getInt("Level", 0);
if(level == 0)
{
continuelocked.setVisibility(View.VISIBLE);
continues.setVisibility(View.GONE);
}
if(level == 1)
{
continuelocked.setVisibility(View.GONE);
continues.setVisibility(View.VISIBLE);
}
SharedPreferences.Editor editor = pref.edit();
editor.putInt("Level", level);
editor.commit();
continues=(Button)findViewById(R.id.buttoncontinue);
continues.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
//How to set this method to return to latest activity that i play before
//if i use random levelactivity?
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
and in intro.class I do this method to make activity random,
check my code below here -
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
button5 = (Button)findViewById(R.id.button5);
if(v==button5) {
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("Level", 1);
editor.commit();
// Here, we are generating a random number
Random generator = new Random();
int number = generator.nextInt(5) + 1;
// The '5' is the number of activities
Class activity = null;
// Here, we are checking to see what the output of the random was
switch(number) {
case 1:
// E.g., if the output is 1, the activity we will open is ActivityOne.class
activity = ActivityOne.class;
break;
case 2:
activity = ActivityTwo.class;
break;
case 3:
activity = ActivityThree.class;
break;
case 4:
activity = ActivityFour.class;
break;
default:
activity = ActivityFive.class;
break;
}
// We use intents to start activities
Intent intent = new Intent(getBaseContext(), activity);
startActivity(intent);
}
and in every Activity "One to Five" I put the same random activity code
#Override
public void onClick(View v) {
// Here, we are generating a random number
Random generator = new Random();
int number = generator.nextInt(5) + 1;
// The '5' is the number of activities
Class activity = null;
// Here, we are checking to see what the output of the random was
switch(number) {
case 1:
// E.g., if the output is 1, the activity we will open is ActivityOne.class
activity = ActivityOne.class;
break;
case 2:
activity = ActivityTwo.class;
break;
case 3:
activity = ActivityThree.class;
break;
case 4:
activity = ActivityFour.class;
break;
default:
activity = ActivityFive.class;
break;
}
// We use intents to start activities
Intent intent = new Intent(getBaseContext(), activity);
startActivity(intent);
}
}
So My question is
First. How to open the last Activity with a Continue button if Activity was Random?
Second. if in every Activity had a same Random code to One until Five, How to set Disabled to Activity that already Opened before?
Anyone can explain about this?
UPDATED
I have found a solution with my second answer, but i dont try it yet so i dont know it work or not
so i changed the code like this
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
button5 = (Button)findViewById(R.id.button5);
if(v==button5) {
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("Level", 1);
editor.commit();
layout7.setVisibility(View.GONE);
layout7.setVisibility(View.VISIBLE);
// Here, we are generating a random number
Random generator = new Random();
number = generator.nextInt(5) + 1;
// The '5' is the number of activities
Class activity = null;
// Here, we are checking to see what the output of the random was
switch(number) {
// E.g., if the output is 1, the activity we will open is ActivityOne.class
case 1: if(one == 1){
activity = ActivityOne.class;
}
else if(one == 2){
Random generatorone = new Random();
number = generatorone.nextInt(5) + 1;
}
break;
case 2: if(two== 1){
activity = ActivityTwo.class;
}
else if(two== 2){
Random generatortwo = new Random();
number = generatortwo.nextInt(5) + 1;
}
break;
case 3:if(three== 1){
activity = ActivityThree.class;
}
else if(three== 2){
Random generatorthree = new Random();
number = generatorthree.nextInt(5) + 1;
}
break;
case 4:if(four == 1){
activity = ActivityFour.class;
}
else if(four == 2){
Random generatorFour = new Random();
number = generatorFour.nextInt(5) + 1;
}
break;
default:if(five== 1){
activity = ActivityFive.class;
}
else if(five== 2){
Random generatorfive = new Random();
number = generatorfive.nextInt(5) + 1;
}
break;
}
// We use intents to start activities
Intent intent = new Intent(getBaseContext(), activity);
startActivity(intent);
}
};
i think, if the int was show ==2 its mean the Activity was already opened before. so it will random again till found activity with ==1
can anyone correct my code above? it is right or not?
and my first question still dont have an answer
First. How to open the last Activity with a Continue button if Activity was Random and the app was re-open/restart?
Thank you in advance, have a good day
For your first question, once you open your random Activity you can use SharedPreferences to store an ID for that Activity, and once you press your continue button, you can read this preferences, get this ID, and open the respective Activity.
For example, create an utility class to handle the SharedPreferences.
public class ActivityManager {
private static ActivityManager instance = null;
private SharedPreferences sharedPref;
private Context context_;
private final String prefName = "preferencesHandler";
public static ActivityManager getInstance(Context context) {
if (instance == null) {
instance = new ActivityManager(context);
}
return instance;
}
private ActivityManager(Context context) {
context_ = context;
sharedPref = context_.getSharedPreferences(prefName,Context.MODE_PRIVATE);
}
public void saveActivity(int ID) {
editor = sharedPref.edit();
// Key,Value
editor.putInt("activity_id",ID);
editor.commit();
}
public int getActivityID() {
// Key, Default Value
return sharedPref.getInt("activity_id",0);
}
}
And once you open each one of your random Activity, set some ID to them and save it using the class above. Then when needed, retrieve that value with getActivityID(). That should do the trick.
For more info on how to use SharedPreferences, please read this link.
EDIT: On your specific case, there's this part of your code:
// Here, we are checking to see what the output of the random was
switch(number) {
case 1:
// E.g., if the output is 1, the activity we will open is ActivityOne.class
activity = ActivityOne.class;
break;
case 2:
activity = ActivityTwo.class;
break;
case 3:
activity = ActivityThree.class;
break;
case 4:
activity = ActivityFour.class;
break;
default:
activity = ActivityFive.class;
break;
}
You can easily use that number variable as an ID. So, once you randomly get that number, you can also save it using the SharedPreferences. And when you press the continue Button, simply read that value and use a switch-case again to get the correct Activity.
I had a very similar problem before where i wanted to show random xml layouts. I've done that - with lots of help by Ben Williams - with a class named DisplayRandomPage.class and I had a main.xml layout with four buttons.
That's the code of the Main.class:
switch (view.getId()) {
case R.id.first_button:
startActivity(new Intent(this, FirstPage.class));
break;
case R.id.second_button:
startActivity(new Intent(this, SecondPage.class));
break;
case R.id.third_button:
startActivity(new Intent(this, ThirdPage.class));
break;
case R.id.random_button:
Intent intent = new Intent(this, DisplayRandomPage.class);
startActivity(intent);
and this is in the DisplayRandomPage.class:
public class DisplayRandomPage extends Activity {
private Integer [] mLinearLayoutIds = {
R.layout.one
R.layout.two,
R.layout.three
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Random random = new java.util.Random();
int rand = random.nextInt(3);
setContentView(mLinearLayoutIds[rand]);
}
}
What i'd like to do is creating a DisplaySpecificPage.class. Above I've shown my main.class with the switch-case-clause. So when i click on the first button, it will start the FirstPage.class, clicking the second, it will start SecondPage.class, and so on. So for each xml-file i have to create a new java-class although the different java-classes do all the same. Only the xml-files are different. So i'd like to put something like this:
pseudo-code:
case R.id.first_button:
startActivity(new Intent(this, DisplaySpecificPage.class)) with R.layout.first_page;
break;
how do i pass the ID from the layout (R.layout.first_page) on?
You should change your switch statement to
final Intent intent = new Intent(this, DisplaySpecificPage.class);
switch (view.getId()) {
case R.id.first_button:
intent.putExtra("mylayout", R.layout.one);
break;
case R.id.second_button:
intent.putExtra("mylayout", R.layout.two);
break;
case R.id.third_button:
intent.putExtra("mylayout", R.layout.three);
break;
case R.id.random_button:
intent.putExtra("mylayout", randomNumber);
startActivity(intent);
}
startActivity(intent);
This way you'd start the same activity no matter which button would be pressed, and inside the DisplaySpecificPage activity's onCreate method you should set the content to this passed layout:
final int layout = getIntent().getIntExtra("mylayout", R.layout.one);
setContentView(layout);
The code above passes an extra parameter to the intent when starting the DisplaySpecificPage activity, with the name: "mylayout".
Inside the DisplaySpecificPage class' onCreate method you just retrieve this extra parameter using the getIntExtra method of the passed intent (getIntent() will return it for you), and you set the content view of this DisplaySpecificPage activity to the passed layout by setContentView(layout).
You should make sure though, to always pass a valid layout identifier to that intent, otherwise you'll get exception when trying to inflate it (so randomNumber should be selected properly).
Update
With adding extras to the Intent you can parametrize your activities.
So using intent.putExtra("paramName", paramValue) you'll pass the paramValue value on the name of paramName to the activity you start by this intent.
You want to start the DisplaySpecificPage activity, but want it to have different layout based on which button you click.
So you create an intent:
final Intent intent = new Intent(this, DisplaySpecificPage.class);
Before starting the activity by calling startActivity(intent), you have to put this extra information inside the intent, so the DisplaySpecificPage activity to know which layout it should set as its content view:
So if you pressed the second button, you want the layout of your new activity to be the one defined by the two.xml inside your res/layout folder. It is referenced by as R.layout.two (which is a static int value).
intent.putExtra("mylayout", R.layout.two);
This line puts the layout's value as an extra into the intent object, and now you can start the activity, the layout reference will be passed to it.
The "mylayout" is a name you choose for your parameter. It can be anything (valid), it will be used inside the DisplaySpecificPage activity to retrieve the layout's reference. It is retrieved by this name:
final int layout = getIntent().getIntExtra("mylayout", R.layout.one);
The getIntExtra method gets the integer value from the intent which has the name "mylayout", and if it's not found, then it will return R.layout.one.
If you want to handle this case (when no parameter with name mylayout is set), you can write
final int layout = getIntent().getIntExtra("mylayout", -1);
if (layout < 0)
{
//TODO: no layout reference was passed
}
Here is my final code:
Main.class:
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void change(final View view) {
Intent intent2 = null;
final Intent intent = new Intent(this, DisplaySpecificPage.class);
switch (view.getId()) {
case R.id.first_button:
intent.putExtra("mylayout", R.layout.layout1);
break;
case R.id.second_button:
intent.putExtra("mylayout", R.layout.layout2);
break;
case R.id.third_button:
intent.putExtra("mylayout", R.layout.layout3);
break;
case R.id.random_button:
intent2 = new Intent(this, DisplayRandomPage.class);
startActivity(intent2);
}
// if the Random button was not clicked, if-condition is true.
if (intent2 == null)
startActivity(intent);
}
}
DisplaySpecificPage.class:
public class DisplaySpecificPage extends Activity{
public void onCreate(Bundle savedInstanceState) {
final int layout = getIntent().getIntExtra("mylayout", R.layout.one);
super.onCreate(savedInstanceState);
setContentView(layout);
}
}
DisplayRandomPage.class:
public class DisplayRandomPage extends Activity {
private Integer [] mLinearLayoutIds = {
R.layout.layout1,R.layout.layout2,R.layout.layout3
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Random random = new java.util.Random();
int rand = random.nextInt(mLinearLayoutIds.length);
setContentView(mLinearLayoutIds[rand]);
}
}
Big thanks to rekaszeru!