How To Set Image From Another Activity's String - android

I'm trying set Image from another activity's string.
My string on MainActivity
public static String imagee; // -- this is out of onCreate
capeMod.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0)
{
MainActivity.imagee = "drawable/pc";
Intent intent = new Intent(context, ModActivity.class);
startActivity(intent);
}
});
On another activity: (yeah, this is completely wrong.)
String imagee = MainActivity.imagee;
private void showImage() {
// int imageResource = R.drawable.icon;
int imageResource = getResources().getIdentifier(imagee, null, getPackageName());
Drawable imagee = getResources().getDrawable(imageResource);
image.setImageDrawable(image);
}
I can set TextView from another activity's string but couldnt set ImageView.How can i solve issue?

Instead of using a String I suggest using the id (which is an int) directly
MainActivity:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout1);
Button capeMod = (Button)findViewById(R.id.capemod);
capeMod.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this, ModActivity.class);
intent.putExtra(ModActivity.EXTRA_DRAWABLE_ID, R.drawable.pc);
startActivity(intent);
}
}
}
}
ModActivity:
public class ModActivity extends Activity {
public static final String EXTRA_DRAWABLE_ID = "drawableId";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myLayout2);
Bundle bundle = getIntent().getExtras();
int drawableId = bundle.getInt(EXTRA_DRAWABLE_ID);
ImageView imageView = (ImageView)findViewById(R.id.myImageView);
imageView.setImageResource(drawableId);
}
}

You can use the Intent.putExtra() to send data as well as String, and in other Activity use Intent.getExtras() to receive the data. Read more here

There is a way to do it. You need to place variable name as
imagee = "pc"; //inside drawable folder.
int resourceId = Activity.getResources().getIdentifier(imagee , "drawable", "your.package.name"); // package name can get by code also.
Drawable imagee = getResources().getDrawable(imageResource);
image.setImageDrawable(image);
Try this code that will work.

You should use something like this:
assuming that you can access to the string value doing like you did with the static string, use resources:
Resources res = getResources();
String imageName= MainActivity.imagee;
int resID = res.getIdentifier(imageName, "drawable", getPackageName());
Drawable drawable = res.getDrawable(resID );
image.setImageDrawable(drawable);
EDIT: even if it works, the correct way to access a value is not through static way, is always better to go via Intents and putExtra :)

Related

App is crashing when I click the button - two intents in a button - using Enum

I need help with my code. Let me try to explain the problem:
At the first activity I have two fields where I'll set values from an Enum, for this I made a button for each field that basically shows me another activity, calls the value and brings it to the main activity. Still in the first activity I have a button that starts another activity and (at the same time) take all the values from the enum end sends to another activity. The point is, everything is working, but this last button no, when I click it the app crashes. What is happening and how can I solve it?
Here goes the code of the first activity:
public class MenuInicial extends AppCompatActivity {
public static final int CONSTANTE_BANZO = 1;
Button escolherM;
Button escolherB;
Button next;
TextView campoM;
TextView campoB;
Intent intent1;
Intent intent2;
Intent intentBundle;
Intent intentNext;
Bundle bundle;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_inicial);
intent1 = new Intent(MenuInicial.this, Montante.class);
campoM = (TextView) findViewById(R.id.fieldM);
escolherM = (Button) findViewById(R.id.chooseM);
String perfilM = getIntent().getExtras().getString("nameM");
campoM.setText(perfilM);
escolherM.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
startActivity(intent1);
}
});
intent2 = new Intent(MenuInicial.this, Banzo.class);
campoB = (TextView) findViewById(R.id.fieldB);
escolherB = (Button) findViewById(R.id.chooseB);
escolherB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
startActivityForResult(intent2, CONSTANTE_BANZO);
}
});
next = (Button) findViewById(R.id.prosseguir);
intentBundle = new Intent(MenuInicial.this, ConferenciaDosDados.class);
intentNext = new Intent(MenuInicial.this, Dados.class);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String perfilM = getIntent().getExtras().getString("nameM");
Float baseMt = getIntent().getExtras().getFloat("baseM");
Float alturaMt = getIntent().getExtras().getFloat("alturaM");
String perfilB = getIntent().getExtras().getString("nameB");
Float baseBz = getIntent().getExtras().getFloat("baseB");
Float alturaBz = getIntent().getExtras().getFloat("alturaB");
bundle.putString("nomeM",perfilM);
bundle.putFloat("baseM",baseMt);
bundle.putFloat("alturaM",alturaMt);
bundle.putString("nomeB",perfilB);
bundle.putFloat("baseB",baseBz);
bundle.putFloat("alturaB",alturaBz);
intentBundle.putExtras(bundle);
startActivity(intentBundle);
startActivity(intentNext);
}
});
}
protected void onActivityResult(int codigo, int resultado, Intent intent){
if(codigo == CONSTANTE_BANZO){
Bundle bundleB = intent.getExtras();
if(bundleB != null){
String perfilB = bundleB.getString("nameB");
campoB.setText(perfilB);
}
}
}
}
next = (Button) findViewById(R.id.prosseguir);
intentBundle = new Intent(MenuInicial.this, ConferenciaDosDados.class);
intentNext = new Intent(MenuInicial.this, Dados.class);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String perfilM = getIntent().getExtras().getString("nameM");
Float baseMt = getIntent().getExtras().getFloat("baseM");
Float alturaMt = getIntent().getExtras().getFloat("alturaM");
String perfilB = getIntent().getExtras().getString("nameB");
Float baseBz = getIntent().getExtras().getFloat("baseB");
Float alturaBz = getIntent().getExtras().getFloat("alturaB");
bundle.putString("nomeM",perfilM);
bundle.putFloat("baseM",baseMt);
bundle.putFloat("alturaM",alturaMt);
bundle.putString("nomeB",perfilB);
bundle.putFloat("baseB",baseBz);
bundle.putFloat("alturaB",alturaBz);
intentBundle.putExtras(bundle);
startActivity(intentBundle);
startActivity(intentNext);
}
});
Which activity do you want to go to? choose one. When you do, you can get those extras then when you need to goto the other activity, you can put those extras there too.
A better way to do it is to create a model (constructor with setters and getters) and put these in a list. At that point you can loop through the list and take what you need. It all depends on what you are doing though as the list will not be instantiated like intent extras would be.
Or, you can use SharedPref which is similar to a HashMap (which is also similar to the Intent Extras). SharedPref will store the key and value on the phones cache and then you can pull from that when you need it. Again, keep in mind that if the user clears the cache on the app, then it'll delete those shared pref.
Finally, you can also use a database such as Parse Server or Firebase.

How to send image to another activity in android?

I have a set of array which i am displaying in imageview during a specified interval of time.What i want when i click image i want to show that image in another activity.How can i do that
code:-
int[] imageArray = {R.drawable.amazon, R.drawable.app_me,
R.drawable.borabora, R.drawable.dubai};
public void showImage(){
m_oHandler = new Handler();
Runnable oRunnable = new Runnable() {
int i = 0;
#Override
public void run() {
img.setImageResource(imageArray[i]);
i++;
if (i > imageArray.length - 1) {
i = 0;
}
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Didn't know where to go
Intent intent = new Intent(MainActivity.this, Second.class);
intent.putExtra("BitmapImage", imageArray);
}
});
m_oHandler.postDelayed(this, 6000);
}
};
m_oHandler.postDelayed(oRunnable, 6000);
}
Do Not Pass Bitmap object.
Instead pass id of drawable resources.
Intent intent = new Intent(MainActivity.this, Second.class);
intent.putExtra("image_res_ids", CollectonUtils.join("/", imageArray);
And in Second Activity,
getIntent().getExtra("image_res_ids");
to get image resource id array.
want when i click image i want to show that image in another activity.
Use img setTag() method for saving current drawable id and get it back on click of view using getTag()
1. set drawable id using setTag:
....
img.setImageResource(imageArray[i]);
img.setTag(imageArray[i]);
....
2. Get id from v inside onClick method:
int click_drawable_id=Integer.parseInt(v.getTag().toString());
intent.putExtra("clicked_img_draw_id", click_drawable_id);
Now instead of passing imageArray Array, just use clicked_img_draw_id to get drawable id and pass it to setImageResource to show clicked image in another Activity.
Your images are drawable resources, which are nothing more that an int. So you can definitely pass them as extras in an Intent.
You can send the array as an extra and then fetch it with getIntent().getIntArrayExtra(EXTRA_IMAGE)
For more details have a look at Intents
you save the index/resource id using setTag i.e do img.setTag(index) as follows.
And fowarding it you can remove the index/resource id from tag and pass as intent extra
#Override
public void run() {
img.setImageResource(imageArray[i]);
img.setTag(i)
i++;
//your code
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Didn't know where to go
Intent intent = new Intent(MainActivity.this, Second.class);
intent.putExtra("IMAGE_RESOURCE", img.getTag());
}
});
just try to send position of your selected image
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
// passing array index
i.putExtra("id", position);
startActivity(i);
get intent
Intent i = getIntent();
// Selected image id
int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
imageView.setImageResource(imageAdapter.mThumbIds[position]);
Check this for more http://www.androidhive.info/2012/02/android-gridview-layout-tutorial/
If you want to pass single image to next activity, than in your case, only pass image index like
Intent intent = new Intent(MainActivity.this, Second.class);
intent.putExtra("BitmapImage", imageArray[i]);
and on next activity get it. like
int image_id= getIntent().getIntExtra("BitmapImage",0);
this image_id is your selected image resouce id and you can set this as setImageresouce to image view.
previewView = (ImageView) findViewById(R.id.imgPostIssue);
First Activity
Intent intent = new Intent(AddNewIssue.this, PostNewIssue.class);
intent.putExtra("picture", byteArray);
finish();
startActivity(intent);
Second Activity
Bundle extras = getIntent().getExtras();
if (extras != null) {
byte[] byteArray = extras.getByteArray("picture");
if (byteArray != null) {
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ImageView image = (ImageView) findViewById(R.id.imgPostIssue);
image.setImageBitmap(bmp);
}
}
Try this out, it will definitely work.. Hope it will help you.
Try using setTag(). Check this out
BitmapCache.java
public class BitmapCache {
private static SparseArray<Bitmap> _bitmapCache = new SparseArray<>();
public static void fillBitmapCache(#NonNull Resources resources) {
if (null == _bitmapCache)
_bitmapCache = new SparseArray<>();
if (_bitmapCache.indexOfKey(R.drawable.amazon) < 0)
_bitmapCache.append(R.drawable.amazon, BitmapFactory.decodeResource(resources, R.drawable.amazon));
if (_bitmapCache.indexOfKey(R.drawable.app_me) < 0)
_bitmapCache.put(R.drawable.app_me, BitmapFactory.decodeResource(resources, R.drawable.app_me));
if (_bitmapCache.indexOfKey(R.drawable.borabora) < 0)
_bitmapCache.put(R.drawable.borabora, BitmapFactory.decodeResource(resources, R.drawable.borabora));
if (_bitmapCache.indexOfKey(R.drawable.dubai) < 0)
_bitmapCache.put(R.drawable.dubai, BitmapFactory.decodeResource(resources, R.drawable.dubai));
}
public static Bitmap getAt(int position) {
return get(keyAt(position));
}
public static int keyAt(int position) {
return _bitmapCache.keyAt(position);
}
public static Bitmap get(#DrawableRes int resId) {
return _bitmapCache.get(resId);
}
public static boolean has(#DrawableRes int resId) {
return _bitmapCache.indexOfKey(resId) < 0;
}
public static void append(#DrawableRes int resId, #NonNull Resources resources) {
_bitmapCache.append(resId, BitmapFactory.decodeResource(resources, resId));
}
public static void put(#DrawableRes int resId, #NonNull Resources resources) {
_bitmapCache.put(resId, BitmapFactory.decodeResource(resources, resId));
}
public static int size() {
return _bitmapCache.size();
}
}
Activity First
private void showImage() {
BitmapCache.fillBitmapCache(getResources());
m_oHandler = new Handler();
Runnable oRunnable = new Runnable() {
int i = 0;
#Override
public void run() {
img.setImageBitmap(BitmapCache.getAt(i));
img.setTag(BitmapCache.keyAt(i));
i++;
if (i >= BitmapCache.size()) {
i = 0;
}
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (null != v.getTag()) {
int resId = (int) v.getTag();
Intent intent = new Intent(MainActivity.this, Second.class);
intent.putExtra("BitmapImage", resId);
}
}
});
m_oHandler.postDelayed(this, 6000);
}
};
m_oHandler.postDelayed(oRunnable, 6000);
}
Second Activity
private void displayImageOnSecond() {
Bundle bundle = getIntent().getExtras();
int resId = bundle.getInt("BitmapImage", 0);
if (resId > 0) {
secondImage.setImageBitmap(BitmapCache.get(resId));
}
}
Also I recommend to use ViewPager and customize it for auto rotate rather than the one you using currently. Runnable may cause memory leaks if Activity has been destroyed

Set dynamically created TextView on frame layout

I want to pass some data from one activity to another and set it in dynamically created TextView over frame layout of that activity..I'm using intent for that but at second activity the data is not getting extracted..Can any one tell me the simple way for this..
Following is my code..
Hidden.java
public class Hidden extends Activity implements OnClickListener {
Button btnnameadd, btnnameremove, btnmobileadd, btnmobileremove, btndone;
EditText etname, etmobile;
ImageView ivlogo;
private AlertDialog dialog;
private Uri mImageCaptureUri;
Intent jump;
//options for image selection
private static final int PICK_FROM_CAMERA = 1;
private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;
LinearLayout llname, llmobile, llimage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hidden);
captureImageInitialization();
init();
}
private void init() {
etname=(EditText)findViewById(R.id.editTextname);
etmobile=(EditText)findViewById(R.id.editTextmobile);
btnnameadd=(Button)findViewById(R.id.buttonnameadd);
btnnameremove=(Button)findViewById(R.id.buttonnameremove);
btnmobileadd=(Button)findViewById(R.id.buttonmobileadd);
btnmobileremove=(Button)findViewById(R.id.buttonmobileremove);
btndone=(Button)findViewById(R.id.buttondone);
llname=(LinearLayout)findViewById(R.id.name);
llmobile=(LinearLayout)findViewById(R.id.mobile);
btnnameadd.setOnClickListener(this);
btnnameadd.setOnClickListener(this);
btnnameremove.setOnClickListener(this);
btnmobileadd.setOnClickListener(this);
btnmobileremove.setOnClickListener(this);
btndone.setOnClickListener(this);
}
#Override
public void onClick(View v) {
jump=new Intent(Hidden.this,Framelayout.class);
if(v.getId()==R.id.buttonnameadd)
{
String strname=etname.getText().toString();
Log.d("Log",strname);
jump.putExtra("Name",strname);
}else if(v.getId()==R.id.buttonnameremove)
{
btnnameremove.setEnabled(false);
llname.removeView(findViewById(R.id.editTextname));
}else if(v.getId()==R.id.buttonmobileadd)
{
String strmobile=etmobile.getText().toString();
Log.d("Log",strmobile);
jump.putExtra("Mobile",strmobile);
Log.d("LOG",jump.putExtra("Mobile",strmobile).toString());
}else if(v.getId()==R.id.buttonmobileremove)
{
llmobile.removeView(findViewById(R.id.editTextmobile));
}else if(v.getId()==R.id.buttondone)
{
Log.d("LOG","1");
startActivity(jump);
}
}
}
FrameLayout.java
public class Framelayout extends Activity implements OnClickListener {
FrameLayout frameLayout;
Button b2,b3;
//private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_framelayout);
frameLayout = (FrameLayout)findViewById(R.id.f1);
b2=(Button)findViewById(R.id.button2);
b3=(Button)findViewById(R.id.buttonload);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
}
public void onClick(View v) {
if(v.getId()==R.id.button2){
Intent i=new Intent(Framelayout.this,Hidden.class);
startActivity(i);
}else if(v.getId()==R.id.buttonload){
Log.d("Log",getIntent().getStringExtra("Name"));
editframelayout();
}
}
private void editframelayout() {
String name=getIntent().getExtras().getString("Name");
String mobile=getIntent().getExtras().getString("Mobile");
TextView tvname=new TextView(this);
tvname.setText(name);
tvname.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tvname.setGravity(Gravity.CENTER);
TextView tvmobile=new TextView(this);
tvmobile.setText(mobile);
tvmobile.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tvmobile.setGravity(Gravity.CENTER);
frameLayout.addView(tvname);
frameLayout.addView(tvmobile);
}
}
You must use one of putExtra() overloaded methods of the intent instance you created to add your data.
Here is a sample:
Intent intent = new Intent(this, SignoutActivity.class); // # this parameter is the context of the caller
intent.putExtra("PARAM_TEXTBOX_TEXT", textboxText);
startActivity(intent);
Edit for the code you added, your design is very poor and doesn't accomplish what is intended.
Every time you click a Button a new instance of Intent is created. you are calling startActivity() only in single case:
else if(v.getId()==R.id.buttondone)
{
Log.d("LOG","1");
startActivity(jump);
}
Now you assume that the parameters added in previous button clicks are still there, but they aren't. When you click buttondone you create a new instance of Intent with no extras at all.
You can work this around as follows:
...
else if(v.getId()==R.id.buttondone)
{
String strname = etname.getText().toString();
if (strname != null && !strname.equals(""))
{
jump.putExtra("Name",strname);
}
String strmobile = etmobile.getText().toString();
if (strmobile != null && !strmobile.equals(""))
{
jump.putExtra("Mobile",strmobile);
}
startActivity(jump);
}
It still isn't well structured, but might do the trick for you
Use getIntent().getStringExtra("Name") instead of getIntent().getExtras().getString("Name");
getIntent().getStringExtra("Name")

How can I get a name of the image having its id?

I have an array of int. Those integers are the resource id's for the pictures:
final int flags[] = new int[] { R.drawable.argentina, R.drawable.austria ... }
and a String that holds the name of the image resource:
String flag = "R.drawable.argentina";
How can I easy check whether flag String is in flags array or not?
When I retrieve a value from the array and assign it the variable for example:
int flag = flag[0];
This flag variable will hold some integer like 2130837665 which is obvious.
How can I retrieve exact name from this array as a String that way I can compare it to the flag String?
You can get the name of the resource by using
String name = getResources().getResourceEntryName(flag]);
This gives name only, argentina in your case
You can get the type by
String type = getResources().getResourceTypeName(flag);
This will return drawable in your case. So you can find whether the id corresponds to the string
use this code
public class MainActivity extends Activity {
Button MyTranslateButton;
private int image[];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image =new int[]{R.drawable.adv_book,R.drawable.background,R.drawable.bid_active,R.drawable.break_finish};
MyTranslateButton = (Button)findViewById(R.id.TranslateButton);
MyTranslateButton.setOnClickListener(MyTranslateButtonOnClickListener);
}
private Button.OnClickListener MyTranslateButtonOnClickListener
= new Button.OnClickListener(){
#SuppressWarnings("null")
public void onClick(View v) {
for(int i=0 ; i < image.length ; i++){
String names[]=new String[image.length];
String name=getResources().getResourceEntryName(image[i]);
Log.i("Image Names is ",name);
names[i]=getResources().getResourceEntryName(image[i]);
}
}
};
}

Android - set random button image clickable

I'm having touble in making my random generated image (which is read as a button) become clickable which leads to each different activity for each different image. So the random images work perfect actually, the only problem it's not clickable Here's my code
final Button imgView = (Button)findViewById(R.id.top1);
Random rand = new Random();
int rndInt = rand.nextInt(4) + 1;
String imgName = "img" + rndInt;
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
imgView.setBackgroundResource(id);
On my layout, I specified the id top1 as a button.
So the above code will look up to my drawable images, which have the names 'img1.jpg', 'img2.jpg', 'img3.jpg' , and 'img4.jpg'.
So what I wanna make is something like, when 'img1.jpg' is generated, it becomes clickable and leads to for example: Activity1.java , for 'img2.jpg' the intent goes to 'Activity2.java', etc.
Thanks much in advance. I'm open for any kind of solution :)
UPDATED:
Here's the full code of my Main class:
public class Main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_x);
final Button imgView = (Button)findViewById(R.id.top1);
Random rand = new Random();
imgView.setOnClickListener(new ActivitySwitch(1,this));
imgView.setOnClickListener(new ActivitySwitch(2,this));
imgView.setOnClickListener(new ActivitySwitch(3,this));
imgView.setOnClickListener(new ActivitySwitch(4,this));
int rndInt = rand.nextInt(4) + 1;
String imgName = "img" + rndInt;
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
imgView.setBackgroundResource(id);
}
and here the ActivitySwitch class:
public class ActivitySwitch implements OnClickListener{
int imageNo;
Context context;
public ActivitySwitch(int imageNo,Context context) {
super();
this.context=context;
this.imageNo = imageNo;
}
#Override
public void onClick(View v) {
Intent it=new Intent();
if(imageNo==1)
{
it.setClass(context, ProjektAID.class);
}
else if (imageNo==2)
{
it.setClass(context, ProjektADH.class);
}
else if (imageNo==3)
{
it.setClass(context, ProjektBOS.class);
}
else if (imageNo==4)
{
it.setClass(context, ProjektBROT.class);
}
}
}
There is a way: create a new class
class ActivitySwitch implements OnClickListener{
int imageNo;
Activity context
public ActivitySwitch(int imageNo,Context context) {
super();
this.context=(Activity)context;
this.imageNo = imageNo;
}
#Override
public void onClick(View v) {
Intent it=new Intent();
if(imageNo==1){
it.setClass(context, Activity1.class);
}
else{
.......
}
startActivityForResult(it,any_integer_value);
}
}
And then in the Activity set:
imgView.setOnClickListener(new ActivitySwitcher(randInt,this);
if this is a button, simple implement the function of onclicklistener of button and call the respective activity from text it gets... ping me if u didn't understand..

Categories

Resources