How to pass an id into parceable? - java

I am trying to implement parceable to pass data to the next screen so on my home activity I am calling a bunch of methods (oncreate, etc.) now I am trying to take from the query made in the oncreate and pass it into the next screen on a onclick, however prior to the onclick I want to add the information by telling parceable to take care of it... However I am not sure how I can pass the information from the onclick into a new class that implements Parceable...
Here is my code attempt: (not sure what I pass into the extra, documentation is lacking on android website)
#Override
public void onClick(View v) {
if (v == add_new_dictionary) {
Log.e("clicked add button", "adding the dictionary... ");
// no return true because it is void on intents
Intent add_new_dictionary_intent = new Intent(MainActivity.this,
add_new_dictionary.class);
startActivity(add_new_dictionary_intent);
} else {
// used to get tag for dictionary
Object tag = v.getTag();
//call parceable
SendIdOfDictionary(tag);
// start new intent based on the tag -
Intent new_dictionary_view = new Intent(MainActivity.this,
dictionary_view.class);
new_dictionary_view.putExtra("d_id", WhatAmISupposeToPassInHere);
startActivity(new_dictionary_view);
}
// parceable is faster than serialization - create class to implement it
}
private void SendIdOfDictionary(Object tag) {
class ParceDictionaryData implements Parcelable {
private String tag;
/* everything below here is for implementing Parcelable */
// 99.9% of the time you can just ignore this
public int describeContents() {
return 0;
}
// write your object's data to the passed-in Parcel
public void writeToParcel(Parcel out, int flags) {
out.writeString(tag);
}
// this is used to regenerate your object. All Parcelables must have
// a CREATOR that implements these two methods
public final Parcelable.Creator<ParceDictionaryData> CREATOR = new Parcelable.Creator<ParceDictionaryData>() {
public ParceDictionaryData createFromParcel(Parcel in) {
return new ParceDictionaryData(in);
}
public ParceDictionaryData[] newArray(int size) {
return new ParceDictionaryData[size];
}
};
// example constructor that takes a Parcel and gives you an object
// populated with it's values
private ParceDictionaryData(Parcel in) {
tag = in.readString();
}
}

Use a bundle, no need for a Parceable here.
Add it to the Intent that starts your 2nd Activity:
Intent i = new Intent();
i.putExtra("tag", yourTag);
Then get it with
getIntent().getExtras().getString("tag");

to pass the values
public void onClick(View view) {
//Launching All products Activity
Intent in = new Intent(getApplicationContext(), ViewMap.class);
// sending address to next activity
in.putExtra("address",strAdd);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
and to receive the value
Intent i = getIntent();
// getting product id (pid) from intent
Bundle extras = getIntent().getExtras();
if (extras != null) {
adress=extras.getString("address");
}

Related

How do I pass the number of clicks and reset the count in another activity?

The codes are messy at this point since I've been going back and forth so much. Every time user clicks the yes/no button I want the results of counts the button has been clicked to display in another activity. I also want to reset the number of clicks from the second activity as well. All that's needed in the first activity is the question and the yes/no button. Is this possible? Thanks in advance.
public class MainActivity extends AppCompatActivity {
private static final String TAG = "SurveyActivity";
private static final String YES_INDEX = "yes votes";
private static final String NO_INDEX = "no votes";
Button mYesButton;
Button mNoButton;
Button mResetButton;
TextView mSurveyQuestion;
private int yesVoteCount = 0;
private int noVoteCount = 0;
private int resetVotes = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Use res ID to retrieve inflated objects and assign to variables
mYesButton = findViewById(R.id.yes_button);
mNoButton = findViewById(R.id.no_button);
mResetButton = findViewById(R.id.reset_button);
mSurveyQuestion = findViewById(R.id.survey_question);
mYesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addVote();
}
});
mNoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addVote();
}
});
// Resetting vote count
mResetButton.setOnClickListener(new View.OnClickListener() {
#Override
***Should this supposed to be in the second activity?
}
});
}
private void addVote() {
if (mYesButton.isPressed()) {
yesVoteCount++;
} else if (mNoButton.isPressed()) {
noVoteCount++;
}
}
In your main activity
btnShowResut.setOnClickListener(new View.OnClickListener() {
#Override
// Create intent for going to another activity
Intent intent = new Intent(this, AnotherActivity.class);
// Put counts datas to intent
intent.putExtra("yesCountKey", yesVoteCount);
intent.putExtra("noCountKey", noVoteCount);
// NEW : Go to another activity by calling it instead
// REQUEST_CODE is an integer variable
startActivityForResult(intent, REQUEST_CODE);
}
});
In Another activity, you can retrieve datas in onCreate method like this and send action to clear counts of your main activity.
...
onCreate(...){
...
// Retrieve datas from intent
int yesCount = getIntent().getIntExtra("yesCountKey", 0);
int noCount = getIntent().getIntExtra("noCountKey", 0);
mResetButton.setOnClickListener(new View.OnClickListener() {
#Override
// Send a boolean to main activity for clearing votes
Intent intent = new Intent();
intent.putExtra("resetVotes", true);
setResult(RESULT_OK, intent);
// Close second activity
finish();
}
});
}
Finally in the main activity override this method and clear votes
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == 2000 && resultCode == RESULT_OK){
boolean reset = data.getBooleanExtra("resetVotes", false);
if(reset){
yesVoteCount = 0;
noVoteCount = 0;
}
}
}
As the mentioned above, you can get the counts by using intent extras.
However if you want to reset the counts in in the second activity you might want to start the Activity B as startActivityForResult() see the Android documentation here.
Then when Activity B end you can reset the counts in the call back method onActivityResult().
If you don't want to do it like this the next best way might be to reset the counts onResume() of Activity A so that when you return to the activity you will start with fresh counts. See life cycle documentation here

How do I add data I have keyed in a EditText box into an array to list in another activity?

Below are the 3 java classes which I am using for my android application development. I would like to add the student data (name and phone number) from the AddActivity to be stored in MainActivity page after clicking "Add". I have researched on this and tried using an array. But I am quite confused on how the logic must be for the code to send the data keyed in AddActivity into the MainActivity page. Can anyone give me a guidance on how to work this out and would really be grateful if you could show me another way rather the way I am trying. I want the data to be stored in a ListView format in the MainActivity after each "Add" I have clicked in the AddActivity page. I do hope that someone will be able to guide me in doing this. Thank you.
MainActivity.java -
https://jsfiddle.net/eb1fprnn/
public class MainActivity extends AppCompatActivity {
ListView listView;
Button addStudent;
ArrayList<Student> students = new ArrayList<Student>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add();
}
public void add() {
Student student;
addStudent = (Button) findViewById(R.id.add);
addStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);
}
});
}
}
AddActivity.java -
https://jsfiddle.net/40k5mas2/
public class AddActivity extends AppCompatActivity {
EditText name, phone;
Button add;
int FphoneNumber;
String Fname;
ArrayList<Student> students;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
students = (ArrayList<Student>) getIntent().getSerializableExtra("AddNewStudent");
setContentView(R.layout.activity_add);
edit();
addStudent();
}
public void edit() {
name = (EditText) findViewById(R.id.StudentName);
phone = (EditText) findViewById(R.id.phone);
final Button addStudent = (Button) findViewById(R.id.AddStudent);
name.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
addStudent.setEnabled(!name.getText().toString().trim().isEmpty());
Fname = name.getText().toString();
String phoneNumber = phone.getText().toString();
FphoneNumber = Integer.parseInt(phoneNumber);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void addStudent() {
add = (Button) findViewById(R.id.AddStudent);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddActivity.this, MainActivity.class);
intent.putExtra("studentName",name.getText().toString() );
intent.putExtra("phoneNumber",phone.getText().toString());
startActivity(intent);
Student student = new Student(Fname, FphoneNumber);
students.add(student);
}
});
}
public void addStudent(){
add = (Button) findViewById(R.id.AddStudent);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddActivity.this,Record.class);
startActivity(intent);
}
});
}
Student.java -
https://jsfiddle.net/gy0g7b0s/
public class Student {
String mName;
int mPhoneNumber;
public Student (String name, int number){
mName = name;
mPhoneNumber = number;
};
public String getmName() {
return mName;
}
public String getmName(String newName) {
return (this.mName = newName);
}
public int getmPhoneNumber() {
return this.mPhoneNumber;
}
public int getmPhoneNumber(int newPhoneNumber) {
return (this.mPhoneNumber = newPhoneNumber);
}
#Override
public String toString() {
return String.format("%s\t%f",this.mName, this.mPhoneNumber);
}
[1] : [Image of Main Activity Page] http://imgur.com/a/pMWt4
[2] : [Image of Add Activity Page] http://imgur.com/a/8YvVc
as mentioned above, the correct way would be to use the startActivityForResult method. Check this.
And how to go about it, Damn easy!
Modifying your code:
public void add() {
Student student;
addStudent = (Button) findViewById(R.id.add);
addStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivityForResult(intent,123);
}
});
}
}
and in the same activity (MainActivity) listen for the result
Also would recommend you to use the parceler.org lib for sending objects
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode== Activity.RESULT_OK && requestCode==123){
// perform your list addition operation here and notify the adapter for change
// the returned data comes in 'data' parameter and would recommend you to use parcels.org lib
// for sending parcelable pojo across activities and fragments.
list.add(Parcels.unwrap(data.getParcelableArrayExtra(YOUR_KEY)));
adapter.notifyDataSetChanged();
}
}
And in your AddActivity, when you add just do this.
public void addStudent() {
// add the 'add' button view to the oncreatemethod
// add = (Button) findViewById(R.id.AddStudent);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do not restart the activity that opened this activty
// this activity is anyways on top of the MainActivity. Just finish this activty setting the result
// Intent intent = new Intent(AddActivity.this, MainActivity.class);
// intent.putExtra("studentName",name.getText().toString() );
// intent.putExtra("phoneNumber",phone.getText().toString());
// startActivity(intent);
// How to do that?
Student student = new Student(Fname, FphoneNumber);
Intent intent = new Intent();
intent.putExtra(YOUR_KEY, Parcels.wrap(student));
// you can also do it without the parcels lib
// intent.putExtra("studentName",name.getText().toString() );
// intent.putExtra("phoneNumber",phone.getText().toString());
setResult(123,intent); // set the result code. it should be the same one as the one your listening on in MainAcitivty
// then just finish this activity.
finish();
// this calls the onActivtyResultMethod in MainActivity which furtther does the logic
// students.add(student);
}
});
}
That should work! Cheers!
Use StartActivityForResult for AddActivity and return object from here and use in MainActivity. For example see here
Since you store the data in a file, the add activity should just write the data to the file. Then the main activity should always read the file to refresh the list.
I will suggest using a static class if you don't want to use a Database.
Or if you should use a file is just very simple to write into a file when you add and read from it in the next activity.
Just create a Static class like this.
public static class MyStaticClass{
private static ArrayList <Student> mStudents = new ArrayList<Student>()
public static void addStudent(Student theNewStudent){
mSudents.add(theNewStudent);
}
public static List<Student> getStudents(){
return mStudents;
}
}
or with a file:
public static class MyFileClass{
private static String pathFile = "Your path";
public static void addStudent(Student theNewStudent){
File file = new OutputStreamWriter(new FileOutputStream(pathFile,true)); //the true is to append to the file
file.write(/*parse your student as a string*/);
file.close();
}
public static List<Student> getStudents(){
ArrayList<Student> students = new ArrayList<>()
File file = new File(pathFile);
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
//parse your line to a student object
students.add(yourNewStudent);
}
sc.close();
return students;
}
}
Just call the add student and the get students in the proper class as follows.
MyStaticClass.addStudent(student);
or
MyFileClass.addStudent(student);
Hope it helps.
In your onclick listener:
public void onClick(View v) {
Intent intent = new Intent(AddActivity.this, MainActivity.class);
Student student = new Student(Fname, FphoneNumber);
MyStaticClass.addStudent(student); // or the FileClass
startActivity(intent);
}
and i cant see where do you retrieve the list. but just use the getStudents of the class.
Intent yourFirstAct= new Intent(firstAct.this,second.class);
yourFirstAct.putExtra("","");
startActivitForResult(yourFirstAct);
in first Activity,
#Override
public void onAcitivityResult(....){
super();
}
in your second activity when you done,
do your stuff whatever you want in second activity. and pass it to mainActivity
Intent yoursecAct= new Intent();
yourSecAct.putExtra("","");
setResult(yourSecAct);
finish();
IF YOU ARE USING IN FRAGMENT
if you do startActivityResult() in fragment means,
your fragment mainActivity must return super() in
public void onAcitivityResult(...){super()}
After getting the details from the student, put the respective details in a bundle and just use intent to go back to the main activity. Then use bundles to extract the data in the main activity.
You can use startActivityForResult for the same. if you haven't found the answer yet then please let me know. I will provide you the code.
Many above answers already defined this thing in a very good way.
This is about communication between Activities. You can use event bus to realize this.
https://github.com/JackZhangqj/EventBus
Then 1. Add event bus dependency to the App's build.grade
compile "de.greenrobot:eventbus:3.0.0
Register and unregister your subscribe in the MainActivity.java
#Override
protected void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
protected void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
3.Post event in the AddActivity.java
EventBus.getDefault().post(new Student(name.getText().toString(), phone.getText().toString()));
4.Implement event handling method in MainActivity
//The student is the added student in the AddActivity.java
public void onEventMainThread(Student student) {
}
To kind of expand a little bit on MadScientist's answer, ListView's need adapters in order set the data in it's view. You'll need to define an ArrayAdapter for your list view to communicate with. This will need to go in your MainActivity and will be initialized in the onCreate method. Assuming you want to display both types of information, you'll need to construct your adapter with the built in layout for showing two items via android.R.layout.simple_list_item_2. If you would like to create your own layout, however, you can look up how to do that here.
public class MainActivity extends AppCompatActivity {
Button addStudent;
ArrayAdapter<Student> adapter;
ArrayList<Student> students = new ArrayList<Student>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_2, students);
ListView listView = (ListView) findViewById(R.id.listView);
listView.addAdapter(adapter);
add();
}
Call the startActivityForResult(intent, 123) in your Listener to start the new activity. Then, once you have typed in your data, add your items to the intent and call finish() in your AddActivity. Override the onActivityResult in your MainActivity to pull the items off your intent and add them to your list. Finally, notify the adapter of the changes via adapter.notifyDataSetChanged()

How Can I use Same Adapter of a GridView on Different activities

Let say I have two Activities, Activity A and Activity B.
Activity A displays a list of images using the Adapter Z.
When user clicks on any image in Activity A, they will be taken to Activity B to show the full image. I'm passing image path and grid position to Activity using Intent.
Now in Activity B, I place a delete button which should delete the imagepath from the gridview adapter.
Problem is:
How can I access the Activity A adapter in activity B to call remove(position) method in my adapter.
So I can call notifyDataSetChanged in onResume of Activity A to update the gridview images.
Activity A
MyGridView = (GridView) findViewById(R.id.gridview);
adapter = new MyAdapter(this);
MyGridView .setAdapter(adapter );
Intent fullImageActivity = new Intent(getApplicationContext(), ActivityB.class);
fullImageActivity.putExtra("position", position);
fullImageActivity.putExtra("path", mediaPath);
startActivity(fullImageActivity);
Activity B
Intent i = getIntent();
// I'm getting position and path from setOnItemClickListener
position = i.getExtras().getInt("position");
path = i.getExtras().getString("path");
// I want to remove path from my adapter after clicking delete button in Activity B
Adapter
public ArrayList<String> images;
public void remove(int position){
images.remove(position);
}
use startActivityForResult.
Intent fullImageActivity = new Intent(getApplicationContext(), ActivityB.class);
fullImageActivity.putExtra("position", position);
fullImageActivity.putExtra("path", mediaPath);
startActivityForResult(fullImageActivity, 2);
check if deleted at particular position in Activity B . here I override onBackPressed() (For Ex.) method
public void onBackPressed(){
super.onBackPressed()
Intent intent=new Intent();
intent.putExtra("isdeleted",true);
intent.putExtra("pos",position);
setResult(2,intent);
finish();
}
Handle it in onActivityResult in Activity A.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
if(data.getBooleanExtra("isdeleted")){
remove from position array and notify dataset change. // pos = data.getIntExtra("pos")
}
}
}
Sorry for TYPO.
The key here is that you need to share the data and not really the adapter.
Using a singleton
You can use a singleton class to hold the image data and then access the same in both the activities. This ensures sync between both activities at all times.
Singleton Class
public class ImageData{
private ArrayList<ImageModel> mDataOfImages;
private ImageData mHelperInstance;
private ImageData(){
//private constructor to ensure singleton
}
public static ImageData getInstance(){
// return an ImageData instance according to your implementation
// of singleton pattern
}
private void setData(ArrayList<ImageModel> newData){
this.mDataOfImages = newData;
}
private void removeImage(int position){
if(this.mDataOfImages !=null && this.mDataOfImages.size() > position){
mDataOfImages.remove(position);
}
}
}
Activity A
private void saveImageData(ArrayList<ImageModel> data){
if(data !=null){
if(mAdapter !=null){
mAdapter.setData(data);
}
}
}
//Call notifydatasetchanged when activity is opened again
#Override
protected void onStart() {
if(mAdapter !=null){
mAdapter.notifyDataSetChanged();
}
}
MyAdapter
public void setData(ArrayList<ImageMode> newData){
if(newData !=null){
ImageDataSingleton.getInstance().setData(newData);
notifyDataSetChanged();
}
}
Activity B
Use the singleton class to display images in Activity B. Because you are using the model array list, you can easily implement right/left swipes and delete multiple images.
//Delete a image
private void deleteImage(){
ImageDataSingleton.getInstance().removeImage(getCurrentPosition());
// Rest of deletion handling like moving to right or left image
}
I think that you should build your remove method in activity A and be sure that it is static:
public static void remove(int position){
images.remove(position);
}
now you can call it from activity B like this:
ActivityA.remove(position);
I think this will work.

No empty constructor: android class

My problem is, I am transferring two arrays between activities. with an return from the one to another Activity. There I am getting these two Activities by the constructor( I think ). Is this correct? Why I am getting the error: no empty constructor?
Here is my class where the Activites are coming from:
public PlanOutputActivity fetchallRoutes(String startStop, String endStop, String time) {
.
.
.
return new PlanOutputActivity(convertArray(),routenArray);
Here is my Activity where i wanna get these two Arrays:
public class PlanOutputActivity extends Activity {
Intent intent;
Object[][] routenArray;
String[][] itemsArray;
DatabaseHelperActivity mdbH;
public int RESULT_OK = 123;
public int REQUEST_OK = 456;
public PlanOutputActivity(String[][] itemsArray, String[][] routenArray){
setContentView(R.layout.planoutputlayout);
this.routenArray = routenArray;
this.itemsArray = itemsArray;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated constructor stub
super.onCreate(savedInstanceState);
}
public void getRoute() {
intent = getIntent();
mdbH = new DatabaseHelperActivity(this);
mdbH.fetchallRoutes(intent.getStringExtra("StartHaltestelle"),intent.getStringExtra("ZielHaltestelle"),intent.getStringExtra("Zeit"));
ListView lvList = (ListView)findViewById(R.id.ListOutput);
ArrayAdapter<DefineRouteActivity> adapter = new RouteAdapterActivity(this, route);
lvList.setAdapter(adapter);
lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
int gKennung = view.getId();
Intent intent = new Intent(getApplicationContext(),DetailOutputActivity.class);
intent.putExtra("Kennung",gKennung);
intent.putExtra("routenArray",routenArray);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
You can't create an instance of an Android Activity using new - it simply doesn't work.
The only ways to create an Activity are either when it is launched from the Apps launcher or if you call startActivity(...) (or one of the other methods such as startActivityForResult(...) etc).
Because of that you shouldn't ever create constructors for an Activity and you should never create public static fields or methods with the intention of accessing data or calling methods in an Activity from any other application class.
If you want to pass data from one Activity to another do it using the extras in an Intent or simply persist the data in SharedPreferences or a database. Alternatively create a 'helper' class to hold the data - using the Singleton pattern is quite common for this.

Make my class take an argument

Well I have a main Screen with 5 buttons. Each time a press a button I want to go a new screen. So far I have other 5 classes (each for each screen) and 5 xmls. But Iam sure that there will be a better way beacuse this screen and the xmls are the same, and what I want to do is change some texts and some data I fetch from a database. I am sure that I can ony another class and only one xml and then pass the values that I want as arguments. (Imagine that in its final state my app must have 15 buttons, so I think it is too mych waste of space and unnecessary to have 15 .java files and 15 xml files that look the same and only some values of images and textviews change). My code for main activity is:
public class MyActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
main2Theme();}
private void main2Theme() {
setContentView(R.layout.main_new);
Button Button100 = (Button)findViewById(R.id.Button100);
Button113.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent i = new Intent(this, OtherScreenName.class);
startActivity(i);
}
}); //and so on for 15 buttons
My OtherScreenName.class is:
public class OtherScreenName extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Theme();
}
#SuppressWarnings("null")
private void Theme() {
Log.d("SnowReportApp","Do first thing");
setContentView(R.layout.otherscreenname); //THIS CHANGES IN EVERY CLASS DEPENDING ON THE ID OF THE BUTTON
String result = "";
InputStream is = null;
StringBuilder sb=null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();//() before
nameValuePairs.add(new BasicNameValuePair("ski_id","OtherScreenName"));
TextView text1 = (TextView) findViewById(R.id.otherscreenname_1);
//THESE 2 CHANGE DEPERNDING ON THE BUTTON PRESSED
//perform action.....
//AND ALSO HERE I NEED THE ID OF THE BUTTON
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(OtherScreenName.this,MyActivity.class);
startActivity(i);
}
});
Can anyone suggest how to give arguments to my class and what it should be the type of them?
If I understand your question correctly, you want to pass arguments to the activity. Normally it would be done through the class constructor, however, activities can't have user defined constructors, only the default one; they can be instantiated only indirectly via intent creation. If you need to pass data between activities, do it by putting extras to bundles, for example:
bundle.putInt("intName",intValue);
then you can extract the data from bundle by
int intValue = bundle.getInt("intName");
Put extras before starting the activity:
Intent i = new Intent(this, YourActivity.class);
Bundle b = new Bundle();
b.putInt("intName",intValue);
i.putExtras(b);
startActivity(i);
and then read the extras in the onCreate method:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
int intValue;
if (b != null)
{
intValue= b.getInt("intName");
}
}
The same way you can pass other data types as String boolean etc. If this is not sufficient and you need to pass some more complex data, then use Parcelable interface.
You can pass parameters with an Intent by adding extra's to it, something like the following:
Intent i = new Intent(this, MyActivity.class);
i.putExtra("paramName", "value");
startActivity(i);
In your activity you can use the getIntent() method to retrieve the Intent and extract your parameter(s) from it:
Intent i = getIntent();
Bundle extras = i.getExtras();
String param = extras.getString("paramName", "default value");
You can place all the different text and data in your Intent, but you can also decide based on the value of an Intent parameter which data and text to retrieve. If it is a lot of data or text you are probably better off using the second approach.
If you want to pass object instead of simple data, you must use parcelable objects as it´s explained in: [http://developer.android.com/reference/android/os/Parcelable.html][1]
Reading and writing with parcelable objects is very similar to the way with a simple data
Intent intent = new Intent(this ,newthing.class);
Bundle b = new Bundle();
b.putParcelable("results", listOfResults);
intent.putExtras(b);
startActivityForResult(intent,0);
Intent i = getIntent();
Bundle extras = i.getExtras();
String param = extras.getParcelable("results");

Categories

Resources