Moving spinner items in a Bundle from one activity to another - java

I'm trying to get the value from a Spinner on my android application and convert it into a String so I can move it over as a data item in a Bundle to another activity. I have successfully managed to move EditText values over using the combination of getText().toString(); methods. I'm looking for the same result but with Spinner items now but have so far had no success.
Here's the code:
This method is called when a user selects a button in the onClick method:
public void commitData(){
Bundle bundle = new Bundle();
bundle.putString("key", txtBuildingName.getText().toString()); //Gets the TEXT that the TEXTVIEW was holding converts it to a String and adds to the Extras bundle
Bundle bundle1 = new Bundle();
bundle1.putString("key1", txtDescription.getText().toString()); // Same again
Bundle bundle2 = new Bundle();
bundle2.putString("key2", type.getItemAtPosition(type.getSelectedItemPosition()).toString());
Bundle bundle3 = new Bundle();
bundle3.putString("key3", project.getItemAtPosition(project.getSelectedItemPosition()).toString());
Intent newIntent = new Intent(this.getApplicationContext(), DataSummary.class);
newIntent.putExtras(bundle);
newIntent.putExtras(bundle1);
startActivityForResult(newIntent, 0);
}
I am getting no results from the project and type lines of code using type.getItemAtPosition().getSelectedItemPosition()).toString(); and the same for project.
Shown below is the code for the Activity that receives and output this data from the entry form.
TextView resultName;
TextView resultDescription;
TextView resultType;
TextView resultProject;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_summary);
//Check if there is anything in the 'bundle' and if not produce message - AVOIDS NULLPOINTEREXCEPTION when navigating to Activity
Bundle bundle = this.getIntent().getExtras();
if (bundle != null){
String name = bundle.getString("key");
String description = bundle.getString("key1"); //gets data from DataEntry activity
String type = bundle.getString("key2");
String project = bundle.getString("key3");
resultName=(TextView)findViewById(R.id.resultName); //adds the TextViews to the activity
resultType=(TextView)findViewById(R.id.resultType);
resultDescription=(TextView)findViewById(R.id.resultDesc);
resultProject=(TextView)findViewById(R.id.resultProject);
resultName.setText(name); // Fills the textviews with imported data
resultType.setText(type);
resultDescription.setText(description);
resultProject.setText(project);
}
else
{
Toast.makeText(DataSummary.this,"Received no data yet!", Toast.LENGTH_LONG).show();
}
}
Anyone got any ideas how to successfully gather the data from the Spinner item?

Why are you passing different bundles? On the side of your receiving Activity you are only getting the first bundle, I guess.
Try your code with these edits:
public void commitData(){
Bundle bundle = new Bundle();
bundle.putString("key", txtBuildingName.getText().toString()); //Gets the TEXT that the TEXTVIEW was holding converts it to a String and adds to the Extras bundle
bundle.putString("key1", txtDescription.getText().toString()); // Same again
bundle.putString("key2", type.getItemAtPosition(type.getSelectedItemPosition()).toString());
bundle.putString("key3", project.getItemAtPosition(project.getSelectedItemPosition()).toString());

Related

How do I pass data between multiple pages using intent (Java) in Android studio?

I want to pass data from the MainActivity to all other activities in my App. I want to let the User type her name, and then on each following page, I want her name to show up there too.
So far I only manage to let the data show up in one more acitvity.
This is the code in the feedback class, where the user will type her name/userName etc.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feedback);
}
public void thanks_Click(View view) {
EditText nmeText = findViewById(R.id.txtNme);
String nme = nmeText.getText().toString();
Intent newPage = new Intent(this, thanksActivity.class);
newPage.putExtra("USERNAME", nme);
startActivity(newPage);
And this is the code in the page where the data will be visible:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thanks);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String userName = extras.getString( "USERNAME");
TextView thanks = findViewById(R.id.idThanks);
thanks.setText("Thanks for the Quiz idea " + userName);
}
I want the variable userName to show in my other pages as well. How do I do that?
You can keep passing that attribute as Extra for every activity - but is probably easier to save in in sharedPreferences:
So, in MainActivity:
public void thanks_Click(View view) {
EditText nmeText = findViewById(R.id.txtNme);
String nme = nmeText.getText().toString();
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putString("USERNAME", nme);
editor.apply();
Intent newPage = new Intent(this, thanksActivity.class);
startActivity(newPage);
}
and every activity that wants to read that attribute:
String name = PreferenceManager.getDefaultSharedPreferences(this).getString("USERNAME", "");

Why isnt my 1 fragment recieving the values of fragment 2? I use Bundle()

I want to pass the values of 1 fragment to another fragment.
I have this code:
Fragment 1:
Fragment_score fragment_score = new Fragment_score();
Bundle bundle = new Bundle();
bundle.putInt("FINISHED_LEVELS", finishedLevels);
bundle.putInt("FAILED_LEVELS", failedLevels);
bundle.putInt("SKIPPED_LEVELS", skippedLevels);
bundle.putInt("USED_HINTS", usedHints);
fragment_score.setArguments(bundle);
Fragment 2:
Bundle bundle = getArguments();
if (bundle != null) {
finishedLevels = bundle.getInt("FINISHED_LEVELS",0);
failedLevels = bundle.getInt("FAILED_LEVELS",0);
skippedLevels = bundle.getInt("SKIPPED_LEVELS",0);
usedHints = bundle.getInt("USED_HINTS", 0);
}
But this doesnt work. I have no clue why. There is no error. But I dont recieve the values of the first fragment in the second fragment. Can anyone help me?

How to edit the values in an Activity opened by a fragment from the same fragment after it has been opened

I open the IndividualCouponsActivity from the fragment foodCouponsFragment within the parent CouponsActivity. I open the IndividualCouponsActivity with an Intent. After opening it, I want to edit the textViews and ImageViews of the IndividualCouponActivity. It should be noted that the IndividualCouponActivity is not a parent of the fragment.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Coupon coupon = foodCoupons.get(position);
Intent foodCouponsIntent = new Intent(getActivity(), IndividualCouponActivity.class);
startActivity(foodCouponsIntent);
IndividualCouponActivity activity = new IndividualCouponActivity();
activity.setValue(coupon.getCouponValue());
activity.setCompany(coupon.getCompanyName());
activity.setInfo(coupon.getDescription());
activity.setPts(coupon.getPts());
activity.setQr(coupon.getPicImageResourceId());
}
});
However, when I run the app, clicking on the listView makes the app shut down. This is what the log says at that time:
FATAL EXCEPTION: main
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference at android.support.v7.app.AppCompatDelegateImplBase.
I suspect that this is rooting from my use of the new IndividualCouponActivity activity to access the class methods. Thanks!
Don't create your activity with new...
Pass the Coupon object to your activity like this:
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putParcelable("coupon", coupon); // or putSerializable()
intent.putExtras(bundle);
intent.setClass(context, IndividualCouponActivity.class);
context.startActivity(intent);
In your activity in onCreate() you can get the passed coupon with:
getIntent().getExtras().getParcelable("coupon"); // or putSerializable()
Then set the values to your views.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Coupon coupon = (Coupon) adapterView.getItemAtPosition(position);
Intent foodCouponsIntent = new Intent(getActivity(), IndividualCouponActivity.class);
Bundle extras = new Bundle();
extras.put("value", coupon.getCouponValue());
extras.put("companyName", coupon.getCompanyName());
extras.put("description",coupon.getDescription());
extras.put("pts", coupon.getPts());
extras.put("picImageResourceId", coupon.picImageResourceId());
foodCouponsIntent.putExtras(extras);
startActivity(foodCouponsIntent);
}
});
and then in your IndividualCouponActivity's onCreate:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get reference to views...
textViewValue = (TextView) findViewById(R.id.textViewValue);
//do this for all views....
//if all objects are String values, if not you know what you have to do...
//here you get values from extras
Bundle data = getIntent().getExtras();
String value = data.getStringExtra("value");
String companyName = data.getStringExtra("companyName");
String description = data.getStringExtra("description");
String pts = data.getStringExtra("pts");
String picImageResourceId = data.getStringExtra("picImageResourceId");
//here update UI views
//example
textViewValue.setText(value);
//do this for all views....
}
maybe there is some typo mistake, but this is the solution...
You can pass data between both activities using "putExtra"
Intent intent = new Intent(getBaseContext(), IndividualCouponActivity.class);
intent.putExtra("COUPON_COMPANY_NAME", coupon.getCompanyName());
startActivity(intent);

String is null while obtaining from another class using getIntent

Right now I am have a activity screen with edittext lines that I am obtaining user input from. When I hit the create event button on the button, the event text should populate into a news feed that I have on another activity.
Here is the portion CreateEvent activity/screen code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_event);
CreateEvent_Button = (Button)findViewById(R.id.create_event_button);
WhatEvent_Text = (EditText)findViewById(R.id.what_event);
WhenEventTime_Text = (EditText)findViewById(R.id.time_event);
WhenEventDate_Text = (EditText)findViewById(R.id.date_event);
WhereEvent_Text = (EditText)findViewById(R.id.where_event);
CreateEvent_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WhatEvent_String = WhatEvent_Text.getText().toString();
WhenEventTime_String = WhenEventTime_Text.getText().toString();
WhenEventDate_String = WhenEventDate_Text.getText().toString();
WhereEvent_String = WhereEvent_Text.getText().toString();
Log.e("What: ", WhatEvent_String);
Log.e("When_Time: ", WhenEventTime_String);
Log.e("When_Date: ", WhenEventDate_String);
Log.e("Where_Event: ", WhereEvent_String);
Intent intent = new Intent(CreateEvent.this,MainActivity.class);
intent.putExtra("WhatEvent_String", WhatEvent_String);
intent.putExtra("WhenEventTime_String", WhenEventTime_String);
intent.putExtra("WhenEventDate_String", WhenEventDate_String);
intent.putExtra("WhereEvent_String", WhereEvent_String);
startActivity(intent);
MainActivity main= new MainActivity();
//make sure you call method from other class correctly
main.addEvent();
}
});
}
When the create event button is pressed, it creates an event into the MainActivity screen/activity; however, the user input is null. I am not sure why this is happening because I believe I am using the intent methods correctly.
Here is my MainActivity screen.
Here is the getIntent method in my onCreate method in my MainActivity
Intent intent = getIntent();
if (null != intent) {
test = intent.getStringExtra("WhatEvent_String");
}
However, when I call my addEvent method:
protected void addEvent() {
// Instantiate a new "row" view.
// final ViewGroup newView = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.list_row, mContainerView, false);
// Set the text in the new row to a random country.
// Because mContainerView has android:animateLayoutChanges set to true,
// adding this view is automatically animated.
//mContainerView.addView(newView, 0);
HitupEvent hitupEvent = new HitupEvent();
hitupEvent.setTitle("Rohit "+ "wants to "+test );
hitupEvent.setThumbnailUrl(roro_photo);
//hitupEvent.setRating(30);
//hitupEvent.setYear(1995);
//hitupEvent.setThumbnailUrl(null);
ArrayList<String> singleAddress = new ArrayList<String>();
singleAddress.add("17 Fake Street");
singleAddress.add("Phoney town");
singleAddress.add("Makebelieveland");
hitupEvent.setGenre(singleAddress);
hitupEventList.add(hitupEvent);
adapter.notifyDataSetChanged();
}
The event input text is null. I am not sure why this is happening.
I tried to resolve it but no luck,
How to send string from one activity to another?
Pass a String from one Activity to another Activity in Android
Any idea as for how to resolve this?!
Thanks!
Don't use Intent to get the String you put through putExtra()
Intent intent = getIntent(); // don't use this
if (null != intent) {
test = intent.getStringExtra("WhatEvent_String");
}
Instead Use Bundle, an example snippet
Bundle extra = getIntent().getExtras();
if(extra!=null){
test= extra.getString("WhatEvent_String");
}
EDIT
I noticed just now that you're calling the method main.addEvent() from the wrong place ! Call it in the MainActivity in the onCreate() method.
Remove these lines
MainActivity main= new MainActivity();
//make sure you call method from other class correctly
main.addEvent();
and in your MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourLayout);
Bundle extra = getIntent().getExtras();
if(extra!=null){
test= extra.getString("WhatEvent_String");
}
addEvent(); // call your addEvent() method here
}

Is it possible to pass a int and a string both from one activty to another , if yes then how to achive it?

I am trying to send a string and a int type data from one activity to another but due to lack of knowledge i don't know how to do it.
With the particular coding given below now i can only send any one of the data type.
searched a lot but not found any answer appropriate for my question. If i have asked any thing wrong plzz notify me as i am new to android Dev.
Any help may be appreciated.
this is my java coding of the two activities :
First.java
public class QM extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qm);
}
public void FLG(View view) {
// Do something in response to button
EditText mEditText= (EditText)findViewById(R.id.editText1);
String str = mEditText.getText().toString();
Intent intent = new Intent(this, Q1.class);
intent.putExtra("myExtra", str);
startActivity(intent);
finish();
}
}
Second.java
public class Q1 extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_q1);
Intent intent = getIntent();
if (intent.hasExtra("myExtra")){
TextView mText = (TextView)findViewById(R.id.textView1);
mText.setText("user name "+intent.getStringExtra("myExtra")+"!"); }
}
}
You can send 2 extras or even more as long you have different keys for it, so in your problem you need 2 extras one for String and one for Integer.
sample:
pass:
Intent intent = new Intent(this, Q1.class);
intent.putExtra("myExtra", str);
intent.putExtra("myExtraInt", yourInt);
get:
Intent intent = getIntent();
if (intent.hasExtra("myExtra") && intent.hasExtra("myExtraInt")){
TextView mText = (TextView)findViewById(R.id.textView1);
mText.setText("user name "+intent.getStringExtra("myExtra")+"!");
int extraInt = intent.getIntExtra(myExtraInt);
}
I'd like to give you some information.
Imagine the Intent's extras to be a (theoretically) infinitely sized bagpack. You can put certain type of data into it in an infinite number as long as each of the data has a unique name which is a string.
Internally it's a table that maps names to values.
So: Yes you can put String and Int simultaneously into the Intent's extras like this.
String str = "Test";
int val = 2933;
Intent i = new Intent(MyActivity.this, NewActivity.class);
i.putExtra("MyStringExtraUniqueName", str);
i.putExtra("MyIntExtraUniqueName", val);
To check for it use i.hasExtra("MyStringExtraUniqueName") as you did already and to get it use i.getExtra("MyStringExtraUniqueName").
BUT if you only use getExtra you'll be returned data of type object. Remember to cast the returned value to the appropriate type or use one of the specialized getter methods for some predefined data types.
See this for the available getters: http://developer.android.com/reference/android/content/Intent.html
Bundle data = new Bundle();
data.putInt("intKey", 5);
data.putString("stringKey", "stackoverflow");
Intent i = new Intent(MyActivity.this, NewActivity.class);
i.putExtras(data);
//And in the second acitvity fetch this way
Bundle data = getIntent().putExtras(b);

Categories

Resources