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.
Related
I am trying to pass an ArrayList of type Album to another activity in Android Studio.
The problem is that the Lastfm API I am using does not implement Parcelable.
I tried making my own Album class and extending their Album class but I got the error
"there is no default constructor available in 'de.umass.lastfm.Album'
Quiz.java - intent.getParcel... not working as Album is not Parcelable
public class Quiz extends AppCompatActivity {
private static TextView tv_quiz;
private static EditText et_quiz;
private ArrayList<Album> albums;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
Intent intent = getIntent();
albums = intent.getParcelableArrayListExtra(MainActivity.ALBUMS_LIST);
}
}
The calling portion of my MainActivity.java.
Intent intent = new Intent(this, Quiz.class);
intent.putExtra(ALBUMS_LIST, allAlbums);
intent.putExtra(DIFFICULTY, difficulty);
startActivity(intent);
Is there any way I can get around this?
Thanks anyway
I took a look at the api you linked, and Album looks extremely difficult to parcel. I would say that you might be better off simply re-loading the list in the next Activity (rather than trying to pass the list).
The only way to "construct" a new Album instance is through the getInfo() static factory method. You could create a new class AlbumWrapper that is parcelable, send a list of AlbumWrapper through the Intent, and then use getInfo() on the other side to re-fetch the albums.
public class AlbumWrapper implements Parcelable {
// insert CREATOR here
public final String artist;
public final String mbid;
public AlbumWrapper(Album a) {
this.artist = a.getArtist();
this.mbid = a.getMbid();
}
private AlbumWrapper(Parcel in) {
this.artist = in.readString();
this.mbid = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(artist);
dest.writeString(mbid);
}
#Override
public int describeContents() {
return 0;
}
}
You can put your list of Albums in the intent like this:
ArrayList<AlbumWrapper> wrappers = new ArrayList<>();
for (Album album : albums) {
AlbumWrapper wrapper = new AlbumWrapper(album);
wrappers.add(wrapper);
}
intent.putParcelableArrayListExtra("ALBUM_WRAPPERS", wrappers);
And then in your next activity you can do something like:
List<AlbumWrapper> wrappers = getIntent().getParcelableArrayListExtra("ALBUM_WRAPPERS");
List<Album> albums = new ArrayList<>();
for (AlbumWrapper wrapper : wrappers) {
Album album = Album.getInfo(wrapper.artist, wrapper.mbid, YOUR_API_KEY);
albums.add(album);
}
Here is the solution
open activity using this code
Bundle bundle = new Bundle();
bundle.putSerializable("data", allAlbums);
bundle.putString(DIFFICULTY", difficulty);
Intent intent = new Intent(this, Quiz.class);
intent.putExtra(bundle);
startActivity(intent);
get intent data
albums = (ArrayList<Album>) getIntent().getExtras().getSerializable("data");
updated Album Class
public class Album implements java.io.Serializable {
//your code
}
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'm programming an Android application and I got a little problem. I'm trying get a value from the Class A in the Class B but it doesn't return the correct value.
Here's my code to better understand (Sorry for my poor english)!
Class A
package com.androidhive.androidlistview;
//import
public class AndroidListViewActivity extends ListActivity {
int day;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// storing string resources into Array
String[] adobe_products = getResources().getStringArray(R.array.adobe_products);
// Binding Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, adobe_products));
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String product = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
day = Integer.parseInt(product.replaceAll("[^\\d.]", ""));
System.out.println(day);
//prints 1 When I click on the first list item, 2 When I click on the second, ...
startActivity(i);
// sending data to new activity
i.putExtra("product", product);
}
});
}
public int getDay() {
return day;
}
}
Class B
package com.androidhive.androidlistview;
//import
#SuppressLint({ "NewApi", "HandlerLeak" })
public class SingleListItem extends Activity {
AndroidListViewActivity alva = new AndroidListViewActivity();
int day;
String url;
String code;
//others variables
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Graphic
new NetworkOperation().execute();
}
class NetworkOperation extends AsyncTask<Void, Void, String> {
protected String doInBackground(Void... params) {
Document doc;
try {
day = alva.getDay();
System.out.println(day);
//prints 0
url = "http://www.planetehockey.com/calendrier.php?saison=45&div=9&club=&journee=" + day + "&jour=&mois=&page=0";
doc = Jsoup.connect(url).get();
//Récupère le texte d'une balise ayant bg_tableau pour class
Elements getId = doc.getElementsByClass("bg_tableau");
code = getId.text();
code = code + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
handler.sendEmptyMessage(1);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
//other code
}
};
}
Thank's a lot for all your answers it helped me a lot:
How I solved the problem:
Class A
i.putExtra("product", product);
startActivity(i);
and:
Class B
int day = Integer.parseInt(i.getStringExtra("product").replaceAll("[^\\d.]", ""));
In your Class A, you're trying to bundle components AFTER the activity has been called.
put the call function like this..
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
day = Integer.parseInt(product.replaceAll("[^\\d.]", ""));
System.out.println(day);
i.putExtra("product", product);
startActivity(i);
The passes the parameter in a bundle to the called activity.
HTH!
There are two simple solutions for your problem,
1. Pass day values in intent to SingleListItem
Or
2. Make day as a Static member and use it with class Name like,
public static int day; and access it `AndroidListViewActivity.day`
and remove public int getDay() method from AndroidListViewActivity as in both activity it refers a different object of AndroidListViewActivity .
Try doing i.putExtra("product", product); before startActivity(i);
In your Activity A you have written the getter method but not setter method to set the value of day in your code. Just write the setter method also and set the value of day.
public void setDay(int p_day)
{
day=p_day;
}
Make the variable day as static. After setting the day value try to get it in activity B.
I hope this will help you.
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);