NullPointerException when passing a double from one class to another using Intent - java

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

Related

How to pass ArrayList of Custom objects to new activity?

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.

How to access a variable declared in the main activity in another activity

i don't know if this is possible or if they is a better programming practice but i'd like to know how to use a varible declared in the main activity in another activity. Source code snippet example is given like so...
public class MainActivity extends ActionBarActivity {
private int a, b;
private EditText first, second;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
first = (EditText) findViewById(R.id.first_entry);
second = (EditText) findViewById(R.id.second_entry); }
public void doMath(View view) throws Exception {
try {
if (!first.getText().toString().equals("")) {
a = Integer.parseInt(first.getText().toString());
}
else {
a = 0;
}
if (!second.getText().toString().equals("")) {
b = Integer.parseInt(gpa_credits1.getText().toString());
}
else {
b = 0;
}
int sum = a + b; }catch (Exception e) {}
now, i would like to create a new activity to use the variable "sum" to do some math like...
public class first_year_second_semester extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newActivity);
int blah = 5;
private TextView soln;
soln = (TextView) findViewById(R.id.the_soln);
soln = (blah / sum) //i.e sum from the previous activity...please i need this
}
You can pass the value from one to other activity using intent or using shared preferences.
Intent intent=new Intent(MainActivity.this,year_second_semester.class);
intent.putExtras("sum",sum);
startActivity(intent);
Then in next activity you can get this value.
Or using shared preferences:
Inside class:
SharedPreferences shared;
Inside onCreate:
shared=getSharedPreferences("app",Context.MODE_PRIVATE);
After computing the sum I.e. after doing sum=a+b;
Editor edit=shared.edit();
edit.putString("sum",sum);
edit.commit();
And in the next activity:
Inside the class:
SharedPreferences shared;
Inside oncreate:
shared=getSharedPreferences("app",Context.MODE_PRIVATE);
Wherver you want:
String yourvalue=shared.getString("sum","default value");
Here your value will be the sum from the main activity.
Create a public static variable in your main activity (where the do math method is) like so:
public static int SUM;
Then in the do math function set that value to the one calculated.
int sum = a+b;
SUM = sum;
Then you can access it via:
MainActivity.SUM

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);

Accessing variables in different classes in Android

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);

Categories

Resources