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.
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 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.
I have an app that currently displays a list of names in a ListView. Each item in the ListView consists of a CheckBox and an EditText.
The list of names is provided by an ArrayList of 'Prospects' objects
When the user selects the CheckBox I want to return the state of this check box and assign it the Propsects object at the relevant position in the ArrayList so it can be saved for use the next time the app is opened (this will be done using CSV).
I'm struggling with the correct listener to use to do this as this is my first attempt at Android programming. I've been unable to find any examples that match what i'm trying to achieve or if I have i've not understood them!.
Any help would be appreciated!
My code is as follows:
package com.veetox.networkmarketingmanager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.veetox.networkmarketingmanager.data.Prospects;
import com.veetox.networkmarketingmanager.helper.FileHelper;
import com.veetox.networkmarketingmanager.helper.ProspectListAdapter;
import com.veetox.networkmarketingmanager.helper.ProspectViewHolder;
import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity
{
public static ArrayList<Prospects> prospectList = new ArrayList<>();
Resources res;
FileHelper fileHelper = new FileHelper(this);
ListView prospectsListEntry;
CheckBox prospectsCheckBox;
EditText prospectsEditText;
ProspectListAdapter pla;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prospectsCheckBox = (CheckBox) findViewById(R.id.pr_checkBox);
prospectsEditText = (EditText) findViewById(R.id.pr_name);
res = getResources();
createProspectList();
prospectsListEntry.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View item, int position, long id)
{
//Create new Prospect cloning Prospect at row in ItemList that was clicked
Prospects prospect = pla.getItem(position);
//Change the state of contacted from true to false or vice versa
prospect.toggleContacted();
//Create a ProspectViewHolder to hold the view for the row clicked
ProspectViewHolder viewHolder = (ProspectViewHolder) item.getTag();
viewHolder.getCheckBox().setChecked(prospect.isChecked());
prospectList.get(position) ;
pla.notifyDataSetChanged();
}
});
}
public void testProspects(View view)
{
prospectList = fileHelper.testProspects();
pla.notifyDataSetChanged();
}
public void createProspectList()
{
fileHelper = new FileHelper(this);
//Comment before testing
//prospectList = fileHelper.loadProspects();
//Uncomment for testing
prospectList = fileHelper.testProspects();
//Create the list
pla = new ProspectListAdapter(this, R.layout.prospects_list_layout, prospectList);
prospectsListEntry = (ListView) findViewById(R.id.prospects_list);
prospectsListEntry.setAdapter(pla);
}
}
package com.veetox.networkmarketingmanager.helper;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import com.veetox.networkmarketingmanager.MainActivity;
import com.veetox.networkmarketingmanager.R;
import com.veetox.networkmarketingmanager.data.Prospects;
import java.util.ArrayList;
/**
* Created by Matt on 29/09/2016.
*/
public class ProspectListAdapter extends ArrayAdapter<Prospects>
{
private Context context;
private int layoutResourceId;
private ArrayList<Prospects> prospect;
public ProspectListAdapter(Context context, int layoutResourceId, ArrayList<Prospects> prospect)
{
super(context, layoutResourceId, prospect);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.prospect = prospect;
}
public int getCount()
{
return prospect.size();
}
public Prospects getItem(int position)
{
return prospect.get(position);
}
public long getItemId(int position)
{
return position;
}
#Override
#NonNull
public View getView(int position, View convertView, #NonNull ViewGroup parent)
{
View v = convertView;
if (v == null)
{
LayoutInflater vi;
vi = LayoutInflater.from(context);
v = vi.inflate(layoutResourceId, parent, false);
}
Prospects prospects = prospect.get(position);
if (prospects != null)
{
TextView prname = (TextView) v.findViewById(R.id.pr_name);
CheckBox complete = (CheckBox) v.findViewById(R.id.pr_checkBox);
if (prname != null)
{
prname.setText(prospects.getName());
}
if (complete != null)
{
complete.setChecked(prospects.isChecked());
}
}
return v;
}
}
package com.veetox.networkmarketingmanager.data;
/**
* A Prospective customer
*/
public class Prospects
{
private String prospectname;
private boolean contacted;
private String stringContacted;
public Prospects(String aName, boolean contacted)
{
prospectname = aName;
this.contacted = contacted;
}
public Prospects(String aName, String contacted)
{
prospectname = aName;
this.stringContacted = contacted;
}
public Prospects(String aName)
{
prospectname = aName;
}
public String getName()
{
return prospectname;
}
public boolean isChecked()
{
return contacted;
}
public void setName (String aName)
{
prospectname = aName;
}
public void setContacted(boolean contacted)
{
this.contacted = contacted;
}
public void toggleContacted()
{
if (contacted)
{
contacted = false;
}
else
{
contacted = true;
}
}
}
package com.veetox.networkmarketingmanager.helper;
import android.content.Context;
import android.widget.Toast;
import com.veetox.networkmarketingmanager.data.Prospects;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Map;
import java.util.Scanner;
/**
* Created by Matt on 28/09/2016.
*/
public final class FileHelper
{
Context context;
public FileHelper(Context aContext)
{
context = aContext;
}
public void saveProspects(ArrayList<Prospects> prospects)
{
ArrayList<Prospects> p = prospects;
BufferedWriter bufferedFileWriter = null;
try
{
File aFile = new File(context.getFilesDir(), "prospects.csv");
aFile.createNewFile();
bufferedFileWriter = new BufferedWriter(new FileWriter(aFile));
for (Prospects eachProspect : p)
{
bufferedFileWriter.write(eachProspect.getName());
bufferedFileWriter.write(",");
bufferedFileWriter.write(String.valueOf(eachProspect.isChecked()));
bufferedFileWriter.newLine();
}
}
catch (Exception e)
{
e.printStackTrace();
// Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
}
finally
{
try
{
bufferedFileWriter.close();
}
catch (Exception e)
{
e.printStackTrace();
//Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
public ArrayList<Prospects> loadProspects()
{
ArrayList<Prospects> prospectsList = new ArrayList<>();
Scanner bufferedScanner = null;
Scanner lineScanner = null;
try
{
File aFile = new File(context.getFilesDir(), "prospects.csv");
bufferedScanner = new Scanner(new BufferedReader(new FileReader(aFile)));
while (bufferedScanner.hasNextLine())
{
lineScanner = new Scanner(bufferedScanner.nextLine());
lineScanner.useDelimiter(",");
String prospect = lineScanner.next();
String contacted = lineScanner.next();
Prospects aProspect = new Prospects(prospect, contacted);
prospectsList.add(aProspect);
}
}
catch (Exception e)
{
e.printStackTrace();
//Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
}
finally
{
try
{
bufferedScanner.close();
}
catch (Exception e)
{
e.printStackTrace();
//Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
}
}
return prospectsList;
}
public ArrayList<Prospects> testProspects()
{
ArrayList<Prospects> p = new ArrayList<>();
Prospects q = new Prospects("Matt Lee", true);
Prospects r = new Prospects("Rosemary Watson", false);
Prospects s = new Prospects("Joe Bloggs", false);
Prospects t = new Prospects("Ronny Corbit", false);
Prospects u = new Prospects("Mr Man", false);
Prospects v = new Prospects("Mr Bond", true);
Prospects w = new Prospects("Mr Blobby", true);
Prospects x = new Prospects("Mary Rose", false);
Prospects y = new Prospects("Jane Doe", false);
Prospects z = new Prospects("Lucy Sanders", false);
p.add(q);
p.add(r);
p.add(s);
p.add(t);
p.add(u);
p.add(v);
p.add(w);
p.add(x);
p.add(y);
p.add(z);
return p;
}
}
You need to move your checkbox check(checked/notChecked) in adapter. you'll need ItemId to access and retrive the clicked item in ListView.
i want to put a 2 column listview in the 2nd column of my first 2 column listview but i dont know how to and is it possible to use the same code to make it a 3 column list view?where in the first column is an image and the 2nd and 3rd column are both text i tried it but it has error... my code goes like this..
main
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
public class WeatherToday extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weathertoday);
ListView view = (ListView) findViewById(R.id.todaylist);
final List<MyStringPair> myStringPairList = MyStringPair.makeData(10);
MyStringPairAdapter adapter = new MyStringPairAdapter(this, myStringPairList);
view.setAdapter(adapter);
}
}
stringpairlist
import java.util.ArrayList;
import java.util.List;
public class MyStringPair {
private String columnOne;
private String columnTwo;
public MyStringPair(String columnOne, String columnTwo) {
super();
this.columnOne = columnOne;
this.columnTwo = columnTwo;
}
public String getColumnOne() {
return columnOne;
}
public void setColumnOne(String columnOne) {
this.columnOne = columnOne;
}
public String getColumnTwo() {
return columnTwo;
}
public void setColumnTwo(String columnTwo) {
this.columnTwo = columnTwo;
}
public static List<MyStringPair> makeData(int n) {
List<MyStringPair> pair = new ArrayList<MyStringPair>();
pair.add(new MyStringPair("Weather Condition", "Partly Cloudy"));
pair.add(new MyStringPair("Temperature", "30 Celcius "));
pair.add(new MyStringPair("Moisture", "Dew Point:" ));
pair.add(new MyStringPair("Wind", "Column2 "));
pair.add(new MyStringPair("Precipitation", "Column2 "));
pair.add(new MyStringPair("Condition", "Pressure:1014 mb "));
return pair;
}
}
adapter
import java.util.List;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class MyStringPairAdapter extends BaseAdapter {
private Activity activity;
private List<MyStringPair> stringPairList;
public MyStringPairAdapter(Activity activity, List<MyStringPair> stringPairList) {
super();
this.activity = activity;
this.stringPairList = stringPairList;
}
#Override
public int getCount() {
return stringPairList.size();
}
#Override
public Object getItem(int position) {
return stringPairList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = activity.getLayoutInflater();
convertView = inflater.inflate(R.layout.listrow, null);
}
TextView col1 = (TextView) convertView.findViewById(R.id.column1);
TextView col2 = (TextView) convertView.findViewById(R.id.column2);
col1.setText(stringPairList.get(position).getColumnOne());
col2.setText(stringPairList.get(position).getColumnTwo());
return convertView;
}
}
i've added a box on the column where i want another 2 column..basically i want to put two more column in the smaller box i want to divide the text into two parts so i need two columns for that but im out of ideas