How to change textviews & imageviews of another activity in Android - android

I have an activity which can take a few seconds to load its content (mainly pictures) from the cloud. Let's say this content is pictures & description from a person. The user can go to pictures & description from another person by clicking on the next button. I'd like to avoid the loading time When this button is clicked.
To do this I have two activities : firstPersonActivity for the first person content, and secondPersonActivity for the second person content.
What I try to do is to load the content of the secondPersonActivity when the user is in the firstPersonActivity, so that the secondPersonActivity can be displayed "directly" (= without needing to load content from the cloud when the next button is clicked in the firstPersonActivity).
But I do not succeed in doing this, I don't know how to modify the views of the secondPersonActivity layout from the firstPersonActivity class.
I tested the following code in my firstPersonActivity but it doesn't work (there is no connexion to the cloud, it's just a test to better understand how it works). R.id.first_image_second_person is the id of my imageview in the secondPersonLayout (= the layout used in the secondPersonActivity).
ImageView firstImageSecondPerson = (ImageView) findViewById(R.id.first_image_second_person);
firstImageSecondPerson.setImageResource(R.drawable.mypicture);
When I click on the next button to go from the firstPersonActivity to the secondPersonActivity, my firstImageSecondPerson imageview is not filled.
Do you see what's wrong ?
Is there a better way to avoid the loading time when the user click on the next button ?

It is not possible to change activity if activity instance is not created. In my opinion to do what You need I would go to single activity with hidden content of second person ( VIEW.INVISIBLE ) and show/hide it when it is needed.
But if second activity must be there, then create some structure for saving bitmaps in memory. In Your code sample You get picture from drawable so we are not talking about some delays, but if images are downloaded from some server then You can create some class which will have those bitmaps created from url and instance of this class can be used on any activity.
So for example Your class for caching pictures would have some method for creating bitmaps like -How to load an ImageView by URL in Android?. And those bitmaps should be saved in some Array or HashMap to have access to it, for example ( pseudo code ):
//some structure for cashing pictures in app
class PictureCache {
static PictureCache instance;
final HashMap<Integer, Bitmap> bitmaps;
//singleton
static PictureCache getInstance(){
if (instance==null)
instance = new PictureCache();
return instance;
}
public PictureCache(){
bitmaps = new HashMap<>;
}
private Bitmap loadBitmap(String url);//#1
public addPicture(Integer personId, String href){
//add to hashMap
bitmaps.put(personId, loadBitmap(href));
}
public Bitmap getPicture(Integer personId){
return bitmaps.get(personId);
}
}
#1 - method from How to load an ImageView by URL in Android?
Using it in first activity:
PictureCache.getInstance().addPicture(12,"http://url.to.bitmap");
Using it in second activity:
Bitmap pic = PictureCache.getInstance().getPicture(12);
Important note - above code was written here and was not tested, it shows solution concept.
Important second note - using such approach with bitmaps in memory can cause to much memory usage

You cannot access the views of SecondActivity before its creation. If you called this activity once only then you are able to access its views by making them static.
One more Solution for this is..
Access the whole data at once and save it in static arraylist with the help of getter-setters. Then on SecondActivity set data from that arraylist.
Hope this will work.

I don't think you can access the view before creating the activity.
You can try to use Glide for caching your images and minimizing loading time.

Try this
Picasso.with(getContext()).load(R.drawable.generatedId).into(imageView);
or
imageView.setImageDrawable(ActivityCompat.getDrawable(getContext(),
R.drawable.generatedID));`

Related

Fill ListView With Items From Previous Activity

I'm new to Android programming, and still teaching myself to code.
Currently I'm teaching myself about GridViews and still coding that project with tutorials so I have nothing to show right now, but the basic idea is the following...
If I have images of groceries in GridView in the first activity and when you click an image you will be able to open a new activity with a larger image and you could input the number how many you things you need, like 5 apples or whatever.
All of that is more or less clear to me how to do.
But how would I send the number and image to a new (third) activity with a ListView that would list all the items you need to buy at the grocery store? How would I be able to fill the list only with items after you enter the number on the previous activity with the large picture and click an "OK" or "Add" button or whatever and not list absolutely everything?
Thanks!
It's difficult at first, but you can use an SQLiteDatabase to store the data.
It's not a quick solution for you, but definitely worth learning about if you're serious to learn android. Here's a link to the official stuff:
https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
I personally used this tutorial:
http://www.androidwarriors.com/2016/02/android-sqlite-database-tutorial-sqlite.html?m=1
Sharing some data between multiple activities or fragments is a very common situation. One way around it is implementing a Singleton Pattern.
In your case you can design some kind of data structure for your purpose and manage it inside shared singleton class. For example something like this:
public class ShoppingListManager {
private static ShoppingListManager instance = new ShoppingListManager();
private List<ShoppingItem> shoppingList;
public static ShoppingListManager getInstance() {
return instance;
}
public List<ShoppingItem> getShoppingList() {
return shoppingList;
}
public void addShoppingItem(ShoppingItem item) {
this.shoppingList.add(item);
}
...
// Make the constructor private so that this class cannot be instantiated
private ShoppingListManager(){
shoppingList = new ArrayList<String>();
}
}
Then you can access your data anywhere in your code and manage shared data in any way you'd like.
ShoppingListManager.getInstance().getShoppingList();
// You can add items in any activity
ShoppingListManager.getInstance().addShoppingItem(item);
One point to remember never store context in singleton classes as it will lead to memory leaks.

Android Gallery objects obtained from network to Individual gallery object

GridGalleryThumbnailFragment to photoActivity
All the gallery objects are obtained from internet, my current setup is whenever user reaches the Fragment a network request is made and if it successful the gallery objects with thumbnails and image urls are returned. When the user clicks on an individual item a intent will start the activity and puts extra intent data with image title and image url and the image is opened in full screen. Now I want to implement a next/previous functionality in the Activity, what is the best approach for it.
Make a second network request in the activity and get the values from this new adapter.
Remove the activity workflow and just replace View in the fragment with the full image view.
Store all the values obtained the first time around in android local storage.
You need two adapters which have the same data in the same order:
a GalleryAdapter and a ImagePagerAdapter
When the GalleryView starts the ImageView the ImageView needs the gallery-s current offset. next/previous is just adding 1 to or subtracting 1 from the offset.
I have implemented something similar but based on a database query using a CursorAdapter and a android.support.v4.view.PagerAdapter . Both GalleryView and ImageView share the same sql.
[Update]
If you donot want to load the data twice you can use a LoaderManager where GalleryView and ImageView both use the same loader-Impementation/loader-ID

Pass image from Listview to a detail activity

I have a listview with text and images from web with JSON (works fine) and when I click on that I want to go to a DetailActivity with some TextViews and the ImageView from list. I can pass all the Textviews from the ListActivity to the DetailActivity but not the ImageView.
I tried to pass the bitmap with putextras and model but nothing. How can approach that issue? Can I call the bitmap from cache direct to the DetailActivity?
You can use ImageLoader
Intent i = getIntent();
// Get the result of flag
flag = i.getStringExtra("flag"); // image
// Locate the TextViews and images in singleitemview.xml
ImageView imgflag = (ImageView) findViewById(R.id.flag);
imageLoader.DisplayImage(flag, imgflag); // use lazylist image loader
You can see this example.
Did you save the image in the local storage? In this case, it would be better to send the Uri of the saved file instead of the raw bitmap.
Passing large amounts of data by intent does not always work. Although not documented, this often fails. See
Issue: Passing large data to second Activity
Starting an activity with large intent extras
and many more.
A good work-around would be to (a) save the bitmap to a file (b) pass the filename, by intent, to the detail activity, (c) In the detail activity re-create the bitmap.
The easiest way to pass complex objects that I have found is using EventBus: https://github.com/greenrobot/EventBus
Using EventBus you avoid having to serialize the data in any way, they are made directly available for other Activities/Fragments and regular classes even.
My answer to this question has some explanation on the subject: Saving information from one fragment and dialog if the user navigates to another fragment
This article also has some nice small examples of how simple it is plus some comparison to other approaches: http://www.stevenmarkford.com/passing-objects-between-android-activities/

Pass an Image from Activity to Adapter Class

I am trying to pass an Image from SingleItem activity to CartAdapter, but i am facing problem, while trying to pass an Item Image.
I want whenever user do click on Add to Cart button in SingleItem activity, need to send Item Image and Strings from SingleItem.java to CartAdapter.java
Note: Able to pass String but trying to pass an Item Image, I am missing some code onButtonClick in SingleItem.java
Like using below line i am getting value for Item Title
myTitle = txttitle.getText().toString();
Log.d(SingleItem.LOG_TAG, "Title :: " + myTitle);
but i don't know how to get an Item Image
myThumb = // here what i should need to write
See my code below:
SingleItem.java::
// below i need your help
myThumb = // here i want to write code to get Image,
// like above i have written code to get String
Instead of sending Bitmap, write the Bitmap to file system and send its location so that the other activity can read the Bitmap from that location.
Sending large data through intents could cause ANRs
Bitmap Class implements Parcelable so you can pass your Bitmap from one class to another class but i will not recommend this. In my experience in case of large Bitmaps, this could cause ANR in android, you can use Singleton Pattern for Interclass communication for heavy objects, if you are using Singleton make sure you read multithreading issues.
Use Hash Map. In hash map put bitmap with key and pass this hash map to the Adapter. And Get that hash map in adapter class.

Android List View

So basically I have a function which is something like that :
public static Bitmap getBitmapFromURL(String src)
, which return decrypted Bitmap.I need to be able to use that Bitmap into a Lazy loading ListView.
Example :
So I have a ListView.I'm downloading encrypted images and use that getBitmapFromURL function to return them as Bitmap,and after that I want to be able to reload the ListView with the new images which getBitmapFromURL returns to me.I want to find a way to save them in cache so when there is like 50 loaded jpg's in ListView I want to be able to delete the first loaded and keep only these which are visible while scrolling the ListView.And do exactly the same thing when I have another 50 loaded images.Any Suggestions how I can do this?
This is the well-known lazyList :
http://open-pim.com/tmp/LazyList.zip
I have created the gridView with spinner I will upload it tomorrow and make it available (: Maybe create a tutorial ... I am off now I will keep you in mind

Categories

Resources