How to load image from file into the memory in android?

106 views Asked by At

I have application with multitab. and user have choice to select background image from file. But when user change the tab the performance is not good and application is going slow down. So I am looking for the way that first load image into the ram and then load into the background. But I don't have any idea how can I do that. any suggestion or tutorial?

here is my code:

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    page=inflater.inflate(R.layout.activity_grc_page, container, false);
    page.setBackgroundResource(background_id);
    ((ImageView)page.findViewById(R.id.pagebackground)).setImageResource(background_id);
    ((ImageView)page.findViewById(R.id.pagebackground)).setScaleType(ImageView.ScaleType.CENTER_CROP);
    final ImageView background_view=((ImageView)page.findViewById(R.id.pagebackground));

    setBackground(background_path,background_id);

    return page;
}

public void setBackground(String path,int ires){
    if(path==null ){
        ((ImageView)page.findViewById(R.id.pagebackground)).setImageResource(ires);
        ((ImageView)page.findViewById(R.id.pagebackground)).setScaleType(ImageView.ScaleType.CENTER_CROP);
    }else{
        if(path.compareTo("")==0){
            ((ImageView)page.findViewById(R.id.pagebackground)).setImageResource(ires);
            ((ImageView)page.findViewById(R.id.pagebackground)).setScaleType(ImageView.ScaleType.CENTER_CROP);
        }else{
            if(path.indexOf("file://")==0){
                path=path.replace("file://", "");
            }
            File f = new File(path);
            if(f.exists()){
                Drawable d = Drawable.createFromPath(f.getAbsolutePath());
                ((ImageView)page.findViewById(R.id.pagebackground)).setImageDrawable(d);
                ((ImageView)page.findViewById(R.id.pagebackground)).setScaleType(ImageView.ScaleType.CENTER_CROP);
            }else{
                ((ImageView)page.findViewById(R.id.pagebackground)).setImageResource(ires);
                ((ImageView)page.findViewById(R.id.pagebackground)).setScaleType(ImageView.ScaleType.CENTER_CROP);
            }

        }

    }
}
1

There are 1 answers

0
Santosh Kathait On

You can use the concept of Lazy loading. In this way you UI will never get hanged and work smoothly..there are many tutorial available online you can check for that