MainActivity(Activity)
String emailid=e1.getText().toString();
Intent i = new Intent(MainActivity.this,LongOperation.class);
i.putExtra("emailid",emailid);
LongOperation(Java class )
Intent i = getIntent();
a = i.getStringExtra("emailid");
ERROR MESSAGE:
'getIntent(java.lang.String)' is deprecated as of API 15: Android
4.0.3 (IceCreamSandwich)
In 1st Class:
Intent i = new Intent(MainActivity.this, LongOperation.class);
i.putExtra("emailid", emailid);
startActivity(i);
In 2nd Class:
Intent i = getIntent();
String emailid= i.getStringExtra("emailid");
Intents are used to pass data from one activity to another activity.
So if you want to pass data to a normal Java class i would suggest you to use a getter function in combination with a static java class.
So LongOperation has to look like that:
public class LongOperation {
private static String eMailID;
// gives the variable eMailID in this class the new value mailID
public static void setMailID(String mailID) {
eMailID = mailID;
}
// add additional code here
}
In the MainActivity you have to do sth like:
String emailid = e1.getText().toString();
// set the variable in the LongOperation class
LongOperation.setMailID(emailid);
I hope I got your question right, there are several other ways but that depends on the structure and logic of your code.
In general I would recommend to work not so much witch static, more object orientated. But in this case static might be easier.
Cheers
Related
I'm a newbie creating a unit converter.
I have two classes, I have this method in the first class:
public String cardName;
public String StartConversion(View view){
Intent intent = new Intent(this, ConversionActivity.class);
startActivity(intent);
return cardName = view.getResources().getResourceEntryName(view.getId());
}
I would like to get and use the cardName's value in my second class, so:
MainActivity myObj = new MainActivity();
Toast.makeText(getApplicationContext(), "cardName: " + myObj.cardName, Toast.LENGTH_LONG).show();
But this doesn't work. I know local variables are only accessible inside their scope so I did this instead. They say you can only access it if you make it a class member, that does work but then it has a NULL value.
Typically, you'd a) create some class, b) make class members "private", then c) expose those members with getter and setter methods.
EXAMPLE:
public class MyClass {
private String cardName;
public void StartConversion(View view){
Intent intent = new Intent(this, ConversionActivity.class);
startActivity(intent);
cardName = view.getResources().getResourceEntryName(view.getId());
}
public getCardName() { return cardName; }
}
Then whatever class wanted to access "cardName" would call:
String cardName = myObject.getCardName();
Look here for more details:
Java Getter and Setter Tutorial, Nam Ha Minh
There exists a train of way to resolve your problem. For instance,
First- the method of StartConversion works to set the card name and then provide a method of getter to access.
Second- Only use the method of StartConversion to return that you want. But you ought to change the code to return view.getResources().getResourceEntryName(view.getId());, to remove the cardName =. The outer class should be called the method to access that you want.
In a word, either call the method to access directly or giving a setter then using the getter to access.
I trying to pass a string from mainActivity to the activity of a
library i been trying using intent but is not recognizing this function has someone done this before?
I get this error:error
create the OFAndroid class like this
public class OFAndroid {
private String text ;
public OFAndroid(String text) {
this.text = text ;
}
public void useText() {
Log.e("TAG" , this.text);
}
}
Inside your MainActivity instantiate OFAndroid:
OFAndroid of = new OFAndroid("some string");
now you can use the passed String
of.useText();
getIntent is a method that is not available in your OFAndroid Class. If you want to access the Intent that was passes to an Activity you should call It from inside an Activity's Class.
For example,
public void show_message(String message){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
I want this method add auto Activity.java when create new activity or java class.
I want to save different methods like this and include it in the my project quickly where it is needed.
What you should do is create a BaseActivity and make your activity extend this BaseActivity. Add all the default methods in this activity so you can use them everywhere. You can refer this Github project for reference. It uses MVP.
Here is direct link to BaseActivity.
You just need to make a Common Utilities class. Just copy and paste the class in whatever project you are using it. Just make its method access specifiers as public staic so that you can easily access it.
For e.g.
CommonUtilities.showToastMessage(String text);
What I would do is create a config class and store all these small things in it. For example have a look at this :
public class Config {
public Context context;
public String sharedPrefsName;
public String carTablesName, carsTableCarColumn, databaseName;
public int databaseNewVersion, databaseOldVersion;
public boolean showNotificationsToCustomer;
public String customerNotificationState;
public String userMobile;
public SharedPreferences preferences;
public String customerChatTableName;
public String customerChatMessageColumn;
public String customerChatSentByCustomerColumn;
public String customerChatTimeColumn;
public String loggedInUserId;
public String loggedInUserName;
public String customerChatSupportNotifyingUrl;
public Config(Context context) {
this.context = context;
customerChatSupportNotifyingUrl = "";
customerChatTableName = "customerChat";
customerChatMessageColumn = "customerMessage";
customerChatTimeColumn = "sentOn";
customerChatSentByCustomerColumn = "isSentByCustomer";
sharedPrefsName = context.getString(R.string.shared_prefs_login_validator);
preferences = context.getSharedPreferences(sharedPrefsName, Context.MODE_PRIVATE);
customerNotificationState = context.getString(R.string.customer_notification_state);
showNotificationsToCustomer = preferences.getBoolean(customerNotificationState, true);
carTablesName = context.getString(R.string.user_car_table);
carsTableCarColumn = context.getString(R.string.user_car_table_car_column);
databaseName = context.getString(R.string.user_db);
databaseNewVersion = 3;
databaseOldVersion = 1;
loggedInUserId = preferences.getString(context.getString(R.string.user_db), "");
userMobile = preferences.getString(context.getString(R.string.user_mobile), "");
loggedInUserName = preferences.getString(context.getString(R.string.user_name), "");
}
}
I've placed all the constants in a single file so you need not look at them always. If your app grows in size this would be extremely useful.
For using a progress dialog I use a class like this :
public class MyProgressDialog extends ProgressDialog {
String title, message;
public MyProgressDialog(Context context, String title, String message) {
super(context);
if (!title.equals("")) this.setTitle(title);
this.setMessage(message);
this.setCancelable(false);
this.setIndeterminate(false);
}
}
This is nothing but a single class that extends ProgressDialog.So you can aquire all the functionalities of the progress dialog class.
Similarly for toast you could do the same. If you want them to appear when the activity gets created simply keep this:
MyProgressDialog dialog=new MyProgressDialog(this,"title","message");
dialog.show();
in your activity's onCreate() method. You can do the same for toast too.
In case if it is a java class just create a constructor and keep that snippet in that constructor..
You need to read about "File Templates" https://riggaroo.co.za/custom-file-templates-android-studio/ this a large topic, but this is worth it.
I must pass an ArrayList from one Activity A to another Activity B.
I did it using getSerializableExtra and putExtra methods. I already know the meaning of these methods, but I don't know if stuff that I passed using them is stored permanently in the new activity or if it is necessary to reload activity A in order to retrieve my data in B.
So the question is: how can I load my data in a initial splash screen and then use it in all my others activity without reloading the splash screen?
Don't use Preference Class! Preferences are only used for settings values. For passing data to another Activity use Serializable or Parcelable. Remember that all the objects which will be passed to another activity have to implement Serializable or Parcelable. So you extend the ArrayList to a custom Class which implements Parcelable or Serializable.
You do this like this:
Intent intent = new Intent(getContext(), SomeClass.class);
intent.putSerializableExtra("value", <your serializable object>);
startActivity(intent);
and receive them like
YourObject yourObject = getIntent().getSerializableExtra("value")
or look here for Parcelable
Help with passing ArrayList and parcelable Activity
Data processed in Activity A does not need to process again in Activity B. If the data is computed in A and you send it to B computed, B receives it computed already.
Here are some ways to do it right: http://developer.android.com/guide/topics/data/data-storage.html
You can use Preference class, in which you can define its static instance. Than create variable according your desire datatype (even ArrayList). Make property for get and set of this variable.
Set the value on splash screen and get anywhere in application where you need.
Try this, if you need , I will upload code also.
I have written some code regarding that, it would help other activities to fetch data easily, use this when the data is not confidential,
public class HelperShared {
public static final String score = "Score";
public static final String tag_User_Machine = "tag_User_Machine",
tag_Machine_Machine = "tag_Machine_Machine",
tag_Draw_Machine = "tag_Draw_Machine",
tag_Total_Machine = "tag_Total_Machine";
public static SharedPreferences preferences;
public static Editor editor;
public HelperShared(Context context) {
this.preferences = context.getSharedPreferences(score,
Activity.MODE_PRIVATE);
this.editor = preferences.edit();
}
/*
* Getter and Setter methods for Machine
*/
public void setUserMachine(int UserMachine) {
editor.putInt(tag_User_Machine, UserMachine);
editor.commit();
}
public void setMachineMachine(int MachineMachine) {
editor.putInt(tag_Machine_Machine, MachineMachine);
editor.commit();
}
public void setDrawMachine(int DrawMachine) {
editor.putInt(tag_Draw_Machine, DrawMachine);
editor.commit();
}
public void setTotalMachine(int TotalMachine) {
editor.putInt(tag_Total_Machine, TotalMachine);
editor.commit();
}
public int getUserMachine() {
return preferences.getInt(tag_User_Machine, 0);
}
public int getMachineMachine() {
return preferences.getInt(tag_Machine_Machine, 0);
}
public int getDrawMachine() {
return preferences.getInt(tag_Draw_Machine, 0);
}
public int getTotalMachine() {
return preferences.getInt(tag_Total_Machine, 0);
}
}
if your question is "how can I load my data in a initial splash screen and then use it in all my others activity without reloading the splash screen?" Than I have better solutions for you.
Create a Class Memdata.java
public class Memdata{
private static Memdata instance = null;
private String userobject;
public static Memdata getInstance(){
if ( instance == null){
instance = new Memdata();
}
return instance;
}
public String getuserobject() {
return userobject;
}
public void setuserobject(String userobject) {
this.userobject= userobject;
}
}
on You Splash Screen' onCreate method, set the value
Memdata obj = Memdata.getInstance();
obj.setuserobject("hello");
Than in any activity, where you want to access this variable, just make its object and get value.
Like in MyActivity class
Memdata obj = Memdata.getInstance();
String str = obj.getuserobject()
You can define any type of variable according your requirement.
You can extend the base Application class and add member variables to it:
public class MyApp extends Application {
private String appLevelString;
public String getAppLevelString() {
return this.appLevelString;
}
public void setAppLevelString(String val) {
this.appLevelString= val;
}
}
You will have to update the manifest file as follows:
<application android:icon="#drawable/icon"
android:label="#string/app_name"
android:name="MyApp">
You can get and set data like this:
//For setting
((MyApp) this.getApplication()).setAppLevelString("Test string");
//For getting
String str = ((MyApp) this.getApplication()).getAppLevelString();
I have problem with starting new Activity in my app.In shorthand it will be app of sound effects(animals,people,fun...)
In my MainActivity there is button with onClick method
public void clic(View v) {
Intent newIntent=new Intent(this,AktivityImage.class);
newIntent.putExtra("id", aFactory.getAnimals());
startActivity(newIntent);
}
Method aFactory.getAnimals() returns array of my own class:
public Entit[] getAnimals(){
return aArrayAnimals;
}
Class Entit is primitive, just constructor and 2 getters.
import java.io.Serializable;
public class Entit implements Serializable{
private int aSound;
private int aImage;
public Entit(int paIdImage,int paIdSound){
aImage=paIdImage;
aSound=paIdSound;
}
public int getImage(){
return aImage;
}
public int getSound(){
return aSound;
}
}
And there is a problem, in class AktivityImage
private Entit[] aEntity;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sounds_layout);
aIntent=this.getIntent();
aEntity=(Entit[]) aIntent.getSerializableExtra("id");
Some tips? Thanks to all.
Like others have explained you could use Pacelable or Serializable both works the same way except in case of Bundle api. Bundle accept serializable and parcelable objects + it accepts parcelable array/arraylist/SparseArray but it doest accept array of serilaizable object as it is. Easiest way is create a Transport class ( again serializable ) some what like
public static class Transport implements Serializable{
public Entit[] data;
public Transport(Entit[] data) {
this.data = data;
}
}
And the modify make an instance of the Transport class and put it in the bundle
Intent newIntent=new Intent(this,AktivityImage.class);
newIntent.putExtra("id", new Transport(aFactory.getAnimals()));
startActivity(newIntent);
And when you read read as a Serializable casted into Transport and takeout the actual data
aIntent=this.getIntent();
aEntity=((Transport) aIntent.getSerializableExtra("id")).data;
If you'd like to pass an object through intents, they should implement the Parcelable interface. Here's the relevant doc. With your class, it should be very simple - all you have is two integers, which fit directly into a parcel without any extra work.
Any object that implements Parcelable can be placed into a bundle (and therefor also placed inside an Intent). Use one of the various getter/setter methods in Intent to set and retrieve your data.
If your class is going to be that simple, and you have a fixed number of Sound Effects then you might want to use Enums instead since Enums are automatically serializable and they can be stored in Intents and Bundles with overwhelming ease.
enum SoundEffects {PIANO, DRUM, ....}
SoundEffects mSound = SoundEffects.DRUM;
Intent intent = new Intent();
intent.putExtra("Sound", mSound);
Bundle bundle = new Bundle();
bundle.putSerializable("Sound", mSound);
and there you go.
Also, primitives like ints and doubles can be passed into Enums and Enums can have getters and setters so that won't be a problem... so using the previous example you could do
enum SoundEffects {PIANO(10, 20), DRUM(25,30), ....}
but then you have to add an constructor to your enum to accept these values.
Throught : http://developer.android.com/reference/android/content/Intent.html
you can use putExtras and getExtras respectively from sender to receiver. Extras can range from int[] to Serializables.