How to display firebase realtime multiple child into recyclerview with cardview? [duplicate] - java

I am trying to display my data from firebase real time database on a listview in the main menu screen once the users log in. The app is running but its not displaying the data.
This is the data in my database
Now for the codes.
MainMenu.java This function is called on the OnCreate().
public void makeItem ()
{
lv = findViewById(R.id.listView);
db = FirebaseDatabase.getInstance().getReference();
helper = new FirebaseHelper(db);
adapter= new AdapterItem(this,helper.retrive());
lv.setAdapter(adapter);
}
CustomListAdapter.java
public class CustomListAdapter{
private String ItemName;
private String Quantity;
private String SerialNo;
private String SupplierName;
private String SupplierEmail;
private String SupplierPhone;
public CustomListAdapter(){
}
public CustomListAdapter (String ItemName,String Quantity,String SerialNo,String SupplierName,String SupplierEmail,String SupplierPhone)
{
this.ItemName = ItemName;
this.Quantity = Quantity;
this.SerialNo = SerialNo;
this.SupplierName = SupplierName;
this.SupplierEmail = SupplierEmail;
this.SupplierPhone = SupplierPhone;
}
public void setItemName (String ItemName)
{
this.ItemName = ItemName;
}
public String getItemName ()
{
return ItemName;
}
public void setQuantity (String Quantity)
{
this.Quantity = Quantity;
}
public String getQuantity ()
{
return Quantity;
}
public void setSerialNo (String SerialNo)
{
this.SerialNo = SerialNo;
}
public String getSerialNo ()
{
return SerialNo;
}
public void setSupplierName (String SupplierName)
{
this.SupplierName = SupplierName;
}
public String getSupplierName()
{
return SupplierName;
}
public void setSupplierEmail (String SupplierEmail)
{
this.SupplierEmail = SupplierEmail;
}
public String getSupplierEmail() {
return SupplierEmail;
}
public void setSupplierPhone (String SupplierPhone)
{
this.SupplierPhone = SupplierPhone;
}
public String getSupplierPhone() {
return SupplierPhone;
}
}
AdapterItem.java
public class AdapterItem extends BaseAdapter {
Context c;
ArrayList<CustomListAdapter> customListAdapters;
public AdapterItem(Context c, ArrayList<CustomListAdapter> customListAdapters) {
this.c = c;
this.customListAdapters = customListAdapters;
}
#Override
public int getCount() {
return customListAdapters.size();
}
#Override
public Object getItem(int position) {
return customListAdapters.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null)
{
convertView=LayoutInflater.from(c).inflate(R.layout.content_main_menu_list,parent,false);
}
TextView ItemName = convertView.findViewById(R.id.name);
TextView SerialNo = convertView.findViewById(R.id.serialNo);
TextView SupplierName = convertView.findViewById(R.id.supplierName);
TextView amount = convertView.findViewById(R.id.amount);
final CustomListAdapter CLA = (CustomListAdapter) this.getItem(position);
ItemName.setText(CLA.getItemName());
SerialNo.setText(CLA.getSerialNo());
SupplierName.setText(CLA.getSupplierName());
amount.setText(CLA.getQuantity());
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(c,CLA.getItemName(),Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
}
content_main_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/app_bar_main_menu">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="0dp"
android:layout_marginTop="0dp" />
content_main_menu_list.xml is a custom layout that i created for every data set to be displayed.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.constraint.ConstraintLayout
android:layout_width="0dp"
android:layout_height="100dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/amount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="TextView"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<TextView
android:id="#+id/serialNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/supplierName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="TextView"
app:layout_constraintTop_toBottomOf="#+id/serialNo" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="23dp"
android:layout_marginBottom="8dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#0171B0"
app:layout_constraintBottom_toTopOf="#+id/serialNo" />
</android.support.constraint.ConstraintLayout>
</android.support.constraint.ConstraintLayout>

The problem in your code lies in the fact that you have in your CustomListAdapter class a field named ItemName but you are using a getter named getItemName(), which is not correct since Firebase is looking in the database for a field named itemName and not ItemName. See the lowercase i letter vs. capital letter I?
There are two ways in which you can solve this problem. The first one would be to change your model class by renaming the fields according to the Java Naming Conventions. So you model class should look like this:
public class CustomListAdapter {
private String itemName, quantity, serialNo, supplierName, supplierEmail, supplierPhone;
public CustomListAdapter() {}
public CustomListAdapter(String itemName, String quantity, String serialNo, String supplierName, String supplierEmail, String supplierPhone) {
this.itemName = itemName;
this.quantity = quantity;
this.serialNo = serialNo;
this.supplierName = supplierName;
this.supplierEmail = supplierEmail;
this.supplierPhone = supplierPhone;
}
public String getItemName() { return itemName; }
public String getQuantity() { return quantity; }
public String getSerialNo() { return serialNo; }
public String getSupplierName() { return supplierName; }
public String getSupplierEmail() { return supplierEmail; }
public String getSupplierPhone() { return supplierPhone; }
}
See in this example, there are private fields and public getters. There is also a simpler solution, to set the value directly on public fields like this:
public class CustomListAdapter {
public String itemName, quantity, serialNo, supplierName, supplierEmail, supplierPhone;
}
Now just remove the current data and add it again using the correct names. This solution will work only if you are in testing phase.
There is also the second approach, which is to use annotations. So if you prefer to use private fields and public getters, you should use the PropertyName annotation only in front of the getter. So your CustomListAdapter class should look like this:
public class CustomListAdapter {
private String ItemName;
private String Quantity;
private String SerialNo;
private String SupplierName;
private String SupplierEmail;
private String SupplierPhone;
public CustomListAdapter() {}
public CustomListAdapter(String itemName, String quantity, String serialNo, String supplierName, String supplierEmail, String supplierPhone) {
ItemName = itemName;
Quantity = quantity;
SerialNo = serialNo;
SupplierName = supplierName;
SupplierEmail = supplierEmail;
SupplierPhone = supplierPhone;
}
#PropertyName("ItemName")
public String getItemName() { return ItemName; }
#PropertyName("Quantity")
public String getQuantity() { return Quantity; }
#PropertyName("SerialNo")
public String getSerialNo() { return SerialNo; }
#PropertyName("SupplierName")
public String getSupplierName() { return SupplierName; }
#PropertyName("SupplierEmail")
public String getSupplierEmail() { return SupplierEmail; }
#PropertyName("SupplierPhone")
public String getSupplierPhone() { return SupplierPhone; }
}

Related

Android : UI and data not survive when screen rotation in MVVM pattern

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, everything is going well untill I try to rotate my screen, I see from my logcat the data is always reload and my ImageView is always refresh, this is my Activity:
public class DetailActivity extends BaseActivity<ActivityDetailBinding, DetailViewModel> implements DetailNavigator {
#Inject
ViewModelProviderFactory factory;
private 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() {
detailViewModel = ViewModelProviders.of(this, factory).get(DetailViewModel.class);
return detailViewModel;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
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 ViewModelFactory class :
#Singleton
public class ViewModelProviderFactory extends ViewModelProvider.NewInstanceFactory {
private final DataManager dataManager;
private final SchedulerProvider schedulerProvider;
#Inject
public ViewModelProviderFactory(DataManager dataManager,
SchedulerProvider schedulerProvider) {
this.dataManager = dataManager;
this.schedulerProvider = schedulerProvider;
}
#Override
public <T extends ViewModel> T create(Class<T> modelClass) {
if (modelClass.isAssignableFrom(DetailViewModel.class)) {
return (T) new DetailViewModel(dataManager,schedulerProvider);
}
throw new IllegalArgumentException("Unknown class name");
}
}
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);
// getNavigator().updateView();
}, 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 if (detailResponse.getOriginal_title() != null) {
originalName.set(detailResponse.getOriginal_title());
} else {
}
if (detailResponse.getFirst_air_date() != null) {
releaseDate.set(detailResponse.getFirst_air_date());
} else {
releaseDate.set(detailResponse.getRelease_date());
}
if (!detailResponse.getOverview().equals("")) {
overview.set(detailResponse.getOverview());
} else {
overview.set(getNavigator().noDesc());
}
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).getName();
if (i != detailResponse.getGenreList().size() - 1) {
genres = genres + ", ";
}
}
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>
<import type="android.view.View" />
<variable
name="viewModel"
type="id.dicoding.eriza.moviecatalogue.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"
app:imageDetailUrl="#{viewModel.posterPath}"
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"
android:visibility="#{viewModel.isConnected ? View.VISIBLE : View.GONE}"
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"
android:text="#{viewModel.releaseDate}"
android:visibility="#{viewModel.isConnected ? View.VISIBLE : View.GONE}"
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"
android:text="#{viewModel.genreMovie}"
tools:text="#string/hint_genres" />
<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.8"
android:stepSize="0.1"
android:visibility="#{viewModel.isConnected ? View.VISIBLE : View.GONE}"
app:layout_constraintStart_toStartOf="parent"
app:ratingBar="#{viewModel.voteAverage}"
app:layout_constraintTop_toBottomOf="#+id/text_genres" />
<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_genres"
android:text="#{viewModel.voteAverage}"
tools:text="#string/hit_rating" />
<TextView
android:id="#+id/text_default_rating"
style="#style/FontText.Rating"
android:textStyle="normal"
android:visibility="#{viewModel.isConnected ? View.VISIBLE : View.GONE}"
app:layout_constraintRight_toLeftOf="parent"
app:layout_constraintStart_toEndOf="#+id/text_rating"
app:layout_constraintTop_toBottomOf="#+id/text_genres"
android: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"
android:text="#{viewModel.overview}"
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 think ViewModelshould manages UI that related data in Activity lifecycle, and tt allows to survive configuration changes in the Application, but in my case, the data is survive, but when I check on my logcat the fetchDetail() in DetailViewModel class is always call when screen rotation, and my ImageView is also refresh when I rotate my screen, so I think the viewModel not manage my UI when screen rotation. is there any problem with my code?
hope anybody can help me to show me where is my fault and what I must do. Thank you very much.

create button on xml file (not new activity) and open new activity

I'm new in android studio and currently creating an app which will retrieve data from existing db of sqlite. based on what I'd found is to create a layout file (not by creating new empty activity) to design on how the display the data. But in the layout, I want the button to open new activity, but somehow it didn't and I didn't found any solution so far. and the image also didn't appeared. This is the code:
DataPOI.java
public class DataPOI {
private int id;
private String category;
private String name;
private String hour;
private String phone_number;
private String address;
private String website;
private int fee_adult_standard;
private int fee_child_standard;
private int fee_senior_standard;
private int fee_adult_MyKad;
private int fee_child_MyKid;
private int fee_senior_MyKad;
private int fee_student_standard;
private int fee_student_MyKad;
private String description;
private byte[] photo;
private String coordinate;
private String door;
private String parking1;
private String parking2;
public DataPOI(int id, String category, String name, String hour, String phone_number,
String address, String website, int fee_adult_standard, int fee_child_standard,
int fee_senior_standard, int fee_adult_MyKad, int fee_child_MyKid,
int fee_senior_MyKad, int fee_student_standard, int fee_student_MyKad,
String description, byte[] photo, String coordinate, String door,
String parking1, String parking2) {
this.id = id;
this.category = category;
this.name = name;
this.hour = hour;
this.phone_number = phone_number;
this.address = address;
this.website = website;
this.fee_adult_standard = fee_adult_standard;
this.fee_child_standard = fee_child_standard;
this.fee_senior_standard = fee_senior_standard;
this.fee_adult_MyKad = fee_adult_MyKad;
this.fee_child_MyKid = fee_child_MyKid;
this.fee_senior_MyKad = fee_senior_MyKad;
this.fee_student_standard = fee_student_standard;
this.fee_student_MyKad = fee_student_MyKad;
this.description = description;
this.photo = photo;
this.coordinate = coordinate;
this.door = door;
this.parking1 = parking1;
this.parking2 = parking2;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHour() {
return hour;
}
public void setHour(String hour) {
this.hour = hour;
}
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number) {
this.phone_number = phone_number;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public int getFee_adult_standard() {
return fee_adult_standard;
}
public void setFee_adult_standard(int fee_adult_standard) {
this.fee_adult_standard = fee_adult_standard;
}
public int getFee_child_standard() {
return fee_child_standard;
}
public void setFee_child_standard(int fee_child_standard) {
this.fee_child_standard = fee_child_standard;
}
public int getFee_senior_standard() {
return fee_senior_standard;
}
public void setFee_senior_standard(int fee_senior_standard) {
this.fee_senior_standard = fee_senior_standard;
}
public int getFee_adult_MyKad() {
return fee_adult_MyKad;
}
public void setFee_adult_MyKad(int fee_adult_MyKad) {
this.fee_adult_MyKad = fee_adult_MyKad;
}
public int getFee_child_MyKid() {
return fee_child_MyKid;
}
public void setFee_child_MyKid(int fee_child_MyKid) {
this.fee_child_MyKid = fee_child_MyKid;
}
public int getFee_senior_MyKad() {
return fee_senior_MyKad;
}
public void setFee_senior_MyKad(int fee_senior_MyKad) {
this.fee_senior_MyKad = fee_senior_MyKad;
}
public int getFee_student_standard() {
return fee_student_standard;
}
public void setFee_student_standard(int fee_student_standard) {
this.fee_student_standard = fee_student_standard;
}
public int getFee_student_MyKad() {
return fee_student_MyKad;
}
public void setFee_student_MyKad(int fee_student_MyKad) {
this.fee_student_MyKad = fee_student_MyKad;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public byte[] getPhoto() {
return photo;
}
public void setPhoto(byte[] photo) {
this.photo = photo;
}
public String getCoordinate() {
return coordinate;
}
public void setCoordinate(String coordinate) {
this.coordinate = coordinate;
}
public String getDoor() {
return door;
}
public void setDoor(String door) {
this.door = door;
}
public String getParking1() {
return parking1;
}
public void setParking1(String parking1) {
this.parking1 = parking1;
}
public String getParking2() {
return parking2;
}
public void setParking2(String parking2) {
this.parking2 = parking2;
}
}
ListPOIadapter.java
public class ListPOIadapter extends BaseAdapter {
private Context mContext;
private List<DataPOI> mPOIList;
public ListPOIadapter(Context mContext, List<DataPOI> mPOIList) {
this.mContext = mContext;
this.mPOIList = mPOIList;
}
#Override
public int getCount() {
return mPOIList.size();
}
#Override
public Object getItem(int i) {
return mPOIList.get(i);
}
#Override
public long getItemId(int i) {
return mPOIList.get(i).getId();
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = View.inflate(mContext, R.layout.data_layout, null);
//edit below this
ImageView myPhoto = (ImageView)v.findViewById(R.id.imageView);
TextView myName = (TextView)v.findViewById(R.id.name);
TextView myHour = (TextView)v.findViewById(R.id.operational_hour);
TextView myContact = (TextView)v.findViewById(R.id.contact_number);
TextView myWebsite = (TextView)v.findViewById(R.id.website);
TextView myAddress = (TextView)v.findViewById(R.id.address);
//myPhoto.setI(mPOIList.get(i).getPhoto());
myName.setText(mPOIList.get(i).getName());
myHour.setText(mPOIList.get(i).getHour());
myContact.setText(mPOIList.get(i).getPhone_number());
myWebsite.setText(mPOIList.get(i).getWebsite());
myAddress.setText(mPOIList.get(i).getAddress());
return v;
}
}
AmusementPark.java
public class AmusementPark extends AppCompatActivity {
private ListView lvPOI;
private ListPOIadapter adapter;
private List<DataPOI> mPOIList;
private AmusementPark_Helper mDBHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_amusement_park);
lvPOI = (ListView)findViewById(R.id.listview_product);
mDBHelper = new AmusementPark_Helper(this);
//Check existis database
File database = getApplicationContext().getDatabasePath(AmusementPark_Helper.DBNAME);
if(false == database.exists()) {
mDBHelper.getReadableDatabase();
//Copy db
if(copyDatabase(this)) {
Toast.makeText(this, "Copy database success", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "Copy database error", Toast.LENGTH_SHORT).show();
return;
}
}
//Get product list in db when db exists
mPOIList = mDBHelper.getListPOI();
//Init adapter
adapter = new ListPOIadapter(this, mPOIList);
//Set adapter for listview
lvPOI.setAdapter(adapter);
}
private boolean copyDatabase (Context context) {
try {
InputStream inputStream = context.getAssets().open(AmusementPark_Helper.DBNAME);
String outFileName = AmusementPark_Helper.DBLOCATION + AmusementPark_Helper.DBNAME;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[]buff = new byte[1024];
int length = 0;
while ((length = inputStream.read(buff)) > 0) {
outputStream.write(buff, 0, length);
}
outputStream.flush();
outputStream.close();
Log.v("Amusement Park", "DB copied");
return true;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
AmusementPark_Helper.java
public class AmusementPark_Helper extends SQLiteOpenHelper {
public static final String DBNAME = "placeofinterest.sqlite";
public static final String DBLOCATION = "/data/data/com.example.lenovo.welcome.ListHelper";
private Context mContext;
private SQLiteDatabase mDatabase;
public AmusementPark_Helper (Context context) {
super(context, DBNAME, null, 1);
this.mContext = context;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public void openDatabase() {
String dbPath = mContext.getDatabasePath(DBNAME).getPath();
if(mDatabase != null && mDatabase.isOpen()) {
return;
}
mDatabase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabase() {
if(mDatabase != null) {
mDatabase.close();
}
}
public List<DataPOI> getListPOI() {
DataPOI placeofinterest = null;
List<DataPOI> poiList = new ArrayList<>();
openDatabase();
Cursor cursor = mDatabase.rawQuery("SELECT * FROM amusement_park", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
//below is depends on data type of each column
placeofinterest = new DataPOI(
cursor.getInt(0), cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4), cursor.getString(5),
cursor.getString(6), cursor.getInt(7), cursor.getInt(8),
cursor.getInt(9), cursor.getInt(10), cursor.getInt(11),
cursor.getInt(12), cursor.getInt(13), cursor.getInt(14),
cursor.getString(15), cursor.getBlob(16), cursor.getString(17),
cursor.getString(18), cursor.getString(19), cursor.getString(20));
poiList.add(placeofinterest);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return poiList;
}
}
data_layout.xml (created not by using "create new empty activity")
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="210dp"
android:background="#89cff0">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
app:srcCompat="#mipmap/ic_launcher_round" />
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/imageView"
android:text="Name of POI"
android:textColor="#000"
android:textSize="19sp" />
<TextView
android:id="#+id/operational_hour"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/name"
android:layout_toRightOf="#id/imageView"
android:text="Operational Hours"
android:textColor="#000"
android:textSize="15sp" />
<TextView
android:id="#+id/contact_number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/operational_hour"
android:layout_toRightOf="#id/imageView"
android:text="Contact Number"
android:textColor="#000"
android:textSize="15sp" />
<TextView
android:id="#+id/website"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/contact_number"
android:layout_toRightOf="#id/imageView"
android:clickable="true"
android:text="Website"
android:autoLink="web"
android:textColor="#000"
android:textSize="15sp" />
<TextView
android:id="#+id/address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/website"
android:layout_toRightOf="#id/imageView"
android:clickable="true"
android:text="Address"
android:textColor="#000"
android:textSize="15sp" />
<Button
android:id="#+id/button_description"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_below="#id/address"
android:layout_marginBottom="5dp"
android:layout_marginRight="5dp"
android:layout_toRightOf="#id/imageView"
android:layout_weight="1"
android:background="#drawable/mybutton"
android:text="Description"
android:textColor="#000" />
<Button
android:id="#+id/button_entrance_fee"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_below="#id/address"
android:layout_marginBottom="5dp"
android:layout_marginRight="5dp"
android:layout_toRightOf="#id/button_description"
android:layout_weight="1"
android:background="#drawable/mybutton"
android:text="Entrance Fee"
android:textColor="#000" />
<Button
android:id="#+id/button_nearest_me"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_below="#id/button_entrance_fee"
android:layout_marginBottom="5dp"
android:layout_marginRight="5dp"
android:layout_toRightOf="#id/imageView"
android:layout_weight="1"
android:background="#drawable/mybutton"
android:text="Nearest Me"
android:textColor="#000" />
<Button
android:id="#+id/button_take_me_there"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_below="#id/button_entrance_fee"
android:layout_marginBottom="5dp"
android:layout_marginRight="5dp"
android:layout_toRightOf="#id/button_nearest_me"
android:layout_weight="1"
android:background="#drawable/mybutton"
android:text="Take Me There"
android:textColor="#000" />
</RelativeLayout>
So, how to open new activity from a button which as no .java? I tried to create a new activity and copy paste from the data_layout.xml but it still not working. I hope my explanation is quite clear. and please help me. Thank you.
In your AmusementPark.java file, change
if(false == database.exists()) {
to
if(database.exists == false) {
Also verify the paths are correct. See this very similar article: How do I get a button to open another activity in Android Studio?
Code taken from article:
Manifest file
<activity
android:name="MyOtherActivity"
android:label="#string/app_name">
</activity>
Activity.java file
Button btn = (Button)findViewById(R.id.open_activity_button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, MyOtherActivity.class));
}
});

ObservableArrayMap with Object as value not getting Observed on value change in editext

I have a model class
public class ScopeDefination extends BaseObservable {
String value;
String key;
boolean isPrivate;
String category;
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public ScopeDefination(String key, String value, boolean isPrivate) {
this.key = key;
this.value = value;
this.isPrivate = isPrivate;
}
public ScopeDefination(String key, String value, boolean isPrivate, String category) {
this.key = key;
this.value = value;
this.isPrivate = isPrivate;
this.category = category;
}
#Bindable
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;notifyPropertyChanged(developer.manish.publicprivatescopecategory.BR.key);
}
#Bindable
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
notifyPropertyChanged(developer.manish.publicprivatescopecategory.BR.value);
}
public boolean isPrivate() {
return isPrivate;
}
public void setPrivate(boolean aPrivate) {
isPrivate = aPrivate;
}
}
and I am trying to use it in a class for data binding like this
ScopeDefination scopeDefination1 = new ScopeDefination(Keys.ADDRESS_HOME,"Address", true, Keys.FINANCIAL_INFO);
ScopeDefination scopeDefination2 = new ScopeDefination(Keys.NAME,"Name", true, Keys.FINANCIAL_INFO);
ObservableArrayMap<String, Object> user = new ObservableArrayMap<>();
user.put(Keys.ADDRESS_HOME, scopeDefination1);
user.put(Keys.NAME, scopeDefination2);
fragmentFirebaseBinderBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_firebase_binder, container, false);
fragmentFirebaseBinderBinding.setUser(user);
My XML is
<?xml version="1.0" encoding="utf-8"?>
<data>
<import type="developer.manish.publicprivatescopecategory.ScopeDefination" />
<import type="android.databinding.ObservableMap" />
<variable
name="user"
type="ObservableMap<String, Object>" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="developer.manish.publicprivatescopecategory.FirebaseBinder">
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text='#{((ScopeDefination)user["username"]).getValue()}'/>
<TextView
android:id="#+id/address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text='#{((ScopeDefination)user["address_home"]).getValue()}' />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text='#{((ScopeDefination)user["username"]).getValue()}' />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text='#{((ScopeDefination)user["address_home"]).getValue()}' />
</LinearLayout>
I am able to show data on UI but when I edit data in Editext the corresponding text view is not getting updated.
What you want is a Two-Way Binding which is slightly different than the normal Binding. See the blog entry from George Mount.
Basically, you'll need to edit your Binding expressions from
android:text='#{((ScopeDefination)user["username"]).getValue()}'
to
android:text='#={((ScopeDefination)user["username"]).value}'
Notice that there is an extra = between the # and the {. This will notify your model whenever the data in the EditText changed. Also, you cannot use methods in Two-Way Binding, but using .value will work. Thanks to #George Mount for pointing this out.

Retrieve result through REST API and show it in a LIST VIEW in a new activity (Minor issue arises with LIST VIEW)

I am retrieving data from a JOB site through REST api. I am able to retrieve the data and even can show that in the same page after Search button. But, I want to show the list view in the new activity . I am using Intent to do this. But, Unfortunately, I am unable to show that. My app crashes and outputs nothing, once I click on it.
MAIN ACTIVITY.java
public class MainActivity extends Activity {
//private String url1 = "http://api.openweathermap.org/data/2.5/weather?q=";
//private String url2 = "&mode=xml";
EditText queryText;
EditText locationText;
EditText sortText;
EditText fromAgeText;
ListView responseView;
// EditText radiusText;
ProgressBar progressBar;
EditText jtText;
EditText chnlText;
EditText countryText;
EditText txText;
static final String API_KEY = "298**70********4";
static final String API_URL = "http://api.xyz.com/abc/apisearch?";
ProgressDialog waitProgress;
EditText startText;
EditText limitRes;
EditText filterText;
EditText userIpText; //="122.171.57.131";
EditText radiusText;
EditText browserText;
EditText version;
EditText stText;
EditText latlongText;
//private HandleXML obj;
String finalUrl;
ArrayList<Result> rList = null;
ArrayList<Result> resultlist;
String tempResponse;
private PostBaseAdapter adapter;
ListView list;
Result result;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initializeUI("java","bangalore","karnataka","date","25","jobsite","fulltime","0","15","14","1","1","india","null","122.172.176.113","chrome","2");
initializeUI();
}
//responseView = (ListView) findViewById(R.id.responseView);
private void initializeUI() {
queryText = (EditText) findViewById(R.id.queryText);
locationText = (EditText) findViewById(R.id.locationText);
txText = (EditText) findViewById(R.id.txText);
sortText = (EditText) findViewById(R.id.sortText);
radiusText = (EditText) findViewById(R.id.radiusText);
stText = (EditText) findViewById(R.id.stText);
jtText = (EditText) findViewById(R.id.jtText);
//startText = (EditText) findViewById(R.id.startText);
limitRes = (EditText) findViewById(R.id.limitRes);
fromAgeText = (EditText) findViewById(R.id.fromAgeText);
//filterText = (EditText) findViewById(R.id.filterText);
//latlongText = (EditText) findViewById(R.id.latlongText);
countryText = (EditText) findViewById(R.id.countryText);
//chnlText = (EditText) findViewById(R.id.chnlText);
userIpText = (EditText) findViewById(R.id.userIpText);
//browserText = (EditText) findViewById(R.id.browserText);
//version = (EditText) findViewById(R.id.version);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
Button queryButton = (Button) findViewById(R.id.queryButton);
//list = (ListView) findViewById(R.id.resultList);
queryButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String query = queryText.getText().toString();
String location = locationText.getText().toString();
String tx = txText.getText().toString();
String sort = sortText.getText().toString();
String radius = radiusText.getText().toString();
String st = stText.getText().toString();
String jobtype = jtText.getText().toString();
//String start = startText.getText().toString();
String limit = limitRes.getText().toString();
String fromAge = fromAgeText.getText().toString();
//String filter = filterText.getText().toString();
//String latlong = latlongText.getText().toString();
String country = countryText.getText().toString();
//String chnlTxt = chnlText.getText().toString();
String userIp = userIpText.getText().toString();
//String browser = browserText.getText().toString();
//String versionTx = version.getText().toString();
//ArrayList<String> arl= new ArrayList<String>();
//arl.add(query);
new RetrieveFeedTask().execute(query, location, tx, sort, radius, st, jobtype,"1",limit,fromAge,"1","1",country,"null",userIp, "chrome","2");
//responseView.setText(url);
Log.e("ERROR","In button call");
Log.i("INFO","Inside Button call");
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.tvTitle)).getText().toString();
// create intent to start another activity
Intent intent = new Intent(MainActivity.this, DetailsActivity.class);
//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(resultlist.get(position).getJobtitle()));
// add the selected text item to our intent.
intent.putExtra("title", name);
startActivity(intent);
}
});
}
class RetrieveFeedTask extends AsyncTask<String, String, String> {
private Exception exception;
String tempResponse = "";
protected void onPreExecute() {
waitProgress = ProgressDialog.show(MainActivity.this, "", "Loading... please wait...");
// progressBar.setVisibility(View.VISIBLE);
// responseView.setAdapter(null);//.setText(" ");
Log.e("ERROR","In onPreExecute call");
Log.i("INFO","Inside onPreExecutecall");
}
protected String doInBackground(String... args) {
// Do some validation here
String query = args[0];
String location = args[1];
String tx = args[2];
String sort = args[3];
String radius = args[4];
String st = args[5];
String jobtype = args[6];
String start = args[7];
String limit = args[8];
String fromAge = args[9];
String filter = args[10];
String latlong = args[11];
String country = args[12];
String chnlTxt = args[13];
String userIp = args[14];
String browser = args[15];
String versionTx = args[16];
finalUrl = API_URL + "publisher=" + API_KEY + "&q=" + query + "&l=" + location + "," + tx + "&sort=" + sort + "&radius=" + radius + "&st=" + st + "&jt=" + jobtype + "&start=" + start + "&limit=" + limit + "&fromage=" + fromAge + "&filter=" + filter + "&latlong=" + latlong + "&co=" + country + "&chnl=" + chnlTxt + "&userip=" + userIp + "&useragent=" + browser + "&v=" + versionTx;
//finalUrl= "http://api.xyz.com/ads/apisearch?publisher=2986470692413324&q=java&l=BANGALORE%2C+karnataka&sort=date&radius=25&st=jobsite&jt=fulltime&start=1&limit=10&fromage=14&filter=1&latlong=1&co=india&chnl=null&userip=122.166.158.225&useragent=Chrome&v=2";
SAXParser();
return "";
}
protected void onPostExecute(String response) {
/* if (response == null || response.trim().equals("")) {
response = "THERE WAS AN ERROR";
}*/
/* if (rList == null) {
responseView.setAdapter(null); //setText("Error");
//return;
}*/
// progressBar.setVisibility(View.GONE);
//Log.i("INFO", response);
// getting values from selected ListItem
// Bundle bundle= new Bundle();
String name = ((TextView) findViewById(R.id.tvTitle)).getText().toString();
Bundle bundle= new Bundle();
// create intent to start another activity
//bundle.putString("name",result.getJobtitle());
Intent intent2 = new Intent(MainActivity.this, ResultListView.class);
//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(resultlist.get(position).getJobtitle()));
// add the selected text item to our intent.
//intent2.putExtra("title", name);
bundle.putString("title",name);
intent2.putExtra("pBundle",bundle);
startActivity(intent2);
//displayData();
if (waitProgress != null) {
waitProgress.dismiss();
}
}
/* protected void onPostExecute()
{ progressBar.setVisibility(View.GONE);
displayData();
}*/
private void SAXParser(){
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
// create a parser
//XMLReader xmlreader = factory.getXMLReader();
SAXParser parser = factory.newSAXParser();
resultlist = new ArrayList<Result>();
URL ul = new URL(finalUrl);
URLConnection uc = ul.openConnection();
ResultHandler resultHandler = new ResultHandler(resultlist);
// assign our handler
// xmlreader.setContentHandler(resultHandler);
// perform the synchronous parse
parser.parse(new InputSource(uc.getInputStream()), resultHandler);
resultlist = resultHandler.getResultList();
Log.e("ERROR","In SAXParser call");
Log.i("INFO","Inside SAXParser");
} catch (Exception e) {
e.printStackTrace();
}
Log.e("ERROR","In doInBackground call");
Log.i("INFO","Inside doInBackgr call");
// SAXParser();
}
}
activity_main.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:fillViewport="true"
android:layout_height="match_parent"
android:layout_width="match_parent">
<LinearLayout
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="portfolio.first_app.practice.com.simplewebapi3.xyzJobActivity">
<EditText
android:id="#+id/queryText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Skill"/>
<!--android:inputType="textEmailAddress"-->
<EditText
android:id="#+id/locationText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Location"/>
<EditText
android:id="#+id/txText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the State"/>
<EditText
android:id="#+id/sortText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Date"/>
<EditText
android:id="#+id/radiusText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Radius"/>
<EditText
android:id="#+id/stText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Site Type"/>
<EditText
android:id="#+id/jtText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Job Type"/>
<!-- <EditText
android:id="#+id/startText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Start Index of the Result"/>-->
<EditText
android:id="#+id/limitRes"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Result Limit"/>
<EditText
android:id="#+id/fromAgeText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Age"/>
<!-- <EditText
android:id="#+id/filterText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Duplicate filter value"/>
<EditText
android:id="#+id/latlongText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the value 1 or 0"/>-->
<EditText
android:id="#+id/countryText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Country"/>
<!-- <EditText
android:id="#+id/chnlText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Group channel"/>-->
<EditText
android:id="#+id/userIpText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the User IP address"/>
<!-- <EditText
android:id="#+id/browserText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Browser"/>
<EditText
android:id="#+id/version"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Version:"/>-->
<Button
android:id="#+id/queryButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
style="#style/Base.Widget.AppCompat.Button.Borderless"
android:text="Search"/>
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true"
android:layout_centerHorizontal="true"
android:visibility="gone" />
</LinearLayout>
</ScrollView>
ResultListView.java
/**
* Created by SouRAV on 6/15/2016.
*/
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by SouRAV on 6/15/2016.
*/
public class ResultListView extends Activity {
TextView textView;
ListView list;
ArrayList<Result> resultlist;
private PostBaseAdapter adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_list_view);
list = (ListView) findViewById(R.id.resultList);
textView = (TextView) findViewById(R.id.textView);
// get the intent from which this activity is called.
Intent intent2 = getIntent();
Bundle bundle= intent2.getBundleExtra("pBundle");
String text = bundle.getString("title");
textView.setText(text);
displayData1();
// fetch value from key-value pair and make it visible on TextView.
//Bundle intent2 = getIntent().getExtras();
//String list_data = intent2.getString("list");
// textView.setText(list_data);
}
private void displayData1() {
adapter = new PostBaseAdapter(ResultListView.this, resultlist);
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
Log.e("ERROR","In displayData call");
Log.i("Info","Inside displaydata");
//Log.i("INFO", response);
// responseView.setText(response);
// ProgressBar.dismiss();
}
}
result_list_view.xml
<LinearLayout android:layout_height="wrap_content"
android:layout_width="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android" >
<ListView android:id="#+id/resultList"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
</ListView>
</LinearLayout>
Result.java
package portfolio.first_app.practice.com.xyzjobactivity3;
/**
* Created by SouRAV on 4/29/2016.
*/
import java.util.ArrayList;
import java.util.ArrayList;
public class Result {
public String jobtitle;
public String company;
public String city;
public String state;
public String country;
public String formattedLocation;
public String source;
public String date;
public String snippet;
public String url;
public String onmousedown;
public String lattitude;
public String longitude;
public String jobkey;
public String sponsored;
public String expired;
public String formattedLocationFull;
public String formattedRelativeTime;
public String getJobtitle() {
return jobtitle;
}
public void setJobtitle(String jobtitle) {
this.jobtitle = jobtitle;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getFormattedLocation() {
return formattedLocation;
}
public void setFormattedLocation(String formattedLocation) {
this.formattedLocation = formattedLocation;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getSnippet() {
return snippet;
}
public void setSnippet(String snippet) {
this.snippet = snippet;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getOnmousedown() {
return onmousedown;
}
public void setOnmousedown(String onmousedown) {
this.onmousedown = onmousedown;
}
public String getLattitude() {
return lattitude;
}
public void setLattitude(String lattitude) {
this.lattitude = lattitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getJobkey() {
return jobkey;
}
public void setJobkey(String jobkey) {
this.jobkey = jobkey;
}
public String getSponsored() {
return sponsored;
}
public void setSponsored(String sponsored) {
this.sponsored = sponsored;
}
public String getExpired() {
return expired;
}
public void setExpired(String expired) {
this.expired = expired;
}
public String getFormattedLocationFull() {
return formattedLocationFull;
}
public void setFormattedLocationFull(String formattedLocationFull) {
this.formattedLocationFull = formattedLocationFull;
}
public String getFormattedRelativeTime() {
return formattedRelativeTime;
}
public void setFormattedRelativeTime(String formattedRelativeTime) {
this.formattedRelativeTime = formattedRelativeTime;
}
public String getDetails() {
String result = jobtitle + ": " + company + "\n" + city + "-" + state
+ "\n" + country + "\n" + formattedLocation +"\n" + source+"\n"+date+
"\n"+snippet+"\n"+url+"\n"+onmousedown+"\n"+lattitude+"\n"+longitude+"\n"
+jobkey+"\n"+sponsored+"\n"+expired+"\n"+formattedLocationFull+"\n"+formattedRelativeTime;
return result;
}
}
I am not showing PARSING XML data as it is working fine. Issue is simple , I am using intent, but unable to display it in LIST VIEW. I am asking about the code inside postExecute();
Implement Result by Parcelable interface. Now after fetchind data from server, just put the ArrayList in intent, and retrieve them in ResultActivity.
In list.setItemClickListener -
Intent intent = new Intent(MainActivity.this, DetailsActivity.class);
intent.putParcelableArrayListExtra("RESULT", resultlist);
intent.putExtra("title", name);
startActivity(intent);
And again in onCreate of Result activity don't forget to initialize resultlist -
resultlist = getIntent().getParcelableArrayExtra("RESULT");
Hope it will help you :)

Arraylist TextView

I created a TextView with an ArrayList, but the output is not showing any text, what am I doing wrong? The xml has all the different views defined in it, with the imageview and multiple textviews, but I cant seem to get it to display any text.
TextItem.java:
public class TextItem {
private int imageId;
private String description;
private String description_real;
private String openingtimes;
private String openingtimes_real;
private String prices;
private String prices_real;
public TextItem(int imageId,
String description,
String description_real,
String openingtimes,
String openingtimes_real,
String prices,
String prices_real) {
this.imageId = imageId;
this.description = description;
this.description_real = description_real;
this.openingtimes = openingtimes;
this.openingtimes_real = openingtimes_real;
this.prices = prices;
this.prices_real= prices_real;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getdescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getdescription_real() {
return description_real;
}
public void setdescription_real(String description_real) {
this.description_real = description_real;
}
public String getopeningtimes(){
return openingtimes;
}
public void setopeningtimes(String openingtimes) {
this.openingtimes = openingtimes;
}
public String getopeningtimes_real(){
return openingtimes_real;
}
public void setopeningtimes_real(String openingtimes_real) {
this.openingtimes_real = openingtimes_real;
}
public String prices(){
return prices;
}
public void setprices(String prices) {
this.prices = prices;
}
public String getprices_real(){
return prices_real;
}
public void setprices_real(String prices_real) {
this.prices_real = prices_real;
}
#Override
public String toString() {
return description + "\n" + description_real + "/n" + "/n" +
openingtimes + "\n" + openingtimes_real + "/n" + "/n" +
prices + "\n" + prices_real + "/n" + "/n" ;
}}
Air.java:
public class Air extends Activity {
public static final String[] description = new String[] {"Lorem"};
public static final String[] description_real = new String[] {"Lorem"};
public static final String[] openingtimes = new String[] { "Lorem"};
public static final String[] openingtimes_real = new String[] {"Lorem"};
public static final String[] prices = new String[] { "Lorem"};
public static final String[] prices_real = new String[] {"Lorem"};
public static final Integer[] images = {
R.drawable.hotel };
ImageView ImageView;
TextView TextView;
List<TextItem> TextItems;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.textview_item);
TextItems = new ArrayList<TextItem>();
for (int i = 0; i < description.length ; i++) {
TextItem item = new TextItem(images[i],
description[i],
description_real[i],
openingtimes[i],
openingtimes_real[i],
prices[i],
prices_real[i]);
TextItems.add(item);
ImageView = (ImageView) findViewById(R.id.picture);
TextView = (TextView) findViewById(R.id.description);
TextView = (TextView) findViewById(R.id.description_real);
TextView = (TextView) findViewById(R.id.openingtimes);
TextView = (TextView) findViewById(R.id.openingtimes_real);
TextView = (TextView) findViewById(R.id.prices);
TextView = (TextView) findViewById(R.id.prices_real);
}
}
}
.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/picture"
android:layout_width="80dp"
android:layout_height="80dp"
android:contentDescription="#string/image"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<TextView
android:id="#+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/picture"
android:paddingBottom="10dp"
android:textColor="#000000"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/description_real"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/description"
android:paddingLeft="10dp"
android:textColor="#666666"
android:textSize="14sp" />
<TextView
android:id="#+id/openingtimes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/description_real"
android:paddingBottom="10dp"
android:textColor="#000000"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/openingtimes_real"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/openingtimes"
android:paddingLeft="10dp"
android:textColor="#666666"
android:textSize="14sp" />
<TextView
android:id="#+id/prices"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/openingtimes_real"
android:paddingBottom="10dp"
android:textColor="#000000"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/prices_real"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/prices"
android:paddingLeft="10dp"
android:textColor="#666666"
android:textSize="14sp" />
</RelativeLayout>
textView.setText("SomeText") is missing
you should do this
yourTextView.setText(textItem.getDescription)
also you are assigning many values to the same textview inside a loop, this is wrong, u gonna have one textItems displayed
code
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
public class StackActivity extends Activity {
public static final String[] description = new String[] { "Lorem" };
public static final String[] description_real = new String[] { "Lorem" };
public static final String[] openingtimes = new String[] { "Lorem" };
public static final String[] openingtimes_real = new String[] { "Lorem" };
public static final String[] prices = new String[] { "Lorem" };
public static final String[] prices_real = new String[] { "Lorem" };
public static final Integer[] images = { R.drawable.ic_launcher };
android.widget.ImageView ImageView;
android.widget.TextView TextView;
List<TextItem> TextItems;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextItems = new ArrayList<TextItem>();
for (int i = 0; i < description.length; i++) {
TextItem item = new TextItem(images[i], description[i],
description_real[i], openingtimes[i], openingtimes_real[i],
prices[i], prices_real[i]);
TextItems.add(item);
ImageView = (android.widget.ImageView) findViewById(R.id.picture);
ImageView.setImageResource(TextItems.get(i).getImageId());
TextView = (android.widget.TextView) findViewById(R.id.description);
TextView.setText(TextItems.get(i).getdescription());
TextView = (android.widget.TextView) findViewById(R.id.description_real);
TextView.setText(TextItems.get(i).getdescription());
TextView = (android.widget.TextView) findViewById(R.id.openingtimes);
TextView.setText(TextItems.get(i).getopeningtimes());
TextView = (android.widget.TextView) findViewById(R.id.openingtimes_real);
TextView.setText(TextItems.get(i).getopeningtimes_real());
TextView = (android.widget.TextView) findViewById(R.id.prices);
TextView.setText(TextItems.get(i).prices());
TextView = (android.widget.TextView) findViewById(R.id.prices_real);
TextView.setText(TextItems.get(i).getprices_real());
TextView.setText(TextItems.get(0).getdescription());
}
}
}

Categories

Resources