1

I am getting a memory leak from the following code. It is an activity that contains a mainViewPager. That viewPager return 4 different fragments, which each have their own ViewPagers that hold images which are being retrieved from the same asyncTask. Here is my code. When I run it I can scroll throught the Pages with some lag. But when I exit the go back into the activity I get an Out Of Memory Error. So it must be a memory leak. I've stared at my code forever and I can't figure out why. Please help me... PS. I am using the Picasso library to fetch the images from a server.

Activity

package info.nightowl.nightowl;

import info.nightowl.nightowl.LocationsGridFragment.onLocationSelectedListener;

public class NightWatch extends FragmentActivity implements onLocationSelectedListener {

public static ArrayList<String> imageUrl = new ArrayList<String>();
public static ArrayList<String> dateList = new ArrayList<String>();
public static ArrayList<String> trendList = new ArrayList<String>();
public static ArrayList<String> nameList = new ArrayList<String>();
public static ArrayList<String> imageLocationsList = new ArrayList<String>();
public static ArrayList<String> imageClubsList = new ArrayList<String>();

public static ArrayList<String> locationsList = new ArrayList<String>();
public static ArrayList<String> clubsList = new ArrayList<String>();
public static ArrayList<String> locationImagesUrl = new ArrayList<String>();
public static ArrayList<String> addressList = new ArrayList<String>();

public static ArrayList<String> hotImageUrl = new ArrayList<String>();
public static ArrayList<String> hotDateList = new ArrayList<String>();
public static ArrayList<String> hotTrendList = new ArrayList<String>();
public static ArrayList<String> hotNameList = new ArrayList<String>();
public static ArrayList<String> hotImageLocationsList = new ArrayList<String>();
public static ArrayList<String> hotImageClubsList = new ArrayList<String>();

FetchClubs fetchClubs = null;

public int width, height;
public JSONArray list;
public final String IMAGE_URL = "http://www.night-owl.info/webservice/";
SharedPreferences prefs;
static FeedFragment feedFragment;
static LocationsFragment locationsFragment;
static HotFragment hotFragment;
static ClubsFragment clubsFragment;
CustomViewPager customPager;
CustomViewPageAdapter theAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_night_watch);

    //Method to set up the tabs
    getSizes();
    setupFragments();
    updateList();

    prefs = getSharedPreferences("prefs", 0);
}

//Called from the fragment which fetches image
public void loadBitmap(String image, ImageView imageView, boolean grid, TextView loadText) {

    int size;
    if (grid) size = (width-width/9)/3;
    else size = width - width/9;
    Log.d("Pager About to load", "Pager Loading bitmap picasso");

    getBitmap load = new getBitmap(image, imageView, size, loadText);
    load.execute(image);

}

public class getBitmap extends AsyncTask<String, Void, Bitmap> {
    String loadImageUrl;
    Bitmap bmp;
    int sizes;
    TextView loadingTextView;
    private final WeakReference<ImageView> imageViewReference;

    public getBitmap(String image, ImageView imageView, int size, TextView loadText){

        imageViewReference = new WeakReference<ImageView>(imageView);
        sizes = size;
        loadingTextView = loadText;
    }

    @Override
    protected void onPreExecute() {
        Log.d("async", "async starting");
        super.onPreExecute();
    }

    @Override
    protected Bitmap doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        try {
            bmp = Picasso.with(NightWatch.this).load(IMAGE_URL+arg0[0]).resize(sizes, 
sizes).get();

        } catch (IOException e) {
            Log.d("ioexc", "Pager IOEXCEPTION IDIOT!!!");
            e.printStackTrace();
        }
        return bmp;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        /*RoundedCornersDrawable drawable = new RoundedCornersDrawable(getResources(), bmp);
        loadImage.setImageDrawable(drawable);
        loadingTextView.setVisibility(View.GONE);
        loadImage.setVisibility(View.VISIBLE);*/

        if(imageViewReference != null && bitmap!= null) {
            final ImageView imageView = imageViewReference.get();
            if(imageView != null) {
                imageView.setImageBitmap(bitmap);
                loadingTextView.setVisibility(View.GONE);
                imageView.setVisibility(View.VISIBLE);
            }
        }

    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.feed, menu);
    return true;
}

//SET UP THE TWO TABS 'FEED' AND 'LOCATIONS'

//Update ArrayList of the image names
public void updateList() {
    imageUrl.clear();
    trendList.clear();
    dateList.clear();
    nameList.clear();
    imageLocationsList.clear();
    imageClubsList.clear();

    locationsList.clear();
    clubsList.clear();
    locationImagesUrl.clear();
    addressList.clear();

    hotImageUrl.clear();
    hotTrendList.clear();
    hotDateList.clear();
    hotNameList.clear();
    hotImageLocationsList.clear();
    hotImageClubsList.clear();

    new getImageUrl().execute();
    new getLocationsUrl().execute();
}

class getImageUrl extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... arg0) {

        JSONParser parser = new JSONParser();
        JSONObject json = parser.getJSONFromUrl(IMAGE_URL + "updateimages.php");

        try {

            list = json.getJSONArray("posts");

            for(int i = 0; i < list.length(); i++) {
                JSONObject c = list.getJSONObject(i);
                String imgSrc = c.getString("source");
                String trend = c.getString("trend");
                String date = c.getString("date");
                String name = c.getString("name");
                String location = c.getString("location");
                String club = c.getString("club");

                imageUrl.add(imgSrc);
                dateList.add(date);
                trendList.add(trend);
                nameList.add(name);
                imageLocationsList.add(location);
                imageClubsList.add(club);

                Log.d("async trend", trendList.get(0));
            }

            Log.d("Got list", imageUrl.get(0) + " " + trendList.get(0));

        } catch(JSONException je) {
            je.printStackTrace();   
        }

        try {

            list = json.getJSONArray("hot");

            for(int i = 0; i < list.length(); i++) {
                JSONObject c = list.getJSONObject(i);
                String imgSrc = c.getString("source");
                String trend = c.getString("trend");
                String date = c.getString("date");
                String name = c.getString("name");
                String location = c.getString("location");
                String club = c.getString("club");

                hotImageUrl.add(imgSrc);
                hotDateList.add(date);
                hotTrendList.add(trend);
                hotNameList.add(name);
                hotImageLocationsList.add(location);
                hotImageClubsList.add(club);
                Log.d("async trend", trendList.get(0));
            }

            Log.d("Got list","hot list" + hotImageUrl.get(0) + " " + hotTrendList.get(0));

        } catch(JSONException je) {
            je.printStackTrace();   
        }

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        hotFragment.updateAdapter();
        feedFragment.updateAdapter();

    }
}

public void scrollMainPager(int pos) {
    customPager.setCurrentItem(pos, true);
}

public void scrollPager(int pos) {
    feedFragment.scrollPager(pos);
}

public void setupFragments() {

    feedFragment = new FeedFragment();
    locationsFragment = new LocationsFragment();
    hotFragment = new HotFragment();
    clubsFragment = new ClubsFragment();

    customPager = (CustomViewPager) findViewById(R.id.customviewpager);
    customPager.setOffscreenPageLimit(3);
    theAdapter = new CustomViewPageAdapter(getSupportFragmentManager());
    customPager.setAdapter(theAdapter);
    customPager.setCurrentItem(1);
}


//GET SIZES OF SCREEN
public void getSizes(){
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    width = size.x;
    height = size.y;
}


public static class CustomViewPageAdapter extends FragmentStatePagerAdapter {

    public CustomViewPageAdapter(FragmentManager fm) {
        super(fm);

    }

    @Override
    public Fragment getItem(int arg0) {

        if(arg0 == 0) return hotFragment;
        else if(arg0 == 1) return feedFragment;
        else if(arg0 == 2) return locationsFragment;
        else if(arg0 == 3) return clubsFragment;

        return null;

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return 4;
    }

}

@Override
public void onLocationSelected(int position) {




}

}

FeedFragment

public class FeedFragment extends Fragment implements OnClickListener {

ToggleButton buttonGrid;
static Spinner spinnerUploadStatus;
CustomEditText et;
CustomScrollTextView tv;
int width, height;
View view;
static boolean isGrid;
ViewPager mPager;
SharedPreferences prefs;
public ImagePagerAdapter mPageAdapter;
Button buttonSwitchFragment;

Integer[] b = { R.drawable.statusunpressed, R.drawable.red,
        R.drawable.green, R.drawable.blue };

List<Integer> spinnerList = new ArrayList<Integer>(Arrays.asList(b));
CustomSpinnerAdapter myAdapter;

@Override
public void onCreate(Bundle savedInstanceState) {

    prefs = getActivity().getSharedPreferences("prefs", 0);
    getSizes();
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.activity_feed, container, false);

    setup();

    return view;
}

@SuppressLint("NewApi")
public void setup() {

    isGrid = false;

    mPager = (ViewPager) view.findViewById(R.id.myviewpager1);
    mPager.setOffscreenPageLimit(0);

    buttonGrid = (ToggleButton) view.findViewById(R.id.button_grid);
    buttonGrid.setOnClickListener(this);

    spinnerUploadStatus = (Spinner) view
            .findViewById(R.id.buttonUploadStatus);

    myAdapter = new CustomSpinnerAdapter(getActivity(),
            R.layout.item_simple_list_item, spinnerList);
    myAdapter
            .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spinnerUploadStatus.setAdapter(myAdapter);
    spinnerUploadStatus.setDropDownWidth((int) TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, 50, getResources()
                    .getDisplayMetrics()));
    spinnerUploadStatus.setOnItemSelectedListener(myOnItemSelectedListener);
    spinnerUploadStatus.getBackground().setAlpha(0);

    buttonSwitchFragment = (Button) view
            .findViewById(R.id.buttonSwitchFragment);
    buttonSwitchFragment.setOnClickListener(this);

    Typeface font = Typeface.createFromAsset(getActivity().getAssets(),
            "NotCourierSans.ttf");
    et = (CustomEditText) view.findViewById(R.id.customEditText1);
    et.updateTypeFace(font);

    tv = (CustomScrollTextView) view
            .findViewById(R.id.customscrolltextview);
    tv.setText("WELCOME TO NIGHTOWL");
    tv.setTypeface(font);
    tv.start(width / 2500.0);

    Log.d("width", "width is " + width);
}

public void getSizes() {
    Display display = getActivity().getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    width = size.x;
    height = size.y;
}

@Override
public void onClick(View v) {

    switch (v.getId()) {

    case R.id.button_grid:

        isGrid = !isGrid;

        updateAdapter();
        break;
    case R.id.buttonSwitchFragment:
        ((NightWatch) getActivity()).scrollMainPager(2);
        break;

    }
}

public OnItemSelectedListener myOnItemSelectedListener = new OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
            long arg3) {
        int colour = arg2;

        spinnerUploadStatus.setSelection(0, true);
        et.sendText(prefs.getString("username", "username invalid"), colour);

    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }

};

public void scrollPager(int position) {

    isGrid = false;
    buttonGrid.setChecked(false);
    updateAdapter();

    mPager.setCurrentItem(position, true);
    Log.d("Pager", "PAGER UPDATED");
}

public static void disableButton(Boolean enabled) {
    spinnerUploadStatus.setEnabled(enabled);
}

public void updateAdapter() {
    int theSize;
    if (!isGrid)
        theSize = NightWatch.imageUrl.size();

    else if (NightWatch.imageUrl.size() % 9 > 0)
        theSize = NightWatch.imageUrl.size() / 9 + 1;
    else
        theSize = NightWatch.imageUrl.size() / 9;

    mPageAdapter = new ImagePagerAdapter(getChildFragmentManager(), theSize);
    mPager.setAdapter(mPageAdapter);

    Log.d("size of viewPager Adapter", "" + theSize);
}

public static class ImagePagerAdapter extends FragmentStatePagerAdapter {

    int mSize;

    public ImagePagerAdapter(FragmentManager fm, int size) {
        super(fm);

        mSize = size;
    }

    @Override
    public Fragment getItem(int arg0) {
        // TODO Auto-generated method stub
        Log.d("Starting imageDetailFragment", "");
        Log.d("Pager", "Pager starting fragment");

        Log.d("GRID", "fuck grid");
        if (!isGrid)
            return ImageDetailFragment.newInstance(
                    arg0, NightWatch.imageUrl, NightWatch.nameList,
                    NightWatch.trendList, NightWatch.dateList);
        else
            return GridFragment.newInstance(arg0, NightWatch.imageUrl);

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return mSize;
    }
}

public class CustomSpinnerAdapter extends ArrayAdapter<Integer> {

    List<Integer> resourceId;
    Context c;

    public CustomSpinnerAdapter(Context context, int textViewResourceId,
            List<Integer> objects) {
        super(context, textViewResourceId, objects);

        resourceId = objects;
        c = context;

    }

    @Override
    public View getDropDownView(int position, View convertView,
            ViewGroup parent) {
        return getCustomDropdownView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    public View getCustomView(int position, View convertView,
            ViewGroup parent) {
        ImageView imageView = new ImageView(c);

        imageView.setImageResource(resourceId.get(position));
        imageView.setLayoutParams(new ListView.LayoutParams(
                (int) TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 50, getResources()
                                .getDisplayMetrics()), (int) TypedValue
                        .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 34,
                                getResources().getDisplayMetrics())));

        return imageView;
    }

    public View getCustomDropdownView(int position, View convertView,
            ViewGroup parent) {
        ImageView imageView = new ImageView(c);

        imageView.setImageResource(resourceId.get(position));
        imageView.setLayoutParams(new ListView.LayoutParams(
                (int) TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 50, getResources()
                                .getDisplayMetrics()), (int) TypedValue
                        .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 34,
                                getResources().getDisplayMetrics())));

        if (position == 0) {
            imageView.setVisibility(View.GONE);
        }

        return imageView;
    }

}

}

ImageDetailFragment

package info.nightowl.nightowl;

import java.io.IOException;
import java.util.ArrayList;

import com.example.nightowl.R;
import com.squareup.picasso.Picasso;

import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ImageDetailFragment extends Fragment implements OnClickListener {

int mImageNum;
ImageView imageView;
TextView trendTextView;
TextView nameTextView;
TextView dateTextView;
TextView loadingTextView;
Button upVoteButton, downVoteButton;
final String list = "voteList";
static SharedPreferences prefs;
SharedPreferences.Editor editor;
public ArrayList<String> imageUrl;
public ArrayList<String> trendList;
public ArrayList<String> nameList;
public ArrayList<String> dateList;
RelativeLayout.LayoutParams rParams;

int width, height;

static ImageDetailFragment newInstance(int imageNum,
        ArrayList<String> imageList, ArrayList<String> tempNameList,
        ArrayList<String> tempTrendList, ArrayList<String> tempDateList) {

    final ImageDetailFragment f = new ImageDetailFragment();
    Bundle args = new Bundle();
    args.putInt("imageNum", imageNum);
    args.putStringArrayList("imageList", imageList);
    args.putStringArrayList("nameList", tempNameList);
    args.putStringArrayList("trendList", tempTrendList);
    args.putStringArrayList("dateList", tempDateList);
    f.setArguments(args);
    return f;
}

public ImageDetailFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mImageNum = getArguments().getInt("imageNum");
        imageUrl = getArguments().getStringArrayList("imageList");
        nameList = getArguments().getStringArrayList("nameList");
        trendList = getArguments().getStringArrayList("trendList");
        dateList = getArguments().getStringArrayList("dateList");
    } else
        mImageNum = -1;
    prefs = getActivity().getSharedPreferences("prefs", 0);
    editor = getActivity().getSharedPreferences("prefs", 0).edit();
    getSizes();
    rParams = new RelativeLayout.LayoutParams((width - width/9), width - width/9);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    final View v = inflater.inflate(R.layout.image_detail_fragment,
            container, false);
    imageView = (ImageView) v.findViewById(R.id.imageView1);

    imageView.setVisibility(View.INVISIBLE);

    loadingTextView = (TextView) v.findViewById(R.id.loadingTextView);
    loadingTextView.setVisibility(View.VISIBLE);

    trendTextView = (TextView) v.findViewById(R.id.trendTextView);
    nameTextView = (TextView) v.findViewById(R.id.nameTextView);
    dateTextView = (TextView) v.findViewById(R.id.dateTextView);
    upVoteButton = (Button) v.findViewById(R.id.buttonUpVote);
    downVoteButton = (Button) v.findViewById(R.id.buttonDownVote);

    rParams.addRule(RelativeLayout.BELOW, nameTextView.getId());
    rParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
    imageView.setLayoutParams(rParams);

    upVoteButton.setOnClickListener(this);
    downVoteButton.setOnClickListener(this);

    if (NightWatch.class.isInstance(getActivity())) {

        Typeface font = Typeface.createFromAsset(getActivity().getAssets(),
                "NotCourierSans.ttf");

        final String image = imageUrl.get(mImageNum);
        ((NightWatch) getActivity()).loadBitmap(image, imageView, false, loadingTextView);
        trendTextView.setText(trendList.get(mImageNum));
        nameTextView.setText(nameList.get(mImageNum));
        dateTextView.setText(dateList.get(mImageNum));

        updateButtonBackgrounds();

        loadingTextView.setTypeface(font);
        trendTextView.setTypeface(font);
        nameTextView.setTypeface(font);
        dateTextView.setTypeface(font);
        Log.d("fragment trend", NightWatch.trendList.get(0));

    }

    return v;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

}

@Override
public void onClick(View v) {

    switch (v.getId()) {
    case R.id.buttonUpVote:

        if (prefs.getInt(imageUrl.get(mImageNum), 0) == -1) {
            downVoteButton
                    .setBackgroundResource(R.drawable.downvoteunpressed);
            upVoteButton.setBackgroundResource(R.drawable.upvotepressed);
            ((NightWatch) getActivity()).sendVote(1,
                    imageUrl.get(mImageNum));

        } else if (prefs.getInt(imageUrl.get(mImageNum), 0) == 0) {
            upVoteButton.setBackgroundResource(R.drawable.upvotepressed);
            ((NightWatch) getActivity()).sendVote(1,
                    imageUrl.get(mImageNum));
        }

        break;
    case R.id.buttonDownVote:

        if (prefs.getInt(imageUrl.get(mImageNum), 0) == 1) {
            downVoteButton
                    .setBackgroundResource(R.drawable.downvotepressed);
            upVoteButton.setBackgroundResource(R.drawable.upvoteunpressed);
            ((NightWatch) getActivity()).sendVote(-1,
                    imageUrl.get(mImageNum));

        } else if (prefs.getInt(imageUrl.get(mImageNum), 0) == 0) {
            downVoteButton
                    .setBackgroundResource(R.drawable.downvotepressed);
            ((NightWatch) getActivity()).sendVote(-1,
                    imageUrl.get(mImageNum));
        }

        break;
    }

};

public void updateButtonBackgrounds() {
    if (prefs.getInt(imageUrl.get(mImageNum), 0) == -1) {
        downVoteButton.setBackgroundResource(R.drawable.downvotepressed);
    } else if (prefs.getInt(imageUrl.get(mImageNum), 0) == 1) {
        upVoteButton.setBackgroundResource(R.drawable.upvotepressed);
    }
}

public static void sendVote(int vote, String imageName) {
    prefs.edit().putInt(imageName, vote).commit();
}

public void getSizes() {
    Display display = getActivity().getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    width = size.x;
    height = size.y;
}
}

HotFragment

package info.nightowl.nightowl;

public class HotFragment extends Fragment implements OnClickListener {

ToggleButton buttonGrid;
static Spinner spinnerUploadStatus;
CustomEditText et;
CustomScrollTextView tv;
int width, height;
View view;
static boolean isGrid;
ViewPager mPager;
SharedPreferences prefs;
public ImagePagerAdapter mPageAdapter;
Button buttonSwitchFragment;

Integer[] b = { R.drawable.statusunpressed, R.drawable.red,
        R.drawable.green, R.drawable.blue };

List<Integer> spinnerList = new ArrayList<Integer>(Arrays.asList(b));
CustomSpinnerAdapter myAdapter;

@Override
public void onCreate(Bundle savedInstanceState) {

    prefs = getActivity().getSharedPreferences("prefs", 0);
    getSizes();
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.activity_feed, container, false);

    setup();

    return view;
}

@SuppressLint("NewApi")
public void setup() {

    isGrid = false;

    mPager = (ViewPager) view.findViewById(R.id.myviewpager1);
    mPager.setOffscreenPageLimit(0);

    buttonGrid = (ToggleButton) view.findViewById(R.id.button_grid);
    buttonGrid.setOnClickListener(this);

    spinnerUploadStatus = (Spinner) view
            .findViewById(R.id.buttonUploadStatus);

    myAdapter = new CustomSpinnerAdapter(getActivity(),
            R.layout.item_simple_list_item, spinnerList);
    myAdapter
            .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spinnerUploadStatus.setAdapter(myAdapter);
    spinnerUploadStatus.setDropDownWidth((int) TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, 50, getResources()
                    .getDisplayMetrics()));
    spinnerUploadStatus.setOnItemSelectedListener(myOnItemSelectedListener);
    spinnerUploadStatus.getBackground().setAlpha(0);

    buttonSwitchFragment = (Button) view
            .findViewById(R.id.buttonSwitchFragment);
    buttonSwitchFragment.setOnClickListener(this);

    Typeface font = Typeface.createFromAsset(getActivity().getAssets(),
            "NotCourierSans.ttf");
    et = (CustomEditText) view.findViewById(R.id.customEditText1);
    et.updateTypeFace(font);

    tv = (CustomScrollTextView) view
            .findViewById(R.id.customscrolltextview);
    tv.setText("WELCOME TO NIGHTOWL");
    tv.setTypeface(font);
    tv.start(width / 2500.0);

    Log.d("width", "width is " + width);
}

public void getSizes() {
    Display display = getActivity().getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    width = size.x;
    height = size.y;
}

@Override
public void onClick(View v) {

    switch (v.getId()) {

    case R.id.button_grid:

        isGrid = !isGrid;

        updateAdapter();
        break;
    case R.id.buttonSwitchFragment:
        ((NightWatch) getActivity()).scrollMainPager(1);
        break;

    }
}

public OnItemSelectedListener myOnItemSelectedListener = new OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
            long arg3) {

        spinnerUploadStatus.setSelection(0, true);
        et.sendText(prefs.getString("username", "username invalid"), arg2);

    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }

};

public void scrollPager(int position) {

    isGrid = false;
    buttonGrid.setChecked(false);
    updateAdapter();

    mPager.setCurrentItem(position, true);
    Log.d("Pager", "PAGER UPDATED");
}

public static void disableButton(Boolean enabled) {
    spinnerUploadStatus.setEnabled(enabled);
}

public void updateAdapter() {
    int theSize;
    if (!isGrid)
        theSize = NightWatch.imageUrl.size();

    else if (NightWatch.imageUrl.size() % 9 > 0)
        theSize = NightWatch.imageUrl.size() / 9 + 1;
    else
        theSize = NightWatch.imageUrl.size() / 9;

    mPageAdapter = new ImagePagerAdapter(getChildFragmentManager(), theSize);
    mPager.setAdapter(mPageAdapter);

    Log.d("size of viewPager Adapter", "" + theSize);
}

public static class ImagePagerAdapter extends FragmentStatePagerAdapter {

    int mSize;

    public ImagePagerAdapter(FragmentManager fm, int size) {
        super(fm);

        mSize = size;
    }

    @Override
    public Fragment getItem(int arg0) {
        // TODO Auto-generated method stub
        Log.d("Starting imageDetailFragment", "");
        Log.d("Pager", "Pager starting fragment");

        Log.d("GRID", "fuck grid");
        if (!isGrid)
            return ImageDetailFragment.newInstance(arg0,
                    NightWatch.hotImageUrl, NightWatch.hotNameList,
                    NightWatch.hotTrendList, NightWatch.hotDateList);
        else
            return GridFragment.newInstance(arg0, NightWatch.imageUrl);

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return mSize;
    }
}

public class CustomSpinnerAdapter extends ArrayAdapter<Integer> {

    List<Integer> resourceId;
    Context c;

    public CustomSpinnerAdapter(Context context, int textViewResourceId,
            List<Integer> objects) {
        super(context, textViewResourceId, objects);

        resourceId = objects;
        c = context;

    }

    @Override
    public View getDropDownView(int position, View convertView,
            ViewGroup parent) {
        return getCustomDropdownView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    public View getCustomView(int position, View convertView,
            ViewGroup parent) {
        ImageView imageView = new ImageView(c);

        imageView.setImageResource(resourceId.get(position));
        imageView.setLayoutParams(new ListView.LayoutParams(
                (int) TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 50, getResources()
                                .getDisplayMetrics()), (int) TypedValue
                        .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 34,
                                getResources().getDisplayMetrics())));

        return imageView;
    }

    public View getCustomDropdownView(int position, View convertView,
            ViewGroup parent) {
        ImageView imageView = new ImageView(c);

        imageView.setImageResource(resourceId.get(position));
        imageView.setLayoutParams(new ListView.LayoutParams(
                (int) TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 50, getResources()
                                .getDisplayMetrics()), (int) TypedValue
                        .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 34,
                                getResources().getDisplayMetrics())));

        if (position == 0) {
            imageView.setVisibility(View.GONE);
        }

        return imageView;
    }

}

}

I dont see a point in posting the rest of the fragments. The memory leak is somewhere here I'm sure I would really appreciate it if someone helped me with this.

2 Answers 2

1

Loading a Bitmap from a URL in such manner will cause IOException. With Picasso, you don't even need asynctask. Simply call this in UI Thread:

Picasso.with(getActivity())
    .load(url)
    .into(imageView); //you can add .resize() before .into()

OR if you really want to have the Bitmap, you use this code:

new AsyncTask<Void, Void, Void>() {
            Bitmap bitmap;
            @Override
            protected void onPreExecute() {
                //some code
            }

            @Override
            protected Void doInBackground(Void... arg0) {
                bitmap = getBitmapFromURL(url);
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                imageView.setImageBitmap(bitmap);
            }
        }.execute();

And getBitmapFromURL():

public Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        return BitmapFactory.decodeStream(input);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
Sign up to request clarification or add additional context in comments.

9 Comments

thanks for your answer, problem is I need it to be a bitmap because I parse it into my custom drawable 'RoundedCornersDrawable' in order to make tbe image round before setting to the image view. I haven't received and IOException thus far. Should I still nnot use picasso???
If you need the Bitmap, then yes, it is not necessary to use Picasso. Just use AsyncTask and getBitmapFromURL() like the given code above. Call your RoundedCornersDrawable parser in onPostExecute before imageView.setImageBitmap(bitmap). Put the AsyncTask in a method, for example, public void loadBitmap().
thanks a lot. And with regards to any memory leaks??? are there any problems. Should I rather make my hotFragment nonstatic or should I rather return HotFragment.newInstance(arg0) in my adapter. Also my Custom FragmentStatePagerAdapters... Should they be static or non static coz I'm confused about that
I tried to summarise all my static and nonstatic fragments in this question because I know all this code might be hard to read... stackoverflow.com/questions/26664442/…
Once, I was having a thinking like yours too. But truly, a static fragment does not have anything to do with memory leak. I think I will answer your question there.
|
1

Ok so I would recommend you stick with using Picasso as this will make your life a lot easier in terms of memory management and the likes. One thing to remember is that the image contained in an imageview can ultimately retrieved as a Bitmap regardless of the image type (eg jpeg, png etc), so if you use Picasso to load the image via a URL you can still retrieve the image as a Bitmap after it is loaded and apply your transformation on it. Picasso also have a function called .transform() which you can use to transform your images by supplying a custom transformation. Here is an example for a rounded transformation, first the code that implements the transformation:

//calcualte the raduis for the rounded images
final float scale = mContext.getResources().getDisplayMetrics().density; //get screen density for   scale
int pixels = (int) ((imageView.getWidth()-5) * scale); //get screen pixels based on density. Imageview is 60dp x 60dp in size, subtract some padding = 55
mRadiusCenter = pixels / 2;                                                 //get the raduis

//now load your image
 Picasso.with(mContext)
        .load(imageUrl)
        .fit().centerCrop()
        .transform(new RoundedTransformation(mRadiusCenter))
        .into(imageView);

The you need to create a class for the RoundedTransformation that implements Picasso Transformation:

// enables hardware accelerated rounded corners
// original idea here : http://www.curious-creature.org/2012/12/11/android-recipe-1-image-with-rounded-corners/
public  class RoundedTransformation implements com.squareup.picasso.Transformation {
  private final int radius;

  // radius is corner radii in dp
  public RoundedTransformation(final int radius) {
      this.radius = radius;
  }

  @Override
  public Bitmap transform(final Bitmap source) {
      final Paint paint = new Paint();
      paint.setAntiAlias(true);
      paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));

      Bitmap output = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);

      Canvas canvas = new Canvas(output);
      canvas.drawCircle(radius, radius, radius, paint);

      if (source != output) {
          source.recycle();
      }

      return output;
  }

  @Override
  public String key() {
      return "rounded";
  }

}

Here are some more links that might prove useful:

https://gist.github.com/julianshen/5829333
Load large images with Picasso and custom Transform object

Hope that helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.