how to pass a data between two activities without intent - android

i have a spinner and a button for registration. the spinner works as...
typeofcompany.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
ba = typeofcompany.getSelectedItem().toString();
typeofcompany.getItemAtPosition(i);
sss = companycode.get(i);
SelectType(companycode.get(i));
sessionmanager.tosaveRegionName(sss);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
when i select an item of the spinner,that item should be passed inside the button's Activity.
i have used the bundle method for the same
like
Intent intent = new Intent(MainActivity.this, CustRegActivity.class);
intent.putExtra("spinneritem", abc);
startActivity(intent);
but this startActivity(intent) is directly getting me inside the the second activity. i just want to send the data withour intent how can i do that....

You can make use of shared preferences. In my case i usually use TinyDB which is very easy to use.
go ahead and sync this statement in your gradle
compile 'com.mukesh:tinydb:1.0.1'
Usage is quite simple.
Just create a new instance of tinyDB and pass the application context. This way
TinyDB tinyDB = new TinyDB(getApplicationContext());
initiate it in the onCreate, then store data this way :
tinyDB.putString("spinneritem", abc);
You can retrieve this string from any activity in the app. In the activity you want to get the data declare a new instance of TinyDB once more just as shown above and retrieve the data stored in the following way:
tinyDB.getString("spinneritem");
You can store all variable types this way, whether its int,boolean or even arrays and objects.

you can add a method to the second activity like this
public void setSpinnerItem(String abc){
.....
}
to set a variable(or static variable) to save the content,
then call it in onItemSelected in the first activity
or better
add a observer interface in first activity with a method called onSpinnerItemSelected(String abc), then set the observer in the second activity.
you can also save the data in the first activity in sp, sqlitedb, or simply in a data class's instance variables, then get them in the second activity

Related

How to pass value via Intent form 1st activity to third?

I need to pass some value from 1st activity into the third. I already pass it form 1st to 2nd like this.
my 1st activity: (I do it in on create method)
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(DisplayRecepit.this, DisplayLogs.class);
intent.putExtra("recepitID", receiptList.get(position).getId());
startActivity(intent);
}
});
And I recieved it in 2nd activity like this: (I do it in on create method)
final long forwardedId = (long) getIntent().getExtras().get(String.valueOf("recepitID"));
List<Logs> logsList = new Select().from(Logs.class).where("Receipt = " + forwardedId).execute();
Now I need somehow pass it from 2nd activity to my third activity.
In my 2nd activity I have a button that takes me to 3rd activity.
I saw some examples on web but I didn't make my app working, so any help is welcome.
Question: I have pass value via intent from 1st activity to 2nd activity. How should I pass this same value from 2nd activity to my 3rd activity?
In your second activity pass this value using intent
Intent i = new Intent(getApplicationContext, Third.class);
i.putExtra("forwardedId",forwardedId);
startActivity(i)
First you have to pass data to 2nd Activity.then you can pass from 2nd to 3rd Activity.
Using default android mechanism its not possible. Still if you cant to achieve this you can use Eventbus : "https://github.com/greenrobot/EventBus" where you post message (can be anything a string, integer, even a class pojo with arrylist) from first activity and catch it anywhere.
Go to above mentioned link add the dependency in your app level build.gradle and sync it.
Create this event Pojo :
public class SomeEvent {
private ArrayList<String> message;
public SomeEvent(ArrayList<String> message) {
this.message = message;
}
public ArrayList<String> getMessage() {
return message;
}
}
Activity 1 :
in onResume() do this :
EventBus.getDefault().register(this);
in onDestroy() do this :
EventBus.getDefault().unregister(this);
to post an event :
Do this only after Eventbus registration.
EventBus.getDefault().post(new SomeEvent(some arraylist);
Now in Activity 3:
just write this method. Don't call it explicitly. Eventbus handles that internally. Make sure the argument of this method is your event class which you post in Eventbus.
public void onEvent(SomeEvent event){
// you got your arraylist which you posted from Activity 1;
ArrayList<String> list = event.getMessage();
}

how to link a new activity in android studio using a clickable text

Please how do I link a new activity from my main activity using a clickable text. I have set the text to clickable from my main.xml but I don't know how to call the new activity from my MainActivity.java class. I know I have to use this code "textView.setOnClickListener(new View.OnClickListener());" I found in a similar question, but I don't know how and where to place it on my MainActivity.java class so that it calls a the next activity I named display
Check out Intent. You use these to start new activities or services within your application.
You're correct in that you have to assign an OnClickListener interface to your text, after you made it clickable. In the interface's onClick() method you would need to do something like this.
For example:
#Override
public void onClick(View v) {
// Create the intent which will start your new activity.
Intent newActivityIntent = new Intent(MainActivity.this, NewActivity.class);
// Pass any info you need in the next activity in your
// intent object.
newActivityIntent.putExtra("aString", "some_string_value");
newActivityIntent.putExtra("anInteger", some_integer_value);
// Start the new activity.
startActivity(newActivityIntent);
}
In the next activity, you can retrieve the intent used to start it, so that you'll have access to the data you passed from the first activity, like so:
#Override
public void onCreate(Bundle savedInstanceState) {
// Get the intent that started this activity.
Intent startingIntent = getIntent();
// Retrieve the values.
String aString = startingIntent.getStringExtra("aString");
Integer anInteger = startingIntent.getIntExtra("anInteger", 0); // 2nd param is the default value, should "anInteger" not exist in the bundle.
// Use the values to your hearts content.
}
Hope that helps.

Pass data between Activitys before start the new activity

I am trying to pass some data to another activity, but I need pass the data when I click in a button , but not start the new activity and when i have multiple past data, launch the new activity and see all the content that I have passed before.
The process is similar to a shopping cart, add products and then another activity you see the list of the cart.
I have been trying with SharePrerences, but I only pass one data.
final SharedPreferences mSettings = this.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = mSettings.edit();
editor.putString(NOMBRE_TAG, tvNotas.getText().toString());
editor.putString(PRECIO_TAG, pantalla.getText()+"");
editor.commit();
with putExtra I do not think it works, because I dont know how much data I will pass
Intent intent = new Intent(this, NAME.class);
intent.putextra("SOMETHING","value");
startActivity(intent);
String data = getIntent().getExtras().getString("SOMETHING");
And i dont know other forms to do it.
The process is similar like
when you use shared preference every "key" like your tags(NOMBRE_TAG,PRECIO_TAG)
will save only one item.
which mean, everytime you save item with this keys it will replace the old items.
i recommender using SQLITE database.
here some example how to start:
Android SQLite Example
You could use a static class, or singleton? This way you can put whatever you want in it from the first activity and retrieve it from the second activity. The only drawback is that it will not survive an application restart.
Use putParcelableArrayList to pass all the data as a array list ---
#Override
public void onSaveInstanceState(final Bundle outState) {
outState.putParcelableArrayList("data", myData);
super.onSaveInstanceState(outState);
}
Then to get this data just use ----
ArrayList<String> myData = new ArrayList<String>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
if (savedInstanceState != null) {
try
{
myData = savedInstanceState.getParcelableArrayList("data");
}
}
myData.add(0, tvNotas.getText().toString());
myData.add(1, pantalla.getText()+"");
}

Sending data from one tab to another which contains a spinner

I want to send data from one tab to another. The one which will receive the data contains a spinner. When that data is passed on, I want to the spinner to change its selection to the one given within the data (it'll be the same as one of the spinner items).
Any ideas how I can use Bundle to do this?
is this in same activity or in a new activity ?
Same activity:
make an onClickListener and change the items in the spinner.
New Activity:
use
Inten intent = new Intent(yourclassname.this, targetClassname.class);
intent.putExtra("ID",DATA);
this.startActivity(intent);
it would help if you provide some code, but for now I hope this helps
As option make array holding data for a spinner static and then create a static method in you destination activity something like this:
public static void setSpinnerData (String[] data) {
spinnerData = data;
}
Then call something like this YourActivity.setSpinnerData (myArray);
Alternativerly you can consider saving data to the application object which is the same for all activities.
You may send the data (something small like a string or an ID) using a broadcast.
In the tab where the data is generated
final Intent i = new Intent(IConstants.UPDATE_SPINNER);
i.putExtra(IConstants.DATA_UPDATE, data);
this.sendBroadcast(i)
IConstants.UPDATE_SPINNER and DATA_UPDATE are just Strings used to identify your message by the receiver. You may also put them in your main activity instead of the interface I used.
In the tab with your spinner, declare an inner class for a broadcast receiver, it can access the spinner of the outer class.
private final class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
if( IConstants.UPDATE_SPINNER.equals(intent.getAction()) ) {
final String data = intent.getIntExtra(IConstants.DATA_UPDATE, "");
// update your spinner
return;
}
// process other messages ...
}
}
Register the broadcast receiver like this, e.g. in onCreate() or onResume()
this.broadcastReceiver = new MyBroadcastReceiver();
final IntentFilter f = new IntentFilter(IConstants.UPDATE_SPINNER);
// for more actions you can add them like this:
// f.addAction(IConstants.UPDATE_ONOTHER_WIDGET);
this.registerReceiver(this.broadcastReceiver, f);
Remember to unregister in onDestroy() or onPause().
Another option would be to use a handler and send messages to the handler. However, you would need the handler, which is located in the receiver, to be accessible in the sender. This way your fragments or activities (the tabs) would be stronger coupled.

android - pass data from one activity to a list in a second activity

new to droid programming. im having a small problem that im sure is simply fixed but ive done some searching and a bunch of tutorials but cant seem to find just what i need so i figured id ask. My app has 2 activites, the first activity is just a simple form where a user enters course information(class title, professor..etc.)
the first activity passes the data which is supposed to be stored in a list in the second activity. problem is that only the first course gets stored in the list, after the first time nothing new gets added to the second activity. Can someone point me in the right direction please? thanks in advance
First Activity
public class CourseDetail extends Activity {
//Course c = new Course();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button save=(Button)findViewById(R.id.save);
save.setOnClickListener(onSave);
}
private View.OnClickListener onSave=new View.OnClickListener() {
public void onClick(View v) {
EditText course=(EditText)findViewById(R.id.course);
EditText professor=(EditText)findViewById(R.id.professor);
EditText location=(EditText)findViewById(R.id.location);
EditText officehrs=(EditText)findViewById(R.id.officehrs);
Intent i=new Intent(CourseDetail.this, CourseList.class);
i.putExtra("myCourse", course.getText().toString());
i.putExtra("myProfessor", professor.getText().toString());
i.putExtra("myLocation", location.getText().toString());
i.putExtra("myOfficehrs", officehrs.getText().toString());
startActivity(i);
}
};
}
Second Activity
public class CourseList extends Activity {
Button btnCourse;
List<Course> model = new ArrayList<Course>();
CourseAdapter adapter=null;
private String dCourse="";
private String dProfessor="";
private String dLocation="";
private String dOfficehrs="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.clist);
ListView list =(ListView)findViewById(R.id.courses);
adapter=new CourseAdapter();
list.setAdapter(adapter);
Course c = new Course();
Bundle extras = getIntent().getExtras();
dCourse = extras !=null ? extras.getString("myCourse") :"no value entered";
dProfessor = extras !=null ? extras.getString("myProfessor") :"no value entered";
dLocation = extras !=null ? extras.getString("myLocation") :"no value entered";
dOfficehrs = extras !=null ? extras.getString("myOfficehrs") :"no value entered";
c.setCourse(dCourse);
c.setProfessor(dProfessor);
c.setLocation(dLocation);
c.setOfficeHrs(dOfficehrs);
btnCourse =(Button)findViewById(R.id.btnCourse);
btnCourse.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
You are just getting the user entered value in CourseDetail activity and displaying the received value inside the CourseList activity, that means you are not storing these values permanently.
Go through this Android - Data Storage document.
When you move to 2nd activity i.e. CourseList activity, at that time fetch the data from the SQLite table and display the same. whenever you get new values from previous activity, at that time just update the list by adding the new data in ArrayList and make a call on adapter.notifyDataSetChanged()
Some suggestions:
Have your CourseList extend ListActivity instead of just Activity - check out some tutorials on that which should help you set things up correctly.
There seems to be a bit of confusion with how you're handling your lists - you have your model variable but don't seem to be doing anything with it. Again, have a look at a ListView tutorial (just google "android listview tutorial").
You seem to have figured out that you can use "intents" to pass information from one activity to another, but since you're only doing this in the onCreate() method, it's only happening once. Try doing this in your ListActivity's adapter once for each item.
Don't give up on Android, keep trying :-)
Some suggestion:
You have to add your object to the adapter: adapter.add(c); after you get the data.
Call adapter.notifyDataSetChanged() to notify the system that your data for the listView has been changed. Call list.invalidate() to refresh it.
I noticed that you set the button with the finish() method. Hmm, if you do so, the next time you get to CourseList Activity from CourseDetail, the adapter will be null again. No previously received data will be available. Is this what you really want?
The problem is you are not adding the newly added items to the List.So before setting adapter you have to add all your objects like
list.add(c);

Categories

Resources