Android Ez vCard library - writing multiple vCards - java

I am trying to use the Android ez vcard library to create vcf file from my object. My problem is I have no idea how to instantiate a List of VCards, like so:
List<VCard> vcards = null ;
I tried:
List<VCard> vcards = new List<VCard>();
but then it insists on implementing methods to look like this:
List<VCard> vcards = new List<VCard>() {
#Override
public void add(int location, VCard object) {
}
#Override
public boolean add(VCard object) {
return false;
}
#Override
public boolean addAll(int location, Collection<? extends VCard> collection) {
return false;
}
#Override
public boolean addAll(Collection<? extends VCard> collection) {
return false;
}
#Override
public void clear() {
}
#Override
public boolean contains(Object object) {
return false;
}
#Override
public boolean containsAll(Collection<?> collection) {
return false;
}
#Override
public VCard get(int location) {
return null;
}
#Override
public int indexOf(Object object) {
return 0;
}
#Override
public boolean isEmpty() {
return false;
}
#NonNull
#Override
public Iterator<VCard> iterator() {
return null;
}
#Override
public int lastIndexOf(Object object) {
return 0;
}
#Override
public ListIterator<VCard> listIterator() {
return null;
}
#NonNull
#Override
public ListIterator<VCard> listIterator(int location) {
return null;
}
#Override
public VCard remove(int location) {
return null;
}
#Override
public boolean remove(Object object) {
return false;
}
#Override
public boolean removeAll(Collection<?> collection) {
return false;
}
#Override
public boolean retainAll(Collection<?> collection) {
return false;
}
#Override
public VCard set(int location, VCard object) {
return null;
}
#Override
public int size() {
return 0;
}
#NonNull
#Override
public List<VCard> subList(int start, int end) {
return null;
}
#NonNull
#Override
public Object[] toArray() {
return new Object[0];
}
#NonNull
#Override
public <T> T[] toArray(T[] array) {
return null;
}
} ;
and when I try to add vcards to it, I get a NullPointerException. How do I solve this?

Try this
List<VCard> vcards = new ArrayList<VCard>();
Hope it helps.

Related

Trying to add documents' names from firestore to List<String>

Hy, I'm trying to add documents names from a collection into a List to apply it on a spinner in my android app, and in the Logs I made it's showing the list of the documents but List.size returns me 0 and so the spinner doesn't show anything...
Here is the spinner setting code:
Spinner listProblem = findViewById(R.id.problemList);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, problemTitles());
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
listProblem.setAdapter(adapter);
And this is the problemList() function:
public List<String> problemTitles() {
problemList = new List<String>() {
#Override
public int size() {
return 0;
}
#Override
public boolean isEmpty() {
return false;
}
#Override
public boolean contains(#Nullable Object o) {
return false;
}
#NonNull
#Override
public Iterator<String> iterator() {
return null;
}
#NonNull
#Override
public Object[] toArray() {
return new Object[0];
}
#NonNull
#Override
public <T> T[] toArray(#NonNull T[] a) {
return null;
}
#Override
public boolean add(String s) {
return false;
}
#Override
public boolean remove(#Nullable Object o) {
return false;
}
#Override
public boolean containsAll(#NonNull Collection<?> c) {
return false;
}
#Override
public boolean addAll(#NonNull Collection<? extends String> c) {
return false;
}
#Override
public boolean addAll(int index, #NonNull Collection<? extends String> c) {
return false;
}
#Override
public boolean removeAll(#NonNull Collection<?> c) {
return false;
}
#Override
public boolean retainAll(#NonNull Collection<?> c) {
return false;
}
#Override
public void clear() {
}
#Override
public String get(int index) {
return null;
}
#Override
public String set(int index, String element) {
return null;
}
#Override
public void add(int index, String element) {
}
#Override
public String remove(int index) {
return null;
}
#Override
public int indexOf(#Nullable Object o) {
return 0;
}
#Override
public int lastIndexOf(#Nullable Object o) {
return 0;
}
#NonNull
#Override
public ListIterator<String> listIterator() {
return null;
}
#NonNull
#Override
public ListIterator<String> listIterator(int index) {
return null;
}
#NonNull
#Override
public List<String> subList(int fromIndex, int toIndex) {
return null;
}
};
prblmDB.collection("Problems").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
int i = -1;
for (QueryDocumentSnapshot document : Objects.requireNonNull(task.getResult())) {
problemList.add(i++, Objects.requireNonNull(document.get("Prblm Title: ")).toString());
Log.d("document title: ", Objects.requireNonNull(document.get("Prblm Title: ")).toString());
}
Log.d("list lenth: ", String.valueOf(problemList.size()));
} else {
Log.e(TAG, "Error getting documents: ", task.getException());
}
Log.println(Log.DEBUG, "ValueEventListener: ", "Done");
SPB.setVisibility(View.INVISIBLE);
Log.i("list value", problemList.toString());
}
}).isSuccessful();
return problemList;
}
pblmDB is a FirebaseFirestore element.
And this is the logs I gets when opening the activity:
D/document title:: violance
global worming
math class
boringness
sadness
D/list lenth:: 0
D/ValueEventListener:: Done
I/list value: com.example.igi.Solution$2#1cdffeb
I/BiChannelGoogleApi: [FirebaseAuth: ] getGoogleApiForMethod() returned Gms: com.google.firebase.auth.api.internal.zzaq#6036be1
D/FirebaseAuth: Notifying id token listeners about user ( XsiavnC7IDSXOlSpvbMLfVbPRtT2 ).
Thanks in advance for everyone that may help me!

In paging library, PagedList value is null

I have tried to implement a user list with pagination using paging library. But despite being able to fetch all data from back-end, the PagedList is null while observing LiveData.
Here are the codes.
UserModel.java
class User{
#SerializedName("user_id")
public int user_id;
#SerializedName("username")
public String username;
#SerializedName("name")
public String name;
#SerializedName("familyname")
public String familyname;
#SerializedName("pp_dir")
public String pp_url; }
public class UserModel {
#SerializedName("users")
public List<User> list;
#SerializedName("last_page")
public boolean lastPage;
#SerializedName("total_page")
public int totalPage;
#SerializedName("total_user_count")
public int totalUserCount;}
UserSearchDataSource.java
public class UserSearchDataSource extends ItemKeyedDataSource<Integer, User> {
public static final int PAGE_SIZE = 15;
private static final int FIRST_PAGE = 1;
#Override
public void loadInitial(#NonNull LoadInitialParams<Integer> params, #NonNull LoadInitialCallback<User> callback) {
RetrofitClient.getInstance().getApi().getAllUsers(FIRST_PAGE, PAGE_SIZE).enqueue(new Callback<UserModel>() {
#Override
public void onResponse(Call<UserModel> call, Response<UserModel> response) {
if (response.body() != null) {
callback.onResult(response.body().list);
System.out.println(response.body().list);
}
else {
System.out.println(response.code());
System.out.println(response.message());
}
}
#Override
public void onFailure(Call<UserModel> call, Throwable t) {
System.out.println(t.getMessage());
}
});
}
#Override
public void loadAfter(#NonNull LoadParams<Integer> params, #NonNull LoadCallback<User> callback) {
RetrofitClient.getInstance().getApi().getAllUsers(FIRST_PAGE, PAGE_SIZE).enqueue(new Callback<UserModel>() {
#Override
public void onResponse(Call<UserModel> call, Response<UserModel> response) {
if (response.body() != null) {
//Integer key = response.body().lastPage ? null : params.key + 1;
callback.onResult(response.body().list);
}
}
#Override
public void onFailure(Call<UserModel> call, Throwable t) {
}
});
}
#Override
public void loadBefore(#NonNull LoadParams<Integer> params, #NonNull LoadCallback<User> callback) {
RetrofitClient.getInstance().getApi().getAllUsers(FIRST_PAGE, PAGE_SIZE).enqueue(new Callback<UserModel>() {
#Override
public void onResponse(Call<UserModel> call, Response<UserModel> response) {
if (response.body() != null) {
//Integer key = (params.key > 1) ? params.key - 1 : null;
callback.onResult(response.body().list);
}
else {
System.out.println(response.message());
}
}
#Override
public void onFailure(Call<UserModel> call, Throwable t) {
System.out.println(t.getMessage());
}
});
}
#NonNull
#Override
public Integer getKey(#NonNull User item) {
return item.user_id;
} }
UserSearchDataSourceFactory.java
public class UserSearchDataSourceFactory extends DataSource.Factory<Integer, User> {
private MutableLiveData<UserSearchDataSource> userLiveDataSource = new MutableLiveData<>();
public UserSearchDataSourceFactory() {
}
#NonNull
#Override
public DataSource<Integer, User> create() {
UserSearchDataSource dataSource = new UserSearchDataSource();
userLiveDataSource.postValue(dataSource);
return dataSource;
}
public MutableLiveData<UserSearchDataSource> getUserLiveDataSource() {
return userLiveDataSource;
} }
UserSearchAdapter.java
public class UserSearchAdapter extends PagedListAdapter<User, UserSearchAdapter.ViewHolder> {
private Context context;
UserSearchAdapter(Context context) {
super(DIFF_CALLBACK);
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.user_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
User model = getItem(position);
if (model != null) {
Picasso.get().load(model.pp_url).into(holder.userPp);
holder.tvUsername.setText(model.username);
holder.tvFullname.setText(model.name.concat(" ").concat(model.familyname));
}
else {
Toast.makeText(context, "Item is null", Toast.LENGTH_LONG).show();
}
}
private static DiffUtil.ItemCallback<User> DIFF_CALLBACK = new DiffUtil.ItemCallback<User>() {
#Override
public boolean areItemsTheSame(#NonNull User oldItem, #NonNull User newItem) {
return oldItem.user_id == newItem.user_id;
}
#SuppressLint("DiffUtilEquals")
#Override
public boolean areContentsTheSame(#NonNull User oldItem, #NonNull User newItem) {
return oldItem.equals(newItem);
}
};
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView userPp;
TextView tvUsername, tvFullname;
public ViewHolder(#NonNull View itemView) {
super(itemView);
userPp = itemView.findViewById(R.id.image_user);
tvUsername = itemView.findViewById(R.id.tv_username);
tvFullname = itemView.findViewById(R.id.tv_fullname);
}
} }
UserSearchViewModel.java
public class UserSearchViewModel extends AndroidViewModel {
private LiveData<PagedList<User>> userPagedList;
LiveData<UserSearchDataSource> liveDataSource;
public UserSearchViewModel(Application application) {
super(application);
}
public LiveData<PagedList<User>> getUserPagedList() {
UserSearchDataSourceFactory userSearchDataSourceFactory = new UserSearchDataSourceFactory();
liveDataSource = userSearchDataSourceFactory.getUserLiveDataSource();
PagedList.Config config = (new PagedList.Config.Builder())
.setEnablePlaceholders(true)
.setPageSize(UserSearchDataSource.PAGE_SIZE)
.build();
userPagedList = new LivePagedListBuilder<>(userSearchDataSourceFactory, config).build();
return userPagedList;
} }
UserSearchFragment.java
mViewModel.getUserPagedList().observe(this, (PagedList<User> users) -> {
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setHasFixedSize(true);
adapter = new UserSearchAdapter(getContext());
adapter.submitList(users);
recyclerView.setAdapter(adapter);
//System.out.println(users.get(0).name);
});

How to read/write java.math.BigInteger when implementing Parcelable interface?

How to read/write java.math.BigInteger properly when implementing Parcelable interface in Android?
I would recommend writing in BigInteger as a String.
public class MyParcelable implements Parcelable {
public static final Creator<MyParcelable> CREATOR = new Creator<MyParcelable>() {
#Override
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
#Override
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
private BigInteger mData;
protected MyParcelable(Parcel in) {
mData = new BigInteger(in.readString());
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(mData.toString());
}
}

How to implement ListIterator?

I created this extension of ArrayList, NullIgnoringArrayList, because it's possible that my application will add nulls from time to time. I know there are various other ways to deal with this, like checking for null before inserting or filtering out nulls when accessing the ArrayList. But I got it in my head to do it this way and it was going fine but now I don't know how to proceed.
I should implement ListIterator because my tests call upon this method. I peaked in the implementation inside ArrayList but there ListItr is a private class that uses the private fields of ArrayList, which I don't have in NullIgnoringArrayList.
To be fair though, I might be overengineering and maybe I should just drop it. On the other hand, one might learn a thing or two.
NullIgnoringArrayList:
public class NullIgnoringArrayList<T> extends ArrayList<T> {
#Override
public boolean add(T element) {
return !isNull(element) && super.add(element);
}
#Override
public void add(int index, T element) {
if (isNull(element)) {
return;
}
super.add(index, element);
}
#Override
public boolean addAll(Collection c) {
return !isNull(c) && super.addAll(c);
}
#Override
public boolean addAll(int index, Collection c) {
return !isNull(c) && super.addAll(index, c);
}
#Override
public ListIterator listIterator() {
throw new NotImplementedException();
}
#Override
public ListIterator listIterator(int index) {
throw new NotImplementedException();
}
}
SimpleListIterator:
public class SimpleListIterator<T> implements ListIterator {
#Override
public boolean hasNext() {
return false;
}
#Override
public Object next() {
return null;
}
#Override
public boolean hasPrevious() {
return false;
}
#Override
public Object previous() {
return null;
}
#Override
public int nextIndex() {
return 0;
}
#Override
public int previousIndex() {
return 0;
}
#Override
public void remove() {
}
#Override
public void set(Object o) {
}
#Override
public void add(Object o) {
}
}
Just delegate method calls to ListIterator<T> of the parent:
public class NullIgnoringArrayList<T> extends ArrayList<T> {
...
#Override
public ListIterator<T> listIterator() {
return new SimpleListIterator<>(super.listIterator());
}
#Override
public ListIterator<T> listIterator(int index) {
return new SimpleListIterator<>(super.listIterator(index));
}
}
public class SimpleListIterator<T> implements ListIterator<T> {
private final ListIterator<T> underlying;
public SimpleListIterator(ListIterator<T> underlying) {
this.underlying = underlying;
}
#Override public boolean hasNext() {return underlying.hasNext();}
#Override public T next() { return underlying.next(); }
#Override public boolean hasPrevious() {return underlying.hasPrevious();}
#Override public T previous() {return underlying.previous();}
#Override public int nextIndex() {return underlying.nextIndex();}
#Override public int previousIndex() {return underlying.previousIndex();}
#Override public void remove() { underlying.remove();}
#Override
public void set(T o) {
if (isNull(o)) {return;}
underlying.set(o);
}
#Override
public void add(T o) {
if (isNull(o)) {return;}
underlying.add(o);
}
}

How to send Parcelable Object that contains doubly nested Parcelable arrays

I am trying to write an object in my startup activty to Parcel then send it to my Main activity using an intent. However I get a null pointer exception when retrieving the ParacelableArrayExtra in my Main activity. So i put in a check for null to handle the the null condition. However, the forecast Object does have data before being put into the intent so this condition should not be met.
I seems as though the Array of objects never gets put inside the intent. I this because I have my data being parceled incorrectly?
StartUpActivity.java
public class StartUpActivity extends AppCompatActivity {
public static final String FORECAST_KEY = "FORECAST_KEY";
private Forecast[] mForecasts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new BackgroundTask(this).execute();
}
#Override
public void startActivityForResult(Intent intent, int requestCode) {
super.startActivityForResult(intent, requestCode);
}
private class BackgroundTask extends AsyncTask {
private Intent mIntent;
private Context mContext;
private static final String TAG = "BACKGROUND_TASK";
public BackgroundTask(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mIntent = new Intent(StartUpActivity.this, MainActivity.class);
}
#Override
protected Object doInBackground(Object[] params) {
mForecasts = getForecasts();
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
// mForecasts is populated and does contain data
mIntent.putExtra(StartUpActivity.FORECAST_KEY, mForecasts);
// mForecasts in not located in mIntent
startActivity(mIntent);
finish();
}
// Other methods omitted
}
}
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
setSupportActionBar(mToolbar);
intent.getParcelableArrayExtra(StartUpActivity.FORECAST_KEY);
Parcelable[] allForecastParcelables = getIntent().getParcelableArrayExtra(StartUpActivity.FORECAST_KEY);
if (allForecastParcelables != null) {
mForecasts = new Forecast[allForecastParcelables.length];
for (int i = 0 ; i < allForecastParcelables.length; i++) {
mForecasts[i] = (Forecast) allForecastParcelables[i];
}
}
else {
mForecasts = null;
}
setupSlidingTabs();
}
Here are my Model objects that implement Parcelable
Forecast.java
public class Forecast implements Parcelable{
Day[] mDays;
public Day[] getDailyForecast() {
return mDays;
}
public void setDailyForecast(Day[] days) {
mDays = days;
}
#Override
public int describeContents() {
return 0;
}
public Forecast() {}
private Forecast(Parcel in) {
in.readTypedArray(mDays, Day.CREATOR);
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeTypedArray(mDays, flags);
}
public static final Creator<Forecast> CREATOR = new Creator<Forecast>() {
#Override
public Forecast createFromParcel(Parcel source) {
return new Forecast(source);
}
#Override
public Forecast[] newArray(int size) {
return new Forecast[size];
}
};
}
Day.java
public class Day implements Parcelable {
private Hour[] mHours;
private Average mAverage;
public Hour[] getHourlyForecast() {
return mHours;
}
public void setHourlyForecast(Hour[] hours) {
mHours = hours;
}
public Average getAverageForecast() {
return mAverage;
}
public void setAverageForecast(Average average) {
mAverage = average;
}
#Override
public int describeContents() {
return 0;
}
public Day() {}
private Day(Parcel in) {
in.readTypedArray(mHours, Hour.CREATOR);
mAverage = in.readParcelable(getClass().getClassLoader());
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeTypedArray(mHours, flags);
dest.writeParcelable(mAverage, flags);
}
public static final Creator<Day> CREATOR = new Creator<Day>() {
#Override
public Day createFromParcel(Parcel source) {
return new Day(source);
}
#Override
public Day[] newArray(int size) {
return new Day[size];
}
};
}
Average.java
public class Average implements Parcelable {
private String mWindCompassDireciton;
public String getWindCompassDireciton() {
return mWindCompassDireciton;
}
public void setWindCompassDireciton(String windCompassDireciton) {
mWindCompassDireciton = windCompassDireciton;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mWindCompassDireciton);
}
public Average() {}
private Average(Parcel in) {
mWindCompassDireciton = in.readString();
}
public static final Creator<Average> CREATOR = new Creator<Average>() {
#Override
public Average createFromParcel(Parcel source) {
return new Average(source);
}
#Override
public Average[] newArray(int size) {
return new Average[size];
}
};
}
And Hour is similar to average.java
Is there anything I am overlooking?
Each ArrayList and object inside the parcelable object should be peaceable too, Check this example. but i recommend you to send GSON and convert it to String and send it between activities as a string and convert it again to your object, Check this example.

Categories

Resources