Storing input data, then calling it back? - java

I'm having a problem where I just don't know how to save input user data and then recall it. Let's say I want to store someone's name, so I believe I would use an Edit Text box, but that's all I can really figure out. I then later want to display that information in another activity. If you could link me to something or guide me in the right direction it would meant the world to me.

Well if you want persistent storage even after the user closed the app, SQLite or sharedpreferences is for you. Otherwise you can juse use Bundles to pass around the small bit of data in intents when starting a new activity.
SQLite guide,Sharedpreferences guide. Hope these helped.

Use an EditText to allow the user to input their name. Get the value from the EditText component via the EditText's getText() method. After that you have lot of different ways you can go. Save it for later or just pass it on via an intent to the next activity.
Good luck.

The term "Storing" should have a scope. Say, you are gonna store the data for a specific code block, or at activity level, or at application level, or you want persistent(storing data in Preferences or Database, for example, storing the game score, etc) or non-persistent(temporary storage: declaring the variables in the activity) storage.
In your case, to get the Text from EditText and send it to next activity:
Declare a global variables,
EditText editText;
String data;
// write this inside onCreate, after the `setContentView()` method
editText = (EditText) findViewById(R.id....);
data = editText.getText().toString();
// say you want to pass the data to next activity on button click, so write this inside //onClick()
Intent intent = new Intent(currentActivityName.this, NextActivityName.class);
intent.putExtra("data", data);
startActivity(intent);
Up till now what we have done is, get text from EditText, and prepared for sending it to next it to next activity. Now, on button click, the data will be sent to next activity.
But on next activity, you need to catch the data, that was sent from previous activity, to use it.
So, in the next activity, write the following code inside onCreate()
Intent intent = getIntent();
String dataReceived = intent.getStringExtra("data");
Log.i("data received", dataReceived);
After doing this check if you got the log, with tag name "data received" and data you sent.

Related

How can I make it so that when I click on a layout, its data is copied and sent to Firebase?

I have an activity with a RecyclerView that contains information. I fill out a form, submit it, then the data is entered into Firebase and the Activity displays the item with the data that I entered.
I want to make it so that when I click on any such item, it is copied to a separate table and then I can display it in another Activity. That is, I want to make an Add to Favorites button.
I've tried doing it myself, but I'm stumped.
In the adapter I tried to call the event handler and pass the data from the element I clicked on. But I'm sure this is wrong. And I don't know how to add to Firebase now.
#Override
public void onBindViewHolder(#NonNull CardAdapter.MyViewHolder holder, int position) {
CardData userData = this.cardData.get(position);
holder.favButn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, Favourites.class);
intent.putExtra("id", userData.getId());
intent.putExtra("lastname", userData.getUserLastName());
intent.putExtra("fullName", userData.getUserName());
intent.putExtra("phone", userData.getUserPhone());
intent.putExtra("email", userData.getUserEmail());
v.getContext().startActivity(intent);
}
});
}
If I do that, and if it works, as far as I understand it, there will only be 1 item on the page where I will be redirected after clicking.
But I want to be able to add at least as many items to favorites on one screen (and they wouldn't disappear from here), then go to the Favourites screen and see them there.
How do I do that?
The first option to solve this is to save Favourites on the Firebase database in relation to your user. Each time you open the Favorites class just retrieve this information and apply them to your layout. This will always trigger wifi or network on your phone which will have some impact on battery life and/or optimization of your application.
My suggestion is to on the "addToFavorites" button you save your data to the local database or SharedPreferences. This way you can get this data even if the user doesn't have an internet connection.
Database
For a database, you can use SQLite or Room DB for Android. It's easy to use and you can implement it fast. Also, you can do a lot with this later if you need it in your app.
SharedPreferences
Using SharedPreferences you can save your favorites as String under some KEY like "Favourites". Each time you add a new one you can retrieve information from SharedPreferences based on your KEY, add a new value, and save it. In your Favourites class, you can just retrieve your KEY and use data to fill your layout. Here you can use something like JSONArray to save all your Favourites and then convert it to string to save it to SharedPreferences and from String convert it back to JSONArray. This is an easy process since JSONArray has .toString() and new JSONArray(string) methods and constructors.
Things to keep in mind
Firebase
Advantage: Clearing cache won't affect as data is stored online Disadvantage: No internet no favourite list
SharedPreferences
Advantage: Clearing cache will flush out whole data
Disadvantage: Available all time, very fast

Moving back, then forward to a previous activity: How to maintain contents of editText fields

I've found what looks like the answer to this here - How to maintain the previous state of an activity - but I'm looking for a solution which works using OnClickListener code. The code I'm currently using to call Activities is:
NextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(GroupRegistrationStep2.this, GroupRegistrationStep3.class));
}
});
Here's what I'm doing. The user is taken through four different screens where they input group data, and they can go back or forward as they enter it. I'm using onBackPressed() to handle going back, but when a user enters some data on a screen (say screen 2), goes back to screen 1 to check something, and then hits Next to return to 2, any data they entered into the fields has gone.
I'd like a way of calling the activity but have it retain the data entered in the editText fields/selected in the spinners, etc.
Can anyone help? I've done a lot of VB.net coding in the past but am new to Java and Android Studio so would appreciate a solution for dummies. If someone could let me know what my code above should be to make this work, plus any other changes I'd need to make, that would be much appreciated.
I think you are trying to create a multiple paged form. Instead of launching new activities for different forms, try using a single activity with multiple fragments and place it in a viewpager. That way you can place "next" and "back" buttons to navigate between the viewpager' fragment and still retaining values within the activity.
If you really like to work with separate activities, you can save key-value pairs temporarily to SharedPreferences. You can achieve this using the code snippet below.
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("FieldName", "Put the value of the field here");
editor.commit();
Then you can retrieve the value by:
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
String value = sharedPref.getString("FieldName", "");
// Now place this value to the activity's field
Be sure to clear the necessary preferences if you have successfully completed the form.

Java to XML Android

New to Android Development and was wondering if there was some way of taking the users input to create an activity? For example say the user is going through the process of setting up a profile of themself. One of the questions is "how many pets do you have?". The user inputs "4" and then clicks the 'Next' button (which opens the next activity).
How would I take the users input of "4" to create four editText objects in the next activity so that the user can now input the name's of his/her's pets?
I'm an ok-ish programmer (have never touched XML before though) so you don't need to go into much detail I just don't know how I would access this variable to create the four editText objects. From what I've found out you can't add strings to the resources at run-time nor can even edit/append files in resources.
I was thinking of writing an XML file from java and making the activity (written in XML) read the XML file if that's even possible? Can XML files read XML files?
this has nothing to do with xml
the user's input will be stored in a different data type like a string. If you need to load a new activity, one thing you can do is pass information in an android Bundle type.
you start new activities with intent data types. the intent data type has a putExtra method, where you can put variables in.
after you startActivity(yourIntent) the new activity can call Bundle and that has a method called getExtra associated with getIntent()
these should guide you at least
Intents.
String 1 = et.getText().toString();
String 2 = et.getText().toString();
String 3 = et.getText().toString();
String 4 = et.getText().toString();
Intent i = new Intent(this, newclass.class).
i.putExtras("key1", 1);
// and so on.
// Then you get the data by.
bundle extras = i.getExtras();
string temps1 = extras.getString("key1", null);
More info here: http://developer.android.com/reference/android/content/Intent.html
What you're asking about is not really the creation of activities, but rather the creation of layouts. As you're already aware, Android allows you to define a layout using xml and Activities have a simple method to call to set their content view based on that xml. Layouts are not required to be defined in xml though; they can be programatically created.
When you start an activity you create an Intent for it, and you are able to add "extras" to this intent; by doing that you can pass parameters into your activity and it can use those as hints for how to build the layout.
Do some research on programatic layouts (http://mylifewithandroid.blogspot.com/2007/12/xml-and-programmatic-layout.html might help) and you will probably figure out what you need to know.
You can pass data (in your case user input) with the help of intent.
You can send data by using putExtra. Here is good tutorial for you.
For dynamic layout you can inflate your current layout and add controls to your current view. For dynamic layout this is good tutorial to refer.
I hope this two two tutorial will help you.

Moving String and Image between Activity Android Application

I've to develop an application that allows user to browse picture and write some information
about him, all these information will stored in a class with Person name,
After he presses NextButton the activiy should moves him to another activity with these information in the second activity he'll type another information about him,
well in the 3rd activity I should receive all these info. from ( 1st and 2nd ) activities then, showing it in the 3rd one ,,
my Questions are:
1- How can move more than one info. I write a code that moves string and other code to move picture, but I couldn't combine them with each other!
2- How can I insert the information that will be typed in the second activity to the same object of Person Class ??
Hope my Questions and my scenario is clear!!
thanks alot
Shomokh =)
-----------------------Updating----------------------------------------
// this is for String info
String FullPersonInfo = person1.toString();
Bundle basket = new Bundle();
basket.putString("key", FullPersonInfo);
Intent intent = new Intent(Form_1.this,Form_2.class);
intent.putExtras(basket);
startActivity(intent);
// I'm confusing how can I add image when i try this code it doesn't work
intent.putExtra("URI", selectedImageUri.toString() );
You can pass in extra information in the intent you are passing in to the next activity and then read the intent using intent.getExtra in the 2nd and 3rd activity. I hope that gives you better idea.
As omkar.ghaisas aluded to above you can pass extras to an Intent. However, you can only pass primitives OR any object which implements the Parcelable interface. Passing string is easy enough but the image data is trickier.
I think you have a couple of options:
Write the image path to disk and then pass the file location as a
string using the Extras in the Intent, plus any other strings you
need, e.g. other metadata
Grab the image as a byte[] array, create a class which implements
Parceleable and shuffle the byte[] around.
I think #1 is probably easier.
you can Create Parcelable object of your class that content all information whcih u want to move from one activity to another.use Bundle.putParcelable and extract all class object in another Activity.
for passing Parcelable custom or complex object between activites see:
Passing a list of objects between Activities
http://prasanta-paul.blogspot.in/2010/06/android-parcelable-example.html
Android: Passing object from one activity to another
and as your application requirement but do't pass whole image in bundle just pass a reference path and text to another activity and retrieve image from path

How to open an activity twice but with different content?

I'm developing a chat app, but I have a problem.
I've a list with the contacts and when I select one contact I'm starting a new activity
Intent i = new Intent(this, MessageScreen.class);
startActivity(i);
but, when I choose another contact to talk I will use the same activity.
but it always open with the last contact screen and the variables still with the old values.
I would like to make something similar to google talk, where you can start to talk with another contact, and all the messages use the same screen, and you can change between the chats fast with no need to reconstruct the screen, reload the messages, etc..
Anyone have any idea of how to implement this?
Sliding between activities isn't a common feature, it sounds like there is one second activity that has a ViewPager that is populated with multiple chats. When starting this activity, they're probably adding the Reorder to front flag to the intent and have overridden onNewIntent to add a new view to the pager.
Try something like*:
i.PutExtra ("key", value);
before starting the activity (e.g. store the user name) and then read your value from the activity and adjust (e.g. UI) it based on the value
note: syntax could differ a bit since I do my Android stuff from C#

Categories