error when using universalimageloader - android

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);

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();
}
}
}

Getting Null Pointer Exception - Using an Interface to Pass Data from an Adapter to a Sub-fragment

I have an Adapter and a Sub-Fragment. I am using an interface to pass data from the Adapter to the Sub-Fragment. The problem I am having is that I keep getting a Null Pointer Exception. I have read through the various posts here relating to the problem and can't figure out where I went wrong. I get the NPE at the line 'passAdapterVariable.passAdapterVariable(mname)'. Based on what I have read I suspect it may be because I am not properly initializing passAdapterVariable. I have tried initializing it several different ways based on other examples but I keep getting the NPE.
Here is the Adapter
public class MatchAdapter extends RecyclerView.Adapter<MatchAdapter.MatchViewHolder> {
//declaration of variables
private Fragment fragment;
private FragmentManager fragmentManager;
private DiscoverPage discoverPage;
private Context context;
private int size;
private int mposition;
private TextView txt_matchname;
private ImageView img_matchpic;
List<String> maImg = new ArrayList<>();
private String mname;
PassAdapterVariable passAdapterVariable;
public interface PassAdapterVariable {
void passAdapterVariable(String mname);
}
//the constructor
public MatchAdapter(List<String> maImg, int size, Context context, DiscoverPage discoverPage){//, PassAdapterVariable passAdapterVariable) {
this.maImg = maImg;
this.context = context;
this.discoverPage = discoverPage;
this.size = size;
//this.passAdapterVariable = (PassAdapterVariable)context;
}
public MatchAdapter(String mname, Context context) {
this.context = context;
this.passAdapterVariable = (PassAdapterVariable)context;
}
//PassAdapterVariable passAdapterVariable = (PassAdapterVariable) context;
#Override
public MatchAdapter.MatchViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.match_items, parent, false);
MatchViewHolder matchViewHolder = new MatchViewHolder(view, maImg, discoverPage);
return matchViewHolder;
}
#Override
public void onBindViewHolder(MatchViewHolder holder, int position) {
Picasso.with(context).load(maImg.get(position)).into(holder.img_match);
holder.setIsRecyclable(false);
}
#Override
public int getItemCount() {
return maImg.size();
}
//viewholder class
public class MatchViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private static final String TAG = "error";
//declare variables
private DiscoverPage discoverPage;
private ImageView img_match;
//ViewHolder constructor
public MatchViewHolder(View itemView, final List<String> maImg, final DiscoverPage discoverPage) {
super(itemView);
//initialize variables inside the viewholder constructor
this.discoverPage = discoverPage;
img_match = (ImageView) itemView.findViewById(R.id.img_match);
txt_matchname = (TextView) itemView.findViewById(R.id.txt_matchname);
img_matchpic = (ImageView) itemView.findViewById(R.id.img_matchpic);
//set click listener for the img_match
img_match.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view == img_match) {
//discoverPage.isHidden();
Fragment currentFragment;
fragment = new ClickedMatch();
fragmentManager = ((AppCompatActivity) context).getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(android.R.id.content, fragment);
transaction.addToBackStack("DiscoverPage");
if ((currentFragment = ((AppCompatActivity) context).getSupportFragmentManager().findFragmentById(R.id.main_container)) != null) {
transaction.hide(currentFragment);
}
else {
transaction.commit();
}
mname = maImg.get(getAdapterPosition());
mposition = getAdapterPosition();
mname = maImg.get(mposition);
passAdapterVariable.passAdapterVariable(mname);
}
}
}
}
Here is the Sub-Fragment
public class ClickedMatch extends Fragment implements MatchAdapter.PassAdapterVariable{
//declare variables
private Toolbar toolbar;
private TextView txt_matchname;
private TextView txt_matchprice;
private ImageView img_matchpic;
private String mname;
private String imgmatch;
List<String> maImg = new ArrayList<>();
int size;
Context context;
DiscoverPage discoverPage;
private String pname;
private int i;
MatchAdapter.PassAdapterVariable passAdapterVariable;
public ClickedMatch() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_clicked_match, container, false);
//initialize variables
toolbar = (Toolbar) view.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);//set toolbar as action bar
txt_matchname = (TextView)view.findViewById(R.id.txt_matchname);
img_matchpic = (ImageView)view.findViewById(R.id.img_matchpic);
//setHasOptionsMenu(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().onBackPressed();
}
});
if(((AppCompatActivity)getActivity()).getSupportActionBar()!= null){
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);
((AppCompatActivity)getActivity()).getSupportActionBar().setHomeButtonEnabled(true);
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("");
}
// MatchAdapter matAdapter = new MatchAdapter(maImg, size, context, discoverPage,
//passAdapterVariable);
// matAdapter.passAdapterVariable = this;
//passAdapterVariable.passAdapterVariable(mname);
//txt_matchname.setText(pname);
MatchAdapter matAdapter = new MatchAdapter(pname, getContext());
matAdapter.passAdapterVariable = this;
passAdapterVariable(pname);
txt_matchname.setText(pname);
return view;
}
#Override
public void passAdapterVariable(String mname) {
this.pname = mname;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
this.getActivity().finish();
}
return super.onOptionsItemSelected(item);
}
}
Here is the error log
08-13 21:53:49.341 12852-12852/com.test.jack E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.test.jack, PID: 12852
java.lang.NullPointerException: Attempt to invoke interface method 'void com.test.jack.MatchAdapter$PassAdapterVariable.passAdapterVariable(java.lang.String)' on a null object reference
at com.test.jack.MatchAdapter$MatchViewHolder.onClick(MatchAdapter.java:138)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
To add some more context, I have a main activity(UserMainPage). A bottom navigation menu selector replaces the UserMainPage with a fragment(DiscoverPage).
DiscoverPage calls the adapter(MatchAdapter). A button click on DiscoverPage replaces DiscoverPage with a sub-fragment(ClickedMatch).
I am trying to pass a variable from MatchAdapter to ClickedMatch.
I was able to pass data from an adapter to a sub-fragment using a Bundle.
I modified my code as follows:
In the adapter I added:
fragment = new ClickedMatch();
Bundle bundle = new Bundle();
bundle.putString("matchname",mname);
fragment.setArguments(bundle);
...
transaction.commit();
In my sub-fragment I added:
Bundle bundle = this.getArguments();
if(bundle != null){
pname = bundle.getString("matchname");
}
There was no need to use an interface. Based on what I have researched I think (and I may be wrong) that creating an interface and then implementing it is better used when communicating between fragments as opposed to communicating between an adapter and a sub-fragment.
Looks like the String "mname" is null when you call passAdapterVariable.passAdapterVariable(mname);
Either you're List maImg is empty || null or the provided adapter position is wrong.
try logging
Log.d(TAG, "pos: " + getAdapterPosition());
mname = maImg.get(getAdapterPosition());
Log.d(TAG, "name: " + mname);
You can add Context parameter in constructor of Adapter with String as
public MatchAdapter(String mname, Context context) {
this.context = context;
}
Now get the context from Fragment as
MatchAdapter matAdapter = new MatchAdapter(pname, getActivity());
matAdapter.passAdapterVariable = this;
passAdapterVariable(pname);
txt_matchname.setText(tname);
return view;
PassAdapterVariable passAdapterVariable = (PassAdapterVariable) context;
Is just a declaration+Assignment statement in your adapter class. At this point in time, context is null.
The variable context is getting assigned only in your constructor. Assign your passAdapterVariable after the context has been assigned
public MatchAdapter(List<String> maImg, int size, Context context, DiscoverPage discoverPage) {
this.maImg = maImg;
this.context = context;
this.discoverPage = discoverPage;
this.size = size;
passAdapterVariable = (PassAdapterVariable) context;
}
Inside MatchAdapter------
Add instance to your interface in constructor that will work as
{
DataInterface passInterface;
Context context;
public MatchAdapter(String mname, Context context1, DataPass pass) {
this.passAdapterVariable = mname;
this.context = context1;
this.passInterface = pass;
}
}
Now get the instance of that interface while calling adapter as
{
MatchAdapter matAdapter = new MatchAdapter(pname, getActivity(),this);
}

OutOfMemory Exception - for adapter.notifiyDataSetChanged() while loading images with picasso

I am facing the outOfMemory exception while loading images with Picasso.
I am creating picasso builder with OkHttp and created Picasso Singleton class to cache images.
Scenario:
I have 100+ image feeds which are to be loaded. I am getting images in sets and each set has 25 image url which i am setting with Picasso. I am using recyclerview and whenever new set of images come in i am calling adapter.notifyDataSetChanged(). I am loading first set - no issues, for 2nd and 3rd set when making retrofit to get next set and adding to existing list and calling - adapter.notifyDataSetChanged(). For 3rd set when I call adapter.NotifyDataSetChanged() app crashes with outOfMemoryException
BUT
When i load all 3 sets of 75 images, I don't face any issues.
Code:
Application Class - where I am building Picasso.
Picasso.Builder builder = new Picasso.Builder(this)
.memoryCache(new LruCache(24000));
builder.downloader(new OkHttpDownloader(this,Integer.MAX_VALUE));
Picasso built = builder.build();
built.setLoggingEnabled(true);
Picasso Singleton Class:
public class PicassoCache {
/**
* Static Picasso Instance
*/
private static Picasso picassoInstance = null;
/**
* PicassoCache Constructor
*
* #param context application Context
*/
private PicassoCache (Context context) {
Downloader downloader = new OkHttpDownloader(context, Integer.MAX_VALUE);
Picasso.Builder builder = new Picasso.Builder(context);
builder.downloader(downloader);
picassoInstance = builder.build();
}
/**
* Get Singleton Picasso Instance
*
* #param context application Context
* #return Picasso instance
*/
public static Picasso getPicassoInstance (Context context) {
if (picassoInstance == null) {
new PicassoCache(context);
return picassoInstance;
}
return picassoInstance;
}
}
Code where I am setting/loading images with Picasso.
PicassoCache.getPicassoInstance(context).load(url).placeholder(R.mipmap.banner_placeholder).into(mView);
Code where I am updating the existing list to load when there is data set changed.
Inside Retorfit OnSuccess message:
if (response.code() == 200) {
List<CampaignCard> newCampaigns = response.body().getCampaigns();
for (int i = 0; i < newCampaigns.size(); i++) {
if (!campaignCards.contains(newCampaigns.get(i))) {
campaignCards.add(newCampaigns.get(i));
}
}
dashBoardAdapter.notifyDataSetChanged();
} else if (response.code() == Params.CODE_422) {
Utils.ShowServiceErrorMessages(getActivity(), response);
} else if (response.code() == Params.CODE_401) {
Utils.Logout(getActivity());
}
Adapter Class:
public class DashboardAdapter extends RecyclerView.Adapter<DashboardAdapter.DashboardViewHolder> implements View.OnClickListener {
private static final int VIEW_TYPE_CAMPAIGN = 1;
private static final int VIEW_TYPE_FEED = 2;
DashboardViewHolder holder;
protected List list;
protected int viewTypeLayout;
Context context;
int position;
Dashboard.DashboardActionList actionList;
Map<String, SourceContent> mPreviewLinkMapper;
ViewGroup parent;
//Picasso p;
public DashboardAdapter(List list, int viewTypeLayout) {
this.list = list;
this.viewTypeLayout = viewTypeLayout;
}
public DashboardAdapter(List list, int viewTypeLayout, Context context, Map<String, SourceContent> mPreviewLinkMapper) {
this.list = list;
this.viewTypeLayout = viewTypeLayout;
this.mPreviewLinkMapper = mPreviewLinkMapper;
}
#Override
public DashboardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context = parent.getContext();
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_feed, parent, false);
return new DashboardViewHolder(view, 2);
}
#Override
public void onBindViewHolder(DashboardViewHolder holder, final int position) {
BindFeedData(holder, position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemCount() {
return list.size();
}
#SuppressWarnings("unchecked")
private void BindFeedData(DashboardViewHolder holder, int position) {
List<Feed> feeds = (List<Feed>) list;
if (holder.mBannerImage != null) {
if (feeds.get(position).getCampaign().getParticipation().getType().toLowerCase().contains("video")) {
holder.mPlayIcon.setVisibility(View.VISIBLE);
String url = feeds.get(position).getCampaign().getParticipation().getThumbnail_url();
Utils.LoadImages(context, url, holder.mBannerImage, false);
} else if (feeds.get(position).getCampaign().getParticipation().getType().toLowerCase().contains("gif")) {
holder.mPlayIcon.setVisibility(View.GONE);
String url = feeds.get(position).getCampaign().getParticipation().getPost_file();
Utils.loadGif(context, url, holder.mBannerImage);
} else if (feeds.get(position).getCampaign().getParticipation().getType().toLowerCase().contains("link") ||
feeds.get(position).getCampaign().getParticipation().getType().toLowerCase().contains("youtube")) {
holder.mPlayIcon.setVisibility(View.GONE);
String slug = feeds.get(position).getCampaign().getSlug();
List<String> images = mPreviewLinkMapper.get(slug).getImages();
Utils.LoadImages(context, images.get(0), holder.mBannerImage, false);
} else {
holder.mPlayIcon.setVisibility(View.GONE);
holder.mBannerImage.setVisibility(View.VISIBLE);
String url = feeds.get(position).getCampaign().getParticipation().getPost_file();
Utils.LoadImages(context, url, holder.mBannerImage, false);
}
}
if (holder.mBrandLogo != null) {
Utils.LoadImages(context, feeds.get(position).getInfluencer().getProfile_picture_url(), holder.mBrandLogo, true);
}
holder.mTitle.setText(feeds.get(position).getInfluencer().getName());
holder.mSubTitle.setText(feeds.get(position).getCampaign().getName());
holder.mTime.setText(feeds.get(position).getCampaign().getTimestamp());
holder.mDescription.setText(feeds.get(position).getCampaign().getParticipation().getPost_content());
holder.mEngagement.setText(feeds.get(position).getCampaign().getParticipation().getMetrics().getEngagements());
holder.mImpresion.setText(feeds.get(position).getCampaign().getParticipation().getMetrics().getImpressions());
}
}
public static class DashboardViewHolder extends RecyclerView.ViewHolder {
ImageView mBannerImage, mFacebook, mTwitter, mInstagram, mPlayIcon, mHotIcon, mLocationIcon;
CircularImageView mBrandLogo;
CustomTextViewRegular mDescription, mTime, mOption1, mOption2, mOption3;
CustomTextViewDemi mTitle, mSubTitle, mImpresion, mEngagement;
LinearLayout mDetailsLayout;
LinearLayout mOptionLayout1, mOptionLayout2, mOptionLayout3;
public ViewGroup dropPreview;
TableRow mTableOptions;
public DashboardViewHolder(View v, int viewtype) {
super(v);
InitFeedViews(v);
}
private void InitFeedViews(View v) {
mTitle = (CustomTextViewDemi) v.findViewById(R.id.adapterHeaderLayoutTitle);
mSubTitle = (CustomTextViewDemi) v.findViewById(R.id.adapterHeaderLayoutSubTitle);
mBrandLogo = (CircularImageView) v.findViewById(R.id.adapterHeaderLayoutLogo);
mTime = (CustomTextViewRegular) v.findViewById(R.id.adapterHeaderLayoutTime);
mBannerImage = (ImageView) v.findViewById(R.id.adapterFeedBannerImage);
mPlayIcon = (ImageView) v.findViewById(R.id.adapterFeedPlayIocn);
mImpresion = (CustomTextViewDemi) v.findViewById(R.id.adapterFeedImpressions);
mEngagement = (CustomTextViewDemi) v.findViewById(R.id.adapterFeedEngagements);
mDescription = (CustomTextViewRegular) v.findViewById(R.id.adapterFeedDescription);
dropPreview = (LinearLayout) v.findViewById(R.id.drop_preview);
}
}
}
You would face "out of memory" issues lot in case of picasso library I would suggest you to use Glide library.
I had lot "out of memory" exception tried all but at last when i used glide it worked well.
Try to resize the image with Picasso library. OutOfMemoryException will be resolved.
For better understanding, refer below link:
https://futurestud.io/tutorials/picasso-image-resizing-scaling-and-fit

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.

Universal image loader on Android Studio

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.

Categories

Resources