So I am making an android app that implements some custom classes. I want to create an object of class Menu_Organizer to other activities, but after I inizialize the object and send it to the next Activity the object is NULL. Here are the classes:
Menu Items class
import java.io.Serializable;
public class Menu_Items implements Serializable {
private String Name = "";
private String Description = "";
private float Price = 0.0f;
private String Category = "";
/* Getters and Setters*/
}
Menu Organizer class:
public class Menu_Organizer implements Serializable {
ArrayList<String> Categories;
ArrayList<Menu_Items> Food;
// EDITED
public Menu_Organizer() {
Categories = new ArrayList<String>();
Food = new ArrayList<Menu_Items>();
}
/* Other class methods */
}
First Activity (main)
public class MainActivity extends AppCompatActivity {
private Button btn;
public Menu_Organizer menu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onclick();
}
public void onclick() {
btn = (Button) findViewById(R.id. btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Menu_Organizer menu = new Menu_Organizer();
menu.New_Menu_Item("Carne", "Pollo", "Pollo Asado Rico!", 4.55f);
Intent activity2= new Intent(MainActivity.this,temp.class);
activity2.putExtra("Menu", menu);
startActivity(activity2);
}
});
}
}
Second Activity
public class temp extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_Second);
Bundle bundle = getIntent().getExtras();
Menu_Organizer menu = (Menu_Organizer) bundle.getSerializable("Menu");
String str= menu.Food.get(0).getName();
}
}
Alright, i think that the issue is, that when you pass your class object in a key value pair, you do it in an Intent object, but when you resolve your intent, you do that via a bundle object. So, in you temp Activity, you should resolve the intent like:
Intent intent = this.getIntent();
Menu_Organizer menu = (Menu_Organizer) intent.getSerializableExtra("Menu");
Try this, this should work. If you want to do it via a bundle, then create a bundle object first, then put whatever you want in that bundle. Add the bundle to your intent, and then resolve the bundle in your next Activity.
Just a tip, Class names generally do not contain _ in them, use CamelCase naming convention for all classes.
I would recommend using EventBus library for this kind of thing. It is quite easy to use and gives you exactly this: sending and receiving custom object classes from one place to another (Fragments, Activities, Services, whatever you wish can send and receive objects).
I personally don't like intents cause they have too many limitations.
Related
I read some example on this website and other but still have error.
It's not a compilation error but my application crash when I click on the button.
There is code of my MainActivity.java (only interesting part) :
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
//blablabla
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.myLayout= (LinearLayout) findViewById(R.id.layoutProp);
Button button = (Button) findViewById(R.id.buttonValider);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openActivity2();
}
});
}
public void openActivity2() {
Intent intent = new Intent(this, Activity2.class);
intent.putExtra(EXTRA_TEXT, text); // this one does not work
intent.putExtra(EXTRA_NUMBER, nbTextView);
startActivity(intent);
}
}
And code in Activity2.java
public class Activity2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
Intent intent = getIntent();
int nbTextView = intent.getIntExtra(MainActivity.EXTRA_NUMBER, 0);
MyTextView[] text = (MyTextView[]) intent.getSerializableExtra(MainActivity.EXTRA_TEXT);
TextView textView1 = (TextView) findViewById(R.id.TVtest);
textView1.setText(""+ nbTextView);
} }
if I comment : MyTextView[] text =(MyTextView[])intent.getSerializableExtra(MainActivity.EXTRA_TEXT);
the application does not crash.
Thank you all very much for your help
You cannot pass views through intents. Views are part of the layout and cannot be shared between activities.
If you want to pass array with custom objects you must implement a Parcelable or Serializable class and use:
getIntent().getParcelableExtra("array");
or
getIntent().getSerializableExtra("array");
Parcelable class will be faster but it is harder to implement.
Another way is to use a library like Gson to parse your data to Json and pass it as a string.
I have one EditText which values i want to store with a button click in an array, in second Activity i want to display these values in Listview. I have some problems with storing and displaying values in another activity.
Use callback.
in ClassA with the stringList:
Create interface
MyCallback callback;
viod setCallback(MyCallback callback){
this.callback = callback;
}
viod onStop(){
callback = null;
}
interface MyCallback{
void doSomething(String string);
}
in ClassB:
implement MyCallback
public class ClassB implements ClassA.MyCallback
set reference in onCreate
ClassA classA = new ClassA();
classA.setCallback(this);
// override method doSomething
#override
void doSomething(String string){
//get your string from your EditText…
}
when the job is done inside class A call:
callback.doSomething(string);
destroy reference inside class B in onStop()
classA.onStop();
You can use an intent when starting the second Activity from your button click.
Intent intent = new Intent(this, SecondActivity.class);
intent.putStringArrayListExtra("EXTRA_ARRAY", arrayList);
startActivity(intent);
In your second activity...
List<String> arrayList = getIntent().getStringArrayListExtra("EXTRA_ARRAY");
you can use a static arrayList inside your activity like that :
class YourActivity extends AppCompatActivity{
public static ArrayList yourArray;
#Override
void onCreate(Bundle savedInstanceState){
.......
// you can use you array to display its content
}
}
and inside your button action do like that
botton.setOnClickListener(new OnClickListener{
#Override
void onClick(View view){
YourActivity.yourArray = this.arrayList;
startActivity(new Intent(getContext , YourActivity.class));
}
});
I have been following a tutorial from this link which is basically about File browse concept in android. Everything works fine but I am getting confused of how passing intents between activities works in android after reading this link. The First activity is as follows,
public class MainActivity extends Activity implements OnClickListener {
private static final int REQUEST_PICK_FILE = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
filePath = (TextView)findViewById(R.id.file_path);
Browse = (Button)findViewById(R.id.browse);
Browse.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()) {
case R.id.browse:
Intent intent = new Intent(this, FilePicker.class);
startActivityForResult(intent, REQUEST_PICK_FILE);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK) {
switch(requestCode) {
case REQUEST_PICK_FILE:
if(data.hasExtra(FilePicker.EXTRA_FILE_PATH)) {
selectedFile = new File
(data.getStringExtra(FilePicker.EXTRA_FILE_PATH));
filePath.setText(selectedFile.getPath());
}
break;
}
}
As far as I understood, its passing the intent "REQUEST_PICK_FILE" and based on what it returns from "FilePicker.Class" , it will perform the action because its StartActivityOnResult. Confusion starts from next activity. Here is the File Picker class,
public class FilePicker extends ListActivity {
public final static String EXTRA_FILE_PATH = "file_path";
public final static String EXTRA_SHOW_HIDDEN_FILES = "show_hidden_files";
public final static String EXTRA_ACCEPTED_FILE_EXTENSIONS = "accepted_file_extensions";
private final static String DEFAULT_INITIAL_DIRECTORY = "/";
.......
protected String[] acceptedFileExtensions;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.........
// Initialize the extensions array to allow any file extensions
acceptedFileExtensions = new String[] {};
// Get intent extras
if(getIntent().hasExtra(EXTRA_FILE_PATH))
Directory = new File(getIntent().getStringExtra(EXTRA_FILE_PATH));
if(getIntent().hasExtra(EXTRA_SHOW_HIDDEN_FILES))
ShowHiddenFiles = getIntent().getBooleanExtra(EXTRA_SHOW_HIDDEN_FILES, false);
if(getIntent().hasExtra(EXTRA_ACCEPTED_FILE_EXTENSIONS)) {
ArrayList<String> collection =
getIntent().getStringArrayListExtra(EXTRA_ACCEPTED_FILE_EXTENSIONS);
acceptedFileExtensions = (String[])
collection.toArray(new String[collection.size()]);
}
}
..............
Whats actually happening here? what does the lines ,
if(getIntent().hasExtra(EXTRA_SHOW_HIDDEN_FILES))
ShowHiddenFiles = getIntent().getBooleanExtra(EXTRA_SHOW_HIDDEN_FILES, false);
actually mean? We are not passing any extras like, "EXTRA_SHOW_HIDDEN_FILES" from previous activity and even EXTRA_SHOW_HIDDEN_FILES has been declared in this class. I seriously don't understand what's happening between these two activities . I am not able to proceed before understanding what's actually going on. Any help would be really great !! Thanks.
what does the lines... actually mean?
It means that if the Intent used to start FilePicker has an EXTRA_SHOW_HIDDEN_FILES, hold onto that value in what I assume is a boolean field on the activity that is not shown in your redacted code listing.
We are not passing any extras like, "EXTRA_SHOW_HIDDEN_FILES" from previous activity
You could, though. You do not have to.
even EXTRA_SHOW_HIDDEN_FILES has been declared in this class
That is fairly typical. FilePicker is declaring an API, and so it exposes the names to be used for incoming and outgoing extras. EXTRA_SHOW_HIDDEN_FILES is public, and so it can be referenced from anywhere, including MainActivity.
I don't know why, but this isn't working. Can anyone see anything wrong with my code.
I have two activities and I'm passing data from two
public class InputActivity extends AppCompatActivity {
EditText number1EditText;
EditText number2EditText;
Button addButton;
InputActivity code looks like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_input);
number1EditText = (EditText)findViewById(R.id.editText);
number2EditText = (EditText)findViewById(R.id.editText2);
addButton = (Button)findViewById(R.id.button);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mIntent = new Intent(getApplicationContext(), AddActivity.class);
mIntent.putExtra("number1", number1EditText.getText().toString());
mIntent.putExtra("number2", number2EditText.getText().toString());
startActivity(mIntent);
}
});
}
AddActivity code looks like this
public class AddActivity extends AppCompatActivity {
TextView answer;
double y=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
answer =(TextView)findViewById(R.id.textView);
String value1 = getIntent().getExtras().getString("number1");
String value2 = getIntent().getExtras().getString("number2");
answer.setText((int) (Double.parseDouble(value1)+Double.parseDouble(value2)));
}
Just looking quickly:
answer.setText((int) (Double.parseDouble(value1)+Double.parseDouble(value2)));
You're passing a int to the method setText() which happens to have an overload that receives a int argument for the cases when you pass the reference from a String in some xml. You may be getting a ResourceNotFoundException.
If you want to show a text with the sum between your values:
answer.setText(String.valueOf((int) (Double.parseDouble(value1)+Double.parseDouble(value2))));
Just keep in mind that there are a lot of checks you have to do first, you may get another exceptions doing this kind of parse, like NumberFormatException for instance.
Suppose we have two simple applications, so we have two different packages.
Each of these packages has an Activity that can be launched by clicking the application icon. Suppose that the two activities are as follows:
MyFirstActivity, which is into the package org.firstexample.firstactivity
MySecondActivity, which is into the package org.secondexample.secondactivity
Suppose we have launched the MyFirstActivity activity, so it is running.
Could the MySecondActivity activity send data directly to the MyFirstActivity activity?
I would like the two activities (which are in different packages) can communicate with each other by exchanging data.
if you are launching MySecondActivity from MyFirstActivity then use this way:
in Activity MyFirstActivity:
Intent intent25 = new Intent(Intent.ACTION_MAIN).addCategory(
Intent.CATEGORY_LAUNCHER).setClassName("org.secondexample",
"org.secondexample.MySecondActivity").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.addFlags(Intent.FLAG_FROM_BACKGROUND).setComponent(new ComponentName("rg.secondexample",
"org.secondexample.MySecondActivity"));
Bundle bundle = new Bundle();
bundle.putString("Name", "test");
intent25.putExtras(bundle);
getApplicationContext().startActivity(intent25);
and in MySecondActivity oncreate()
Bundle bundle = this.getIntent().getExtras();
String name = bundle.getString("Name");
If you want to pass data without resuming on destroying activity then you have to make listener for that..
public class MyFirstActivity extends Activity implements OnDataChanged {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public void onChange(int a) {
Log.e("", "a : " + a);
}
}
MySecondActivity.java
public class MySecondActivity extends Activity {
private OnDataChanged mOnDataChanged;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sendData(10);
}
public interface OnDataChanged {
public void onChange(int a);
}
private void sendData(int a) {
mOnDataChanged.onChange(a);
}
}
MySecondActivity is sending 10 to MyFirstActivity by implementing listener of MySecondActivity...