Android - Dynamically set intent Extras - java

I'm trying to pass an ID to my new activity on creation.
The obvious solution seems to be to use "Intent.putExtra(name, value);".
But as the intent is only created on click, all of my buttons have the same Intent extras (useally null).
Is there any way i can initialize these from a loop?
for ( int i = 0; i< IDList.size() ; i++)
{
//Get Information from ID
btnDetails.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(getApplicationContext(),DetailActivity.class);
intent.putExtra("", IDList.get(i));
startActivity(intent);
}
});
//Add To Screen
}
In the code snippit IDList.get(i) is out of scope and a new Final Int isn't checked until the button is clicked, also going out of scope.
Is there any other was i can send the variable on click?

You can a inner class that implements OnClickListener and takes as parameter the id. For instance
private class MyOnClickListener implements OnClickListener {
private final int mId;
public MyOnClickListener(int id) {
mId = id;
}
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), DetailActivity.class);
intent.putExtra("", mId);
startActivity(intent);
}
}
for ( int i = 0; i< IDList.size() ; i++) {
btnDetails.setOnClickListener(new MyOnClickListener(IDList.get(i)));
}

Related

How to pass data between activity using parcelable in android studio

i have a recyclerview shows the list of movie,
i want when the item movie clicked can pass data to detail using parcelable
this my viewHolderAdapter
public class MovieVHolder extends RecyclerView.ViewHolder {
TextView mTxtTitleMovie, mTxtDescriptionMovie, mTxtDateMovie;
ImageView mImgPosterMovie;
public MovieVHolder(#NonNull final View itemView) {
super(itemView);
mTxtTitleMovie = itemView.findViewById(R.id.txt_title_movie);
mTxtDescriptionMovie = itemView.findViewById(R.id.txt_desc_movie);
mTxtDateMovie = itemView.findViewById(R.id.txt_date_movie);
mImgPosterMovie = itemView.findViewById(R.id.img_movie);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(context, DetailActivity.class);
context.startActivity(i);
}
});
}
public void bind(ListMovieEntity listMovieEntity) {
mTxtTitleMovie.setText(listMovieEntity.getMovieTittle());
mTxtDescriptionMovie.setText(listMovieEntity.getMovieDescription());
mTxtDateMovie.setText(listMovieEntity.getMovieDate());
Glide.with(context)
.load("https://image.tmdb.org/t/p/w185/"+listMovieEntity.getMoviePosterPath())
.into(mImgPosterMovie);
}
}
and I've added parcelable in model class
change itemviewclick like this
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(context, DetailActivity.class);
//addthis i.putExtra(DetailActivity.MOVIE, entListMovie.get(getPosition()));
context.startActivity(i);
}
});
and in the detail make like this
add this
public static final String MOVIE = "movie";
in method onCreate() add this
YourList yourList = getIntent().getParcelableExtra(MOVIE);
after that, just set the data
textview.setText(yourList.getBlaBla());
Intent supports three ways to pass data:
Direct: put our data into intents directly
Bundle: create a bundle and set the data here
Parcelable: It is a way of “serializing” our object.
Passing data: Direct
Intent i = new Intent(context, DetailActivity.class);
i.putExtra("title", mTxtTitleMovie.getText().toString();
i.putExtra("surname", edtSurname.getText().toString();
i.putExtra("email", edtEmail.getText().toString();
context.startActivity(i);
Bundle
Intent i = new Intent(context, DetailActivity.class);
Bundle b = new Bundle();
b.putString("name", edtName.getText().toString());
b.putString("surname", edtSurname.getText().toString());
b.putString("email", edtEmail.getText().toString());
i.putExtra("personBdl", b);
context.startActivity(i);
Passing data: Parcelable
Let’s suppose we have a class called Person that contains three attributes:name, surname and email.
Now if we want to pass this class it must implement the Parcelable interface like that
public class Person implements Parcelable {
private String name;
private String surname;
private String email;
// Get and Set methods
#Override
public int describeContents() {
return hashCode();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(surname);
dest.writeString(email);
}
// We reconstruct the object reading from the Parcel data
public Person(Parcel p) {
name = p.readString();
surname = p.readString();
email = p.readString();
}
public Person() {}
// We need to add a Creator
public static final Parcelable.Creator<person> CREATOR = new Parcelable.Creator<person>() {
#Override
public Person createFromParcel(Parcel parcel) {
return new Person(parcel);
}
#Override
public Person[] newArray(int size) {
return new Person[size];
}
};
Now we simply pass data like that:
Intent i = new Intent(EditActivity.this, ViewActivity.class);
Person p = new Person();
p.setName(edtName.getText().toString());
p.setSurname(edtSurname.getText().toString());
p.setEmail(edtEmail.getText().toString());
i.putExtra("myPers", p);
startActivity(i);
As you notice we simply put our object Person into the Intent. When we receive the data we have:
Bundle b = i.getExtras();
Person p = (Person) b.getParcelable("myPers");
String name = p.getName();
String surname = p.getSurname();
String email = p.getEmail();

Android Pass value to another activity

I have a MainActivity with 30 buttons (Ids: imageButton1,imageButton2...). On the click event, I'm starting a new activity called KlikNaDugme:
MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
buttons = new ImageButton[30];
for (int i = 0; i < buttons.length; i++) {
buttons[i] = (ImageButton) findViewById(R.id.imageButton + i);
vr = i;
buttons[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent myIntent = new Intent(HomeActivity.this, KlikNaDugme.class).putExtra("vrijednost", vr);
startActivity(myIntent);
}
});
}
}
I'm trying to pass vr to the KlikNaDugme activity, which is declared as a public int.
KlikNaDugme Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_klik_na_dugme);
int x = getIntent().getExtras().getInt("vrijednost");
System.out.println(x);
}
The problem is that it always gets a value of 29. How can I pass the id correctly?
Store the value of i in the button's tag:
buttons = new ImageButton[30];
for(int i=0; i<buttons.length; i++) {
{
buttons[i] = (ImageButton) findViewById(getResources().getIdentifier("imageButton" + (i + 1), "id", this.getPackageName()));
buttons[i].setTag(i);
buttons[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(HomeActivity.this, KlikNaDugme.class)
myIntent.putExtra("vrijednost", Integer.parseInt(view.getTag().toString()));
startActivity(myIntent);
}
});
}
}
The problem lies here:
buttons[i] = (ImageButton) findViewById(R.id.imageButton + i);
What you are doing is that you're creating an invalid resource reference and then finding your view upon that reference, which is obviously wrong. Remember findViewById() needs a resource id which is generated by Android Studio itself.
The solution is to save all of your 20-30 views references in an array and then use a loop to set click listeners on them
Add the vr value as tag to button and then use getTag() method to get the vr value inside onclicklistener
for(int i=0; i<buttons.length; i++) {
{
buttons[i] = (ImageButton) findViewById(R.id.imageButton + i);
vr = i;
buttons[i].setTag(vr); // This will se the vr value as tag
buttons[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int vr = (int)view.getTag() // this will get the vr value from view
Intent myIntent = new Intent(HomeActivity.this,
KlikNaDugme.class).putExtra("vrijednost", vr);
startActivity(myIntent);
}
});
}
R.id.what_ever will give you an integer value that generated by android studio in R class not the what_ever string. You should use getResources().getIdentifier() to get correct id of resource and pass it to findViewById().
Please try this code. It will get you the correct id of ImageButtons:
buttons = new ImageButton[30];
for(int i=0; i<buttons.length; i++) {
{
String buttonID = "imageButton" + (i+1);
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i] = (ImageButton) findViewById(resID);
buttons[i].setTag(i);
//vr = i;
buttons[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View args0) {
Intent myIntent = new Intent(HomeActivity.this,
KlikNaDugme.class).putExtra("vrijednost", (int)args0.getTag());
startActivity(myIntent);
}
});
}
Enjoy it.

looping through an array backwards from current position

I am quite new to java and android so be patient with me. I have an xml layout containing two buttons. One containing text of "previous" and the other "next". I also have a class containing array of strings which loops in an ascending order in a textView when a "next" button is clicked.
What i want is that i want the array to loop backwards from its current position when the "previous" button is clicked. Any ideas?
Question Class
// This file contains questions from QuestionBank
class Question{
// array of questions
private String mQuestions [] = {
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
// method returns number of questions
int getLength(){
return mQuestions.length;
}
// method returns question from array textQuestions[] based on array index
String getQuestion(int a) {
return mQuestions[a];
}
}
Main Activity.java
public class MainActivityextends AppCompatActivity {
private QuestionLibraryBeginner mQuestionLibrary = new QuestionLibraryBeginner();
private int mQuestionNumber = 1; // current question number
//initialising navigation buttons
private Button mPrevious;
private Button mNext;
private TextView mQuestionText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_beginner_review);
mPrevious = (Button) findViewById(R.id.previous);
mNext = (Button) findViewById(R.id.next);
mQuestionText = (TextView) findViewById(R.id.txtQuestion);
// receive the current question number from last activity by Intent
Intent intent = getIntent();
currentQuestionNumber = intent.getIntExtra("quizNumber", 0); // receiving the number of questions the user has attempted from previous activity
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// checking against total number of questions the user has attempted instead of total number of questions from Question Class
if (mQuestionNumber < currentQuestionNumber) {
updateQuestion();
}
});
mPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// i want it to loop backwards from here
}
});
// logic to update question from array
private void updateQuestion() {
if (mQuestionNumber < mQuestionLibrary.getLength()) {
mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
mQuestionNumber++;
}
}
}
I would suggest to do this:
1) Rename updateQuestion method to nextQuestion
2) Create a method to decrease the mQuestionNumber like this:
private void prevQuestion(){
if(mQuestionNumber > 0){
mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
mQuestionNumber--;}
}
Here's a solution accounting for bounds
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
showNextQuestion();
}
});
mPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
showPreviousQuestion();
}
});
private void showNextQuestion() {
showQuestion(1);
}
private void showPreviousQuestion() {
showQuestion(-1);
}
private void showQuestion(int increment) {
int newQuestionNumber = mQuestionNumber + increment;
if (newQuestionNumber >= 0 && newQuestionNumber < mQuestionLibrary.getLength()) {
mQuestionNumber = newQuestionNumber;
mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
}
}
It can be done by just adding a flag to mention the move,
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateQuestion(true);
});
mPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateQuestion(false);
}
});
And the method would look like:
private void updateQuestion(boolean forward) {
if(forward && mQuestionNumber < mQuestionLibrary.getLength())
mQuestionNumber++
else if (mQuestionNumber>1)
mQuestionNumber--;
mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
}
I would change the following methodes:
would remove mQuestionNummer++; from update question.
You can increment mQuestions directly in the onClickMethode of NextButton.
So you can implement your solution simply by decrement mQuestion-- in onClick of previous Button.
Code would look like this:
public class MainActivityextends AppCompatActivity {
private QuestionLibraryBeginner mQuestionLibrary = new
QuestionLibraryBeginner();
private int mQuestionNumber = 1; // current question number
//initialising navigation buttons
private Button mPrevious;
private Button mNext;
private TextView mQuestionText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_beginner_review);
mPrevious = (Button) findViewById(R.id.previous);
mNext = (Button) findViewById(R.id.next);
// receive the current question number from last activity by Intent
Intent intent = getIntent();
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mQuestionNumber < mQuestionLibrary.getLength()) {
mQuestionNumber++;
updateQuestion();
}
});
mPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// i want it to loop backwards from here
if(mQuestionNumber > 0){
mQuestionNumber--;
updateQuestion();
}
else
{}//don't do anything to prevent IndexOutOfBounds
}
});
// logic to update question from array
private void updateQuestion() {
if (mQuestionNumber < mQuestionLibrary.getLength()) {
mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
}
}
}
You need to don't mess logic of your application with view logic, decouple them.
Just make class Question able to provide previous and next questions. Also according to oop principles (solid, grasp) fetch information from class and make decision outside is wrong, make class to do it's work. Oop it's about telling classes to do things, not work instead of them.
class Questions {
private int index = 0;
private String[] mQuestions;
//better to don't hardcode and provide questions in constructor
public Question(String[] questions) {
this.questions = questions;
}
//we don't need this method
int getLength(){
return mQuestions.length;
}
//provide human readable information about current position in question list
// when you want to provide this information to user introduce label field in activity
public String currentPosition() {
int questionPosition = index + 1;
int questionsLength = mQuestions.length;
return String.format("current question number is %d from %d" , questionPosition, questionsLength);
}
//return next question when available, if next not available returns last question from array
public String next() {
int lastIndex = mQuestions.length - 1;
if(index < lastIndex) {
index++;
}
return mQuestions[index];
}
//return current question
public String current() {
return mQuestions[index];
}
//return previous question when available, if previous not available returns first question from array
public String previous() {
int firstIndex = 0;
if(index > firstIndex) {
index--;
}
return mQuestions[index];
}
}
And how to use it in Activity:
public class MainActivity extends AppCompatActivity {
//better to don't hardcode here, but provide this class from
//constructor of MainActivity just like questions array provide
// to constructor in Questions class
private Questions questions = new Questions(new String[]{"q1","q2"});
private Button mPrevious;
private Button mNext;
private TextView mQuestionText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_beginner_review);
mPrevious = (Button) findViewById(R.id.previous);
mNext = (Button) findViewById(R.id.next);
Intent intent = getIntent();
//when create Activity populate question field with first question
mQuestionText.setText(questions.current());
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mQuestionText.setText(questions.next());
}
});
mPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mQuestionText.setText(questions.previous());
}
});
}
}
p.s. you may improve this code further in way to introduce Observer pattern, Activity is a view, Questions is model.

How do I iteratively add to a List on button click in java?

I want to add values to an array/list and then store these in shared preferences, to then display on another activity.
When I try my code it only seems to save the first value, and if I add more it just overwrites the value.
I do not want to create the List each time I click the button so I have put it at the very beginning.
If there isn't an existing value then the message should be added to the List and stored in shared preferences as Status_0, if there is an existing value then it should be added as Status_1 - but it's not. I think it is because it is not saving properly in the List but I'm not sure how to do that.
Here's my code:
public class EnterReadingsActivity extends AppCompatActivity implements View.OnClickListener {
private EditText erTemperatureEditText;
private Button erSubmitBtn;
public List<String> values = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.onActivityCreateSetTheme(this);
setContentView(R.layout.activity_enterreadings);
init();
}
private void init() {
erTemperatureEditText = (EditText) findViewById(R.id.erTemperatureEditText);
erSubmitBtn = (Button) findViewById(R.id.erSubmitBtn);
erSubmitBtn.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view.getId()==R.id.erSubmitBtn) {
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
String message = erTemperatureEditText.getText().toString();
editor.putInt("Status_size", values.size());
int status_size = values.size();
for (int i = status_size; i < status_size + 1; i++) {
editor.putString("Status_" + i, message);
values.add(message);
editor.commit();
}
}
}
}
Edit:
int status_size = values.size();
for(int i = 0; i < status_size + 1; i++)
{
String value = values.get(i);
if (value != null) {
values.add(value);
status_size++;
String textView_i = "textView" + i;
TextView textView_i = new TextView(this);
textView_i.setLayoutParams(new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.WRAP_CONTENT));
textView_i.setText(value);
historyBackgroundInside.addView(textView_i);
}
}
It is incorrect to use the sharedPreferences to pass data from one activity to another.
The data are usually entered into an object (Bundle) which will be passed in the intent and then taken up in the next activity.
another way is to use the extras that works like Bundle
public class EnterReadingsActivity extends AppCompatActivity implements View.OnClickListener {
private EditText erTemperatureEditText;
private Button erSubmitBtn;
public List<String> values = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.onActivityCreateSetTheme(this);
setContentView(R.layout.activity_enterreadings);
init();
}
private void init() {
erTemperatureEditText = (EditText) findViewById(R.id.erTemperatureEditText);
erSubmitBtn = (Button) findViewById(R.id.erSubmitBtn);
erSubmitBtn.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view.getId()==R.id.erSubmitBtn) {
String message = erTemperatureEditText.getText().toString();
values.add(message);
}
//Here you should enter the condition that allows you to
//call the method to go to the next activity
//ex: click of a button, I have the list reaches a size
//Add a example code
if (values.size() == 10) {
passDataAndGoInAnotherActivity();
}
}
public void passDataAndGoInAnotherActivity () {
Intent i = new Intent (this, NameOfYouNextActivity.class);
i.putExtra("status_list", values);
// Or use Bundle
// Bundle bundle = new Bundle();
// bundle.putSerializable("status_list", values);
// i.putExtra("bundle", values)
startActivity(i)
}
}
to take in the other activity values using this code
public class NameOfYourNextActivity extends AppCompatActivity {
public List<String> values;
public ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.onActivityCreateSetTheme(this);
setContentView(R.layout.activity_nameoflayout);
listview = (ListView) findViewById(R.id.listView);
Intent intent = getIntent();
//If you first method
if (intent != null && intent.hasExtra("status_list")) {
List<String> values = (List<String>)intent.getSerializableExtra("status_list")
}
//If you second method (Bundle)
// if (intent != null && intent.hasExtra("Bundle")) {
// Bundle bundle = intent. getBundleExtra("Bundle")
// if (bundle != null && bundle.containsKey("status_list")) {
// List<String> values = (List<String>)intent.getSerializableExtra(String name)
// }
if (values != null) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
listview.setAdapter(adapter);
}
}
}
I did the update of the code to give you a solution that comes close to what you need..
Remember to create the next activity and insert it in the manifest.
Change the name of the class based on your activity and enter the correct layout name.
Remember to include in your layout a list view (change id in my code) that will allow you to print your values.
In this example it uses a simple adapter with a layout provided by Android, but you can create something custom.
Here you will find an excellent guide

what is the use of this handler while writing android code?

Here in the below code a songsManager object is created and then why is this.songsList used to store the song files and why not only songsList is used. Main question is what is the use of this and what exactly is it and when it is used?
My main doubt is that here since no other songsList is declared so there is no chance of songsList clashing so why to specifically refer to it as the songsList declared in the present class. Mainly I use it when there are arguments passed to a function whose names are same as that of objects or variables declared within the class so to avoid confusion and to tell the compiler that I want to use the object declared in that class and not the one passed as an argument I used this.. Please correct me if I am wrong and add to my knowledge about this.
The code lines of interest are followed by //
please see to it
public class CustomizedListView extends Activity{
private int currentIndex;
private String[] menuItems = {"Play","Share Music Via","Details"};
private LinkedList<File> songsList = new LinkedList<File>();//
private ArrayList<HashMap<String, String>> songsListdata = new ArrayList<HashMap<String, String>>();
private MediaMetadataRetriever mmr = new MediaMetadataRetriever();
private Utilities utils=new Utilities();
ListView list=null;
ModifiedAdapter adapter=null;
SongsManager plm=null;//
Button search;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);
plm = new SongsManager();//
File extStore = Environment.getExternalStorageDirectory();
// get all songs from sdcard
this.songsList = plm.getFilesInFolder(extStore);//
for (int i = 0; i < songsList.size(); i++) {
// creating new HashMap
HashMap<String, String> song = new HashMap<String, String>();
mmr.setDataSource(songsList.get(i).getAbsolutePath().toString());
//getting artist
String artist = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST);
if(artist==null)
artist=mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
//getting Duration
String len = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
long Len=0;
try
{
Len=Integer.parseInt(len);
}
catch(Exception e)
{
Log.i(null, ":conversion error");
}
len=utils.milliSecondsToTimer(Len);
Log.i(null, "length"+len);
song.put("songTitle", (songsList.get(i)).getName().substring(0, ((songsList.get(i)).getName().length() - 4)));
song.put("songArtist", artist);
song.put("duration", len);
song.put("songPath",songsList.get(i).getAbsolutePath().toString());
// adding HashList to ArrayList
songsListdata.add(song);
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new ModifiedAdapter(this, songsListdata);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
final String songPath =songsList.get(position).getAbsolutePath().toString();
AlertDialog.Builder builder = new AlertDialog.Builder(CustomizedListView.this);
builder.setTitle((songsList.get(position)).getName().substring(0, ((songsList.get(position)).getName().length() - 4)));
builder.setItems(menuItems, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
if(item==0)
{
Intent in = new Intent(getApplicationContext(),MainActivity.class);
// Sending songIndex to PlayerActivity
in.putExtra("songIndex", position);
setResult(100, in);
// Closing PlayListView
finish();
}
else if(item==2)
{
Intent details = new Intent(getApplicationContext(),Details.class);
details.putExtra("songPath", songPath);
startActivity(details);
}
else if(item==1)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("audio/*");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(songPath)));
startActivity(intent);
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
//Search for a song implementations
search=(Button)findViewById(R.id.searchForSong);
search.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent launchBrowser=new Intent(getApplicationContext(), Browser.class);
startActivity(launchBrowser);
}
});
}
}
Actually this answer should be broken in a few steps
1
THIS operator
it will refer to the current object/scope in which it is used
for eg:
say a button listener is made like this
new button(context).setOnClickListener(new View.onClickListener(public void onClick(View v){
//Using this here to refers to this onclicklistener
});
// for a constructor
public classname(int arg1){
//so to initialise the arg1 of yur class with this arg1
//for just thesake of.clarity you write
this.arg1=arg1;
}
2
this used here with the songlist is redundant and is of no signficance as ther e is no conflict.
Hope this helps you.
this keyword is used to refere to the current object
So you can access any member of current object using this.member. As in your example you are accesig songList within the current object so there is no difference between using this and not using this.
More use of this keyword
as you mentioned about the following example
private int a;
void method(int a){
this.a = a;
}
here this is used to refer to the member of current object as the names are same. if you used
void method(int b){
a = b;
}
then there would be no difference between using this and not using this
Some More Example
private int a = 5;
public void method() {
int a = 6;
System.out.println(a); // will print 6
System.out.println(this.a); // will print 5
}
int the following example the second one is pointing to the member variable of current object so it is printing 5.

Categories