Can I use 2 bundle in one Activity (Android Studio)? - java

My app is a quiz app with two levels, so I have 3 Activities:
"beginner level", "advance level" and "result".
I want the "result" Activity to take the result from the "beginner" and "advance" activities .
I try this code on "beginner" activity :
Intent in = new Intent(getApplicationContext(),resultBage.class);
in.putExtra("correct",correct);
in.putExtra("wrong",wrong);
startActivity(in);
on "advance" activity :
Intent a = new Intent(getApplicationContext(),resultBage.class);
a.putExtra("correct2",correct2);
a.putExtra("wrong2",wrong2);
startActivity(a);
on "result" activity :
Bundle bundel = getIntent().getExtras();
if(bundel != null){
int correct = bundel.getInt("correct",0);
int wrong = bundel.getInt("wrong",0);
corText.setText("correct = "+correct);
wrongTex.setText("wrong = "+wrong);
}
Bundle bundle2 = getIntent().getExtras();
if(bundle2 != null){
int correct2 = bundle2.getInt("correct2",0);
int wrong2 = bundle2.getInt("wrong2",0);
corText.setText("correct = "+correct2);
wrongTex.setText("wrong = "+wrong2);
}
The problem is it's work fine if I use just one bundle what can I do?
note : I also try StringBuffer but it's same problem
StringBuffer bcResult = new StringBuffer();
bcResult.append("Correct answers: " + beginner.correct + "\n");
StringBuffer brResult = new StringBuffer();
brResult.append("Wrong Answers: " + beginner.wrong + "\n");
corText.setText(bcResult);
wrongTex.setText(brResult);

You can't get extra data from one activity into a 3-level activity like you're trying to do. You can use shared preferences to save the data in one activity and then access any other activity you wish.
BTW, you can achieve in the following way what you're looking for.
You have to pass data from one activity to another and then another into the next including the data from 1st activity.
In your 2nd activity, you have to do like this:
Bundle bundel = getIntent().getExtras();
if(bundel != null){
int correct = bundel.getInt("correct",0);
int wrong = bundel.getInt("wrong",0);
corText.setText("correct = "+correct);
wrongTex.setText("wrong = "+wrong);
}
Intent a = new Intent(getApplicationContext(),resultBage.class);
a.putExtra("correct",correct);
a.putExtra("wrong",wrong);
a.putExtra("correct2",correct2);
a.putExtra("wrong2",wrong2);
startActivity(a);

This doesn't work due to the same non-null Bundle being returned in both cases. You should use Bundle.containsKey to check which keys are present to figure out which of the two sets of parameters is being passed.

Bundle bundel = getIntent().getExtras();
if(bundel != null){
int correct = bundel.getInt("correct",0);
int wrong = bundel.getInt("wrong",0);
int correct2 = bundle2.getInt("correct2",0);
int wrong2 = bundle2.getInt("wrong2",0);
if(correct !=null && wrong !=null){
corText.setText("correct = "+correct);
wrongTex.setText("wrong = "+wrong);}else{
corText.setText("correct = "+correct2);
wrongTex.setText("wrong = "+wrong2);}
}

Related

Android studio. Bundle returns only the last value from selected

I have a listView with custom adapter, where I have an checkBox and TextView, and when I select some CheckBoxes, I'm adding them into bundle and send into another fragment. In that fragment I have a simple TextView, where I need to get the value from bundle and show in that TextView. But the problem is, that when I'm getting the selected values from bundle and set in TextView, it shows only the last value. How can i solve this? Thank you.
Here the fragment where I'm adding the selected values into bundle.
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<Profession> professionList = dataAdapter.getProfessionList();
ArrayList<String> getProfessions = new ArrayList<>();
personalInfoFragment = new PersonalInfoFragment();
for (int i = 0; i < professionList.size(); i++) {
Profession profession = professionList.get(i);
if (profession.isSelected()) {
getProfessions.add(profession.getName());
Bundle setProfessions = new Bundle();
setProfessions.putStringArrayList("String", getProfessions);
personalInfoFragment.setArguments(setProfessions);
}
}
replaceFragment();
}
});
Ok watch here. the PersonalInfoFragment is the fragment where i need to send the values. And the replaceFragment method replaces the fragment. I done debug and I'm adding the selected values into bundle successfully.
On nextButton click it saves the selected data into bundle and replaces the fragment.
Now here's the fragment where I need to get the bundle and show in textView.
Bundle bundle = getArguments();
if (bundle != null) {
ArrayList<String> getProfessionName = bundle.getStringArrayList("String");
if (getProfessionName != null) {
for (int i = 0; i < getProfessionName.size(); i++) {
profession_text.setTextColor(Color.BLACK);
profession_text.setText(getProfessionName.get(i) + ",");
}
}
}
ProfessionText is my textView where I need to set the values. But in that textView shows only the last item from bundle. How to fix this? Thank you for reading.
You can change your code like,
for (int i = 0; i < professionList.size(); i++) {
Profession profession = professionList.get(i);
if (profession.isSelected()) {
getProfessions.add(profession.getName());
}
}
Bundle setProfessions = new Bundle();
setProfessions.putStringArrayList("String", getProfessions);
personalInfoFragment.setArguments(setProfessions);
replaceFragment();
And in next fragment,
profession_text.setTextColor(Color.BLACK);
profession_text.setText("");
if (getProfessionName != null) {
for (int i = 0; i < getProfessionName.size(); i++) {
String txt = profession_text.getText().toString() + getProfessionName.get(i) + ", ";
profession_text.setText(txt);
}
}
From what i can see..u need a list of values to be displayed right..what is happening here is on each iteration you set a new value for professional text which overwrites the one that was there previously..thats why you are seeing the last value..i think if you want a list of textviews you have to create a new textview in the loop..which in this case you are better off using a listview or recycler view.

How to show google profile name in another activity

Hello i am building one app which will take google profile name and then it will be displayed in another activity as EditText.
ActivityGoogle
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String personPhotoUrl = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
textView_name.setText(personName);
textView_email.setText(email);
// by default the profile url gives 50x50 px image only
// we can replace the value with whatever dimension we want by
// replacing sz=X
personPhotoUrl = personPhotoUrl.substring(0,
personPhotoUrl.length() - 2)
+ 400;
new LoadProfileImage(imageView_profile_image).execute(personPhotoUrl);
} else {
Toast.makeText(getApplicationContext(),
"Person information is null", Toast.LENGTH_LONG).show();
any idea how to take name from this and display it in EditText
ActivityUser
profilename = (EditText)findViewbyId(R.id.profilename);
(I posted it as a comment but I think it solved the issue, so I post it as answer and add some explanation)
Have a look at these links : 1 2 3. A Bundle is exactly what you need.
This code is taken from one of the links and it's what you need. It saves a value on the Bundle:
ActivityGoogle
Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value); // <-- key is the same
Then, on your ActivityUser add the following (note that key variable must be the same in both Activity):
ActivityUser
String value = getIntent().getExtras().getString(key); // <-- as the key here

How to pass a string Arraylist from one activity to another?

Now I tried to use intent extra's to pass and receive through bundle string array list but for some reason the list never passes, when I try to use get(0) to retrieve the first string from the list I get a null pointer error, can someone please help me on this?
First Activity (signup activity):
public static final String string_array = "geoquiz.android.bignerdranch.com.string_array";
final ArrayList<String> myStringArray = new ArrayList<>();
myStringArray.add(username.getText().toString());
myStringArray.add(firstName.getText().toString());
myStringArray.add(lastName.getText().toString());
Intent i = new Intent(signUpActivity.this,loginActivity.class);
i.putExtra("string_array", myStringArray);
startActivity(i);
Second Activity (login activity):
final Bundle stringArrayList = getIntent().getExtras();
final ArrayList<String> stringArray = new ArrayList<> ();
stringArray = stringArrayList.getStringArrayList("string_array");
if(username.getText().toString().equals(stringArray.get(0)))
Toast.makeText(loginActivity.this, "You have successfully logged in!", Toast.LENGTH_SHORT).show();
Instead of i.putExtra() use i.putStringArrayListExtra().
Also, add a log entry to make sure the array is populated as you expect.
Log.i("myStringArray", myStringArray.toString());
Intent i = new Intent(signUpActivity.this,loginActivity.class);
i.putStringArrayListExtra("string_array", myStringArray); //modified
startActivity(i);
Also, take out final in this code:
final Bundle stringArrayList = getIntent().getExtras();
//final ArrayList<String> stringArray = new ArrayList<> (); //no need for this line
ArrayList<String> stringArray = stringArrayList.getStringArrayList("string_array"); //just declare and assign
See documentation here
I think that you get wrong the arrayList from the intent in second activity:
Intent intent = getIntent();
ArrayList<String> stringArray = intent.getStringArrayListExtra("string_array");

How to check for null on an object and then move on if it is NULL?

In Java, what is the best way to check if an object has value or is returning null? Most examples I have found are not very good. Basically I have this code:
mDBApi.getSession().setAccessTokenPair(reAuthTokens);
System.out.println(reAuthTokens);
if(reAuthTokens.equals(null)) {
mDBApi.getSession().startAuthentication(Main.this);
Log.e(TAG, "Keys not set -- I'm starting authentication");
}
I'm trying to get reAuthTokens to be checked for value and if it has none, move on and authenticate. However, I just get a NullPointerException on the if statement line. Is there something I can do better?
____________OnCreate for rcook________________________
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
//AccessTokenPair tokens=null;
//AccessTokenPair tokens = getStoredKeys();
//System.out.println(access + "here I am");
//clearKeys();
//Log.e(TAG, "keys cleared");
AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys, ACCESS_TYPE);
mDBApi = new DropboxAPI<AndroidAuthSession>(session);
AccessTokenPair reAuthTokens = new AccessTokenPair(APP_KEY, APP_SECRET);
mDBApi.getSession().setAccessTokenPair(reAuthTokens);
System.out.println(reAuthTokens);
if(reAuthTokens == null) {
mDBApi.getSession().startAuthentication(Main.this);
Log.e(TAG, "Keys not set -- I'm starting authentication");
}
//
/*read settings*/
mSettings = getSharedPreferences(PREFS_NAME, 0);
boolean hide = mSettings.getBoolean(PREFS_HIDDEN, false);
boolean thumb = mSettings.getBoolean(PREFS_THUMBNAIL, true);
int space = mSettings.getInt(PREFS_STORAGE, View.VISIBLE);
int color = mSettings.getInt(PREFS_COLOR, -1);
int sort = mSettings.getInt(PREFS_SORT, 3);
mFileMag = new FileManager();
mFileMag.setShowHiddenFiles(true);
mFileMag.setSortType(sort);
if (savedInstanceState != null)
mHandler = new EventHandler(Main.this, mFileMag, savedInstanceState.getString("location"));
else
mHandler = new EventHandler(Main.this, mFileMag);
mHandler.setTextColor(color);
mHandler.setShowThumbnails(thumb);
mTable = mHandler.new TableRow();
/*sets the ListAdapter for our ListActivity and
*gives our EventHandler class the same adapter
*/
mHandler.setListAdapter(mTable);
setListAdapter(mTable);
/* register context menu for our list view */
registerForContextMenu(getListView());
mStorageLabel = (TextView)findViewById(R.id.storage_label);
mDetailLabel = (TextView)findViewById(R.id.detail_label);
mPathLabel = (TextView)findViewById(R.id.path_label);
mPathLabel.setText("path: /sdcard");
updateStorageLabel();
mStorageLabel.setVisibility(space);
mHandler.setUpdateLabels(mPathLabel, mDetailLabel);
/* setup buttons */
int[] img_button_id = {R.id.help_button, R.id.home_button,
R.id.back_button, R.id.info_button,
R.id.manage_button, R.id.multiselect_button,
R.id.dropbox_button
};
int[] button_id = {R.id.hidden_copy, R.id.hidden_attach,
R.id.hidden_delete, R.id.hidden_move};
ImageButton[] bimg = new ImageButton[img_button_id.length];
Button[] bt = new Button[button_id.length];
for(int i = 0; i < img_button_id.length; i++) {
bimg[i] = (ImageButton)findViewById(img_button_id[i]);
bimg[i].setOnClickListener(mHandler);
if(i < 4) {
bt[i] = (Button)findViewById(button_id[i]);
bt[i].setOnClickListener(mHandler);
}
}
Intent intent = getIntent();
if(intent.getAction().equals(Intent.ACTION_GET_CONTENT)) {
bimg[5].setVisibility(View.GONE);
mReturnIntent = true;
} else if (intent.getAction().equals(ACTION_WIDGET)) {
Log.e("MAIN", "Widget action, string = " + intent.getExtras().getString("folder"));
mHandler.updateDirectory(mFileMag.getNextDir(intent.getExtras().getString("folder"), true));
}
}
Use if (reAuthTokens == null)) instead. You're not trying to compare contents of objects; you're trying to compare references. "is reAuthTokens points to the same address as null?"
EDIT following updates from OP: reAuthTokens is of type AccessTokenPair (and I'm betting many readers initially thought this to be a List... I know I did). It is instantiated in this line:
AccessTokenPair reAuthTokens = new AccessTokenPair(APP_KEY, APP_SECRET);
Which is why the following condition will always be false: reAuthTokens == null. That's why, when coding if (reAuthTokens == null), you get a "dead code" warning: the compiler knows that this condition can never be true, as you instantiate reAuthTokens a few lines above.
So, the type of comparison you're after is not about reference, but about content. You want to check whether reAuthTokens is "empty". But that doesn't make sense from the code you had quoted. How come you instantiate the object, and then want to check if it's "empty"?
I think your logic isn't right. You should first obtain the access token pair from where you expect it to be (the session?), and compare the result to null. Something like this:
AccessTokenPair reAuthTokens = mDBApi.getSession().getAccessTokenPair();
if (reAuthTokens == null) {
reAuthTokens = new AccessTokenPair(...);
mDBApi.getSession().setAccessTokenPair(reAuthTokens);
}

creating an object in java

i have a simple doubt in android programming. I am not familiar with java coding.so it might be a simple problem.
In the first two lines I am retrieving an array, which i passed from another activity to this activity...Then i am creating an array list . I am creating an object in the 4th line. Now comes the problem ...
I have to run a for loop to get the url value, which i have to pass it in the BaseFeedParser class. but i cant use the 4th line, i.e creating the object inside the loop because it will create a new object each time... which should not happen ... how can i fix this probelm?
Intent myintent = getIntent();
String[] ActiveURL = myintent.getStringArrayExtra("URL");
List<String> titles = new ArrayList<String>();
BaseFeedParser parser = new BaseFeedParser(url);
// fetching all active URLs
for (int i = 0; i < ActiveURL.length + 1; i++) {
url = ActiveURL[i];
messages.addAll(parser.parse());
}
// now getting the titles out of the messages for display
for (Message msg : messages) {
titles.add(msg.getTitle());
}
Thanks in advance ...
There are some problems in your java code :
Intent myintent = getIntent();
//variables are named in camel case, starting with a lower case letter
String[] activeURL = myintent.getStringArrayExtra("URL");
List<String> titles = new ArrayList<String>();
//we will use parser later, see below
//BaseFeedParser parser = new BaseFeedParser(url);
// fetching all active URLs
//it's very easy to loop through a table in java / C / C++
//learn the pattern, it's the simplest, you got confused with the final index
for (int i = 0; i < activeURL.length ; i++) {
//here you don't change the former object url was referencing,
//you are saying that you give the name url to another object in the array
//it doesn't create any new item, change giving them a name to use them
url = activeURL[i];
//create a new parser for each url, except if they can be recycled
//i.e they have a property setUrl
messages.addAll( new BaseFeedParser(url).parse());
}
// now getting the titles out of the messages for display
for (Message msg : messages) {
titles.add(msg.getTitle());
}
Indeed, you could even shorten the whole thing by
Intent myintent = getIntent();
String[] activeURL = myintent.getStringArrayExtra("URL");
List<String> titles = new ArrayList<String>();
// fetching all active URLs
//use a for each loop
for ( String url : activeURL ) {
//loop through messages parsed from feed to add titles
for (Message msg : new BaseFeedParser(url).parse() ) {
titles.add(msg.getTitle());
}
}
if you don't need the List of Message you called messages.

Categories