I have simply used a custom list inside a fragment.I have retrieved those data from api using volley.It shows following error.I am getting any idea to resolve this,Can somebody please help me.
java.lang.NullPointerException: Attempt to invoke virtual method 'com.android.volley.toolbox.ImageLoader com.example.user.ekta.AppController.getImageLoader()' on a null object reference
at com.example.user.ekta.MyBookAdapter.<init>(MyBookAdapter.java:25)
at com.example.user.ekta.FullInfoTabFragment.onCreateView(FullInfoTabFragment.java:85).
This is my Fragment class
package com.example.user.ekta;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class FullInfoTabFragment extends Fragment {
private static final String EXTRA_SRORT_CARD_MODEL = "EXTRA_SRORT_CARD_MODEL";
// String transitionTag;
private SportCardModel sportCardModel;
private Toolbar toolbar;
private ImageView ivPhoto;
private static final String TAG = FullInfoTabFragment.class.getSimpleName();
private static final String url = "http://myeducationhunt.com/public/schools";
private ProgressDialog pDialog;
private List<MyBook> ourBooksListItems = new ArrayList<MyBook>();
private ListView listView;
private MyBookAdapter adapter;
public static FullInfoTabFragment newInstance(SportCardModel sportCardModel) {
FullInfoTabFragment fragment = new FullInfoTabFragment();
Bundle args = new Bundle();
args.putParcelable(EXTRA_SRORT_CARD_MODEL, sportCardModel);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
sportCardModel = getArguments().getParcelable(EXTRA_SRORT_CARD_MODEL);
}
if (savedInstanceState != null) {
sportCardModel = savedInstanceState.getParcelable(EXTRA_SRORT_CARD_MODEL);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_full_info, container, false);
toolbar = (Toolbar) view.findViewById(R.id.toolbar);
ivPhoto = (ImageView) view.findViewById(R.id.ivPhoto);
listView = (ListView) view.findViewById(R.id.list);
adapter = new MyBookAdapter(getActivity(), ourBooksListItems);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// OurSchool ourSchool = new OurSchool();
// Intent i = new Intent(getContext(), SchoolDetails.class);
// i.putExtra("id", ourSchoolsListItems.get(position).schoolId);
// i.putExtra("name", ourSchoolsListItems.get(position).schoolName);
// i.putExtra("location", ourSchoolsListItems.get(position).schoolLocation);
// i.putExtra("logo", ourSchoolsListItems.get(position).schoolLogo);
// i.putExtra("email", ourSchoolsListItems.get(position).schoolEmail);
// i.putExtra("website", ourSchoolsListItems.get(position).schoolWebsite);
// i.putExtra("created_at", ourSchoolsListItems.get(position).createdAt);
// i.putExtra("updated_at", ourSchoolsListItems.get(position).updatedAt);
// startActivity(i);
}
});
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading…");
pDialog.show();
// Creating volley request obj
JsonArrayRequest schoolRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
pDialog.hide();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
MyBook myBook = new MyBook();
myBook.bookName = obj.getString("name");
myBook.bookAuthor = obj.getString("location");
myBook.bookCover= obj.getString("logo");
// adding schools to ourSchool list
ourBooksListItems.add(myBook);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(schoolRequest);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
toolbar.setTitle(sportCardModel.getSportTitle());
toolbar.setNavigationIcon(R.drawable.ic_back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().onBackPressed();
}
});
toolbar.setBackgroundColor(ContextCompat.getColor(getContext(), sportCardModel.getBackgroundColorResId()));
ivPhoto.setImageResource(sportCardModel.getImageResId());
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putParcelable(EXTRA_SRORT_CARD_MODEL, sportCardModel);
super.onSaveInstanceState(outState);
}
static class DividerItemDecoration extends RecyclerView.ItemDecoration {
private static final int[] ATTRS = new int[]{android.R.attr.listDivider};
private Drawable mDivider;
/**
* Default divider will be used
*/
public DividerItemDecoration(Context context) {
final TypedArray styledAttributes = context.obtainStyledAttributes(ATTRS);
mDivider = styledAttributes.getDrawable(0);
styledAttributes.recycle();
}
/**
* Custom divider will be used
*/
public DividerItemDecoration(Context context, int resId) {
mDivider = ContextCompat.getDrawable(context, resId);
}
#Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
int left = parent.getPaddingLeft();
int right = parent.getWidth() - parent.getPaddingRight();
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
int top = child.getBottom() + params.bottomMargin;
int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
}
}
And this is my adapter class
package com.example.user.ekta;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import java.util.List;
/**
* Created by user on 11/27/2016.
*/
public class MyBookAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<MyBook> ourbooksList;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public MyBookAdapter(Activity activity, List<MyBook> ourbooksListsList) {
this.activity = activity;
this.ourbooksList = ourbooksListsList;
}
#Override
public int getCount() {
return ourbooksList.size();
}
#Override
public Object getItem(int location) {
return ourbooksList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_books, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView bookCover = (NetworkImageView) convertView
.findViewById(R.id.bookCover);
TextView bookName = (TextView) convertView.findViewById(R.id.bookName);
TextView boookAuthor = (TextView) convertView.findViewById(R.id.bookAuthor);
MyBook m = ourbooksList.get(position);
bookCover.setImageUrl(m.getBookCover(), imageLoader);
bookName.setText("Name: " + m.getBookName());
boookAuthor.setText("Address: " + String.valueOf(m.getBookAuthor()));
return convertView;
}
}
AppController.getInstance() is returning null, you have not initialized your Appcontroller.
If AppController extends your application, then you have to change your manifest
android:name= "path to AppController" in app section.
Related
I am getting this error when doing intent. I don't know why it is coming. I need to go to the fragment to activity. I need to go to the next activity with the api in this application. I have tried many times and I am not getting the answer.**Cannot resolve method 'putExtra(java.lang.String, <lambda parameter>)'**I have given the image below How to do fragment to activity intent i am new android devloper
package com.kannada.newspaper.india.utils;
import static com.kannada.newspaper.india.Constant.EXTRA_OBJC;
import static com.kannada.newspaper.india.Constant.getApiUrl;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import com.kannada.newspaper.india.AppConfig;
import com.kannada.newspaper.india.Constant;
import com.kannada.newspaper.india.MainActivity;
import com.kannada.newspaper.india.R;
import com.kannada.newspaper.india.activities.ActivityCategoryDetail;
import com.kannada.newspaper.india.adapters.GalleryAdapter;
import com.kannada.newspaper.india.model.Category;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class FragmentCategory extends Fragment {
private Call<CallbackHome> callbackCall = null;
SharedPref sharedPref;
private View root_view;
public static final String EXTRA_OBJC = "key.EXTRA_OBJC";
private GalleryAdapter adapterCategory;
private GridView gridView;
private List<Category> mensWears;
private GalleryAdapter adapter;
private Category category;
public FragmentCategory() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,
Bundle savedInstanceState) {
requestAction();
category = (Category) getActivity().getIntent().getSerializableExtra(Constant.EXTRA_OBJC);
// Inflate the layout for this fragment
root_view = inflater.inflate(R.layout.fragment_phones,container,false);
((TextView) root_view.findViewById(R.id.txt_title_category)).setText(getResources().getString(R.string.home_title_category));
return root_view;
}
private void requestAction() {
new Handler().postDelayed(this::requestHomeData, Constant.DELAY_TIME);
}
private void requestHomeData() {
this.callbackCall = RestAdapter.createAPI(getApiUrl).getHome(AppConfig.REST_API_KEY);
this.callbackCall.enqueue(new Callback<CallbackHome>() {
public void onResponse(Call<CallbackHome> call, Response<CallbackHome> response) {
CallbackHome responseHome = response.body();
if (responseHome == null || !responseHome.status.equals("ok")) {
return;
}
displayData(responseHome);
}
public void onFailure(Call<CallbackHome> call, Throwable th) {
Log.e("onFailure", th.getMessage());
if (!call.isCanceled()) {
}
}
});
}
private void displayData(CallbackHome responseHome) {
displayCategory(responseHome.category);
}
private void displayCategory(List<Category> list) {
GridView gridView = (GridView) root_view.findViewById(R.id.gridHolder);
adapterCategory = new GalleryAdapter(getActivity(), list);
gridView.setAdapter(adapterCategory);
GalleryAdapter.setOnItemClickListener((v, obj, position) -> {
Intent intent = new Intent(getActivity(), ActivityCategoryDetail.class);
intent.putExtra(EXTRA_OBJC, obj);
startActivity(intent);
});
LinearLayout lyt_category = root_view.findViewById(R.id.lyt_category);
if (list.size() > 0) {
// lyt_category.setVisibility(View.VISIBLE);
} else {
// lyt_category.setVisibility(View.GONE);
}
}
}
GalleryAdapter adapter
public class GalleryAdapter extends BaseAdapter {
private Context context;
private List<Category> mensWears;
public GalleryAdapter(Context context, List<Category> mensWears) {
this.context = context;
this.mensWears = mensWears;
}
public static void setOnItemClickListener(Object o) {
}
#Override
public int getCount() {
return mensWears.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i,View view,ViewGroup viewGroup) {
final Category mensWear = mensWears.get(i);
if (view == null) {
final LayoutInflater layoutInflater = LayoutInflater.from(context);
view = layoutInflater.inflate(R.layout.custom_gallery_layout, null);
}
//For text
TextView prdId = view.findViewById(R.id.category_name);
ImageView imageView = view.findViewById(R.id.category_image);
// prdId.setText(prdId.toString());
Picasso.get()
.load(getApiUrl + "/upload/category/" + mensWears.get(i).category_image())
.placeholder(R.drawable.ic_thumbnail)
.into(imageView);
prdId.setText(mensWears.get(i).getItemName());
// //For images
// final ImageView imageView = view.findViewById(R.id.name);
// if(!TextUtils.isEmpty(mensWear.getItemName())){
//
//// Picasso.with(context).load(imageUrlFromServer+mensWear.category_image())
//// .into(imageView);
return view;
}
}
You cannot put Object type in putExtra , it has to be either serailized, string, double and other primitive type.
You can do like this:
Category category = (Category)adapter.getItemAtPosition(pos);
or this should also work:
Category category = (Category) obj
then,
intent.putExtra(EXTRA_OBJC,category)
Note: Your Category class should implement parcelable or serilizable to be passed as an intent.
public class Category implements Serializable {
..........}
I am trying to create a form that has a recyclerView for address and above the RecyclerView there is a Button which onClick able to add more address fields inside this RecyclerView but not able to do that instead when the button has clicked the app crashed.
Here is the Log output I got
Process: com.fitness.client, PID: 101621
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean androidx.recyclerview.widget.RecyclerView$ViewHolder.shouldIgnore()' on a null object reference
at androidx.recyclerview.widget.RecyclerView$LayoutManager.removeAndRecycleAllViews(RecyclerView.java:10079)
at androidx.recyclerview.widget.RecyclerView.removeAndRecycleViews(RecyclerView.java:1174)
at androidx.recyclerview.widget.RecyclerView.setAdapterInternal(RecyclerView.java:1197)
at androidx.recyclerview.widget.RecyclerView.setAdapter(RecyclerView.java:1156)
at com.fitness.client.ui.main.fragments.listing.ListingFragment$1.onClick(ListingFragment.java:144)
at android.view.View.performClick(View.java:6608)
at android.view.View.performClickInternal(View.java:6585)
at android.view.View.access$3100(View.java:785)
at android.view.View$PerformClick.run(View.java:25921)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
And here is the code of my fragment
AND btw the BUTTON name is "address"
package com.fitness.client.ui.main.fragments.listing;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import com.fitness.client.BR;
import com.fitness.client.R;
import com.fitness.client.api.RetroFitFactory;
import com.fitness.client.api.product.ProductDetailResponse;
import com.fitness.client.api.user.UserProfileResponse;
import com.fitness.client.api.user.UserService;
import com.fitness.client.base.classes.BaseFragment;
import com.fitness.client.base.classes.BaseRecyclerViewAdapter;
import com.fitness.client.base.classes.BaseViewHolder;
import com.fitness.client.databinding.ItemOfferingBinding;
import com.fitness.client.databinding.ItemProductListingBinding;
import com.fitness.client.objects.Product;
import com.fitness.client.ui.main.fragments.listing.adapter.AddressAdapter;
import com.fitness.client.ui.main.fragments.listing.adapter.DescriptionAdapter;
import com.fitness.client.ui.main.fragments.listing.adapter.EmailAdapter;
import com.fitness.client.ui.main.fragments.listing.adapter.FacilitesAdapter;
import com.fitness.client.ui.main.fragments.listing.adapter.PhoneAdapter;
import com.fitness.client.ui.main.fragments.listing.adapter.TagAdapter;
import com.fitness.client.ui.main.fragments.listing.adapter.TermsAdapter;
import com.fitness.client.ui.main.fragments.listing.adapter.TimingAdapter;
import com.fitness.client.ui.offering.OfferingActivity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
public class ListingFragment extends BaseFragment<ItemProductListingBinding, ListingViewModel, ListingNavigator> implements ListingNavigator {
public String TAG = "ListingFragment";
private AddressAdapter addressAdapter;
private EmailAdapter emailAdapter;
private FacilitesAdapter facilitesAdapter;
private PhoneAdapter phoneAdapter;
private DescriptionAdapter descriptionAdapter;
private TermsAdapter termsAdapter;
private TagAdapter tagAdapter;
private TimingAdapter timingAdapter;
private OfferingAdapter offeringAdapter;
private LinearLayout addressLayout;
private LinearLayout.LayoutParams layoutParams;
private int ids = 0;
private int hint = 0;
public static ListingFragment getInstance(Context context) {
return (ListingFragment) ListingFragment.instantiate(context, ListingFragment.class.getName());
}
#Override
public int getBindingVariable() {
return BR.listing_view_model;
}
#Override
public int getLayoutId() {
return R.layout.item_product_listing;
}
#Override
public void init(View view, Bundle savedInstances) {
addressAdapter = new AddressAdapter(new ArrayList<>());
emailAdapter = new EmailAdapter(new ArrayList<>());
facilitesAdapter = new FacilitesAdapter(new ArrayList<>());
phoneAdapter = new PhoneAdapter(new ArrayList<>());
descriptionAdapter = new DescriptionAdapter(new ArrayList<>());
termsAdapter = new TermsAdapter(new ArrayList<>());
tagAdapter = new TagAdapter(new ArrayList<>());
timingAdapter = new TimingAdapter(new ArrayList<>());
offeringAdapter = new OfferingAdapter(new ArrayList<>());
getViewDataBinding().addressList.setAdapter(addressAdapter);
getViewDataBinding().emailList.setAdapter(emailAdapter);
getViewDataBinding().facilitiesList.setAdapter(facilitesAdapter);
getViewDataBinding().phoneList.setAdapter(phoneAdapter);
getViewDataBinding().descriptionList.setAdapter(descriptionAdapter);
getViewDataBinding().termsAndConditionsList.setAdapter(termsAdapter);
getViewDataBinding().tagList.setAdapter(tagAdapter);
getViewDataBinding().timingList.setAdapter(timingAdapter);
getViewDataBinding().offeringList.setAdapter(offeringAdapter);
getViewModel().requestData();
// LayoutInflater inflater = (LayoutInflater)
// Objects.requireNonNull(getContext()).getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LayoutInflater inflater = LayoutInflater.from(getContext());
View view1 = inflater != null ? inflater.inflate(R.layout.item_edit_box, null) : null;
// addressLayout =getViewDataBinding().layoutmain;
if (view != null) {
addressLayout = view1 != null ? view1.findViewById(R.id.createLayout) : null;
}
Log.e("Listing Fragment", String.format("Recyler View LAYOUT %s", addressLayout));
// addressLayout = view.findViewById(R.id.createLayout);
layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(5, 5, 5, 5);
final int[] i = {0};
getViewDataBinding().address.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i[0] = i[0] + 1;
// TextView more = new TextView(getContext());
// more.setText(String.format("Address %s", i[0]));
// more.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_START);
// more.setVisibility(View.VISIBLE);
ids++;
hint++;
EditText newEdit = new EditText(getContext());
newEdit.setHint(String.format("Address %s", hint));
newEdit.setId(ids);
newEdit.setMinLines(4);
Log.e("New Edittext: ", String.valueOf(ids));
newEdit.setInputType(InputType.TYPE_CLASS_TEXT);
// addressLayout.addView(more);
addressLayout.addView(newEdit,layoutParams);
getViewDataBinding().addressList.addView(addressLayout);
AddressAdapter addressAdapter1 = new AddressAdapter(new ArrayList<>());
// getViewDataBinding().addressList.addView(addressLayout);
getViewDataBinding().addressList.setAdapter(addressAdapter1);
addressAdapter1.notifyDataSetChanged();
// getViewDataBinding().moreAddress.setAdapter(addressAdapter);
// addressAdapter.notifyDataSetChanged();
// ListingFragment fragment = (ListingFragment) getFragmentManager().findFragmentByTag(TAG);
// if (fragment != null) {
// fragment.addressAdapter.getAdapter().newAddeddata();
// }
// getViewDataBinding().
// getViewDataBinding().moreAddress.setAdapter(addressAdapter);
// addressAdapter.notifyDataSetChanged();
// RecyclerView recyclerView = new RecyclerView(getContext());
// recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
// recyclerView.setHasFixedSize(true);
// recyclerView.setAdapter(addressAdapter);
}
});
}
#Override
public void updateProductList(List<Product> products) {
if (products != null && products.size() > 0) {
for (Product product : products) {
getViewModel().requestProductDetails(product.getId());
}
} else {
showToast("No products found");
}
}
#Override
public void setUpProductDetails(ProductDetailResponse data) {
offeringAdapter.addData(data.getData().getOffer_package());
}
#Override
public void setProfileInformation(UserProfileResponse body) {
getViewDataBinding().name.setText(body.getData().getName());
timingAdapter.addData(body.getData().getTiming_info());
termsAdapter.addData(Collections.singletonList(body.getData().getMerchant_info().getTermscondition()));
Log.e("Listing Fragment", "Terms: " + Collections.singletonList(body.getData().getMerchant_info().getTermscondition()));
tagAdapter.addData(Collections.singletonList(body.getData().getMerchant_info().getBusiness_tags()));
descriptionAdapter.addData(Collections.singletonList(body.getData().getMerchant_info().getDescription()));
addressAdapter.addData(body.getData().getAddress());
if (body.getData().getFacilities_info().getFacilities() != null)
facilitesAdapter.addData(Arrays.asList(body.getData().getFacilities_info().getFacilities().split(",")));
List<String> emailList = Arrays.asList(body.getData().getContact_info().getAlter_email_1(),
body.getData().getContact_info().getAlter_email_2(),
body.getData().getContact_info().getAlter_email_3(),
body.getData().getContact_info().getAlter_email_4());
// emailAdapter.addData(emailList);
emailAdapter.addData(emailList);
Log.e("Listing Fragment", "Email: " + emailList);
// phoneAdapter.addData(body.getData().getContact_info());
List<String> phoneList = Arrays.asList(body.getData().getContact_info().getAlter_mobile_1(),
body.getData().getContact_info().getAlter_mobile_2(),
body.getData().getContact_info().getAlter_mobile_3(),
body.getData().getContact_info().getAlter_mobile_4());
Log.e("Listing Fragment", "Phone Number: " + phoneList);
phoneAdapter.addData(phoneList);
// phoneAdapter.addData(Arrays.asList(body.getData().getContact_info().getAlter_mobile_1(),
// );
getViewDataBinding().update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showLoading("Loading", "Please wait while update your profile");
RetroFitFactory.getRetrofitCallFor(UserService.class)
.updateUserProfile();
}
});
}
class OfferingAdapter extends BaseRecyclerViewAdapter<OfferingAdapter.OfferingHolder, ProductDetailResponse.Offer_packageEntity> {
public OfferingAdapter(List<ProductDetailResponse.Offer_packageEntity> data) {
super(data);
}
#NonNull
#Override
public OfferingHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new OfferingHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_offering, parent, false));
}
class OfferingHolder extends BaseViewHolder<ProductDetailResponse.Offer_packageEntity, ItemOfferingBinding> {
public OfferingHolder(View itemView) {
super(itemView);
}
#Override
protected void bindObject(ProductDetailResponse.Offer_packageEntity object) {
getViewDataBinding().setOffering(object);
getViewDataBinding().viewSch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), OfferingActivity.class);
intent.putParcelableArrayListExtra("data", object.getDays_timing());
startActivity(intent);
}
});
/* adapter.clear();
ProductDetailResponse.Days_timingEntity placeHolder = new ProductDetailResponse.Days_timingEntity();
placeHolder.setDay("Day");
placeHolder.setWeek("Week");
adapter.addData(Collections.singletonList(placeHolder));
adapter.addData(object.getDays_timing());*/
}
}
}
}
Create functions in your adapter, named addItem and removeItem
watch this video for a more detailed explanation
: https://www.youtube.com/watch?v=enTvZm9LOGc&t=247s
I want to display what my array list value is. So, I want to loop with the size of array list as the limit. But after I add some value through a function, and want to get the size of it, it always 0. I still newbie in android programming. I had search in google, but still confused and not understand what the problem is. Thanks for you guys help
I had tried to set through global variable, but it's not work
Here is my activity file
package bobby.irawan.aticket;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
public class DetailPromoActivity extends AppCompatActivity {
private ListView listView;
private TextView nama_detail_promo_tv;
private String nama_detail_promo;
private DetailPromoAdapter adapter;
private int counter_header=0, counter_promo = 0;
private View layout_kupon;
private int id_link_promo;
private RequestQueue requestQueue;
private String url = "192.168.11.134:8000";
private TextView header_promo, kupon_promo, notif_promo;
private ArrayList<DetailPromo> detailPromos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_promo);
View view = findViewById(R.id.layout_kupon);
header_promo = view.findViewById(R.id.header_promo_tv);
kupon_promo = view.findViewById(R.id.kode_promo_tv);
id_link_promo = (int) getIntent().getSerializableExtra("id_promo");
nama_detail_promo = (String) getIntent().getSerializableExtra("nama_promo");
String nama_ota = (String) getIntent().getSerializableExtra("nama_ota");
listView = findViewById(R.id.lv_detpro);
layout_kupon = findViewById(R.id.layout_kupon);
header_promo = layout_kupon.findViewById(R.id.header_promo_tv);
kupon_promo = layout_kupon.findViewById(R.id.kode_promo_tv);
notif_promo = layout_kupon.findViewById(R.id.notif_promo_tv);
requestQueue = Volley.newRequestQueue(this);
nama_detail_promo_tv = findViewById(R.id.nama_detail_promo);
nama_detail_promo_tv.setText(nama_detail_promo);
setDetailPromotoClass(id_link_promo);
adapter = new DetailPromoAdapter(detailPromos,this);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Promo "+nama_ota);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
//Set kupon
System.out.println("Size detpro "+counter_header+" "+counter_promo);
if(counter_header == 0 && counter_promo == 0){
notif_promo.setVisibility(View.VISIBLE);
header_promo.setVisibility(View.GONE);
kupon_promo.setVisibility(View.GONE);
System.out.println("Masuk sini");
}
else if(counter_header == 0){
header_promo.setText("PROMO PESAWAT");
}
else{
kupon_promo.setText("Tidak perlu");
}
}
class DetailPromoAdapter extends BaseAdapter {
private List<DetailPromo> detailPromo;
private Context context;
public DetailPromoAdapter(List<DetailPromo> detailPromo, Context context) {
this.detailPromo = detailPromo;
this.context = context;
}
#Override
public int getCount() {
System.out.println("Detail promo size"+detailPromo.size());
return detailPromo.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.detail_promo_adapter, parent, false);
TextView nama_detail_promo = convertView.findViewById(R.id.isi_detail_promo);
if(detailPromo.get(position).getDetpro_role().equals("detail_promo")){
nama_detail_promo.setText(detailPromo.get(position).getDetpro_list());
}
return convertView;
}
}
public void setDetailPromotoClass(int id_linkpro){
detailPromos = new ArrayList<DetailPromo>();
String url_promo = "http://"+url+"/detail_promo/"+id_linkpro;
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url_promo, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
for(int i=0; i<jsonArray.length(); i++){
JSONObject data_promo = jsonArray.getJSONObject(i);
int id_detpro = data_promo.getInt("id");
int id_promo = data_promo.getInt("promo_id");
int id_linkpro = data_promo.getInt("linkpro_id");
String detpro_list = data_promo.getString("detpro_list");
String detpro_role = data_promo.getString("detpro_role");
detailPromos.add(new DetailPromo(id_detpro,id_promo,id_linkpro,detpro_list,detpro_role));
System.out.println("Data promo yang diklik "+id_promo+" "+id_linkpro+" "+detpro_list+" "+detpro_role);
adapter.notifyDataSetChanged();
if(detpro_role.equals("header_promo")){
header_promo.setText(detailPromos.get(i).detpro_list);
System.out.println("Ada header");
counter_header++;
}
if(detpro_role.equals("kode_promo")){
System.out.println("Ada kupon");
kupon_promo.setText(detailPromos.get(i).detpro_list);
counter_promo++;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(request);
}
}
I am making a flash card app with SwipeCard
This is my FlashCardActivity:
import android.os.Bundle;
import android.text.style.TtsSpan;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import com.google.gson.Gson;
import com.lorentzos.flingswipe.SwipeFlingAdapterView;
import org.koreanlab.fabloading.R;
import org.koreanlab.fabloading.adapter.CardListAdapter;
import org.koreanlab.fabloading.basickit.BasicCompatActivity;
import org.koreanlab.fabloading.basickit.remote.RemoteService;
import org.koreanlab.fabloading.basickit.remote.ServiceGenerator;
import org.koreanlab.fabloading.item.CardItem;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class FlashCardActivity extends BasicCompatActivity {
private String TAG = getClass().getSimpleName();
private ArrayList<CardItem> cardList;
private ArrayAdapter<String> cardAdapter;
private CardListAdapter cardListAdapter;
private int i;
CardItem newCard;
#BindView(R.id.frame)
SwipeFlingAdapterView flingContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flashcard);
ButterKnife.bind(this);
cardList = new ArrayList<>();
Log.d(TAG, "cardList created");
// get Two Words;
cardList.add(getCardItem());
cardList.add(getCardItem());
Log.d(TAG, "added Card");
cardListAdapter = new CardListAdapter(this, R.layout.card_item, cardList);
Log.d(TAG, "adapter created: " + (cardListAdapter == null ? "cardAdapter is NULL" : "cardAdapter is not NULL"));
flingContainer.setAdapter(cardListAdapter);
Log.d(TAG, "adapter set: " + (flingContainer == null ? "flingContainer is NULL" : "flingContainer is not NULL"));
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
cardList.remove(0);
cardListAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
makeToast(FlashCardActivity.this, "Left!");
}
#Override
public void onRightCardExit(Object dataObject) {
makeToast(FlashCardActivity.this, "Right!");
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
Log.d(TAG, "onAdapterAboutToEmpty: "+itemsInAdapter);
cardList.add(getCardItem());
cardListAdapter.notifyDataSetChanged();
Log.d("LIST", "notified");
i++;
}
#Override
public void onScroll(float scrollProgressPercent) {
View view = flingContainer.getSelectedView();
view.findViewById(R.id.item_swipe_right_indicator).setAlpha(scrollProgressPercent < 0 ? -scrollProgressPercent : 0);
view.findViewById(R.id.item_swipe_left_indicator).setAlpha(scrollProgressPercent > 0 ? scrollProgressPercent : 0);
}
});
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
makeToast(FlashCardActivity.this, "Clicked!");
}
});
}
#OnClick(R.id.right)
public void right() {
/**
* Trigger the right event manually.
*/
flingContainer.getTopCardListener().selectRight();
}
#OnClick(R.id.left)
public void left() {
flingContainer.getTopCardListener().selectLeft();
}
public CardItem getCardItem() {
// No problem here.
return newCard;
}
}
Notice that, getCardItem() just get one card. First of all, it calls two cards and the cardList has two cards when activity has created. And after that I'd like to get just one card after swipe. getCardItem() has no problem. I can see that I receives the data from my Server.
This is my custom CardListAdapter:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import org.koreanlab.fabloading.R;
import org.koreanlab.fabloading.item.CardItem;
import java.util.ArrayList;
import java.util.List;
public class CardListAdapter extends ArrayAdapter {
private final String TAG = this.getClass().getSimpleName();
private Context context;
private int cardResId;
private int frontResId;
private int backResId;
private List<CardItem> cardList;
private LayoutInflater mInflater;
//this, R.layout.card_item, R.id.card_front, R.id.card_back, cardList
public CardListAdapter(Context context, int cardResId, ArrayList<CardItem> cardList) {
super(context, cardResId);
this.context = context;
this.cardResId = cardResId;
this.cardList = cardList;
mInflater = LayoutInflater.from(context);
}
public void setItem(CardItem newItem) {
Log.d(TAG, "setItem");
for (int i = 0; i < cardList.size(); i++) {
CardItem item = cardList.get(i);
if (item.seq == newItem.seq) {
cardList.set(i, newItem);
break;
}
}
}
#Override
public int getCount() {
Log.d(TAG, "getVIew");
return 0;
}
public int getPosition(CardItem item) {
Log.d(TAG, "getPosition = "+item);
return cardList.indexOf(item);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
convertView = mInflater.inflate(cardResId, parent,false);
holder = new ViewHolder();
Log.d(TAG, "getView");
holder.frontTV = convertView.findViewById(R.id.card_front);
holder.backTV = convertView.findViewById(R.id.card_back);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.frontTV.setText((String)getItem(position));
holder.backTV.setText((String)getItem(position));
return convertView;
}
static class ViewHolder
{
TextView frontTV, backTV;
}
}
I checked many blogs and other Q&A, but I haven't figured it out how to solve this problem. That activity keeps going back after receiving 'one word' data from the Server and It doesn't show any error messages.
so what im looking to do here is i currently have an array of bitmap images that i have retrieved from a instagram galley and what i want tot do is enlarge these images to full screen on tap and then return to the original array once tapped again (i understand this may mean retrieving "standard_resolution" as well as "low_resolution"
Main Activity
package net.londatiga.android.example;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import net.londatiga.android.instagram.Instagram;
import net.londatiga.android.instagram.InstagramRequest;
import net.londatiga.android.instagram.InstagramSession;
import net.londatiga.android.instagram.InstagramUser;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
public class MainActivity extends Activity {
private InstagramSession mInstagramSession;
private Instagram mInstagram;
private ProgressBar mLoadingPb;
private GridView mGridView;
private static final String CLIENT_ID = "83549f9eb76f4a5b90daf6e4e14da107";
private static final String CLIENT_SECRET = "6df26b0c8f664323a07126bfe8511651";
private static final String REDIRECT_URI = "http://www.yahoo.com";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mInstagram = new Instagram(this, CLIENT_ID, CLIENT_SECRET, REDIRECT_URI);
mInstagramSession = mInstagram.getSession();
if (mInstagramSession.isActive()) {
setContentView(R.layout.activity_user);
InstagramUser instagramUser = mInstagramSession.getUser();
mLoadingPb = (ProgressBar) findViewById(R.id.pb_loading);
mGridView = (GridView) findViewById(R.id.gridView);
((TextView) findViewById(R.id.tv_name)).setText(instagramUser.fullName);
((TextView) findViewById(R.id.tv_username)).setText(instagramUser.username);
((Button) findViewById(R.id.btn_logout)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mInstagramSession.reset();
startActivity(new Intent(MainActivity.this, MainActivity.class));
finish();
}
});
ImageView userIv = (ImageView) findViewById(R.id.iv_user);
DisplayImageOptions displayOptions = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_user)
.showImageForEmptyUri(R.drawable.ic_user)
.showImageOnFail(R.drawable.ic_user)
.cacheInMemory(true)
.cacheOnDisc(false)
.considerExifParams(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
.writeDebugLogs()
.defaultDisplayImageOptions(displayOptions)
.build();
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
AnimateFirstDisplayListener animate = new AnimateFirstDisplayListener();
imageLoader.displayImage(instagramUser.profilPicture, userIv, animate);
new DownloadTask().execute();
} else {
setContentView(R.layout.activity_main);
((Button) findViewById(R.id.btn_connect)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mInstagram.authorize(mAuthListener);
}
});
}
}
private void showToast(String text) {
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
}
private Instagram.InstagramAuthListener mAuthListener = new Instagram.InstagramAuthListener() {
#Override
public void onSuccess(InstagramUser user) {
finish();
startActivity(new Intent(MainActivity.this, MainActivity.class));
}
#Override
public void onError(String error) {
showToast(error);
}
#Override
public void onCancel() {
showToast("OK. Maybe later?");
}
};
public 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);
}
}
}
}
public class DownloadTask extends AsyncTask<URL, Integer, Long> {
ArrayList<String> photoList;
protected void onCancelled() {
}
protected void onPreExecute() {
}
protected Long doInBackground(URL... urls) {
long result = 0;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>(1);
params.add(new BasicNameValuePair("count", "20"));
InstagramRequest request = new InstagramRequest(mInstagramSession.getAccessToken());
String response = request.createRequest("GET", "/users/21846697/media/recent", params);
if (!response.equals("")) {
JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
JSONArray jsonData = jsonObj.getJSONArray("data");
int length = jsonData.length();
if (length > 0) {
photoList = new ArrayList<String>();
for (int i = 0; i < length; i++) {
JSONObject jsonPhoto = jsonData.getJSONObject(i).getJSONObject("images").getJSONObject("low_resolution");
photoList.add(jsonPhoto.getString("url"));
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
mLoadingPb.setVisibility(View.GONE);
if (photoList == null) {
Toast.makeText(getApplicationContext(), "No Photos Available", Toast.LENGTH_LONG).show();
} else {
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = (int) Math.ceil((double) dm.widthPixels / 2);
width=width-50;
int height = width;
PhotoListAdapter adapter = new PhotoListAdapter(MainActivity.this);
adapter.setData(photoList);
adapter.setLayoutParam(width, height);
mGridView.setAdapter(adapter);
}
}
}
}
PhotoListAdapter
package net.londatiga.android.example;
import net.londatiga.android.example.R;
import net.londatiga.android.example.MainActivity.AnimateFirstDisplayListener;
import java.util.ArrayList;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.content.Context;
public class PhotoListAdapter extends BaseAdapter {
private Context mContext;
private ImageLoader mImageLoader;
private AnimateFirstDisplayListener mAnimator;
private ArrayList<String> mPhotoList;
private int mWidth;
private int mHeight;
public PhotoListAdapter(Context context) {
mContext = context;
DisplayImageOptions displayOptions = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.instagram_logo)
.showImageForEmptyUri(R.drawable.instagram_logo)
.showImageOnFail(R.drawable.instagram_logo)
.cacheInMemory(true)
.cacheOnDisc(false)
.considerExifParams(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.writeDebugLogs()
.defaultDisplayImageOptions(displayOptions)
.build();
mImageLoader = ImageLoader.getInstance();
mImageLoader.init(config);
mAnimator = new AnimateFirstDisplayListener();
}
public void setData(ArrayList<String> data) {
mPhotoList = data;
}
public void setLayoutParam(int width, int height) {
mWidth = width;
mHeight = height;
}
#Override
public int getCount() {
return (mPhotoList == null) ? 0 : mPhotoList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageIv;
if (convertView == null) {
imageIv = new ImageView(mContext);
imageIv.setLayoutParams(new GridView.LayoutParams(mWidth, mHeight));
imageIv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageIv.setPadding(0, 0, 0, 0);
} else {
imageIv = (ImageView) convertView;
}
mImageLoader.displayImage(mPhotoList.get(position), imageIv, mAnimator);
return imageIv;
}
}