How send variable in OnClickListener - android

I will make anonym function onClick for new widget. I load variable data from res/raw. But i need some ID for load it. I use getResources().getIdentifier()
It looks like this:
TextView ans = new TextView(this);
String exm = "demo";
ans.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(FullscreenActivity.this, Video.class);
intent.putExtra("ex", getResources().getIdentifier( exm,"raw", getPackageName()));
startActivity(intent);
}
}
);
I have error about variable non inner class variable. But i can't final it - it will be variable. How can i send my variable in new Object OnClickListener and function onClick ?

have it as a class variable
public class MyActivity extends Activity {
String exm = "demo";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ans.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(FullscreenActivity.this, Video.class);
intent.putExtra("ex", getResources().getIdentifier( exm,"raw", getPackageName()));
startActivity(intent);
}
}
);
}
}

The easiest way is to make it a member variable of your containing Activity.

Related

How to pass intent from Adapter class to other activity but my variable is in other activity

I have a problem. I want to pass my intent String "EmailHolder" from "WarehouseActivity" to "ProfilWarehouseActivity" by click on a recyclerview item in my Adapter Class which is named as "WarehouseAdapter". I want to pass the EmailHolder to fill my data when the user updates data inside ProfilWarehouseActivity.
Here is the "Intent" from my "WarehouseActivity" class :
private String EmailHolder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_warehouse);
Bundle extras = getIntent().getExtras();
EmailHolder = extras.getString("emailuser");
Here is how I make intent in Adapter Class "WarehouseAdapter" to pass ID data into "ProfilWarehouseActivity" :
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull WarehouseAdapter.ViewHolder holder, final int position) {
holder.namaitem.setText(listItems.get(position).get(Konfigurasi_Warehouse.TAG_WAREHOUSENAMA));
holder.stockitem.setText("Stock : "+listItems.get(position).get(Konfigurasi_Warehouse.TAG_WAREHOUSESTOCK));
holder.merekitem.setText("Merek : "+listItems.get(position).get(Konfigurasi_Warehouse.TAG_WAREHOUSEMEREK));
holder.tglin.setText("Tanggal Masuk : "+listItems.get(position).get(Konfigurasi_Warehouse.TAG_WAREHOUSETGLIN));
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v ) {
String idItem = listItems.get(position).get(Konfigurasi.TAG_ITEMID);
passid(idItem);
}
});
}
private void passid(String idItem) {
Intent intent = new Intent(context, ProfilWarehouseActivity.class);
intent.putExtra(Konfigurasi_Warehouse.WAREHOUSE_ID,idItem);
//i think this is for get my EmailHolder from WarehouseActivity to pass it with Intent from this Adapter class
context.startActivity(intent);
}
My question is How to pass Intent with a string "EmailHolder" that contain Intent value through my WarehouseAdapter (Adapter class), but "EmailHolder" is from my WarehouseActivity?
EDIT : Here is how i used the Adapter class from my WarehouseActivity
final WarehouseAdapter mAdapter = new WarehouseAdapter( WarehouseActivity.this,list);
mRecyclerView.setLayoutManager(new LinearLayoutManager(WarehouseActivity.this));
mRecyclerView.setAdapter(mAdapter);
You can have couple of options to solve this:
Option 1:
If you want to start "ProfilWarehouseActivity" activity from the adapter, then you need to pass the "EmailHolder" from "WarehouseActivity" to your adapter by either its constructor, or a setter:
Passing String into Adapter Constructor
final WarehouseAdapter mAdapter = new WarehouseAdapter( WarehouseActivity.this, list, EmailHolder);
Passing String using a Setter
In "ProfilWarehouseActivity" activity:
mAdapter.setEmailHolder(EmailHolder);
In WarehouseAdapter adapter:
private String mEmailHolder;
public void setEmailHolder(String emailHolder) {
this.mEmailHolder = emailHolder;
}
....
private void passid(String idItem) {
Intent intent = new Intent(context, ProfilWarehouseActivity.class);
intent.putExtra(Konfigurasi_Warehouse.WAREHOUSE_ID, idItem);
intent.putExtra("EmailHolder", mEmailHolder);
//i think this is for get my EmailHolder from WarehouseActivity to pass it with Intent from this Adapter class
context.startActivity(intent);
}
Option 2:
The other option is to create a listener and implement it in "ProfilWarehouseActivity", And pass the itemId as a parameter to the listener callback. Then let your "ProfilWarehouseActivity" call the "WarehouseActivity" instead of the WarehouseAdapter whenever this listener is triggered.
In WarehouseAdapter adapter:
public interface ItemClickListener {
public void onItemClick(int idItem);
}
ItemClickListener mItemClickListener;
public void setItemClickListener(ItemClickListener listener) {
mItemClickListener = listener;
}
private void passid(String idItem) {
if (mItemClickListener != null)
mItemClickListener.onItemClick(idItem);
}
In "ProfilWarehouseActivity" activity:
class ProfilWarehouseActivity extends AppCompatActivity implements WarehouseAdapter.ItemClickListener {
private String EmailHolder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_warehouse);
Bundle extras = getIntent().getExtras();
EmailHolder = extras.getString("emailuser");
}
#Override
onItemClick(int itemId) {
Intent intent = new Intent(this, ProfilWarehouseActivity.class);
intent.putExtra(Konfigurasi_Warehouse.WAREHOUSE_ID, idItem);
intent.putExtra("EmailHolder", EmailHolder);
startActivity(intent);
}
...
final WarehouseAdapter mAdapter = new WarehouseAdapter( WarehouseActivity.this,list);
mAdapter.setItemClickListener(this);
Pass the emailHolder value to your Adapter while creating your Adapter constructor. If I am not wrong, you might be calling the Adapater from your Activity, so just pass the value as constructor parameter.
wareHouseAdapter = new new WarehouseAdapter( WarehouseActivity.this,list,EmailHolder);
And in the WarehouseAdapter
WarehouseAdapter(otherparameter,String emailHolder) {
this.emailHolder= emailHolder;
}
And on clicking the recyclerView item
private void passid(String idItem) {
Intent intent = new Intent(context, ProfilWarehouseActivity.class);
intent.putExtra(Konfigurasi_Warehouse.WAREHOUSE_ID,idItem);
//i think this is for get my EmailHolder from WarehouseActivity to pass it with Intent from this Adapter class
intent.putExtra("emailHolder",emailHolder);
context.startActivity(intent);
}
i think i accidently found the answer (inspired from the other answer before me, thank you)... i just need to set String "EmailHolder" in "WarehouseActivity" to "public static" :
public static String EmailHolder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_warehouse);
mRecyclerView = findViewById(R.id.recyclerViewItemWar);
Bundle extras = getIntent().getExtras();
EmailHolder = extras.getString("emailuser");
And then use intent from "WarehouseAdapter" like this :
private void passid(String idItem) {
Intent intent = new Intent(context, ProfilWarehouseActivity.class);
intent.putExtra(Konfigurasi_Warehouse.WAREHOUSE_ID,idItem);
intent.putExtra("emailuser",WarehouseActivity.EmailHolder); //i add this
context.startActivity(intent);
}
is it fine to change String from "private" to "public static"..?
For that you have use "interface " You cant directly pass value in Constructor also.

PutExtra getExtra in RecyclerView not working

I need help.
I create android recyclerview cardview project, when data list from cardview clicked (use putExtra dan getExtra) will call new activity , but not working (in new activity blank no content).
this my code (CardViewAndroidAdapter.java) my full code error when i paste in here - ask in stackoverflow
holder.btnDetail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra("PUT_PHOTO", getListAndroid().get(position).getPhoto());
intent.putExtra("PUT_DESK", getListAndroid().get(position).getDesk());
context.startActivity(intent);
}
});
this my code (DetailActivity.java) my full code error when i paste in here
public class DetailActivity extends AppCompatActivity {
private static final String GET_PHOTO = "get_photo";
private static final String GET_DESK = "get_desk";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
getSupportActionBar().setTitle("Detail Version");
getIncomingIntent();
}
private void getIncomingIntent() {
if(getIntent().hasExtra(GET_PHOTO)&&getIntent().hasExtra(GET_DESK)){
String getPhoto=getIntent().getStringExtra(GET_PHOTO);
String getDesk = getIntent().getStringExtra(GET_DESK);
TextView detail=findViewById(R.id.tv_detail);
detail.setText(getDesk);
ImageView img_item_photo=findViewById(R.id.img_item_photo);
Glide.with(this)
.load(getPhoto)
.into(img_item_photo);
}
}
Replace this:
intent.putExtra("PUT_PHOTO", getListAndroid().get(position).getPhoto());
intent.putExtra("PUT_DESK", getListAndroid().get(position).getDesk());
with this:
intent.putExtra(DetailActivity.GET_PHOTO, getListAndroid().get(position).getPhoto());
intent.putExtra(DetailActivity.GET_DESK, getListAndroid().get(position).getDesk());
It should work now.

Multiple Instances and Multiple Activities calling the same Activity

I have three Activities. MainActivity,ActivityB and ActivityC. In activity A and B there are two buttons source and destination in both activities. in Activity C there is a list of data. when button is clicked (either Source or destination) from activity A and B. both Activities are calling Activity C
code for Activity A is following
public class MainActivity extends Activity {
TextView source,destination;
Button sendSource,sendDestination,btnTob;
String src,des,activity,checksrc,checkdes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
source=(TextView)findViewById(R.id.tv_rcvDataA);
destination=(TextView)findViewById(R.id.tv_rcvDataAa);
sendSource=(Button)findViewById(R.id.btn_sendA);
sendDestination=(Button)findViewById(R.id.btn_sendAa);
btnTob=(Button)findViewById(R.id.btn_toB);
sendSource.setText("source");
sendDestination.setText("destination");
src=sendSource.getText().toString();
des=sendDestination.getText().toString();
activity=getClass().getSimpleName();
sendSource.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent send= new Intent(MainActivity.this,ActivityC.class);
send.putExtra("source",src);
send.putExtra("Activity",activity);
startActivity(send);
}
});
sendDestination.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent senda= new Intent(MainActivity.this,ActivityC.class);
senda.putExtra("destination",des);
senda.putExtra("Activity",activity);
startActivity(senda);
}
});
btnTob.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent movetoB= new Intent(MainActivity.this,ActivityB.class);
startActivity(movetoB);
finish();
}
}); }}
and code for Activity B is
public class ActivityB extends Activity {
TextView sourceB,destinationB;
Button sendSourceB,sendDestinationB;
String src,des,activity,checksrc,checkdes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
sourceB=(TextView)findViewById(R.id.tv_rcvDataB);
destinationB=(TextView)findViewById(R.id.tv_rcvDataBa);
sendSourceB=(Button)findViewById(R.id.btn_sendB);
sendDestinationB=(Button)findViewById(R.id.btn_sendDataBa);
activity=getClass().getSimpleName();
sendDestinationB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent senda= new Intent(ActivityB.this,ActivityC.class);
senda.putExtra("destination",src);
senda.putExtra("Activity",activity);
startActivity(senda);
}
});
sendSourceB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent send= new Intent(ActivityB.this,ActivityC.class);
send.putExtra("source",src);
send.putExtra("Activity",activity);
startActivity(send);
}
});}}
now how to check in activityC which activity is calling this activity and which buttonclicklistener is calling the intent
You need to send the value for determine what value and what activity via Intent.putExtra(). Please be remember that you need to set the key as the first parameter for Intent.putExtra(), like
intent.putExtra(THIS_IS_THE_KEY, THIS_IS_YOUR_VALUE);
You need to create something like this:
// This is the key for your putExtra
// you need to create this as global variable.
public static final String FROM_KEY = "FROM";
public static final String ACTIVITY_KEY = "ACTIVITY";
public static final boolean IS_FROM_SOURCE = true;
// This is a sample to send data to Activity C
// where the activity caller is B and from source
Intent senda= new Intent(ActivityB.this,ActivityC.class);
senda.putExtra(FROM_KEY, IS_FROM_SOURCE);
senda.putExtra(ACTIVITY_KEY,"activity_a");
Then in your Activity C, you need to receive the Intent Extra.
You can get the value in Activity onCreate(), something like this:
Bundle extras = getIntent().getExtras();
boolean from = extras.getBoolean(FROM_KEY);
String act = extras.getString(ACTIVITY_KEY);
// do something here if from activity a
if(act.equals("activity_a")) {
if(IS_FROM_SOURCE) {
// do something if from source
} else {
// do something if from destination.
}
} else { // if from activity a
if(IS_FROM_SOURCE) {
// do something if from source
} else {
// do something if from destination.
}
}
In onCreate or anytime after that method is called in Activity-C, you should do the following:
Intent intent = getIntent();
if (intent != null) {
String activity = intent.getStringExtra("Activity");
String src = intent.getStringExtra("source");
// Do something with those values
}

How to get data from other activity in android?

I have two activities such as Activity A and B and I'm trying to pass two different strings from A to B using Bundle and startActivity(intent).
Like that:
Intent intent = new Intent(A.this, B.class);
Bundle bundle = new Bundle();
bundle.putString("vidoedetails", filedetails);
//bundle.putString("videoname", filename);
intent.putExtras(bundle);
//intent.putExtra("videofilename", filename);
//intent.putExtra("vidoefiledetails", filedetails);
startActivity(intent);
And in class B I'm using two TextViews to display the strings from class A seperately.
Like that:
Intent i = getIntent();
Bundle extras = i.getExtras();
filedetails = extras.getString("videodetails");
filename = extras.getString("videoname");
The problem is filedetils get printed in class B but not the file name.
Any solution for this?
you have a typo:
bundle.putString("vidoedetails", filedetails);
should be
bundle.putString("videodetails", filedetails);
I know I am 9 days late on this answer, but this is a good example of why I create a constants class. With a constants class, it doesnt matter if it is misspelled ("video" -> "vidoe") because it will be 'misspelled' in both places as you are referencing it through a well known location.
Constants.java
public static String WELL_KNOWN_STRING "org.example.stackoverflow.4792829";
Activity1.java
bundle.putString(Constants.WELL_KNOWN_STRING, filedetails);
Activity2.java
filedetails = extras.getString(Constants.WELL_KNOWN_STRING);
Yes, you spelled wrongly videodetails:
Yours: vid*OE*details
Correct: vid*EO*details
// First activity
actvty_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(v.getContext(),SECONDACTIVITY.class);
startActivityForResult(i, STATIC_INTEGER_VALUE);
}
});
/* This function gets the value from the other activity where we have passed a value on calling this activity */
public void activity_value() {
Intent i = getIntent();
Bundle extras=i.getExtras();
if(extras !=null) {
// This is necessary for the retrv_value
rtrv_value = extras.getString("key");
if(!(rtrv_value.isEmpty())) {
// It displays if the retrieved value is not equal to zero
myselection.setText("Your partner says = " + rtrv_value);
}
}
}
// Second activity
myBtn.setOnClickListener(new View.OnClickListener () {
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), FIRSTACTIVITY.class);
Bundle bundle = new Bundle();
bundle.putString("key", txt1.getText().toString());
// Here key is just the "Reference Name" and txt1 is the EditText value
intent.putExtras(bundle);
startActivity(intent);
}
});
Here's another way to pass data between Activities. This is just an example from a tutorial I was following. I have a splash screen that runs for 5 seconds and then it would kill the sound clip from:
#Override
protected void onPause() {
super.onPause();
ourSong.release();
}
I decided I wanted the sound clip to continue playing into the next activity while still being able to kill/release it from there, so I made the sound clip, MediaPlayer object, public and static, similar to how out in System.out is a public static object. Being new to Android dev but not new to Java dev, I did it this way.
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
public class Splash extends Activity {
public static MediaPlayer ourSong; // <----- Created the object to be shared
// this way
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
ourSong = MediaPlayer.create(Splash.this, R.raw.dubstep);
ourSong.start();
Thread timer = new Thread() {
public void run() {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent openStartingPoint = new Intent(
"expectusafterlun.ch.androidtutorial.MENU");
startActivity(openStartingPoint);
}
}
};
timer.start();
}
}
Then from the next activity, or any other activity, I could access that MediaPlayer object.
public class Menu extends ListActivity {
String activities[] = { "Count", "TextPlay", "Email", "Camera", "example4",
"example5", "example6" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(Menu.this,
android.R.layout.simple_expandable_list_item_1, activities));
}
#Override
protected void onPause() {
super.onPause();
Splash.ourSong.release(); // <----- Accessing data from another Activity
// here
}
}

Proper Android Intent Helper Class Usage?

I have two classes a MainActivity.class and a IntentsUtils.class.
Here is my IntentsUtils.class:
public class IntentsUtils
{
public void invokeWebBrowser(Activity activity)
{
String url = "http://snipt.net/Martin/android-intent-usage/";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
activity.startActivity(intent);
}
}
If I wanted to run invokeWebBrowser() from my MainActivity.class, what would be the best method?
Thanks.
Button button = (Button) findViewById(R.id.launch_br_btn);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick() {
IntentUtils.invokeWebBrowser(MainActivity.this);
}
})
put this to your onCreate() method of MainActivity.

Categories

Resources