So say a user enters a total in an EditText field in my Incomings class, I then want this to be passed to my Results class. How do I go about this in Android? I know the best way is to use Accessor methods.
My Incomings class:
public void onClick(View v) {
String userLoan = etLoan.getText().toString();
String userGrant = etGrant.getText().toString();
String userFirst = etFirst.getText().toString();
float fUserLoan = Float.parseFloat(userLoan);
float fUserGrant = Float.parseFloat(userGrant);
float fUserFirst = Float.parseFloat(userFirst);
float totalIncomings = fUserLoan + fUserGrant + fUserFirst;
Intent intent = new Intent(v.getContext(), Outgoings.class);
startActivity(intent);
}
});
My results class has a blank function and will calculate the totals
I have tried using accessor methods in my MainAcivity class:
public float getTotalOutgoings() {
return totalOutgoings;
}
public void setTotalOutgoings(float totalOutgoings) {
this.totalOutgoings = totalOutgoings;
}
public float getTotalIncomings() {
return totalIncomings;
}
public void setTotalIncomings(float totalIncomings) {
this.totalIncomings = totalIncomings;
}
public float getTotalResult() {
return totalResult;
}
public void setTotalResult(float totalResult) {
this.totalResult = totalResult;
}
Any suggestions?
Pass Intent extras:
Intent intent = new Intent(v.getContext(), Outgoings.class);
intent.putExtra ("total",totalIncomings);
startActivity(intent);
Then access in your next Activity with
Intent i = getIntent();
float totalComings = i.getFloatExtra("total",-1.0);
Now about your Results class. It depends exactly what you want to do with that class. If all you need is a simple calculation, make a static method. And data passing is usually the other way around. The Activity calls a data class, gives it data, then the data class does whatever it needs to do and returns the result to the Activity.
use
Bundle bd = new Bundle();
bd.putFloat("key",value);
intent.putExtras(bd);
startActivityForResult(intent,1);
On other class
Bundle bund= getIntent().getExtras();
float value= bd.getFloat("key");
Are you trying to call a function on your MainActivity?
MainActivity m = (MainActivity) getActivity();
m.setTotalIncomings(XXX);
Related
I am trying to pass a double value from one class (MaterialCollect), to another Class (Main Activity). I am receiving a NullPointerException error in my Main Activity class when I try to define rho_m. I have followed passing a double with no success. I have attached an exert of my MainActivity, MaterialCollect and MatrixBase class files. According to the logcat the issue seems to be in the line not successfully creating a new Bundle. I am new to Java thank you.
public class MainActivity extends Activity{
double rho_m;
double E_maxial;
double E_mtrans;
double UTS_m;
double v_m;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Intent intent;
intent = new Intent(MainActivity.this, MaterialCollect.class);
startActivity(intent);
Intent it = new Intent();
Bundle nylon66params = it.getExtras();
rho_m = nylon66params.getDouble("nylon66.matrixrho");
Log.d("print out","THE VALUE OF " + Double.toString(rho_m));
}}
MaterialCollect class:
public class MaterialCollect extends AppCompatActivity {
MatrixBase nylon66 = new MatrixBase(1140, 2.7e9, 2.7e9, 2800e6, 0.33);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent it = new Intent(MaterialCollect.this, MainActivity.class);
Bundle nylon66values = new Bundle();
nylon66values.putDouble("nylon66.matrixrho", nylon66.matrixrho);
nylon66values.putDouble("nylon66.matrixaxialTmodulus", nylon66.matrixaxialTmodulus);
nylon66values.putDouble("nylon66.matrixtransTmodulus", nylon66.matrixtransTmodulus);
nylon66values.putDouble("nylon66.matrixpoissons",nylon66.matrixpoissons);
nylon66values.putDouble("nylon66.UTS",nylon66.matrixpoissons);
it.putExtras(nylon66values);
Log.d("ADebugTag", "Value: " + Double.toString(nylon66.matrixrho));
startActivity(it);
}}
and MatrixBase
public class MatrixBase {
double matrixrho;
double matrixaxialTmodulus;
double matrixtransTmodulus;
double matrixpoissons;
double matrixUTS;
MatrixBase(double matrixrho, double matrixaxialTmodulus, double matrixtransTmodulus, double matrixpoissons, double matrixUTS) {
this.matrixrho = matrixrho;
this.matrixaxialTmodulus = matrixaxialTmodulus;
this.matrixtransTmodulus = matrixtransTmodulus;
this.matrixpoissons = matrixpoissons;
this.matrixUTS = matrixUTS;
}}
From what you have posted i am guessing you need to get a value back in your MainActivity.
Your MainActivity code is incorrect (you are creating a new Bundle and additionnaly your are calling back your MaterialCollect Activity).
You need simply to get the extras from the callee using getIntent().getExtras()
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
rho_m = b.getDouble("nylon66.matrixrho");
if (rho_m != null)
{
Log.d("print out","THE VALUE OF " + Double.toString(rho_m));
}
}
As demidust points there is a loop... you start a MainActivity that starts a MaterialCollect which starts another MainActivity...
Check How to manage startActivityForResult on Android? if you need to get a value from another activity.
It is better to use Serialize class as you can pass the whole model to activity. please check below updated code
public class MatrixBase implements Serializable {
double matrixrho;
double matrixaxialTmodulus;
double matrixtransTmodulus;
double matrixpoissons;
double matrixUTS;
MatrixBase(double matrixrho, double matrixaxialTmodulus, double matrixtransTmodulus, double matrixpoissons, double matrixUTS) {
this.matrixrho = matrixrho;
this.matrixaxialTmodulus = matrixaxialTmodulus;
this.matrixtransTmodulus = matrixtransTmodulus;
this.matrixpoissons = matrixpoissons;
this.matrixUTS = matrixUTS;
}}
Change code in MaterialCollect
Intent it = new Intent(MaterialCollect.this, MainActivity.class);
it.putExtra("it",nylon66)
startActivity(it);
and get the whole item with the below code in MainActivity oncreate method
MatrixBase matrixBase= (MatrixBase)getIntent().getSerializableExtra("it");
then you can access all the data from the single model
I've got 2 activities and a class that extends Application where I'm trying to store global variables with a kind of setter getter functions.
The main activity sets some views and a chart; then calls the second activity which should be setting values to be used afterwards on the previous chart.
Then pressing backbutton and returning to the previous activity onRestart is called and the chart is refreshed.
The problem is I lose my theorically global variables somewhere. Debugging i realized that the functions work perfectly fine while im adding values in the second activity but when I return to the first activity globalXCount returns '0' again. Why is that?
I think im missunderstanding some point regarding lifecycles.
I attach some fragments of the code.
First activity:
public class MainActivity extends Activity {
Global glObj = new Global();
CombinedChart mChart;
private int itemcount;
float displayed;
private final List<String> mMonthList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itemcount = ((Global) this.getApplication()).getGlobalXCount();
displayed = itemcount/20;
mChart = (CombinedChart) findViewById(R.id.mchart);
populateHeaderList();
setChartSettings();
Intent intent = new Intent(MainActivity.this, QandA.class);
startActivity(intent);
}
#Override
protected void onRestart() {
super.onRestart();
itemcount = ((Global) this.getApplication()).getGlobalXCount();
displayed = itemcount/20;
populateHeaderList();
setChartSettings();
}
Second activity:
public class QandA extends Activity {
Global glObj = new Global();
ViewFlipper flipper;
private float lastX;
...
}else{
//TODO If all information if correctly filled
trainedmins = et1.getText().toString();
localLineValue = Integer.parseInt(trainedmins) * Integer.parseInt(statusQ1);
//Add values to lines
glObj.setLineXvalues(localLineValue);
// TODO Add new Bar value //
//Add 1 more value to count
glObj.addGlobalXCount();
}
...
Global class:
public class Global extends Application {
//TODO
public Integer globalXCount;
private List<Integer> lineXvalues = new ArrayList<>();
private List<Integer> barXvalues = new ArrayList<>();
//////
public Integer getGlobalXCount() {
if (this.globalXCount == null){
this.globalXCount = 0;
return this.globalXCount;
}else{
return this.globalXCount;
}
}
public void addGlobalXCount() {
if (this.globalXCount == null){
this.globalXCount = 0;
}else{
this.globalXCount = this.globalXCount + 1;
}
}
Thanks in advance.
First of all, register your custom Application context in AndroidManifest.xml within the <application>-tag.
<application
android:name="<your_package>.Global" ...>
Access the global application context within your activities like this:
Global glObj = (Global) getApplicationContext();
glObj.addGlobalXCount();
Do not create a new instance with new! Always retrieve the instance via getApplicationContext().
Furthermore, I would suggest you to initialize your class field glObj within the onCreate()-method of your Activities.
I have created the class textViewTable In this class i am saving data related to TextViews That I want to Pass to Next Activity.
public class TextViewTable implements Serializable {
private String FONT;
private String TEXT;
private float TEXT_SIZE;
private ColorStateList TEXT_COLOR;
private float MARGIN_TOP;
private float MARGIN_BOTTOM;
private float MARGIN_LEFT;
private float MARGIN_RIGHT;
private Boolean BoldFlag;
private Boolean ItalicFlag;
private Boolean NormalFlag;
public TextViewTable(){
}
public TextViewTable(String FONT, String TEXT, float TEXT_SIZE, ColorStateList TEXT_COLOR, float MARGIN_TOP, float MARGIN_BOTTOM, float MARGIN_LEFT, float MARGIN_RIGHT, Boolean boldFlag, Boolean italicFlag, Boolean normalFlag) {
this.FONT = FONT;
this.TEXT = TEXT;
this.TEXT_SIZE = TEXT_SIZE;
this.TEXT_COLOR = TEXT_COLOR;
this.MARGIN_TOP = MARGIN_TOP;
this.MARGIN_BOTTOM = MARGIN_BOTTOM;
this.MARGIN_LEFT = MARGIN_LEFT;
this.MARGIN_RIGHT = MARGIN_RIGHT;
BoldFlag = boldFlag;
ItalicFlag = italicFlag;
NormalFlag = normalFlag;
}
}
From my activit i want to send ArrayList of Objects of TextViewTable class.
I have use the below function to send the ArrayList. But every time I am getting null pointer exception. Please Help to solve this.
public void onClick(View view)
{
Intent intent = new Intent(getApplicationContext(), displayImage.class);
Bundle bundleObject = new Bundle();
bundleObject.putSerializable("key", textViewsData);
intent.putExtras(bundleObject);
try {
startActivity(intent);
}catch (Exception e){
System.out.println(e);
}
}
};
Currently using Bundle.putSerializable for sending TextViewTable class object ArrayList to next Activity but not implementing Serializable interface in TextViewTable class:
public class TextViewTable implement Serializable{
....
}
you can follow ρяσѕρєя K's answer OR also you can do like below code:
public class GeneralClass{
public static ArrayList<TextViewTable> data = new ArrayList<TextViewTable>();
}
and then you can store your data in above arraylist on first activity like below:
Collections.copy(GeneralClass.data,textViewsData);
and now you can use GeneralClass.data arraylist in your second activity;
Sending the POJO from one activity to another acitivity:
Bundle bundle = new Bundle();
ArrayList<StatusData> passData = new ArrayList<StatusData>();
bundle.putSerializable("key", passData);
intent.putExtras(bundle);
startActivity(intent);
//then the transaction part
Getting the bundle`:
Bundle bundle = new Bundle();
bundle = getIntent().getExtras();
ArrayList<StatusData> dataReceived = (ArrayList<StatusData>)bundle.getSerializable("key"));
and then do whatever you like.Hope this helps.Cheers.
You can also use Parcelable.
First Activity
public void shareCustomArrayListObject(ArrayList<CUSTOMOBJECT> arrayList) {
if (arrayList != null && arrayList.size() > 0) {
Intent intent = new Intent(getApplicationContext(), displayImage.class);
Bundle bundleObject = new Bundle();
bundle.putSerializable("KEY", arrayList);
intent.putExtras(bundleObject);
}
}
Second activity where you want to retrieve the arraylist
private ArrayList<CUSTOMOBJECT> arrayList;
Bundle bundle=YOURACTIVITY.getBundle();
if(bundle==null){
bundle=getArguments();
}
if(bundle.getSerializable("KEY")!=null){
arrayList=(ArrayList)bundle.getSerializable("KEY");
}
and also if you have made a bean class for the arraylist
you need to implement
public class CUSTOMOBJECT implements Serializable{
and you done :)
you should use Parcelable object to pass data between activities as below:
Passing data from activity A to activity B
Intent intent=new Intent(A.this,B.class);
intent.putParcelableArrayListExtra("key", array_list);
startActivity(intent);
Getting data in Activity B from activity A
Intent intent=getIntent();
array_list = intent.getParcelableArrayListExtra("key");
So simple.
I hope this will help you.
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);
This question already has answers here:
Transferring int variable between activities Android
(2 answers)
Closed 9 years ago.
So I have this class where I push a button, and at the and I get the int maxpluseen which I want to pass over to ClassB.
private void populateBtn() {
foto1 = (Button) this.findViewById(R.id.button2);
foto1.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SimpleDateFormat")
#Override
public void onClick(View v) {
int maxpluseen = maxIndex + 1;
Log.d("LOG!", "Uiteindelijk resultaat " + maxpluseen);
Intent myIntent = new Intent(classA.this, classB.class);
classA.this.startActivity(myIntent);
}
});
}
I tried doing the following:
public static int Access(int maxpluseen){
return maxpluseen;
}
And In classB
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info);
int maxpluseen = 0;
int test = classA.Access(maxpluseen);
Log.d("LOG!", "Test int tussen klassen= " + test);
}
But it gives back 0 (so my int isn't passed from classA to classB. What am I doing wrong here?
in class A:
Intent myIntent = new Intent(classA.this, classB.class);
myIntent.putExtra("number", maxpluseen)
classA.this.startActivity(myIntent);
in Class B:
int getal;
getal = getIntent().getExtras().getInt("number");
......
here you are passing ClassA.Access() a value of 0, thus returning a value of 0.
int maxpluseen = 0;
int test = classA.Access(maxpluseen);
First of all, you should mention that your Classes aren't normal classes, but Activities.
Secondly, you should really use all-English variable names (maxplusone).
You can add data to the Intent, you use to start the new Activity with, which you can read more about
Here in a different question or here in the Intent developer description
Is classA your main?
If so, create an object to classB. Write a function to set the int value, so that you can do something like classBObject.setInt(value). Then, in your foto1's onClick() method, call that function.