How can you fetch album images from facebook using graph api? - java

I have successfully fetched user profile image in my android application.Using me/posts I am able to get full_picture links in my list view.I want images in my list view.How can i achieve that?I need to have album id for fetching images from an album.How can I get album id using graph explorer.I have used this link in graph explorer.
https://graph.facebook.com/v2.3/me/albums?fields=id
but unable to fetch album id.
Graph Request
loginbtn.registerCallback(callbackmanager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
loginbtn.setVisibility(View.GONE);
Bundle params = new Bundle();
params.putString("fields", "message,created_time,id,full_picture,status_type,source,comments.summary(true),likes.summary(true)");
params.putString("limit", "10");
GraphRequestAsyncTask data = new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/posts", params, HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
try {
JSONObject jsonObject = response.getJSONObject();
JSONArray jsonArray = jsonObject.getJSONArray("data");
for(int i=0;i<jsonArray.length();i++) {
String array=jsonArray.getString(i).toString();
System.out.println(array);
}
System.out.println(" User timeline Messages" + jsonArray);
// List data = converttoArrayList(jsonArray);
Facebook fab=jsonToFacebook(jsonArray.toString());
System.out.println("Data is:-" + data);
System.out.println("UserID is:-" + loginResult.getAccessToken().getUserId());
ArrayAdapter<User> adapter = new ArrayAdapter<User>(MainActivity.this, android.R.layout.simple_list_item_1,fab);
listviewtimeline.setAdapter(adapter);
} catch (JSONException j) {
j.printStackTrace();
}
}
}
).executeAsync();
// Log.d("DEBUG",response.getJSONObject().toString());
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
}
private Facebook jsonToFacebook(String result) {
Facebook fb = null;
if (result != null && result.length() > 0) {
try {
Gson gson = new Gson();
Log.d(TAG, "jsonToFacebook: " + gson.toString());
fb = gson.fromJson(result, Facebook.class);
} catch (IllegalStateException ex) {
// just eat the exception
}
} else {
Log.d(TAG, "jsonToFacebook: result length is zero?: ");
}
return fb;
}
User.java
public class User {
// String s="message,created_time,id,full_picture,status_type,source,comments.summary(true),likes.summary(true)";
#SerializedName("created_time")
String created_time;
#SerializedName("id")
String id;
#SerializedName("status_type")
String status_type;
#SerializedName("source")
String source;
#SerializedName("message")
String message;
#SerializedName("full_picture")
private String full_picture;
#SerializedName("name")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return getMessage();
}
#SerializedName("user")
private FacebookUser User;
#SerializedName("text")
String text;
public FacebookUser getUser() {
return User;
}
public void setUser(FacebookUser user) {
User = user;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getCreated_time() {
return created_time;
}
public void setCreated_time(String created_time) {
this.created_time = created_time;
}
public String getFull_picture() {
return full_picture;
}
public void setFull_picture(String full_picture) {
this.full_picture = full_picture;
}
public String getStatus_type() {
return status_type;
}
public void setStatus_type(String status_type) {
this.status_type = status_type;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
}
Facebook.java
public class Facebook extends ArrayList<User> {
}
FacebookUser.java
public class FacebookUser {
#SerializedName("name")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:orientation="vertical"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="fblogin.example.com.fblogin.MainActivity">
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:orientation="vertical">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listviewtimeline"></ListView>
</LinearLayout>
</LinearLayout>

Related

Android Data Binding not Update UI after retreive data from webservice

I try to implement MVVM by Mindorks to show data from here :(https://api.themoviedb.org/3/movie/384018?api_key=67bc513a7a353631119fdffe5f7377a8&language=en-US) in my Activity. I try using databinding for update UI, but after the data is update, databinding not update my textview. here my Detail Activity Class :
public class DetailActivity extends BaseActivity<ActivityDetailBinding, DetailViewModel> implements DetailNavigator {
#Inject
DetailViewModel detailViewModel;
public static final String INTENT_ID = "id_intent";
public static final String INTENT_FLAG = "id_flag";
private ActivityDetailBinding mActivityDetailBinding;
public static Intent newIntent(Context context) {
return new Intent(context, DetailActivity.class);
}
#Override
public int getBindingVariable() {
return BR.viewModel;
}
#Override
public int getLayoutId() {
return R.layout.activity_detail;
}
#Override
public DetailViewModel getViewModel() {
return detailViewModel;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
detailViewModel.setNavigator(this);
mActivityDetailBinding = getViewDataBinding();
initView();
initData(savedInstanceState);
}
private void initData(Bundle savedInstanceState) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
int id = extras.getInt(INTENT_ID, 0);
int flag = extras.getInt(INTENT_FLAG, 0);
detailViewModel.fetchDetail(id, flag);
}
}
private void initView() {
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
#Override
public void ShowProgressDialog(Boolean loading) {
if (loading) {
showLoading();
} else {
hideLoading();
}
}
}
and my BaseActivity like this :
public abstract class BaseActivity<T extends ViewDataBinding, V extends BaseViewModel> extends AppCompatActivity
implements BaseFragment.Callback {
// TODO
// this can probably depend on isLoading variable of BaseViewModel,
// since its going to be common for all the activities
private ProgressDialog mProgressDialog;
private T mViewDataBinding;
private V mViewModel;
/**
* Override for set binding variable
*
* #return variable id
*/
public abstract int getBindingVariable();
/**
* #return layout resource id
*/
public abstract
#LayoutRes
int getLayoutId();
/**
* Override for set view model
*
* #return view model instance
*/
public abstract V getViewModel();
#Override
public void onFragmentAttached() {
}
#Override
public void onFragmentDetached(String tag) {
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
performDependencyInjection();
super.onCreate(savedInstanceState);
performDataBinding();
}
public T getViewDataBinding() {
return mViewDataBinding;
}
#TargetApi(Build.VERSION_CODES.M)
public boolean hasPermission(String permission) {
return Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
}
public void hideKeyboard() {
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
}
public void hideLoading() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.cancel();
}
}
public void showLoading() {
hideLoading();
mProgressDialog = CommonUtils.showLoadingDialog(this);
}
public boolean isNetworkConnected() {
return NetworkUtils.isNetworkConnected(getApplicationContext());
}
public void performDependencyInjection() {
AndroidInjection.inject(this);
}
#TargetApi(Build.VERSION_CODES.M)
public void requestPermissionsSafely(String[] permissions, int requestCode) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(permissions, requestCode);
}
}
// public void showLoading() {
// hideLoading();
// mProgressDialog = CommonUtils.showLoadingDialog(this);
// }
private void performDataBinding() {
mViewDataBinding = DataBindingUtil.setContentView(this, getLayoutId());
this.mViewModel = mViewModel == null ? getViewModel() : mViewModel;
mViewDataBinding.setVariable(getBindingVariable(), mViewModel);
mViewDataBinding.setLifecycleOwner(this);
mViewDataBinding.executePendingBindings();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
this is my ViewModel class :
public class DetailViewModel extends BaseViewModel<DetailNavigator> {
private final ObservableField<String> originalName = new ObservableField<>();
private final ObservableField<String> releaseDate = new ObservableField<>();
private final ObservableField<String> overview = new ObservableField<>();
private final ObservableField<String> genreMovie = new ObservableField<>();
private final ObservableField<String> posterPath = new ObservableField<>();
private final ObservableField<String> voteAverage = new ObservableField<>();
public DetailViewModel(DataManager dataManager, SchedulerProvider schedulerProvider) {
super(dataManager, schedulerProvider);
}
public void fetchDetail(int id, int flag) {
if (flag == 1) {
getNavigator().ShowProgressDialog(true);
getCompositeDisposable().add(getDataManager()
.getApiHelper().doDetailMovie(id, URLConfig.API_KEY, getDataManager().getLanguage())
.subscribeOn(getSchedulerProvider().io())
.observeOn(getSchedulerProvider().ui())
.subscribe(detailResponse -> {
setUpData(detailResponse);
getNavigator().ShowProgressDialog(false);
}, throwable -> {
getNavigator().ShowProgressDialog(false);
}));
} else if (flag == 2) {
getNavigator().ShowProgressDialog(true);
getCompositeDisposable().add(getDataManager()
.getApiHelper().doDetailTV(id, URLConfig.API_KEY, getDataManager().getLanguage())
.subscribeOn(getSchedulerProvider().io())
.observeOn(getSchedulerProvider().ui())
.subscribe(detailResponse -> {
setUpData(detailResponse);
getNavigator().ShowProgressDialog(false);
}, throwable -> {
getNavigator().ShowProgressDialog(false);
}));
}
}
private void setUpData(DetailResponse detailResponse) {
if (detailResponse.getOriginal_name() != null) {
originalName.set(detailResponse.getOriginal_name());
} else {
originalName.set(detailResponse.getOriginal_title());
}
originalName.notifyChange();
if (detailResponse.getFirst_air_date() != null) {
releaseDate.set(detailResponse.getFirst_air_date());
} else {
releaseDate.set(detailResponse.getRelease_date());
}
overview.set(String.valueOf(detailResponse.getOverview()));
posterPath.set(String.valueOf(detailResponse.getPoster_path()));
voteAverage.set(String.valueOf(detailResponse.getVote_average()));
String genres = "";
for (int i = 0;i<detailResponse.getGenreList().size();i++){
genres = genres+detailResponse.getGenreList().get(i);
}
genreMovie.set(genres);
}
public ObservableField<String> getOriginalName() {
return originalName;
}
public ObservableField<String> getReleaseDate() {
return releaseDate;
}
public ObservableField<String> getOverview() {
return overview;
}
public ObservableField<String> getGenreMovie() {
return genreMovie;
}
public ObservableField<String> getPosterPath() {
return posterPath;
}
public ObservableField<String> getVoteAverage() {
return voteAverage;
}
}
and this is my DetailResponse Class :
public class DetailResponse {
#SerializedName("original_name")
private String original_name ;
#SerializedName("original_title")
private String original_title ;
#SerializedName("release_date")
private String release_date ;
#SerializedName("first_air_date")
private String first_air_date ;
#SerializedName("vote_average")
private Double vote_average ;
#SerializedName("overview")
private String overview ;
#SerializedName("poster_path")
private String poster_path;
#SerializedName("genres")
private List<Genre> genreList;
public String getOriginal_name() {
return original_name;
}
public String getOriginal_title() {
return original_title;
}
public String getRelease_date() {
return release_date;
}
public String getFirst_air_date() {
return first_air_date;
}
public Double getVote_average() {
return vote_average;
}
public String getOverview() {
return overview;
}
public String getPoster_path() {
return poster_path;
}
public List<Genre> getGenreList() {
return genreList;
}
public static class Genre{
#SerializedName("name")
private String name ;
public String getName() {
return name;
}
}
}
and last one, here how I try to get data in my UI using databinding, this is my layout :
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".ui.detail.DetailActivity">
<data>
<variable
name="viewModel"
type="test.ui.detail.DetailViewModel" />
</data>
<androidx.core.widget.NestedScrollView
android:id="#+id/nestedScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:animateLayoutChanges="true">
<com.github.florent37.shapeofview.shapes.ArcView
android:id="#+id/shape_header"
android:layout_width="match_parent"
android:layout_height="#dimen/size300dp"
android:alpha="0.7"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:shape_arc_cropDirection="outside"
app:shape_arc_height="#dimen/size30dp"
app:shape_arc_position="bottom">
<com.flaviofaria.kenburnsview.KenBurnsView
android:id="#+id/image_header"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="#drawable/poster_avengerinfinity"
android:tint="#6F000000" />
</com.github.florent37.shapeofview.shapes.ArcView>
<com.github.florent37.shapeofview.shapes.RoundRectView
android:id="#+id/shape_poster"
android:layout_width="#dimen/size150dp"
android:layout_height="#dimen/size200dp"
android:layout_marginTop="#dimen/margin250dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/shape_header"
app:shape_roundRect_bottomLeftRadius="#dimen/corner10dp"
app:shape_roundRect_bottomRightRadius="#dimen/corner10dp"
app:shape_roundRect_topLeftRadius="#dimen/corner10dp"
app:shape_roundRect_topRightRadius="#dimen/corner10dp">
<ImageView
android:id="#+id/image_poster"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="#string/hint_poster"
android:scaleType="fitXY"
app:imageDetailUrl="#{viewModel.posterPath}"
android:src="#drawable/poster_avengerinfinity" />
</com.github.florent37.shapeofview.shapes.RoundRectView>
<TextView
android:id="#+id/text_title"
style="#style/FontText.Title.Detail"
android:layout_marginTop="#dimen/margin15dp"
android:textSize="#dimen/font_large_size"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/shape_poster"
android:text="#{viewModel.originalName}"
tools:text="#string/hint_title" />
<TextView
android:id="#+id/text_title_release"
style="#style/FontText"
android:layout_marginTop="#dimen/margin10dp"
android:text="#string/text_release"
app:layout_constraintEnd_toStartOf="#+id/guideline"
app:layout_constraintTop_toBottomOf="#+id/text_title" />
<TextView
android:id="#+id/text_release"
style="#style/FontText"
android:layout_marginStart="#dimen/margin2dp"
android:layout_marginTop="#dimen/margin10dp"
app:layout_constraintStart_toEndOf="#+id/text_title_release"
app:layout_constraintTop_toBottomOf="#+id/text_title"
tools:text="#string/hint_release" />
<TextView
android:id="#+id/text_genres"
style="#style/FontText.Normal"
android:layout_marginStart="#dimen/margin15dp"
android:layout_marginTop="#dimen/margin10dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/text_release"
tools:text="#string/hint_genres" />
<TextView
android:id="#+id/text_duration"
style="#style/FontText.Normal.White"
android:layout_marginTop="#dimen/margin10dp"
android:layout_marginEnd="#dimen/margin15dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/text_release"
tools:text="#string/hint_duration" />
<RatingBar
android:id="#+id/rating_bar"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:layout_marginStart="#dimen/margin15dp"
android:layout_marginTop="#dimen/margin5dp"
android:isIndicator="true"
android:numStars="5"
android:rating="3.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/text_duration" />
<TextView
android:id="#+id/text_rating"
style="#style/FontText.Rating.Orange"
android:layout_marginStart="#dimen/margin5dp"
app:layout_constraintRight_toLeftOf="parent"
app:layout_constraintStart_toEndOf="#+id/rating_bar"
app:layout_constraintTop_toBottomOf="#+id/text_duration"
tools:text="#string/hit_rating" />
<TextView
android:id="#+id/text_default_rating"
style="#style/FontText.Rating"
android:textStyle="normal"
app:layout_constraintRight_toLeftOf="parent"
app:layout_constraintStart_toEndOf="#+id/text_rating"
app:layout_constraintTop_toBottomOf="#+id/text_duration"
tools:text="#string/hint_default_rating" />
<TextView
android:id="#+id/text_desc"
style="#style/FontText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/margin15dp"
android:layout_marginTop="#dimen/margin25dp"
android:layout_marginEnd="#dimen/margin15dp"
android:paddingBottom="#dimen/padding100dp"
app:layout_constraintTop_toBottomOf="#+id/rating_bar"
tools:text="#string/hint_desc" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.5" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>
</layout>
I try to show one data first, that is OriginalName for text_title, went I debug my application
public ObservableField<String> getOriginalName() {
return originalName;
}
getOriginalName in class ViewModel, just called before I retrieve my response, but after OriginalName is set, the UI not update and getOriginalName is never called again.I already add originalName.notifyChange(); after the data is set, but it doesn't seem change anything.
I already frustased.. so please... I hope anybody can help me to show me what to do. Thank you very much.
Remove this below line from Detail Activity
setContentView(R.layout.activity_detail);
In your base activity you have performDataBinding method which set the layout id using DataBindingUtil class.
mViewDataBinding = DataBindingUtil.setContentView(this, getLayoutId());
this.mViewModel = mViewModel == null ? getViewModel() : mViewModel;
mViewDataBinding.setVariable(getBindingVariable(), mViewModel);
mViewDataBinding.setLifecycleOwner(this);
mViewDataBinding.executePendingBindings();

How to Load a Json data into dropdown Spinner Using Android Fragments

I need to Show Registration Form With Spinner Using Fragments and get the data using Json
This is kind of register form. At the bottom we have change language button which will reset the form and will be shown in arabic / english.
[
{
"Id":1,
"TitleEN":"Kuwait",
"TitleAR":"الكويت",
"CurrencyId":1,
"CurrencyEN":"Kuwaiti Dinar",
"CurrencyAR":"دينار كويتى",
"CodeEN":"KWD",
"CodeAR":"د.ك",
"Code":"965"
},
{
"Id":2,
"TitleEN":"Emirates",
"TitleAR":"الإمارات",
"CurrencyId":2,
"CurrencyEN":"Emirati Dirham",
"CurrencyAR":"درهم إماراتي",
"CodeEN":"AED",
"CodeAR":"درهم",
"Code":"971"
},
{
"Id":3,
"TitleEN":"Saudi Arabia",
"TitleAR":"السعودية",
"CurrencyId":3,
"CurrencyEN":"Saudi Riyal",
"CurrencyAR":"ريال سعودى",
"CodeEN":"SAR",
"CodeAR":"ر.س",
"Code":"966"
}
]
Note.I assume you have followed the first 3 steps from this [question][1]
and will start from the following
Step 1
Add spinner in xml
<Spinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="#string/spinner_title" />
Step 2
In ApiInterface Class add the following code
#GET("/app/app.asmx/GetCountries")
Call<List<Country>> getCountry();
Step 3
Create new model class by name Country
public class Country {
#SerializedName("Id")
#Expose
private Integer id;
#SerializedName("TitleEN")
#Expose
private String titleEN;
#SerializedName("TitleAR")
#Expose
private String titleAR;
#SerializedName("CurrencyId")
#Expose
private Integer currencyId;
#SerializedName("CurrencyEN")
#Expose
private String currencyEN;
#SerializedName("CurrencyAR")
#Expose
private String currencyAR;
#SerializedName("CodeEN")
#Expose
private String codeEN;
#SerializedName("CodeAR")
#Expose
private String codeAR;
#SerializedName("Code")
#Expose
private String code;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitleEN() {
return titleEN;
}
public void setTitleEN(String titleEN) {
this.titleEN = titleEN;
}
public String getTitleAR() {
return titleAR;
}
public void setTitleAR(String titleAR) {
this.titleAR = titleAR;
}
public Integer getCurrencyId() {
return currencyId;
}
public void setCurrencyId(Integer currencyId) {
this.currencyId = currencyId;
}
public String getCurrencyEN() {
return currencyEN;
}
public void setCurrencyEN(String currencyEN) {
this.currencyEN = currencyEN;
}
public String getCurrencyAR() {
return currencyAR;
}
public void setCurrencyAR(String currencyAR) {
this.currencyAR = currencyAR;
}
public String getCodeEN() {
return codeEN;
}
public void setCodeEN(String codeEN) {
this.codeEN = codeEN;
}
public String getCodeAR() {
return codeAR;
}
public void setCodeAR(String codeAR) {
this.codeAR = codeAR;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
Step 4
find view in activity or fragment and add call the request and get response and add the response in spinner adapter.Initialize a string list out side the onCreate method
List<String> codes = new ArrayList<String>();
APIInterface apiInterfacePages;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
apiInterfacePages= PageApiClient.getRetrofit().create(APIInterface.class);
Call<List<Country>> getCountry = apiInterfacePages.getCountry();
getCountry.enqueue(new Callback<List<Country>>() {
#Override
public void onResponse(Call<List<Country>> call, Response<List<Country>> response) {
countryList = response.body();
for (int i = 0; i < countryList.size(); i++) {
codes.add(countryList.get(i).getCode());
}
ArrayAdapter<String> adapterTime = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, codes);
spinner.setAdapter(adapterTime);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivity.this, "" + countryList.get(i).getTitleEN(), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public void onFailure(Call<List<Country>> call, Throwable t) {
}
});
}

error at retrieving data from firebase database with for loop

I want to retrieve all child of my firebase database with for loop and data will be shown in recyclerview in a fragment. When I go event fragment, app crash and the error point out to the line of for looping
here is my code,
events.java(this is fragment)
FirebaseDatabase.getInstance().getReference().child("Users/" + mUser.getUid() + "/Groups/RequestedGroups").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()){
value = ds.child("GroupID").getValue().toString();
groupId.add(value);
}
retrieveGroups(groupId);
}
private void retrieveGroups(ArrayList<String> groupId) {
if(groupId != null){
for(String value : groupId){
FirebaseDatabase.getInstance().getReference().child("Events/"+value).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot d : dataSnapshot.getChildren()){
Event_Retrieve e = d.getValue(Event_Retrieve.class); // error point out this line
list.add(e);
}
adapter = new MyAdapter(events.this.getActivity(),list);
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(events.this.getActivity(), "oops", Toast.LENGTH_SHORT).show();
}
});
}
}
}
Event_Retrieve.java
public class Event_Retrieve {
public String eventname;
public String eventdescription;
public String eventdate;
public String eventtime;
public String eventphotourl;
public String latitude;
public String lingitude;
public ArrayList<String> acceptedmember;
public ArrayList<String> invitedmember;
public Event_Retrieve(){
}
public Event_Retrieve(String eventname, String eventdescription, String eventdate, String eventtime, String eventphotourl, String latitude, String lingitude, ArrayList<String> acceptedmember, ArrayList<String> invitedmember) {
this.eventname = eventname;
this.eventdescription = eventdescription;
this.eventdate = eventdate;
this.eventtime = eventtime;
this.eventphotourl = eventphotourl;
this.latitude = latitude;
this.lingitude = lingitude;
this.acceptedmember = acceptedmember;
this.invitedmember = invitedmember;
}
public String getEventname() {
return eventname;
}
public String getEventdescription() {
return eventdescription;
}
public String getEventdate() {
return eventdate;
}
public String getEventtime() {
return eventtime;
}
public String getEventphotourl() {
return eventphotourl;
}
public String getLatitude() {
return latitude;
}
public String getLingitude() {
return lingitude;
}
public ArrayList<String> getAcceptedmember() {
return acceptedmember;
}
public ArrayList<String> getInvitedmember() {
return invitedmember;
}
}
fragment_event.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background"
tools:context=".places">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/eventID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:text="Events"
android:textColor="#000"
android:textSize="30sp" />
<android.support.v7.widget.RecyclerView
android:id="#+id/myRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Logcat error
E/HotwordDetector: Error at creating and/or starting hotword recognition.
java.lang.IllegalArgumentException: Invalid speaker model provided
at com.google.speech.micro.GoogleHotwordRecognizer.nativeNew(Native Method)
at com.google.speech.micro.GoogleHotwordRecognizer.<init>(SourceFile:6)
at com.google.android.libraries.assistant.hotword.k.a(SourceFile:66)
at com.google.android.libraries.assistant.hotword.k.at(SourceFile:35)
at com.google.android.apps.gsa.voiceinteraction.hotword.a.dGU(SourceFile:48)
at com.google.android.voiceinteraction.GsaVoiceInteractionService.dGU(SourceFile:109)
at com.google.android.voiceinteraction.g.oa(SourceFile:13)
at com.google.android.libraries.assistant.hotword.f.a(SourceFile:30)
at com.google.android.libraries.assistant.hotword.g.run(Unknown Source)
at com.google.android.libraries.gsa.runner.a.b.run(Unknown Source)
at com.google.android.apps.gsa.shared.util.concurrent.b.cq.bsW(SourceFile:2)
at com.google.android.apps.gsa.shared.util.concurrent.b.cp.run(SourceFile:5)
at com.google.android.apps.gsa.shared.util.concurrent.b.i.run(Unknown Source)
at com.google.android.apps.gsa.shared.util.concurrent.b.bs.run(SourceFile:3)
at com.google.android.apps.gsa.shared.util.concurrent.b.bs.run(SourceFile:3)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:760)
at com.google.android.apps.gsa.shared.util.concurrent.b.o.run(SourceFile:6)
My Database Structure
this is test data

Some items from database not being displayed in cardview

I am having a problem with cardview not displaying some from the database.
My app connects to a grails back end which has a PostgreSQL db.
I have a cardview inside a recyclerview. It receives 7 values in form of JSON but on running the app, only 5 are displayed. I try doing System.out of the JSON in the stack trace and I find that all the 7 values are received so everything is okay on that front.
For clarity purposes, the fields that are not being displayed are labs("labs") and drugs administered("drugsAdministered").
Here is the main class(ClinicalHistory.java), the adapter class, the xml and the stack-trace.
ClinicalHistory.java
public class ClinicalHistory extends AppCompatActivity {
RecyclerView clinicalHistory_rv;
SwipeRefreshLayout swipeRefreshLayout;
List<com.example.user.eafya.models.ClinicalHistory> clinicalHistory_List;
com.example.user.eafya.models.ClinicalHistory clinicalHistory;
ClinicalHistoryAdapter clinicalHistoryAdapter;
private StringRequest clinicalHistoryRequest;
private LinearLayout no_data;
private LinearLayoutManager linearLayoutManager;
private RequestQueue requestQueue;
private ProgressDialog pb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clinical_history);
initWidgets();
fetchData();
}
private void fetchData() {
pb = new ProgressDialog(this);
pb.setIcon(R.mipmap.ic_launcher);
pb.setTitle("Please wait");
pb.setCancelable(false);
pb.setMessage("Loading data..");
pb.show();
clinicalHistoryRequest = new StringRequest(Request.Method.GET, Configs.URL_LOGIN + Configs.CLINICALHISTORY_PATH, new Response.Listener<String>() {
#Override
public void onResponse(String result) {
pb.dismiss();
System.out.print("======================================"+ result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("mVisit");
for (int i=0;i<jsonArray.length();i++){
System.out.print("----------------"+jsonArray.getJSONObject(i).getString("labs"));
}
Log.d("myError: ", String.valueOf(jsonArray.length()));
if(jsonArray.length()<1) {
clinicalHistory_List.clear();
no_data.setVisibility(View.VISIBLE);
}else if( jsonArray.length()>0){
if(no_data.getVisibility()==View.VISIBLE){
no_data.setVisibility(View.GONE);
}
for(int i=0 ; i<jsonArray.length() ; i++){
JSONObject data = jsonArray.getJSONObject(i);
clinicalHistory = new com.example.user.eafya.models.ClinicalHistory();
clinicalHistory.setDate(data.getString("dateCreated"));
clinicalHistory.setHospital(data.getString("hospitalAttended"));
clinicalHistory.setDoctor(data.getString("attendingDoctor"));
clinicalHistory.setLabs(data.getString("labs"));
clinicalHistory.setChiefComplains(data.getString("chiefComplains"));
clinicalHistory.setDrugs(data.getString("drugsAdministered"));
clinicalHistory_List.add(clinicalHistory);
}
clinicalHistoryAdapter = new ClinicalHistoryAdapter(ClinicalHistory.this, clinicalHistory_List);
linearLayoutManager = new LinearLayoutManager(ClinicalHistory.this);
clinicalHistory_rv.setLayoutManager(linearLayoutManager);
clinicalHistory_rv.setItemAnimator(new DefaultItemAnimator());
clinicalHistory_rv.setAdapter(clinicalHistoryAdapter);
clinicalHistory_rv.setSaveEnabled(true);
clinicalHistory_rv.setSaveFromParentEnabled(true);
clinicalHistoryAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
Log.d("MaeraJ",e.toString());
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
pb.dismiss();
AlertDialog.Builder dialog = new AlertDialog.Builder(ClinicalHistory.this);
dialog.setTitle("Something went wrong !!");
dialog.setCancelable(true);
dialog.setIcon(R.mipmap.ic_launcher);
dialog.setMessage("Check your data connection");
dialog.setPositiveButton("RETRY", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//retry
dialogInterface.dismiss();
fetchData();
}
});
dialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//cancel
dialogInterface.dismiss();
}
});
dialog.create();
dialog.show();
Log.d("Maera",volleyError.toString());
}
});
requestQueue.add(clinicalHistoryRequest);
}
private void initWidgets() {
requestQueue = Volley.newRequestQueue(this);
no_data = findViewById(R.id.nodata_LY);
clinicalHistory_rv = findViewById(R.id.clinicalHistory_RV);
clinicalHistory_List = new ArrayList<>();
swipeRefreshLayout = findViewById(R.id.swipeContainer);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
refresh();
}
});
}
private void refresh() {
try {
clinicalHistory_List.clear();
fetchData();
swipeRefreshLayout.setRefreshing(false);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.home:
onBackPressed();
break;
}
return super.onOptionsItemSelected(item);
}
}
Adapter class(ClinicalHistoryAdapter.java)
public class ClinicalHistoryAdapter extends RecyclerView.Adapter<ClinicalHistoryAdapter.myViewHolder> {
Context ctx;
List<ClinicalHistory> clinicalHistoryList;
ClinicalHistory clinicalHistoryModel;
LayoutInflater inflater;
public ClinicalHistoryAdapter(Context ctx, List<ClinicalHistory> clinicalHistoryList) {
this.ctx = ctx;
this.clinicalHistoryList = clinicalHistoryList;
inflater = LayoutInflater.from(ctx);
}
public class myViewHolder extends RecyclerView.ViewHolder {
TextView clinicalHist_date_TV,clinicalHist_hospital, clinicalHist_doctor,clinicalHist_chiefComplains, clinicalHist_labs, clinicalHist_drugs;
ImageView clinicalHist_img;
public myViewHolder(View itemView) {
super(itemView);
clinicalHist_img = itemView.findViewById(R.id.clinicalHist_image_IV);
clinicalHist_date_TV = itemView.findViewById(R.id.clinicalHist_date__TV);
clinicalHist_hospital = itemView.findViewById(R.id.clinicalHist_hospital_TV);
clinicalHist_doctor = itemView.findViewById(R.id.clinicalHist_doctor);
clinicalHist_chiefComplains = itemView.findViewById(R.id.clinicalHist_chief_complains_TV);
clinicalHist_labs = itemView.findViewById(R.id.clinicalHist_labs_TV);
clinicalHist_drugs = itemView.findViewById(R.id.clinicalHist_drugs_TV);
}
}
#Override
public ClinicalHistoryAdapter.myViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View my_view = inflater.inflate(R.layout.clinical_history_item,viewGroup,false);
return new myViewHolder(my_view);
}
#Override
public void onBindViewHolder(ClinicalHistoryAdapter.myViewHolder myViewHolder, final int position) {
clinicalHistoryModel = new ClinicalHistory();
clinicalHistoryModel = clinicalHistoryList.get(position);
myViewHolder.clinicalHist_date_TV.setText(clinicalHistoryModel.getDate());
myViewHolder.clinicalHist_hospital.setText(clinicalHistoryModel.getHospital());
myViewHolder.clinicalHist_doctor.setText(clinicalHistoryModel.getDoctor());
myViewHolder.clinicalHist_chiefComplains.setText(clinicalHistoryModel.getChiefComplains());
myViewHolder.clinicalHist_labs.setText(clinicalHistoryModel.getLabs());
myViewHolder.clinicalHist_drugs.setText(clinicalHistoryModel.getDrugs());
myViewHolder.clinicalHist_doctor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
goToDetails(position);
}
});
myViewHolder.clinicalHist_hospital.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
goToDetails(position);
}
});
Glide.with(ctx).load(clinicalHistoryModel.getImg()).placeholder(R.drawable.loader).error(R.drawable.header).into(myViewHolder.clinicalHist_img);
}
private void goToDetails(int pos) {
clinicalHistoryModel = clinicalHistoryList.get(pos);
Intent intent = new Intent(ctx,MedicalDetailActivity.class);
intent.putExtra("dateCreated", clinicalHistoryModel.getDate());
intent.putExtra("clinicalHist_img", clinicalHistoryModel.getImg());
intent.putExtra("hospitalAttended", clinicalHistoryModel.getHospital());
intent.putExtra("attendingDoctor", clinicalHistoryModel.getDoctor());
intent.putExtra("chiefComplaints", clinicalHistoryModel.getChiefComplains());
intent.putExtra("labs", clinicalHistoryModel.getLabs());
intent.putExtra("drugs", clinicalHistoryModel.getLabs());
ctx.startActivity(intent);
}
#Override
public int getItemCount() {
return clinicalHistoryList.size();
}
}
The xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_margin="2dp"
android:orientation="horizontal"
android:padding="2dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/clinicalHist_image_IV"
android:layout_width="110dp"
android:layout_height="80dp"
android:layout_gravity="top"
android:scaleType="fitXY"
android:src="#drawable/header" />
<LinearLayout
android:padding="4dp"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textAlignment="textStart"
android:layout_gravity="start"
android:id="#+id/clinicalHist_date__TV"
android:text="21/09/2012"
android:textColor="#color/colorAccent"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Medium"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:textAlignment="textStart"
android:layout_gravity="start"
android:id="#+id/clinicalHist_hospital_TV"
android:text="Hema Hospital"
android:textColor="#color/colorAccent"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Medium"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:id="#+id/clinicalHist_doctor"
android:text="Dr.Lilian"/>
<TextView
android:layout_gravity="center"
android:id="#+id/clinicalHist_labs_TV"
android:text=" Brucella "
android:textColor="#000"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Medium"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:layout_gravity="center"
android:id="#+id/clinicalHist_chief_complains_TV"
android:text=" Headache "
android:textColor="#000"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Medium"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:layout_gravity="center"
android:id="#+id/clinicalHist_drugs_TV"
android:text=" Brufen "
android:textColor="#000"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Medium"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
The stack trace
I/System.out: ======================================{"mVisit":[{"id":1,"chiefComplains":"Headache","dateCreated":"2017-08-11T21:00:00Z","labs":"Brucella","hospitalAttended":"Hema Hospital","drugsAdministered":"Tramadol","attendingDoctor":"Dr. Kisinga"
I have found the solution. The problem was in the model.
This was my previous model. Note the parameters in the
setDrugs() and setLabs().
public class ClinicalHistory {
String img;
String date;
String labs;
String hospital;
String chiefComplains;
String doctor;
String drugs;
public ClinicalHistory() {
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getHospital() {
return this.hospital = hospital ;
}
public void setHospital(String hospital) {
this.hospital = hospital;
}
public String getChiefComplains(){return this.chiefComplains = chiefComplains;}
public void setChiefComplains(String chiefComplains){ this.chiefComplains = chiefComplains;}
public String getLabs() {
return this.labs = labs ;
}
public void setLabs(String hospital) {
this.labs = labs;
}
public String getDoctor() {
return this.doctor = doctor ;
}
public void setDoctor(String doctor) {
this.doctor = doctor;
}
public void setDrugs(String hospital) {
this.drugs = drugs;
}
public String getDrugs() {
return this.drugs = drugs ;
}
public void setDate(String date) {
this.date = date;
}
public String getDate() {
return date;
}
}
After I made this change it worked
public class ClinicalHistory {
String img;
String date;
String labs;
String hospital;
String chiefComplains;
String doctor;
String drugs;
public ClinicalHistory() {
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getHospital() {
return this.hospital = hospital ;
}
public void setHospital(String hospital) {
this.hospital = hospital;
}
public String getChiefComplains(){return this.chiefComplains = chiefComplains;}
public void setChiefComplains(String chiefComplains){ this.chiefComplains = chiefComplains;}
public String getLabs() {
return this.labs = labs ;
}
public void setLabs(String labs) {
this.labs = labs;
}
public String getDoctor() {
return this.doctor = doctor ;
}
public void setDoctor(String doctor) {
this.doctor = doctor;
}
public void setDrugs(String drugs) {
this.drugs = drugs;
}
public String getDrugs() {
return this.drugs = drugs ;
}
public void setDate(String date) {
this.date = date;
}
public String getDate() {
return date;
}
}

Parcelable of Custom Classes

I am currently trying to pass an ArrayList of the class event into another activity as follows.events is an ArrayList of the Event class.
Intent i = new Intent(ViewEvents.this, UserFeed.class);
i.putParcelableArrayListExtra("events",events);
startActivity(i);
I am then retrieving the data as follows:
Intent i = getIntent();
ArrayList<Event> events = i.getParcelableArrayListExtra("events");
My Issue is that I get an Umarshing unknown type code 32 at offset 5788. I am not too sure how to fix this or why this is occurring. I have posted all the code for all three classes down below.Any help would be appreciated to solve this issue.
public class Event implements Parcelable {
public String tvEventName;
public String tvEventInfo;
public String tvDescription;
public String ivEventImage;
public String organizerName;
public String eventId;
public String veneuId;
public String organizerId;
public Venue venue;
public Organizer organizer;
public Event(String tvEventName, String tvEventInfo, String tvDescription, String ivEventImage, String eventId, String veneuId,Venue venue,Organizer organizer) {
this.tvEventName = tvEventName;
this.tvEventInfo = tvEventInfo;
this.tvDescription = tvDescription;
this.ivEventImage = ivEventImage;
this.eventId = eventId;
this.veneuId = veneuId;
}
public Event() {
}
protected Event(Parcel in) {
tvEventName = in.readString();
tvEventInfo = in.readString();
tvDescription = in.readString();
ivEventImage = in.readString();
organizerName = in.readString();
eventId = in.readString();
veneuId = in.readString();
organizerId = in.readString();
}
public static final Creator<Event> CREATOR = new Creator<Event>() {
#Override
public Event createFromParcel(Parcel in) {
return new Event(in);
}
#Override
public Event[] newArray(int size) {
return new Event[size];
}
};
public static Event fromJSON(JSONObject jsonObject)throws JSONException {
Event event = new Event();
//Getting the name of the event
JSONObject nameEvent = jsonObject.getJSONObject("name");
event.tvEventName = nameEvent.getString("text");
//Getting the description for the event Time and location only
JSONObject eventInfo = jsonObject.getJSONObject("start");
event.tvEventInfo = eventInfo.getString("utc");
SimpleDateFormat existingUTCFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat requiredFormat = new SimpleDateFormat("MM-dd hh:mm a");
event.eventId = jsonObject.getString("id");
try{
Date getDate = existingUTCFormat.parse(event.tvEventInfo);
String mydate = requiredFormat.format(getDate);
event.tvEventInfo = mydate;
}
catch(ParseException e){
e.printStackTrace();
}
//Getting the description of the event
JSONObject eventDescription = jsonObject.getJSONObject("description");
event.tvDescription = eventDescription.getString("text");
//Getting a thumbnail of the image for futer use.
try{
jsonObject.getJSONObject("logo");
JSONObject logo = jsonObject.getJSONObject("logo");
JSONObject original= logo.getJSONObject("original");
event.ivEventImage = original.getString("url");
Log.i("Ingo",event.ivEventImage);
}
catch (Exception exception){
event.ivEventImage ="#drawable/tree";
}
event.veneuId = jsonObject.getString("venue_id");
event.organizerId = jsonObject.getString("organizer_id");
return event;
}
public Organizer getOrganizer() {
return organizer;
}
public void setOrganizer(Organizer organizer) {
this.organizer = organizer;
}
public String getOrganizerId() {
return organizerId;
}
public void setOrganizerId(String organizerId) {
this.organizerId = organizerId;
}
public String getTvEventName() {
return tvEventName;
}
public void setTvEventName(String tvEventName) {
this.tvEventName = tvEventName;
}
public String getTvEventInfo() {
return tvEventInfo;
}
public void setTvEventInfo(String tvEventInfo) {
this.tvEventInfo = tvEventInfo;
}
public Venue getVenue() {
return venue;
}
public void setVenue(Venue venue) {
this.venue = venue;
}
public String getTvDescription() {
return tvDescription;
}
public void setTvDescription(String tvDescription) {
this.tvDescription = tvDescription;
}
public String getIvEventImage() {
return ivEventImage;
}
public void setIvEventImage(String ivEventImage) {
this.ivEventImage = ivEventImage;
}
public String getVeneuId() {
return veneuId;
}
public void setVeneuId(String veneuId) {
this.veneuId = veneuId;
}
public String getOrganizerName() {
return organizerName;
}
public String getEventId() {
return eventId;
}
public void setEventId(String eventId) {
this.eventId = eventId;
}
public void setOrganizerName(String organizerName) {
this.organizerName = organizerName;
}
#Override
public int describeContents() {
return 0;
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(tvEventName);
dest.writeString(tvEventInfo);
dest.writeString(tvDescription);
dest.writeString(ivEventImage);
dest.writeString(organizerName);
dest.writeString(eventId);
dest.writeString(veneuId);
dest.writeString(organizerId);
dest.writeParcelable( this.venue,flags);
dest.writeParcelable(this.organizer,flags);
}
}
CLASS 2
public class Venue implements Parcelable {
public String address;
public String city;
public String region;
public String postalCode;
public String country;
public String latitude;
public String longitude;
public String simpleAddress;
public Venue() {
}
public Venue(String address, String city, String region, String postalCode, String country, String latitude, String longitude, String simpleAddress) {
this.address = address;
this.city = city;
this.region = region;
this.postalCode = postalCode;
this.country = country;
this.latitude = latitude;
this.longitude = longitude;
this.simpleAddress = simpleAddress;
}
protected Venue(Parcel in) {
address = in.readString();
city = in.readString();
region = in.readString();
postalCode = in.readString();
country = in.readString();
latitude = in.readString();
longitude = in.readString();
simpleAddress = in.readString();
}
public static final Creator<Venue> CREATOR = new Creator<Venue>() {
#Override
public Venue createFromParcel(Parcel in) {
return new Venue(in);
}
#Override
public Venue[] newArray(int size) {
return new Venue[size];
}
};
public static Venue fromJSON(JSONObject jsonObject)throws JSONException {
Venue venue = new Venue();
if(jsonObject.getString("address_1") == null){
if(jsonObject.getString("address_2") == null)
venue.address = "No Location Available";
else
venue.address = jsonObject.getString("address_2");
}
else
venue.address = jsonObject.getString("address_1");
venue.city = jsonObject.getString("city");
venue.region = jsonObject.getString("region");
venue.postalCode = jsonObject.getString("postal_code");
venue.country = jsonObject.getString("country");
venue.latitude = jsonObject.getString("latitude");
venue.longitude = jsonObject.getString("longitude");
venue.simpleAddress =venue.address +","+ venue.city +","+ venue.country;
Log.i("SIMPLE", venue.simpleAddress);
return venue;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getSimpleAddress() {
return simpleAddress;
}
public void setSimpleAddress(String simpleAddress) {
this.simpleAddress = simpleAddress;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(address);
dest.writeString(city);
dest.writeString(region);
dest.writeString(postalCode);
dest.writeString(country);
dest.writeString(latitude);
dest.writeString(longitude);
dest.writeString(simpleAddress);
}
}
CLASS 3
public class Organizer implements Parcelable{
public String description;
public String organizerId;
public String numePastEvents;
public String numFutureEvents;
public String website;
public String facebookUsername;
public String twitter;
public String name;
public Organizer() {
}
protected Organizer(Parcel in) {
description = in.readString();
organizerId = in.readString();
numePastEvents = in.readString();
numFutureEvents = in.readString();
website = in.readString();
facebookUsername = in.readString();
twitter = in.readString();
name = in.readString();
}
public static final Creator<Organizer> CREATOR = new Creator<Organizer>() {
#Override
public Organizer createFromParcel(Parcel in) {
return new Organizer(in);
}
#Override
public Organizer[] newArray(int size) {
return new Organizer[size];
}
};
public static Organizer fromJson(JSONObject jsonObject){
Organizer organizer = new Organizer();
try {
organizer.description = jsonObject.getJSONObject("description").getString("text");
} catch (JSONException e) {
organizer.description ="NA";
e.printStackTrace();
}
try {
organizer.organizerId = jsonObject.getString("id");
} catch (JSONException e) {
organizer.organizerId = "NA";
e.printStackTrace();
}
try {
organizer.numePastEvents = jsonObject.getString("num_past_events");
} catch (JSONException e) {
organizer.numePastEvents = "Na";
e.printStackTrace();
}
try {
organizer.numFutureEvents = jsonObject.getString("num_future_events");
} catch (JSONException e) {
organizer.numFutureEvents = "NA";
e.printStackTrace();
}
try {
organizer.website = jsonObject.getString("website");
} catch (JSONException e) {
Log.i("Error",e.getMessage());
organizer.website = "NA";
e.printStackTrace();
}
try {
organizer.facebookUsername = jsonObject.getString("facebook");
} catch (JSONException e) {
organizer.facebookUsername = "NA";
e.printStackTrace();
}
try {
organizer.name = jsonObject.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
try {
organizer.twitter = jsonObject.getString("twitter");
} catch (JSONException e) {
e.printStackTrace();
}
return organizer;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTwitter() {
return twitter;
}
public void setTwitter(String twitter) {
this.twitter = twitter;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getOrganizerId() {
return organizerId;
}
public void setOrganizerId(String organizerId) {
this.organizerId = organizerId;
}
public String getNumePastEvents() {
return numePastEvents;
}
public void setNumePastEvents(String numePastEvents) {
this.numePastEvents = numePastEvents;
}
public String getNumFutureEvents() {
return numFutureEvents;
}
public void setNumFutureEvents(String numFutureEvents) {
this.numFutureEvents = numFutureEvents;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getFacebookUsername() {
return facebookUsername;
}
public void setFacebookUsername(String facebookUsername) {
this.facebookUsername = facebookUsername;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(description);
dest.writeString(organizerId);
dest.writeString(numePastEvents);
dest.writeString(numFutureEvents);
dest.writeString(website);
dest.writeString(facebookUsername);
dest.writeString(twitter);
dest.writeString(name);
}
When implementing the Parcelable interface, it is an absolute requirement that your reads and writes exactly match each other. In your case, this is your Event(Parcel) constructor and void writeToParcel().
However, your writeToParcel() implementation includes two writes that your constructor does not read.
dest.writeParcelable( this.venue,flags);
dest.writeParcelable(this.organizer,flags);
You have to either remove these or add matching reads to your constructor.
venue = in.readParcelable(Venue.class.getClassLoader());
organizer = in.readParcelable(Organizer.class.getClassLoader());

Categories