How to Display array list in another Activity? - android

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

Related

Split code to two classes

I have a class with a lot of code. I want to put some of the methods into another class, but load them from the class that i already have. I don't want to change the contentview either. I tried
Class1:
public class Class1 extends Activity {
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState;
Intent intent = new Intent (this, Class2.class);
startActivity(intent);
}
}
Class2:
public class Class2 extends Class1 {
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
method2();
}
}
public void method2 {
Log.e("Error", "Wut?")
}
When i run that code, the app just displays the error message over and over. The app is probably running the "method2" method over and over again... I just want to run the "method2"once. I don't want the code in the same file either, because there is gonna be a lot of code...
All you have to do is call the class2 in a object Class. Remember that is a java class so. Call it!
Class2 newClass = new Class2();
newClass. method2();
The class2 is not a activity, is only a class for has all your methods.. It is would not extends of nothing!
As I see no sense in your approach here's a workaround.
public class Class1 extends Activity {
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState;
if(!this instanceof Class2)
{
Intent intent = new Intent (this, Class2.class);
startActivity(intent);
}
}
}

Custom Objects not being passed to other Activity via intent PutExtra

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.

Pass custom class instance between activities

I have a custom class 'Game' which i init at top of activity code. I then go to another activity, usually i pass arraylists etc but i want to move to passing my custom class.....
My custom class 'game' is a bunch of strings and arraylists with getter and setter mehtods.
i get a
Game is not a parcelable or serializable object
error when I try to add it to the intent. Any ideas what i can do here?
//Init Instance of Game class
Game newGame = new Game();
Set my listener. It works for
//Setup onclick listeners
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(this_Activity.this, next_Activity.class);
i.putExtra("players", myList);
i.putExtra("newGame", (Parcelable) newGame);
startActivityForResult(i, 0);
}
});
Also, your class Game may to implement interface Serializable:
public class Game implements Serializable {
...
}
You have to change listener in first activity:
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(this_Activity.this, next_Activity.class);
i.putExtra("players", myList);
i.putExtra("newGame", newGame);
startActivityForResult(i, 0);
}
});
And change method onCreate in next_Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Game newGame = (Game) getIntent().getExtras().getSerializable("newGame");
}
Game class need to implement Parcelable.

How to use notifyDataSetChanged with finish()

I have a list view which show list of task, on selecting task it shows details about task, when I delete the particular task it returns to the previous activity by finish(). but it does not update the list.
I want to know how and where to use notifyDataSetChanged method and add adapter method is never used.
Other than notifyDataSetChanged() solution is also accepted :) i just want to update the list when it returns to the previous activity.
Do it with startActivityForResult(). When you create intent to open new activity open it for result. The task being deleted is your result. So when it's marked as deleted and you return to your previous activity, the result triggers and you can delete the marked item + call the notify.
More info here : http://developer.android.com/training/basics/intents/result.html
you can use the notifyDataSetChanged on the onResume method, this always update the data itself when the Activity shows
You can also notify your parent activity before finishing your current activity. You just have to register a Receiver in your main activity and all others activities will be able to notify that activity. You can even send data!
As my english is not that good, sample code :
The MainActivity class
public class MainActivity extends AppCompatActivity {
// you can define your name for your receiver as a constant,
// so you can access it from other activities if you want
public static final String MY_SUPER_INTERNAL_NOTIFICATION = "MY_SUPER_INTERNAL_NOTIFICATION";
public static final String MY_OBJECT = "my_object";
public static final String MY_OBJECT_POSITION = "my_object_position" ;
private MyCustomAdapter adapter;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.listView);
// set up your list with your adapter and data...
adapter = new MyCustomAdapter(this);
// [...] I suppose you know how to do that, I dont write everything
listView.setAdapter(adapter);
// when you click on a row from your list,
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(
MainActivity.this,
SecondActivity.class
);
// you can for example put data in a Bundle and pass it to the other activity
// then on the onCreate you can use that data as you want
Bundle bundle = new Bundle();
// IMPORTANT be sure that the object you are putting in the bundle is Serializable (implements Serializable)
bundle.putSerializable(MY_OBJECT, adapter.getItem(position));
// you can also for example send the position of the row you clicked
bundle.putInt(MY_OBJECT_POSITION, position);
// put your bundle in the intent
intent.putExtras(bundle);
startActivity(intent);
}
});
// register your Receiver! don't forget to do that or you will never be notified
LocalBroadcastManager
.getInstance(this)
.registerReceiver(
broadcastReceiver,
new IntentFilter(MY_SUPER_INTERNAL_NOTIFICATION)
);
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
// get the position sent by the other activity
int position = intent
.getExtras()
.getInt(SecondActivity.MY_EXAMPLE_KEY);
adapter.deleteItem(position);
}
}
};
// adapter class...
private class MyCustomAdapter extends BaseAdapter {
ArrayList<MyObject> data;
public MyCustomAdapter(Context context) {
}
public void deleteItem(int position){
// delete your item from the list of data
data.remove(position);
// dont forget to notify
notifyDataSetChanged();
}
#Override
public int getCount() {
return 0;
}
#Override
public MyObject getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return null;
}
// adapter class, you can extend your favorite type of adapter
}
}
The SecondActivity class :
public class SecondActivity extends AppCompatActivity {
public static final String MY_EXAMPLE_KEY = "EXAMPLE";
private MyObject myObject;
private int myObjectPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
myObject = (MyObject) getIntent()
.getExtras()
.getSerializable(MainActivity.MY_OBJECT);
myObjectPosition = getIntent()
.getExtras()
.getInt(MainActivity.MY_OBJECT_POSITION);
// do all your stuff with your object
// before calling finish do this
beforeFinishDoThisStuff();
}
private void beforeFinishDoThisStuff() {
sendBroadcastToMainActivity();
finish();
}
private void sendBroadcastToMainActivity() {
// create an intent and put your Receiver name as action name
// like you defined in your MainActivity
Intent intent = new Intent(MainActivity.MY_SUPER_INTERNAL_NOTIFICATION);
Bundle bundle = new Bundle();
// put whatever you want, here I put just the previous position of the object in the list
bundle.putInt(MY_EXAMPLE_KEY, myObjectPosition);
intent.putExtras(bundle);
// notify your MainActivity
LocalBroadcastManager
.getInstance(this)
.sendBroadcast(intent);
// after this finish !
}
}
Hope you understand how to notify activities with BroadcastManager. It's very powerful and simple to use.
Have fun coding !

How to use a method of activity1 for activity1, calling this method from activity2?

I have a method in MainActivity. java
public void spinset(String[] a)
{
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, a);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin_main = (Spinner) findViewById(R.id.spinner);
spin_main.setAdapter(adapter);
spin_main.setPrompt("Член семьи");
spin_main.setSelection(0);
}
I need to call this method on onCLick event in Dialog_mem.java
...
MainActivity ma=new MainActivity();
...
public void onClick(View v) {
switch(v.getId())
{ case R.id.mem_btnOK:
datasource.open();
datasource.putrecord("Mem_Name", memname.getText().toString());
datasource.insertrecord("Members");
date=datasource.curspinner("Members", "Mem_Name");
datasource.close();
//HERE
ma.spinset(date);
default:
dismiss();}
}
But I need this method to work for my MainActivity, not for Dialog_mem.
Or is there a way to know in MainActivity that the button in Dialog_mem was clicked? Or Maybe you know another way to do this?
you can implement your own interfaces to give call back to previous activity this can be done as shown below
public interface myListener {
public void doMyWork(boolean success, Object message);
}
make your mainActivity implement this listener and override unimplemented methods:
public class MainActivity extends Activity implements myListener{
onCreate(Bundle savedInstanceState){
Dialog_mem dm = new Dialog_mem();
dm.setmyListener(this);
}
public void doMyWork(boolean success,Object message){
// your code here
// call spinset from here
}
}
create the setmyListener() method in Dialog_mem
public class Dialog_mem {
myListener listener;
public void setmyListener(myListener listener){
this.listener = listener
}
}
make a callback from Dialog_mem to MainActivity by calling this method when you want to do your work in spinset method.
public void onClick(View v) {
switch(v.getId())
{ case R.id.mem_btnOK:
datasource.open();
datasource.putrecord("Mem_Name", memname.getText().toString());
datasource.insertrecord("Members");
date=datasource.curspinner("Members", "Mem_Name");
datasource.close();
//HERE
listener.doMyWork(success,message);
default:
dismiss();}
}
start Dialog_mem by calling startActivityForResult and in case of ok send a result code.
In your MainActivity onActivityResult will be called when you come back from Dialog_mem here you can check the result code and call your function.

Categories

Resources