Universal image loader on Android Studio - android

I tried to run it on eclip and it works but on android studio, it fails. I can not find a solution to this problem. I want to load a photo from openFirst(), Error openFirst()
public class MidFragment extends Fragment {
// private ProgressDialog mProgressDialog;
private ImageView mImageView;
private VideoView mVideoView;
private View mView;
private DisplayImageOptions mOptions;
private ImageLoader mImageLoader;
private Context mContext;
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
private ArrayList<ParseObject> objectList = new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.mid_fragment, container, false);
initComponent();
mContext = container.getContext();
return mView;
}
private void initComponent() {
mImageView = (ImageView)mView.findViewById(R.id.image);
mVideoView = (VideoView)mView.findViewById(R.id.video);
mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mVideoView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
// mProgressDialog = new ProgressDialog(getActivity());
// mProgressDialog.setTitle("Please wait a moment...");
// mProgressDialog.setMessage("Loading...");
// mProgressDialog.setIndeterminate(false);
}
public void reloadData(int index){
// mProgressDialog.show();
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Data");
query.whereEqualTo("school",(Number)index);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
objectList = (ArrayList<ParseObject>) list;
// mProgressDialog.dismiss();
if (!list.isEmpty())
openFirst();
}
});
}
private void openFirst(){
mImageLoader = ImageLoader.getInstance();
mImageLoader.init(ImageLoaderConfiguration.createDefault(mContext));
mOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.build();
ParseObject parseObject = objectList.get(0);
ParseFile parseFile = parseObject.getParseFile("file");
Log.e("****************************",""+parseFile.getUrl());
if (parseObject.getNumber("type") == (Number)1){
// mVideoView.setVisibility(View.VISIBLE);
// mImageView.setVisibility(View.GONE);
// mVideoView.setVideoURI();
}else{
mVideoView.setVisibility(View.GONE);
mImageView.setVisibility(View.VISIBLE);
ImageLoader.getInstance().displayImage(parseFile.getUrl(), mImageView, mOptions, animateFirstListener);
}
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
}
Logcat
05-18 23:23:02.258 10496-10496/animuco.com.ckemi E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: animuco.com.ckemi, PID: 10496
java.lang.NullPointerException
at com.nostra13.universalimageloader.core.ImageLoaderConfiguration$Builder.<init>(ImageLoaderConfiguration.java:196)
at com.nostra13.universalimageloader.core.ImageLoaderConfiguration.createDefault(ImageLoaderConfiguration.java:127)
at animuco.com.ckemi.Fragment.MidFragment.openFirst(MidFragment.java:99)
at animuco.com.ckemi.Fragment.MidFragment.access$200(MidFragment.java:42)
at animuco.com.ckemi.Fragment.MidFragment$3.done(MidFragment.java:92)
at animuco.com.ckemi.Fragment.MidFragment$3.done(MidFragment.java:86)
at com.parse.Parse$6$1.run(Parse.java:944)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:212)
at android.app.ActivityThread.main(ActivityThread.java:5135)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
at dalvik.system.NativeStart.main(Native Method)
thanks for your help

Quite possibly mContext is null. Since this is fragment just remove mContext and use getActivity() instead.

Related

Null pointer exception unable to solve?

Calling my async task class from my oncreate in OpensubcontentActivity, it is executing fine but while calling the same async task class from vivcontentAdapter in onBindViewHolder it is giving null pointer error in progressdialog.
OpensubcontentActivity
public class OpenSubContentActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private vivcontentAdapter vivcontentAdapteradapter;
static String stack_info[] = new String[10];
static int top = -1;
static String ObjectId;
static List<Information> data_content = new ArrayList<>();
public static Map info_map = null;
Boolean file_flag;
File file;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open_sub_content);
setEveryThing();
Intent mIntent = getIntent();
context = this;
ObjectId = mIntent.getStringExtra("CabinetID");
new getData().execute();
}
public void setEveryThing() {
floatingActionMenu = (FloatingActionMenu) findViewById(R.id.floating_menu);
newfolder = (FloatingActionButton) findViewById(R.id.idtem__folder);
newdoc = (FloatingActionButton) findViewById(R.id.idtem_doc);
upload = (FloatingActionButton) findViewById(R.id.idtem_upload);
capture = (FloatingActionButton) findViewById(R.id.idtem_photo);
toolbar = (Toolbar) findViewById(R.id.toolBar);
toolbar.setTitleTextColor(0xFFFFFFFF);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(("Example"));
recyclerView = (RecyclerView) findViewById(R.id.list_file);
vivcontentAdapteradapter = new vivcontentAdapter(this, data_content);
recyclerView.setAdapter(vivcontentAdapteradapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
class getData extends AsyncTask<Void, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(OpenSubContentActivity.this);
pDialog.setMessage("Fetching Content...");
pDialog.show();
pDialog.setCanceledOnTouchOutside(false);
}
#Override
protected String doInBackground(Void... voids) {
info_map = new HashMap();
String title = "";
String results = "";
int count = 0;
if (ObjectId.startsWith("0c")) {
Log.d("first", "coming");
CmisObject object = MainActivity.session.getObject(MainActivity.session.createObjectId(ObjectId));
Folder folder = (Folder) object;
//Document document = (Document)object;
OperationContext operationContext = MainActivity.session.createOperationContext();
ItemIterable<CmisObject> childrenn = folder.getChildren(operationContext);
ItemIterable<CmisObject> page = childrenn.getPage();
Iterator<CmisObject> pageItems = page.iterator();
while (pageItems.hasNext()) {
CmisObject item = null;
item = pageItems.next();
//System.out.println(item.getId());
if (item != null && item.getName() != null) {
if (item.getId().startsWith("0b")) {
Information info = new Information();
info.title = item.getName();
info.iconId = icons[0];
info.folderId_open_Id = item.getId();
title = title + "\n" + item.getName();
info_map.put(count, info.folderId_open_Id);
data_content.add(info);
count++;
}
return results;
}
#Override
protected void onPostExecute(String s) {
pDialog.dismiss();
vivcontentAdapteradapter.notifyDataSetChanged();
}
}
}
}
}
}
vivcontentAdapter
In this activity i am calling async task class of opensubcontentactivity.But while calling from here in progress dialog it is giving error in asynctask class getData()
Using -
OpenSubContentActivity openSubContentActivity=new OpenSubContentActivity();
openSubContentActivity.new getData().execute();
vivcontentAdapter
public class vivcontentAdapter extends RecyclerView.Adapter<vivcontentAdapter.MyViewHolder> {
private final LayoutInflater inflater;
List<Information> data_content = Collections.emptyList();
Context context;
public vivcontentAdapter(Context context, List<Information> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data_content = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.customrow, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final vivcontentAdapter.MyViewHolder holder, final int position) {
Information current = data_content.get(position);
holder.title.setText(current.title);
holder.icon.setImageResource(current.iconId);
holder.keyicon.setImageResource(current.checkin_icon);
holder.title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String store_objectID = (String) OpenSubContentActivity.info_map.get(position);
if (store_objectID.startsWith("0b")) {
OpenSubContentActivity.top++;
OpenSubContentActivity.stack_info[OpenSubContentActivity.top] = store_objectID; OpenSubContentActivity.ObjectId = store_objectID;
OpenSubContentActivity openSubContentActivity=new OpenSubContentActivity();
openSubContentActivity.new getData().execute();
} else {
OpenSubContentActivity.ObjectId = store_objectID;
OpenSubContentActivity openSubContentActivity=new OpenSubContentActivity();
openSubContentActivity.new getData().execute();
}
Toast.makeText(context, "Open", Toast.LENGTH_SHORT).show();
}
});
holder.txtOptionDigit.setOnClickListener(new View.OnClickListener() {
#SuppressLint("RestrictedApi")
#Override
public void onClick(View v) {
//Display option menu
});
}
#Override
public int getItemCount() {
return data_content.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView title, txtOptionDigit;
ImageView icon, keyicon;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.textvw);
icon = (ImageView) itemView.findViewById(R.id.imageView);
keyicon = (ImageView) itemView.findViewById(R.id.key_icon);
txtOptionDigit = (TextView) itemView.findViewById(R.id.txtOptionDigit);
}
}
}
}
Error-
03-30 00:21:40.690 10385-10385/reva.irving E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
03-30 00:21:40.690 10385-10385/reva.irving E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
03-30 00:22:04.228 10385-10385/reva.irving E/AndroidRuntime: FATAL EXCEPTION: main
Process: reva.irving, PID: 10385
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ProgressDialog.setMessage(java.lang.CharSequence)' on a null object reference
at reva.irving.OpenSubContentActivity$getData.onPreExecute(OpenSubContentActivity.java:103)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:620)
at android.os.AsyncTask.execute(AsyncTask.java:567)
at reva.irving.OpenSubContentActivity.call(OpenSubContentActivity.java:84)
at reva.irving.vivcontentAdapter$1.onClick(vivcontentAdapter.java:59)
at android.view.View.performClick(View.java:5647)
at android.view.View$PerformClick.run(View.java:22462)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6205)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
To perform clicks in a Recycler view you need to change your adapter. Add an interface to act as the click listener and implement it in your activity, like so:
public class vivcontentAdapter extends RecyclerView.Adapter<vivcontentAdapter.MyViewHolder> {
private final LayoutInflater inflater;
List<Information> data_content = Collections.emptyList();
Context context;
private OnClickItem clickListener;
public vivcontentAdapter(Context context, List<Information> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data_content = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.customrow, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final vivcontentAdapter.MyViewHolder holder, final int position) {
Information current = data_content.get(position);
holder.title.setText(current.title);
holder.icon.setImageResource(current.iconId);
holder.keyicon.setImageResource(current.checkin_icon);
holder.txtOptionDigit.setOnClickListener(new View.OnClickListener() {
#SuppressLint("RestrictedApi")
#Override
public void onClick(View v) {
//Display option menu
});
}
#Override
public int getItemCount() {
return data_content.size();
}
public void setClickListener(OnClickItem listener){
this.listener = listener;
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title, txtOptionDigit;
ImageView icon, keyicon;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.textvw);
icon = (ImageView) itemView.findViewById(R.id.imageView);
keyicon = (ImageView) itemView.findViewById(R.id.key_icon);
txtOptionDigit = (TextView) itemView.findViewById(R.id.txtOptionDigit);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
listener.onClickListItem(pos);
}
}
public interface OnClickItem{
void onClickListItem(int position);
}
}
Now in your activity you can catch the cliicks and run the async task:
public class OpenSubContentActivity extends AppCompatActivity implements vivcontentAdapter.OnClickItem{
private RecyclerView recyclerView;
private vivcontentAdapter vivcontentAdapteradapter;
static String stack_info[] = new String[10];
static int top = -1;
static String ObjectId;
static List<Information> data_content = new ArrayList<>();
public static Map info_map = null;
Boolean file_flag;
File file;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open_sub_content);
setEveryThing();
Intent mIntent = getIntent();
context=this;
ObjectId = mIntent.getStringExtra("CabinetID");
new getData().execute();
}
public void setEveryThing() {
floatingActionMenu = (FloatingActionMenu) findViewById(R.id.floating_menu);
newfolder = (FloatingActionButton) findViewById(R.id.idtem__folder);
newdoc = (FloatingActionButton) findViewById(R.id.idtem_doc);
upload = (FloatingActionButton) findViewById(R.id.idtem_upload);
capture = (FloatingActionButton) findViewById(R.id.idtem_photo);
toolbar = (Toolbar) findViewById(R.id.toolBar);
toolbar.setTitleTextColor(0xFFFFFFFF);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(("Example"));
recyclerView = (RecyclerView) findViewById(R.id.list_file);
vivcontentAdapteradapter = new vivcontentAdapter(this, data_content);
vivcontentAdapteradapter.setClickListener(this);
recyclerView.setAdapter(vivcontentAdapteradapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
public void onClickListItem(int position){
new getData().execute();
}
class getData extends AsyncTask<Void, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(OpenSubContentActivity.this);
pDialog.setMessage("Fetching Content...");
pDialog.show();
pDialog.setCanceledOnTouchOutside(false);
}
#Override
protected String doInBackground(Void... voids) {
info_map = new HashMap();
String title = "";
String results = "";
int count = 0;
if (ObjectId.startsWith("0c")) {
Log.d("first", "coming");
CmisObject object = MainActivity.session.getObject(MainActivity.session.createObjectId(ObjectId));
Folder folder = (Folder) object;
//Document document = (Document)object;
OperationContext operationContext = MainActivity.session.createOperationContext();
ItemIterable<CmisObject> childrenn = folder.getChildren(operationContext);
ItemIterable<CmisObject> page = childrenn.getPage();
Iterator<CmisObject> pageItems = page.iterator();
while (pageItems.hasNext()) {
CmisObject item = null;
item = pageItems.next();
//System.out.println(item.getId());
if (item != null && item.getName() != null) {
if (item.getId().startsWith("0b")) {
Information info = new Information();
info.title = item.getName();
info.iconId = icons[0];
info.folderId_open_Id = item.getId();
title = title + "\n" + item.getName();
info_map.put(count, info.folderId_open_Id);
data_content.add(info);
count++;
}
return results;
}
#Override
protected void onPostExecute(String s) {
pDialog.dismiss();
vivcontentAdapteradapter.notifyDataSetChanged();
}
}
}

(java.util.ArrayList)' on a null object reference, onPostExecute in implimentaition of Json searchQuery

MyFragment
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
// Inflate the layout for this fragment
final View layoutSearch = inflater.inflate(R.layout.fragment_search, container, false);
mswipeRefreshLayout=(SwipeRefreshLayout) layoutSearch.findViewById(R.id.searchMoviesRefresh);
mswipeRefreshLayout.setOnRefreshListener(this);
textVolleyError = (TextView) layoutSearch.findViewById(R.id.textVolleyError);
listMovieHits = (RecyclerView) layoutSearch.findViewById(R.id.search_movies);
listMovieHits.setLayoutManager(new LinearLayoutManager(getActivity()));
search=(SearchView) layoutSearch.findViewById(R.id.searchView1);
search.setQueryHint("Start typing to search...");
buttonBarcode = (ImageButton) layoutSearch.findViewById(R.id.imageButton2);
buttonAudio = (ImageButton) layoutSearch.findViewById(R.id.imageButton1);
search.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
}
});search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
L.t(getActivity(), newText);
if (newText.length() > 3) {
listMovieHits.setVisibility(layoutSearch.getVisibility());
searchForMovies m = (searchForMovies) new searchForMovies().execute(newText);
} else {
listMovieHits.setVisibility(layoutSearch.INVISIBLE);
}
return false;
}
});
listMovieHits.setAdapter(mAdapterBoxOffice);
if (savedInstanceState != null) {
mlistMovies = savedInstanceState.getParcelableArrayList(STATE_MOVIES);
} else {
L.t(getActivity(), "executing task from the fragment");
/*new TaskLoadSearchMovies(this).execute();*/
}
/* mAdapterBoxOffice.setMovieList(filteredProductResults);
mAdapterBoxOffice.SetOnclickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
container.getContext().startActivity(new Intent(container.getContext(), Details_Activity.class));
}
});*/
return layoutSearch;
}
public void filterProductArray(String newText){
String sName;
filteredProductResults.clear();
for (int i=0; i<mlistMovies.size(); i++)
{
sName=mlistMovies.get(i).getTitle().toLowerCase();
if (sName.contains(newText.toLowerCase()))
{
filteredProductResults.add(mlistMovies.get(i));
}
}
}
class searchForMovies extends AsyncTask<String, Void, String>
{
Parser parser;
JSONArray listMovies;
String url=new String();
String textSearch;
ProgressDialog progressDialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
listMovies=new JSONArray();
parser =new Parser();
progressDialog=new ProgressDialog(getActivity());
progressDialog.setCancelable(false);
progressDialog.setMessage("Searching....");
progressDialog.getWindow().setGravity(Gravity.CENTER);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
url="http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey={MyID}="+params+"limit=30";
String returnMovieResult= getMovieList();
this.textSearch=params[0];
return returnMovieResult;
}
private String getMovieList() {
Movie tempMovie=new Movie();
String mathFound="N";
try{
JSONObject response = Requestor.sendRequestBoxOfficeMovies(requestQueue, url);
ArrayList<Movie> listMovies = Parser.parseMoviesJSON(response);
L.m(String.valueOf(listMovies));
}catch (Exception e){
e.printStackTrace();
return "error";
}
return ("Exception");
}
protected void onPostExecute(String result){
super.onPostExecute(result);
if(result.equalsIgnoreCase("Exception Caught"))
{
Toast.makeText(getActivity(), "Unable to connect to server,please try later", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
else
{
//calling this method to filter the search results from productResults and move them to
//filteredProductResults
filterProductArray(textSearch);
listMovieHits.setAdapter(mAdapterBoxOffice);
mAdapterBoxOffice.setFilteredMovies(mlistMovies);
progressDialog.dismiss();
}
}
}
AdapterClass
public class AdapterBoxOffice extends RecyclerView.Adapter<AdapterBoxOffice.ViewHolderBoxOffice> {
private LayoutInflater layoutInflater;
private ArrayList<Movie> mlistMovies = new ArrayList<>();
private VolleySingleton volleySingleton;
private ImageLoader imageLoader;
private DateFormat dateFormat = new SimpleDateFormat("yyy-MM-dd");
private int previousPosition=0;
AdapterView.OnItemClickListener mOnItemClickListener;
public AdapterBoxOffice(Context context) {
layoutInflater = LayoutInflater.from(context);
volleySingleton = VolleySingleton.getsInstance();
imageLoader = volleySingleton.getImageLoader();
}
public void setMovieList(ArrayList<Movie> listMovies) {
this.mlistMovies = listMovies;
notifyDataSetChanged();
}
public void setFilteredMovies(ArrayList<Movie> filteredProductResults){
this.mlistMovies=filteredProductResults;
}
#Override
public ViewHolderBoxOffice onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.custom_movie_box_office, parent, false);
ViewHolderBoxOffice viewHolder = new ViewHolderBoxOffice(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolderBoxOffice holder, int position) {
Movie currentMovie = mlistMovies.get(position);
holder.movieTitle.setText(currentMovie.getTitle());
Date movieReleaseDate = currentMovie.getReleaseDateTheater();
if (movieReleaseDate != null) {
String formmattedDate = dateFormat.format(movieReleaseDate);
holder.movieReleaseDate.setText(formmattedDate);
} else {
holder.movieReleaseDate.setText(Constants.NA);
}
int audienceScore=currentMovie.getAudienceScore();
if (audienceScore==-1){
holder.movieAudienceScore.setRating(0.0F);
holder.movieAudienceScore.setAlpha(0.5F);
}
else
{
holder.movieAudienceScore.setRating(currentMovie.getAudienceScore() / 20.0F);
holder.movieAudienceScore.setAlpha(1.0F);
}
if(position>previousPosition)
{
comeagain.materialdesign.anim.AnimationUtils.animate(holder, true);
}else {
comeagain.materialdesign.anim.AnimationUtils.animate(holder, false);
}
previousPosition=position;
String urlThumbnail = currentMovie.getUrlThumbnail();
loadImages(urlThumbnail, holder);
}
private void loadImages(String urlThumbnail, final ViewHolderBoxOffice holder) {
if (urlThumbnail != null) {
imageLoader.get(urlThumbnail, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
holder.movieThumbnail.setImageBitmap(response.getBitmap());
}
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
}
#Override
public int getItemCount() {
return mlistMovies.size();
}
class ViewHolderBoxOffice extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView movieThumbnail;
private TextView movieTitle;
private TextView movieReleaseDate;
private RatingBar movieAudienceScore;
public ViewHolderBoxOffice(View itemView) {
super(itemView);
movieThumbnail = (ImageView) itemView.findViewById(R.id.movieThumbnail);
movieTitle = (TextView) itemView.findViewById(R.id.movieTitle);
movieReleaseDate = (TextView) itemView.findViewById(R.id.movieReleaseDate);
movieAudienceScore = (RatingBar) itemView.findViewById(R.id.movieAudienceScore);
}
}
LogCat
01-23 22:00:18.141 19563-19563/comeagain.materialdesign E/AndroidRuntime: FATAL EXCEPTION: main
Process: comeagain.materialdesign, PID: 19563
java.lang.NullPointerException: Attempt to invoke virtual method 'void comeagain.materialdesign.adapters.AdapterBoxOffice.setFilteredMovies(java.util.ArrayList)' on a null object reference
at comeagain.materialdesign.fragments.FragmentSearch$searchForMovies.onPostExecute(FragmentSearch.java:270)
at comeagain.materialdesign.fragments.FragmentSearch$searchForMovies.onPostExecute(FragmentSearch.java:209)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I want to implement search query in Json Api, the problem is that the I am getting a null exception . I do not know why the filteredArray is returning null, I really do not know where is the problem, Please help me solve this issue.

Load Image in Viewpager

I have 3 fragment in viewpager (LeftFragment, MidFragment and Right Fragment)
LeftFragment contain a listview, when clicking on listview item, an image will be loaded on MidFragment. I've encountered a bug and spent a lot of time but still unresolved. Here is my code:
LeftFragmnet
public class LeftFragment extends Fragment{
private ListView listView;
private List<ParseObject> ob;
private ProgressDialog mProgressDialog;
private ListViewAdapter adapter;
private List<School> schoollist = null;
private View v;
MainActivity mainActivity = new MainActivity();
MidFragment midFragment = new MidFragment();
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.left_fragment, container, false);
initComponent();
new RemoteDataTask().execute();
return v;
}
private void initComponent() {
listView = (ListView)v.findViewById(R.id.lv_left);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mainActivity.viewPager.setCurrentItem(1);
School school = schoollist.get(position);
// midFragment.index = Integer.parseInt(school.getIndex());
midFragment.reloadData(Integer.parseInt(school.getIndex()));
}
});
}
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(getActivity());
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle("Please wait a moment...");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
schoollist = new ArrayList<School>();
try{
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("School");
query.orderByAscending("index");
ob = query.find();
for (ParseObject name : ob){
School map = new School();
map.setIndex(String.valueOf(name.get("index")));
map.setCount(String.valueOf(name.get("count")));
map.setName(String.valueOf(name.get("name")));
schoollist.add(map);
}
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
adapter = new ListViewAdapter(getActivity(), schoollist);
listView.setAdapter(adapter);
mProgressDialog.dismiss();
super.onPreExecute();
}
}
}
MidFragment
public class MidFragment extends Fragment {
// private ProgressDialog mProgressDialog;
private ImageView mImageView;
private VideoView mVideoView;
private DisplayImageOptions options;
private ImageLoader imageLoader = ImageLoader.getInstance();
private Context mContext;
private ImageLoadingListener animateFirstListener;
private ArrayList<ParseObject> objectList = new ArrayList<>();
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// imageLoader.init(ImageLoaderConfiguration.createDefault(mContext));
// mImageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.build();
animateFirstListener = new AnimateFirstDisplayListener();
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.mid_fragment, container, false);
initComponent(view);
mContext = container.getContext();
return view;
}
private void initComponent(View view) {
mImageView = (ImageView) view.findViewById(R.id.image);
mVideoView = (VideoView) view.findViewById(R.id.video);
mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mVideoView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
// mProgressDialog = new ProgressDialog(getActivity());
// mProgressDialog.setTitle("Please wait a moment...");
// mProgressDialog.setMessage("Loading...");
// mProgressDialog.setIndeterminate(false);
}
public void reloadData(int index){
// mProgressDialog.show();
objectList.clear();
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Data");
query.whereEqualTo("school",(Number)index);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
objectList = (ArrayList<ParseObject>) list;
// mProgressDialog.dismiss();
if (!list.isEmpty())
openFirst();
}
});
}
private void openFirst(){
ParseObject parseObject = objectList.get(0);
ParseFile parseFile = parseObject.getParseFile("file");
if (parseObject.getNumber("type") == (Number)1){
}else{
// mVideoView.setVisibility(View.GONE);
// mImageView.setVisibility(View.VISIBLE);
imageLoader.displayImage(parseFile.getUrl(), mImageView, options, animateFirstListener);
}
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
}
layout MidFragment
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<VideoView
android:id="#+id/video"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:visibility="gone" />
<ImageView
android:id="#+id/image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:contentDescription="#string/app_name" />
</RelativeLayout>
Logcat
05-28 15:41:56.116 19297-19297/animuco.com.ckemi E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: animuco.com.ckemi, PID: 19297
java.lang.IllegalArgumentException: view must not be null
at com.nostra13.universalimageloader.core.imageaware.ViewAware.<init>(ViewAware.java:70)
at com.nostra13.universalimageloader.core.imageaware.ViewAware.<init>(ViewAware.java:50)
at com.nostra13.universalimageloader.core.imageaware.ImageViewAware.<init>(ImageViewAware.java:44)
at com.nostra13.universalimageloader.core.ImageLoader.displayImage(ImageLoader.java:365)
at com.nostra13.universalimageloader.core.ImageLoader.displayImage(ImageLoader.java:340)
at animuco.com.ckemi.Fragment.MidFragment.openFirst(MidFragment.java:119)
at animuco.com.ckemi.Fragment.MidFragment.access$200(MidFragment.java:36)
at animuco.com.ckemi.Fragment.MidFragment$3.done(MidFragment.java:101)
at animuco.com.ckemi.Fragment.MidFragment$3.done(MidFragment.java:95)
at com.parse.Parse$6$1.run(Parse.java:944)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1016)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
I'm not sure but I think the error is due to update the view of viewpager
sorry for my weak english
Thanks for the interest of the people
There are a few issues with the code. IMO.
Your fragment holds a reference to its activity, you already have one call getActivity().
Left fragment holds a reference to Mid fragment - bad practice.
On your RemoteDataTask you call super.onPreExecute() at your
onPostExecute() method, its usually unimplemented but it may cause
you errors in the future.
And to answer your question. You are initilyzing a new instance of MidFragment at your left fragment which isnt attached anywhere therfore MidFragment doesnt start his lifecycle and doesnt call onCreateView(). The Midfragment that LeftFragment is using isnt the same as the one that the ViewPager is using.

error when using universalimageloader

I found a bug in my application and I can not fix it. I use SwipeRefreshLayout and he helped discover a bug. when I'm on a fragment of a list and try to update SwipeRefreshLayout and if this time I go to another fragment of the application will take off.
ERROR:
java.lang.NullPointerException
at com.nostra13.universalimageloader.core.ImageLoaderConfiguration$Builder.<init>(ImageLoaderConfiguration.java:196)
at com.nostra13.universalimageloader.core.ImageLoaderConfiguration.createDefault(ImageLoaderConfiguration.java:127)
at com.managment.pavel.managmentgradle.fragments.adapters.EmployeeListAdapter.<init>(EmployeeListAdapter.java:52)
at com.managment.pavel.managmentgradle.fragments.EmployeessList$1.onPostExecute(EmployeessList.java:109)
at com.managment.pavel.managmentgradle.fragments.EmployeessList$1.onPostExecute(EmployeessList.java:69)
at android.os.AsyncTask.finish(AsyncTask.java:417)
at android.os.AsyncTask.access$300(AsyncTask.java:127)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
I just use the library ImageLoader which is initialized in the constructor of the fragment:
which is initialized in the constructor of the adapter:
public class EmployeeListAdapter extends SectionedBaseAdapter {
private ArrayList<String> sections;
private ArrayList<List<EmployeesListBean>> employees;
private ImageLoader imageLoader = ImageLoader.getInstance();
private DisplayImageOptions options;
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
private Context context;
public EmployeeListAdapter(ArrayList<EmployeesListBean> employeesListBeans, Context context) {
this.context = context;
Map<String, List<EmployeesListBean>> map = new HashMap<>();
for (EmployeesListBean employeesListBean : employeesListBeans) {
if (!map.containsKey(employeesListBean.getDepart_name()))
map.put(employeesListBean.getDepart_name(), new ArrayList<EmployeesListBean>());
map.get(employeesListBean.getDepart_name()).add(employeesListBean);
}
sections = new ArrayList<>(map.keySet());
employees = new ArrayList<>(map.values());
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.build();
imageLoader.init(ImageLoaderConfiguration.createDefault(context));
}
error points to a string:
imageLoader.init(ImageLoaderConfiguration.createDefault(context));
please tell me what I'm doing wrong? initialization may need to do elsewhere?
EDITE MY FRAGMENT(FULL):
public class EmployeessList extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
private String link;
private PinnedHeaderListView listView;
private SwipeRefreshLayout swipeLayout;
private ProgressDialog progressDialog;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.employeelist, null);
swipeLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_employe_list);
swipeLayout.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.CYAN);
swipeLayout.setOnRefreshListener(this);
listView = (PinnedHeaderListView) v.findViewById(R.id.pinnedListView);
link=getArguments().getString(MyActivity.ARGUMENT_LINK);
if (InternetResiver.isOnline(getActivity())) {
progressDialog = MyProgress.getProgressDialog(getActivity());
progressDialog.show();
setData();
} else {
AlertDialog alert = InternetResiver.getAlertDialog(getActivity());
alert.show();
}
return v;
}
#Override
public void onRefresh() {
if (InternetResiver.isOnline(getActivity())) {
setData();
} else {
AlertDialog alert = InternetResiver.getAlertDialog(getActivity());
alert.show();
}
}
public void setData(){
new MyAsincTask(getActivity()){
int city = 0;
int holiday = 0;
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(Document document) {
super.onPostExecute(document);
ArrayList<EmployeesListBean> employeesListBeans = new ArrayList<>();
Elements elementsUid = document.select("uid");
Elements elementsStaffName = document.select("staff_name");
Elements elementsDepartName = document.select("depart_name");
Elements elementsLocation = document.select("location");
Elements elementsInTime = document.select("in_time");
Elements elementsOutTime = document.select("out_time");
Elements elementsLateness = document.select("lateness");
Elements elementsPhoto = document.select("photo");
for (int i = 0; i < elementsUid.size(); i++) {
EmployeesListBean employeesListBean = new EmployeesListBean();
employeesListBean.setUid(elementsUid.get(i).ownText());
employeesListBean.setStaff_name(elementsStaffName.get(i).ownText());
employeesListBean.setDepart_name(elementsDepartName.get(i).ownText());
employeesListBean.setLocation(elementsLocation.get(i).ownText());
employeesListBean.setIn_time(elementsInTime.get(i).ownText());
employeesListBean.setOut_time(elementsOutTime.get(i).ownText());
employeesListBean.setLateness(elementsLateness.get(i).ownText());
employeesListBean.setPhoto(elementsPhoto.get(i).ownText());
employeesListBeans.add(employeesListBean);
if (employeesListBeans.get(i).getOut_time().equals("на смене") && elementsLocation.get(i).ownText().equals("city")) {
city += 1;
}
if(employeesListBeans.get(i).getOut_time().equals("на смене") && elementsLocation.get(i).ownText().equals("holiday")){
holiday += 1;
}
}
EmployeeListAdapter sectionedAdapter = new EmployeeListAdapter(employeesListBeans, getActivity());
listView.setAdapter(sectionedAdapter);
progressDialog.cancel();
swipeLayout.setRefreshing(false);
getActivity().setTitle("Сотрудники(city:" + city + ",holiday:" + holiday + ")");
}
}.execute(link);
}
}
MY ADAPTER(FULL):
public class EmployeeListAdapter extends SectionedBaseAdapter {
private ArrayList<String> sections;
private ArrayList<List<EmployeesListBean>> employees;
private ImageLoader imageLoader = ImageLoader.getInstance();
private DisplayImageOptions options;
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
private Context context;
public EmployeeListAdapter(ArrayList<EmployeesListBean> employeesListBeans, Context context) {
this.context = context;
Map<String, List<EmployeesListBean>> map = new HashMap<>();
for (EmployeesListBean employeesListBean : employeesListBeans) {
if (!map.containsKey(employeesListBean.getDepart_name()))
map.put(employeesListBean.getDepart_name(), new ArrayList<EmployeesListBean>());
map.get(employeesListBean.getDepart_name()).add(employeesListBean);
}
sections = new ArrayList<>(map.keySet());
employees = new ArrayList<>(map.values());
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.build();
imageLoader.init(ImageLoaderConfiguration.createDefault(context));
}
#Override
public Object getItem(int section, int position) {
return employees.get(section).get(position);
}
#Override
public long getItemId(int section, int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getSectionCount() {
return sections.size();
}
#Override
public int getCountForSection(int section) {
return employees.get(section).size();
}
#Override
public View getItemView(int section, int position, View convertView, ViewGroup parent) {
LinearLayout layout;
if (convertView == null) {
LayoutInflater inflator = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout = (LinearLayout) inflator.inflate(R.layout.itememploee, null);
} else {
layout = (LinearLayout) convertView;
}
((TextView) layout.findViewById(R.id.staff_name_text)).setText(employees.get(section).get(position).getStaff_name());
((TextView) layout.findViewById(R.id.depart_name_text)).setText("Должность: " + employees.get(section).get(position).getDepart_name());
((TextView) layout.findViewById(R.id.location_text)).setText("Отель: " + employees.get(section).get(position).getLocation());
((TextView) layout.findViewById(R.id.in_time_text)).setText("Пришел: " + employees.get(section).get(position).getIn_time());
((TextView) layout.findViewById(R.id.out_time_text)).setText("Ушел: " + employees.get(section).get(position).getOut_time());
((TextView) layout.findViewById(R.id.lateness_text)).setText("Опоздание: " + employees.get(section).get(position).getLateness());
imageLoader.displayImage(employees.get(section).get(position).getPhoto(), (CircleImageView) layout.findViewById(R.id.employeePhoto), options, animateFirstListener);
if (employees.get(section).get(position).getOut_time().equals("на смене")) {
layout.setBackgroundColor(context.getResources().getColor(R.color.employe_positive));
}else{
layout.setBackgroundColor(context.getResources().getColor(R.color.employe_negative));
}
return layout;
}
#Override
public View getSectionHeaderView(int section, View convertView, ViewGroup parent) {
LinearLayout layout;
if (convertView == null) {
LayoutInflater inflator = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout = (LinearLayout) inflator.inflate(R.layout.header_item_employee, null);
} else {
layout = (LinearLayout) convertView;
}
((TextView) layout.findViewById(R.id.textItem)).setText(sections.get(section));
return layout;
}
}
Always a good idea to have a look at the source code for your open source library :).
Code is here (I am assuming you're using the latest version):
https://github.com/nostra13/Android-Universal-Image-Loader/blob/master/library/src/com/nostra13/universalimageloader/core/ImageLoaderConfiguration.java
The line in question:
195 public Builder(Context context) {
196 this.context = context.getApplicationContext();
197 }
This means the context is null. Have a look at your adapter and see if that's indeed the case.
Additionally, and very important to note, you only need to initialize the image loader once not every time you're using it. Do it in your main launcher activity or better yet, in your application class (as long as you've overridden it in your manifest). If you need to override the default options, every method has an override that allows you to specify the loading options.
Update:
To create an application class, follow this tutorial:http://www.intridea.com/blog/2011/5/24/how-to-use-application-object-of-android
Then in the onCreate() method of the application class, initialize your ImageLoader by calling the init() method. Do not do this in a transitional class (your adapter). The Application class has access to the ApplicationContext which is what you need to be passing to the init() method.
Update2:
As per https://github.com/nostra13/Android-Universal-Image-Loader/wiki/Quick-Setup you can initialize it in your main activity if you prefer.
public class MyActivity extends Activity {
#Override
public void onCreate() {
super.onCreate();
// Create global configuration and initialize ImageLoader with this config
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
...
.build();
ImageLoader.getInstance().init(config);
...
}
}
To get an instance of the image loader anywhere in your app, simply use the singleton instance by calling ImageLoader.getInstance()
private ImageLoader imageLoader = ImageLoader.getInstance();
do this
private ImageLoader imageLoader ;
constructor(){
DisplayImageOptions defaultDisplayImageOptions = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error).cacheInMemory(true)
.cacheOnDisk(true).build();
ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
context).threadPriority(Thread.NORM_PRIORITY - 2)
.denyCacheImageMultipleSizesInMemory()
.defaultDisplayImageOptions(defaultDisplayImageOptions);
ImageLoaderConfiguration config = builder.build();
// Initialize ImageLoader with configuration.
ImageLoader.getInstance().init(config);
}
Try it this way in your constructor:
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
//do whatever you want
.writeDebugLogs()
.build();
imageLoader.init(config);

Unable to retrieve Array from Aync task in Activity Using Universal Image Loader for Android and Flickr

I am trying to fetch a list of photos from a photo set in flickr
using universal image loader
My Base Activity ImagePagerActivity calls FetchPhotos which extends Async Task.
Code Follows
public class ImagePagerActivity extends BaseActivity {
private static final String STATE_POSITION = "STATE_POSITION";
public static final String API_KEY="mykey";
public static final String USER_ID="myid";
DisplayImageOptions options;
private Photos thePhotoList;
ViewPager pager;
private String thePhotos="";
private final int[] timeout={3,10};
private String url="http://www.flickr.com/services/rest/?method=flickr.photosets.getPhotos&format=json&api_key="+API_KEY+"&photoset_id=111111111";
private String[] imageUrls;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_pager);
Bundle bundle = getIntent().getExtras();
String url="http://www.flickr.com/services/rest/?method=flickr.photosets.getPhotos&format=json&api_key="+API_KEY+"&photoset_id=72157633359614452";
setContentView(R.layout.pics);
try{
((ViewAnimator)findViewById(R.id.PictureAnimator)).removeAllViews();
}catch (Exception e) {}
thePhotoList = new Photos(url);
thePhotoList.execute();
imageUrls=thePhotoList.imageList;
//imageUrls = bundle.getStringArray(Extra.IMAGES);
int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);
if (savedInstanceState != null) {
pagerPosition = savedInstanceState.getInt(STATE_POSITION);
}
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error)
.resetViewBeforeLoading()
.cacheOnDisc()
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565)
.displayer(new FadeInBitmapDisplayer(300))
.build();
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new ImagePagerAdapter(this.imageUrls));
pager.setCurrentItem(pagerPosition);
}
private class Photos extends com.flickr.FetchPhotos{
#Override
public void onFetchError() {}
public Photos(String url) {super(ImagePagerActivity.this, url);}
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt(STATE_POSITION, pager.getCurrentItem());
}
private class ImagePagerAdapter extends PagerAdapter {
private String[] images;
private LayoutInflater inflater;
ImagePagerAdapter(String[] images) {
this.images = images;
inflater = getLayoutInflater();
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
#Override
public void finishUpdate(View container) {
}
#Override
public int getCount() {
return images.length;
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.item_pager_image, view, false);
ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
imageLoader.displayImage(images[position], imageView, options, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
spinner.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
String message = null;
switch (failReason.getType()) {
case IO_ERROR:
message = "Input/Output error";
break;
case DECODING_ERROR:
message = "Image can't be decoded";
break;
case NETWORK_DENIED:
message = "Downloads are denied";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
Toast.makeText(ImagePagerActivity.this, message, Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
}
});
((ViewPager) view).addView(imageLayout, 0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate(View container) {
}
}
}
next is the FetchPhotos class
public abstract class FetchPhotos extends AsyncTask<Void, Void, Boolean>{
private Context context;
private ProgressDialog pd;
private String thePhotos="";
private String url;
private final int[] timeout={3,10};
public ArrayList<PictureInfo> thePics;
public String[] imageList;
public FetchPhotos(Context context,String url) {
this.context=context;
this.url=url;
}
public String[] fillGalery(JSONObject theFeed) {
// TODO Auto-generated method stub
String[] imageUrls = null;
try{
JSONArray Categories=theFeed.getJSONArray("photo");
imageUrls=new String[Categories.length()];
for (int i=0;i<(Categories.length()>15?15:Categories.length());i++){
JSONObject pic = Categories.getJSONObject(i);
String url1="http://farm"+pic.getString("farm")+".staticflickr.com/"+pic.getString("server")+"/"+
pic.getString("id")+"_"+pic.getString("secret")+".jpg";
imageUrls[i]=url1;
System.out.println(imageUrls[i]);
}
return imageUrls;
}
catch(Exception e){
}
return imageUrls;
}
#Override
protected void onPreExecute() {
pd=ProgressDialog.show(context, "downloading", "please wait");
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Void... arg0) {
try{
thePhotos = new Internet().GetRequest(url, null, timeout);
return true;
}catch (Exception e) {
return false;
}
}
#Override
protected void onPostExecute(Boolean result) {
pd.dismiss();
if(result){
try {
thePhotos=thePhotos.split("\\(")[1];
thePhotos.replace("\\)", "");
imageList=fillGalery(new JSONObject(thePhotos).getJSONObject("photoset"));
} catch (Exception e) {Log.e("karp", "photolist2: "+e.getMessage());onFetchError();onFetchError();}
}else{
onFetchError();
}
super.onPostExecute(result);
}
public abstract void onFetchError();
public void LoadPhoto(PictureInfo pi){
Log.d("karp", "LoadPhoto");
if(!(pi.executed)){
new LoadPics(pi).execute();
pi.executed=true;
}
}
private class LoadPics extends RemoteImage{
private ImageView ivTarget;
private ProgressBar pb;
public LoadPics(PictureInfo pi) {
super(pi.url);
this.ivTarget=pi.iv;
this.pb=pi.pb;
}
#Override
public void onSuccess(Bitmap remoteBitmap) {
try{
pb.setVisibility(View.INVISIBLE);
ivTarget.setImageBitmap(remoteBitmap);
}catch (Exception e) {}
}
#Override
public void onFail() {pb.setVisibility(View.INVISIBLE);}
}
}
I have created Photos class in Image Pager
and then Im trying to access fill gallery
Now Im trying to fill a string array with the image urls from flickr
using the method fillGallery that reurns a string array
In my base activity im calling
thePhotoList = new Photos(url);
thePhotoList.execute();
imageUrls=thePhotoList.imageList;
but try as i may i cant get an array in imageUrls which is a String Array.
When i use a hard coded string array with urls for images in it, the code works.
Any help would be really appreciated.
Im sure im doing something very silly as I am new to this.
Many thanks . Cheers!
I got it to work . Needed to add a listener interface , call the method from onPostExecute,
Implement it in the activity, access the variable in the implementation of the listeners abstract method. Should have researched a bit more before posting,but was stuck with the problem too long . Apologies.

Categories

Resources