How can I show image in Recyclerview - Recyclerview image display error - java

Firstly sorry if my english explanation is bad. My issue is, I am trying to make weather app and I want to show 5 day forecast.I keep the data in arraylist that I pull in api and send to my adapter class. As you know weahter icons are expressed as string in weather api. such as "010d" is sunny something like that.I am going to show recyclerview that I wrote 5 day forecast. Everything is working but icons doesn't show. I am sharing codes that I did.
I am getting data in forecast class
My forecast class
public class forecast extends AppCompatActivity {
ActivityResultLauncher<String> permissionLauncher;
LocationManager locationManager;
LocationListener locationListener;
ImageView forecast_back_icon;
RecyclerView recyclerviewforecast;
String API_KEY_FORECAST;
String URL_FORECAST;
Double Latitude,Longitude;
ArrayList<RecyclerviewModel> arrayList;
ForecastAdapter forecastAdapter;
public forecast(){
super();
}
public void init(){
arrayList = new ArrayList<>();
forecast_back_icon = findViewById(R.id.forecast_back_icon);
recyclerviewforecast = findViewById(R.id.RecyclerviewForecast);
get_forecast_data(Latitude,Longitude);
forecast_back_icon();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forecast);
Intent intent = getIntent();
Latitude = intent.getDoubleExtra("lat",0);
Longitude = intent.getDoubleExtra("long",0);
System.out.println("LATİTUDE "+Latitude+" Longitude "+Longitude);
init();
}
public void forecast_back_icon(){
forecast_back_icon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent IntentForecastToMain = new Intent(forecast.this,MainActivity.class);
startActivity(IntentForecastToMain);
}
});
}
public void get_forecast_data(Double Lat, Double Long){
//EXAMPLE URL
//https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API%20key}
API_KEY_FORECAST = "c29ecfafd4a70caad8fee38d6054bfc7";
URL_FORECAST = "https://api.openweathermap.org/data/2.5/onecall?lat="+Lat+"&lon="+Long+"&exclude=current,minutely,hourly,alerts&appid="+API_KEY_FORECAST;
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, URL_FORECAST, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray daily = response.getJSONArray("daily");
for(int i=0;i<daily.length();i++){
String temp = daily.getJSONObject(i).getJSONObject("temp").getString("day");
String feels_like = daily.getJSONObject(i).getJSONObject("feels_like").getString("day");
String pressure = daily.getJSONObject(i).getString("pressure");
String humidity = daily.getJSONObject(i).getString("humidity");
String wind_speed = daily.getJSONObject(i).getString("wind_speed");
String icon = daily.getJSONObject(i).getJSONArray("weather").getJSONObject(0).getString("icon");
String description = daily.getJSONObject(i).getJSONArray("weather").getJSONObject(0).getString("description");
arrayList.add(new RecyclerviewModel(temp,humidity,feels_like,pressure,description,wind_speed,icon));
}
}
catch (JSONException e) {
e.printStackTrace();
}
forecastAdapter = new ForecastAdapter(arrayList);
recyclerviewforecast.setAdapter(forecastAdapter);
recyclerviewforecast.setLayoutManager(new LinearLayoutManager(forecast.this));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(request);
System.out.println("forecast class arraylist size : --> "+arrayList.size());
}
}
My adapter class
public class ForecastAdapter extends RecyclerView.Adapter<ForecastAdapter.MyForecastViewHolder> {
ArrayList<RecyclerviewModel> ForecastArraylist;
ForecastDailyIconConverter forecastDailyIconConverter;
public ForecastAdapter(ArrayList<RecyclerviewModel> ForecastArraylist){
this.ForecastArraylist = ForecastArraylist;
System.out.println("ForecastAdapter arraylist size : --- > "+ForecastArraylist.size());
}
#NonNull
#Override
public MyForecastViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
RecyclerviewForecastRowBinding recyclerviewForecastRowBinding = RecyclerviewForecastRowBinding.inflate(LayoutInflater.from(parent.getContext()),parent,false);
return new MyForecastViewHolder(recyclerviewForecastRowBinding);
}
#Override
public void onBindViewHolder(#NonNull MyForecastViewHolder holder, int position) {
System.out.println("we are in onbindviewholder.... ");
Double temperature = Double.parseDouble(ForecastArraylist.get(position).getTemperature()) - 273.15;
System.out.println(temperature);
Double feels_like = Double.parseDouble(ForecastArraylist.get(position).getFeels_like()) - 273.15;
holder.binding.txtRecyclerviewDay.setText("day "+(position+1));
holder.binding.txtRecyclerviewTemp.setText("temperature:"+temperature.toString().substring(0,4)+"°");
holder.binding.txtRecyclerviewFeelslike.setText("feels like:"+feels_like.toString().substring(0,4)+"°");
holder.binding.txtRecyclerviewHumidity.setText("humidity:%"+ForecastArraylist.get(position).getHumadity());
holder.binding.txtRecyclerviewPressure.setText("pressure:"+ForecastArraylist.get(position).getPressure()+"hPa");
holder.binding.txtRecyclerviewWindSpeed.setText("wind speed:"+ForecastArraylist.get(position).getWind_speed()+"km/h");
holder.binding.txtRecyclerviewCloud.setText(ForecastArraylist.get(position).getDescription());
String icon_id = ForecastArraylist.get(position).getId();
forecastDailyIconConverter = new ForecastDailyIconConverter();
int id1 = forecastDailyIconConverter.ConvertIntoNumeric(icon_id);
load_weather_icon(id1,holder);
}
public void load_weather_icon(int id1,MyForecastViewHolder holder){
if(id1>=200 && id1 <= 232){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.thunderstorm);
}
else if(id1>=300 && id1<= 321){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.showerrain);
}
else if(id1>=500 && id1<= 504){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.rain);
}
else if(id1 == 511){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.snow);
}
else if(id1>=520 && id1<= 531){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.showerrain);
}
else if(id1>=600 && id1<= 622){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.snow);
}
else if(id1>=701 && id1<= 781){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.mist);
}
else if(id1 == 800 ){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.clearsky);
}
else if(id1 == 801){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.fewclouds);
}
else if(id1 == 802){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.scatteredclouds);
}
else if(id1 == 803){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.brokenclouds);
}
else if(id1 == 804){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.brokenclouds);
}
}
#Override
public int getItemCount() {
return ForecastArraylist.size();
}
public class MyForecastViewHolder extends RecyclerView.ViewHolder{
private RecyclerviewForecastRowBinding binding;
public MyForecastViewHolder(#NonNull RecyclerviewForecastRowBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
}
}
I have tried to write icons in onbindviewholder without load_weather_icon() funct and it hasn't worked
My recyclerview_row xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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="wrap_content"
android:orientation="horizontal"
android:weightSum="100"
android:background="#FA8072"
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="vertical"
android:padding="5dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_weight="40"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
>
<TextView
android:id="#+id/txt_recyclerview_day"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="day:"
android:textColor="#color/white"
></TextView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
>
<TextView
android:id="#+id/txt_recyclerview_temp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="temp:"
android:textColor="#color/white"
></TextView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
>
<TextView
android:id="#+id/txt_recyclerview_feelslike"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="feels like:"
android:textColor="#color/white"></TextView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<TextView
android:id="#+id/txt_recyclerview_pressure"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="pressure:"
android:textColor="#color/white"></TextView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<TextView
android:id="#+id/txt_recyclerview_humidity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="humidity:"
android:textColor="#color/white"></TextView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<TextView
android:id="#+id/txt_recyclerview_wind_speed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="wind speed:"
android:textColor="#color/white"></TextView>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="60"
android:layout_margin="5dp"
android:padding="5dp"
android:gravity="right"
android:orientation="vertical"
>
<ImageView
android:id="#+id/recyclerview_cloud_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_alignParentTop="true"
android:layout_centerInParent="true"
></ImageView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txt_recyclerview_cloud"
android:text=""
android:gravity="center"
android:layout_margin="5dp"
android:padding="5dp"
android:textColor="#color/white"
></TextView>
</LinearLayout>
enter image description here

Use Glide or Picasso library
They are best in these type of Application

Related

Tab item title in tablayout displaying not well arranged

I am working on an existing project where tablayout is integrated but the tab items title are not displaying well arranged. Below is screenshot of what it looks like and also a screenshot of how i want it to look like
This is actually how i want the tab item title displaying
This is my xml file code snippet:
<?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=".salesinvoice.fragments.SalesInvoiceInstanceFragment">
<data>
<variable
name="salesRecord"
type="com.mainsoftdc.costoma.salesinvoice.entities.SalesRecord" />
<variable
name="eventHandler"
type="com.mainsoftdc.costoma.salesinvoice.eventhandlers.SalesInvoiceInstanceEventHandler" />
<import type="com.mainsoftdc.costoma.shared.utils.DecimalFormatter" />
<import type="com.mainsoftdc.costoma.shared.utils.MoneyFormatter" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/sales_instance_top_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorGreyLight"
android:orientation="horizontal"
android:paddingLeft="#dimen/padding_xs"
android:paddingRight="#dimen/padding_xs"
app:layout_constraintTop_toTopOf="parent">
<Button
android:id="#+id/btn_edit_sale_instance_customer_name"
style="#style/BtnTextPrimarySmNoPadding"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="#{() -> eventHandler.editCustomerName()}"
android:padding="#dimen/padding_xs"
android:text="#string/sales_instance_edit_customer_name"
android:textColor="#color/colorPrimary"
android:textSize="#dimen/text_12sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btn_close_sale_instance"
style="#style/BtnTextPrimarySmNoPadding"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="#{() -> eventHandler.closeSaleInstance()}"
android:padding="#dimen/padding_xs"
android:text="#string/sales_instance_close_invoice"
android:textColor="#color/colorRed"
android:textSize="#dimen/text_12sp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/sales_product_list_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingStart="#dimen/padding_xs"
android:paddingTop="#dimen/padding_xxs"
android:paddingEnd="#dimen/padding_xs"
android:paddingBottom="#dimen/no_padding"
app:layout_constraintTop_toBottomOf="#id/sales_instance_top_layout">
<TextView
android:id="#+id/sales_instance_items"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="#dimen/padding_xs"
android:text="#string/sales_instance_all_items"
android:textColor="#android:color/black"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.button.MaterialButton
android:id="#+id/btn_add_item_to_sales"
style="#style/BtnSecondarySmOutlined"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="0dp"
android:gravity="center"
android:minWidth="0dp"
android:minHeight="0dp"
android:onClick="#{() -> eventHandler.addItemToSalesBook()}"
android:padding="#dimen/padding_xs"
android:text="#string/sales_instance_add_item"
android:textSize="#dimen/text_10sp"
app:icon="#drawable/ic_add_circle_black_24dp"
app:iconSize="14dp"
app:iconTint="#color/colorAccent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<LinearLayout
android:id="#+id/sales_instance_product_list"
style="#style/ListPage"
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="vertical"
app:layout_constraintBottom_toTopOf="#id/sales_instance_buttons"
app:layout_constraintTop_toBottomOf="#id/sales_product_list_header"
>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/sales_instance_product_list_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:layout_marginBottom="#dimen/margin_md"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
</LinearLayout>
<LinearLayout
android:id="#+id/sales_instance_sales_summary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorGreyLight"
android:orientation="horizontal"
android:paddingLeft="#dimen/padding_sm"
android:paddingRight="#dimen/padding_sm"
android:paddingTop="#dimen/padding_xs"
android:paddingBottom="#dimen/padding_xs"
app:layout_constraintBottom_toTopOf="#id/sales_instance_buttons">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_weight="2"
android:orientation="vertical">
<TextView
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/sales_instance_total_volume"
android:textColor="#color/colorBlack" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{DecimalFormatter.format(salesRecord.totalProductsSold)}"
android:textColor="#color/colorPrimaryDark"
android:textSize="#dimen/text_16sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_weight="3"
android:orientation="vertical"
android:textColor="#color/colorBlack">
<TextView
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end"
android:text="#string/sale_instance_total_value"
android:textColor="#color/colorBlack" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end"
android:text="#{MoneyFormatter.format(salesRecord.totalSellingPrice)}"
android:textColor="#color/colorPrimaryDark"
android:textSize="#dimen/text_16sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/sales_instance_buttons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:orientation="horizontal"
android:paddingLeft="#dimen/padding_xs"
android:paddingTop="#dimen/no_padding"
android:paddingRight="#dimen/padding_xs"
android:paddingBottom="#dimen/no_padding"
app:layout_constraintBottom_toBottomOf="parent">
<com.google.android.material.button.MaterialButton
android:id="#+id/sale_instance_quote_btn"
style="#style/BtnTextPrimarySm"
android:layout_width="0dp"
android:layout_height="38dp"
android:layout_gravity="start"
android:layout_margin="0dp"
android:layout_marginLeft="#dimen/margin_md"
android:layout_weight="1"
android:background="#drawable/xml_drawable_rectangle_border"
android:onClick="#{() ->eventHandler.saveAsQuote()}"
android:text="#string/sales_instance_quote_btn"
android:textAlignment="viewStart"
android:textColor="#android:color/white"
android:textSize="#dimen/text_14sp" />
<com.google.android.material.button.MaterialButton
android:id="#+id/sale_instance_checkout_print_btn"
style="#style/BtnTextPrimarySm"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_margin="0dp"
android:layout_marginRight="#dimen/margin_md"
android:layout_weight="2"
android:background="#drawable/xml_drawable_rectangle_border"
android:onClick="#{() ->eventHandler.captureAmountPaidAndCompleteSales()}"
android:text="#string/sale_instance_proceed_to_checkout"
android:textAlignment="viewEnd"
android:textColor="#android:color/white"
android:textSize="#dimen/text_14sp" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
This is my Adapter Code snippet:
public class SalesInvoicePagerAdapter extends FragmentStatePagerAdapter {
private SalesInvoiceViewModel salesInvoiceViewModel;
private List<SalesRecord> activeSalesRecords = new ArrayList<>();
#SuppressLint("UseSparseArrays")
public SalesInvoicePagerAdapter(final Fragment ownerFragment, SalesInvoiceViewModel salesViewModel) {
super(ownerFragment.getChildFragmentManager());
salesInvoiceViewModel = salesViewModel;
salesInvoiceViewModel.getActiveSalesRecords().observe(ownerFragment, new Observer<List<SalesRecord>>() {
#Override
public void onChanged(#Nullable List<SalesRecord> salesRecords) {
activeSalesRecords = salesRecords;
notifyDataSetChanged();
}
});
salesInvoiceViewModel.newSaleAlert.observe(ownerFragment, new Observer<SalesRecord>() {
#Override
public void onChanged(#Nullable SalesRecord salesRecord) {
Log.i("New Alert", String.valueOf(activeSalesRecords.size()));
activeSalesRecords.add(salesRecord);
notifyDataSetChanged();
}
});
salesInvoiceViewModel.saleClosedAlert.observe(ownerFragment, new Observer<Integer>() {
#Override
public void onChanged(Integer instancePosition) {
if(activeSalesRecords.size() > 0) {
activeSalesRecords.remove((int) instancePosition);
notifyDataSetChanged();
}
}
});
salesInvoiceViewModel.saleUpdatedAlert.observe(ownerFragment, new Observer<Pair<Integer, SalesRecord>>() {
#Override
public void onChanged(#Nullable Pair<Integer, SalesRecord> updatedSalesRecordPair) {
if(updatedSalesRecordPair != null) {
activeSalesRecords.remove((int) updatedSalesRecordPair.first);
activeSalesRecords.add(updatedSalesRecordPair.first, updatedSalesRecordPair.second);
notifyDataSetChanged();
}
}
});
}
#Override
public Fragment getItem(int i) {
Log.i("Set Current", String.valueOf(activeSalesRecords.size()));
if (activeSalesRecords.size() > 0) {
Fragment fragment = new SalesInvoiceInstanceFragment();
Bundle bundle = new Bundle();
bundle.putString(IntentExtras.SALES_INSTANCE_GUID, activeSalesRecords.get(i).getGuid());
bundle.putInt(IntentExtras.SALES_INSTANCE_FRAGMENT_POSITION, i);
fragment.setArguments(bundle);
return fragment;
}
return null;
}
#Override
public int getCount() {
return activeSalesRecords.size();
}
// #Nullable
#Override
public CharSequence getPageTitle(int position) {
Log.i("NAME: ", activeSalesRecords.get(position).getCustomerName());
Log.i("Page Title: ", activeSalesRecords.get(position).getCustomerName());
return activeSalesRecords.get(position).getCustomerName();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
This is my Fragment file code snippet:
public class SalesInvoiceFragment extends BaseFragment implements View.OnClickListener {
private static final String LOG_TAG = SalesInvoiceFragment.class.getName();
private FragmentSalesInvoiceBinding dataBinding;
private SalesInvoicePagerAdapter salesInvoicePagerAdapter;
private SalesInvoiceViewModel salesInvoiceViewModel;
private Activity parentActivity;
private AuthorityVerification authorityVerification;
#Inject
public SharedPreferencesRepository sharedPreferencesRepository;
#Inject
public SubscriptionPlanService subscriptionPlanService;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i("Tab", "CHECKING...");
daggerComponent.inject(this);
dataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_sales_invoice, container, false);
salesInvoiceViewModel = ViewModelProviders.of(this, new CostomaViewModelFactory((CostomaApplication) getActivity().getApplication())).get(SalesInvoiceViewModel.class);
authorityVerification = new AuthorityVerification(requireActivity());
parentActivity = getActivity();
return dataBinding.getRoot();
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
dataBinding.salesInvoiceFragmentTabLayout.setupWithViewPager(dataBinding.salesInvoiceFragmentViewPager);
salesInvoicePagerAdapter = new SalesInvoicePagerAdapter(this, salesInvoiceViewModel);
dataBinding.salesInvoiceFragmentViewPager.setAdapter(salesInvoicePagerAdapter);
Log.i("ONCRE", "START");
// for(int i=0; i < salesInvoicePagerAdapter.getCount(); i++) {
// Log.i("DeTitle", "PAGE TITLE");
// Log.i("DeTitle: ", salesInvoicePagerAdapter.getPageTitle(i).toString());
// //dataBinding.salesInvoiceFragmentTabLayout.addTab(dataBinding.salesInvoiceFragmentTabLayout.newTab().setText(salesInvoicePagerAdapter.getPageTitle(i)));
// dataBinding.salesInvoiceFragmentTabLayout.getTabAt(i).setText(salesInvoicePagerAdapter.getPageTitle(i));
// }
if (!subscriptionPlanService.hasActiveSubscription()) {
dataBinding.startSaleBtn.setVisibility(View.GONE);
dataBinding.noActiveSubLabel.setVisibility(View.VISIBLE);
} else {
dataBinding.startSaleBtn.setVisibility(View.VISIBLE);
dataBinding.noActiveSubLabel.setVisibility(View.GONE);
dataBinding.startSaleBtn.setOnClickListener(this);
}
setDisplayedViewsForActiveSalesCount(0);
salesInvoiceViewModel.salesCountChangedAlert.observe(this, new Observer<Integer>() {
#Override
public void onChanged(#NonNull Integer totalActiveSales) {
Log.i("Set Current", String.valueOf(salesInvoicePagerAdapter.getCount()));
if (totalActiveSales > 0) {
// dataBinding.salesInvoiceFragmentTabLayout.addTab(dataBinding.salesInvoiceFragmentTabLayout.newTab().setText(salesInvoicePagerAdapter.getPageTitle(totalActiveSales - 1)));
for(int i=0; i < salesInvoicePagerAdapter.getCount(); i++) {
// Log.i("DeTitle", "PAGE TITLE");
// Log.i("DeTitle: ", salesInvoicePagerAdapter.getPageTitle(i).toString());
//dataBinding.salesInvoiceFragmentTabLayout.addTab(dataBinding.salesInvoiceFragmentTabLayout.newTab().setText(salesInvoicePagerAdapter.getPageTitle(i)));
dataBinding.salesInvoiceFragmentTabLayout.getTabAt(i).setText(salesInvoicePagerAdapter.getPageTitle(i));
}
dataBinding.salesInvoiceFragmentViewPager.setCurrentItem(totalActiveSales - 1);
// if (dataBinding.salesInvoiceFragmentTabLayout.getTabCount() == 2) {
// dataBinding.salesInvoiceFragmentTabLayout.setTabMode(TabLayout.MODE_FIXED);
// } else {
// dataBinding.salesInvoiceFragmentTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
// }
}
setDisplayedViewsForActiveSalesCount(totalActiveSales);
setActivityTitle(totalActiveSales);
}
});
}
private void setDisplayedViewsForActiveSalesCount(int activeSalesCount) {
if (activeSalesCount > 0) {
dataBinding.salesInvoiceFragmentViewPager.setVisibility(View.VISIBLE);
dataBinding.salesInvoiceFragmentBlankSales.setVisibility(View.GONE);
} else {
dataBinding.salesInvoiceFragmentViewPager.setVisibility(View.GONE);
dataBinding.salesInvoiceFragmentBlankSales.setVisibility(View.VISIBLE);
}
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
salesInvoiceViewModel.commitActiveSales();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_sale_btn:
showAddSaleDialog();
break;
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.sales_invoice_menu, menu);
boolean currentPdfGenerationValue = sharedPreferencesRepository.getBooleanValue(SharedPreferenceKeys.GENERATE_PDF_FOR_INVOICE);
boolean currentMerchantReceiptValue = sharedPreferencesRepository.getBooleanValue(SharedPreferenceKeys.PRINT_MERCHANT_COPY_FOR_RECEIPT);
menu.findItem(R.id.menu_item_invoice_pdf_generation_setting).setChecked(currentPdfGenerationValue);
menu.findItem(R.id.menu_item_invoice_merchant_copy_receipt).setChecked(currentMerchantReceiptValue);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_item_create_sales_instance:
if (!subscriptionPlanService.hasActiveSubscription()) {
ToastUtils.showLongToast(requireActivity(), "You do not have an active subscription!");
return true;
}
showAddSaleDialog();
break;
case R.id.menu_item_invoice_pdf_generation_setting:
boolean generateInvoice = !item.isChecked();
item.setChecked(generateInvoice);
sharedPreferencesRepository.saveBooleanValue(SharedPreferenceKeys.GENERATE_PDF_FOR_INVOICE, generateInvoice);
break;
case R.id.menu_item_invoice_merchant_copy_receipt:
boolean printMerchantReceipt = !item.isChecked();
item.setChecked(printMerchantReceipt);
sharedPreferencesRepository.saveBooleanValue(SharedPreferenceKeys.PRINT_MERCHANT_COPY_FOR_RECEIPT, printMerchantReceipt);
}
return true;
}
private void showAddSaleDialog() {
NewSaleDialog dialog = new NewSaleDialog();
dialog.setSalesInvoiceViewModel(salesInvoiceViewModel);
dialog.show(getFragmentManager(), NewSaleDialog.FRAGMENT_TAG);
}
private void setActivityTitle(int totalSalesCount) {
if (parentActivity != null) {
if (totalSalesCount > 0) {
parentActivity.setTitle(getString(R.string.menu_item_sales_invoice) + " - " + String.valueOf(totalSalesCount));
} else {
parentActivity.setTitle(R.string.menu_item_sales_invoice);
}
}
parentActivity.getActionBar();
}
}
I have tried everything i can to make it display well but is not working. I will welcome any assistance as i need to get this resolved now.
Thanks in advance....

Unable to add more than one item in a listview

I am working on a tasks app, for which I created a list view that shows list items consitsting of task names, their priority etc. The data given to the list view is from an sqlite database. I, however, am unable to add more than one item to the list. I have no idea why. I have created a method to do so, but it doesn't seem to work. I don't know if the error is due to the database or my method itself. Even debugging didn't help. Please note that I am using a list adapter since I am using a custom listview.
Code for Activity where list is shown :
package com.example.taskmasterv3;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class TaskSummary extends AppCompatActivity {
ListView lvTaskList;
TextView tvBreak, tvBreakAfterEvery, txt1, txt2, text1, hmm;
TextView break_duration_mins;
ArrayList<SubtaskPartTwo> subtaskList = new ArrayList<>();
String subtname;
String pri;
String time;
DBHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_summary);
lvTaskList = findViewById(R.id.lvTaskList);
tvBreak = findViewById(R.id.tvBreak);
tvBreakAfterEvery = findViewById(R.id.tvBreakAfterEvery);
txt1 = findViewById(R.id.txt1);
txt2 = findViewById(R.id.txt2);
break_duration_mins = findViewById(R.id.break_duration_mins);
text1 = findViewById(R.id.text1);
hmm = findViewById(R.id.hmm);
dbHelper = new DBHelper(this);
subtname = getIntent().getStringExtra("subtaskname");
pri = getIntent().getStringExtra("pri");
time = getIntent().getStringExtra("time");
// Using adapter for listview :
SubtaskDetailAdapter adapter = new SubtaskDetailAdapter(this, subtaskList);
lvTaskList.setAdapter(adapter);
SubtaskPartTwo subtaskPartTwo = new SubtaskPartTwo(subtname, pri, time);
subtaskList.add(subtaskPartTwo);
adapter.addANewSubTask(subtaskPartTwo);
double working_hours = getIntent().getIntExtra("working_hours", 1);
double working_minutes = getIntent().getIntExtra("working_minutes", 0);
double without_break_hours = getIntent().getIntExtra("without_break_hours", 1);
double without_break_minutes = getIntent().getIntExtra("without_break_minutes", 0);
double break_duration = getIntent().getIntExtra("break_duration", 20);
String a = working_hours + " h";
txt1.setText(a);
String b = working_minutes + " m";
break_duration_mins.setText(b);
String c = break_duration + " m";
txt2.setText(c);
//Mathematics
double g = working_hours * 100;
double h = g + working_minutes;
double i = h + break_duration;
double j = i / 60;
double p = (int) j;
double q = j - p;
double r = q * 60;
without_break_hours = p;
without_break_minutes = r;
String d = without_break_hours + " h";
String e = without_break_minutes + " m";
text1.setText(d);
hmm.setText(e);
}
}
Code for Adapter Class :
package com.example.taskmasterv3;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class SubtaskDetailAdapter extends ArrayAdapter<SubtaskPartTwo> {
private final Context context;
private ArrayList<SubtaskPartTwo> values;
public boolean deleted;
public SubtaskDetailAdapter(Context context, ArrayList<SubtaskPartTwo> list) {
//since your are using custom view,pass zero and inflate the custom view by overriding getview
super(context, 0 , list);
this.context = context;
this.values = list;
}
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
//check if its null, if so inflate it, else simply reuse it
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.task_summary_item, parent, false);
}
//use convertView to refer the childviews to populate it with data
TextView tvSubtaskName = convertView.findViewById(R.id.tvlolitaskname);
ImageView ivPri = convertView.findViewById(R.id.ivloliPri);
ImageView ivTime = convertView.findViewById(R.id.ivloliTime);
tvSubtaskName.setText(values.get(position).getSubtaskName());
if (values.get(position).getPri() == "h")
{
ivPri.setImageResource(R.drawable.priority_high);
}
if (values.get(position).getPri() == "m")
{
ivPri.setImageResource(R.drawable.priority_med);
}
if (values.get(position).getPri() == "l")
{
ivPri.setImageResource(R.drawable.priority_low);
}
if (values.get(position).getTime() == "more")
{
ivPri.setImageResource(R.drawable.time_symbol_more);
}
if (values.get(position).getPri() == "med")
{
ivPri.setImageResource(R.drawable.time_symbol_med);
}
if (values.get(position).getPri() == "less")
{
ivPri.setImageResource(R.drawable.time_symbol_less);
}
//return the view you inflated
return convertView;
}
//to keep adding the new subtasks try the following
public void addANewSubTask(SubtaskPartTwo newSubTask){
ArrayList<SubtaskPartTwo> newvalues = new ArrayList<>(this.values);
newvalues.add(newSubTask);
this.values = newvalues;
notifyDataSetChanged();
}
}
XML code for listview activity :
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="#+id/parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background"
tools:context=".TaskSummary">
<!-- hello -->
<ScrollView
android:id="#+id/scrollView2"
android:layout_width="wrap_content"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="#+id/okay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:orientation="vertical">
<ListView
android:id="#+id/lvTaskList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp">
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:id="#+id/tvBreak"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="8dp"
android:fontFamily="#font/roboto"
android:text="Total Working Time (Including Breaks)"
android:textColor="#B8AEAE"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:id="#+id/txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="8dp"
android:layout_weight="1"
android:fontFamily="#font/roboto"
android:gravity="right"
android:text="00 h"
android:textColor="#B8AEAE"
android:textSize="20sp" />
<TextView
android:id="#+id/break_duration_mins"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:layout_weight="1"
android:gravity="left"
android:text="20 m"
android:textColor="#B8AEAE"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
<!-- hello -->
<!-- hello -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:id="#+id/tvWorktimeWithoutBreak"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="8dp"
android:fontFamily="#font/roboto"
android:text="Work Time Before Each Break"
android:textColor="#B8AEAE"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="8dp"
android:layout_weight="1"
android:fontFamily="#font/roboto"
android:gravity="right"
android:text="00 h"
android:textColor="#B8AEAE"
android:textSize="20sp" />
<TextView
android:id="#+id/hmm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:layout_weight="1"
android:gravity="left"
android:text="20 m"
android:textColor="#B8AEAE"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<!-- hello -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/tvBreakAfterEvery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:fontFamily="#font/roboto"
android:text="Break Duration"
android:textColor="#B8AEAE"
android:textSize="20sp"
app:layout_constraintBottom_toTopOf="#+id/lvTaskList"
app:layout_constraintEnd_toStartOf="#+id/lvTaskList"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/txt2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:fontFamily="#font/roboto"
android:gravity="center_horizontal"
android:text="30 m"
android:textColor="#B8AEAE"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="#+id/btnStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:layout_margin="16dp"
android:text="Start" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
EDIT : Database Code
package com.example.taskmasterv3;
public class TaskInfo extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_info);
tvTaskName = findViewById(R.id.tvTaskName);
btnProceed = findViewById(R.id.btnProceed);
dbHelper = new DBHelper(this);
tvTaskName.setVisibility(View.INVISIBLE);
if (tvTaskName.getText().equals(""))
{
tvTaskName.setClickable(false);
}
else
{
tvTaskName.setClickable(true);
}
btnSaveTaskName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvTaskName.setVisibility(View.VISIBLE);
tvTaskName.setText(etTaskName.getText().toString().toUpperCase().trim());
etTaskName.setVisibility(View.GONE);
btnSaveTaskName.setVisibility(View.GONE);
btnNewSubtask.setEnabled(true);
}
});
tvTaskName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String tasksname = tvTaskName.getText().toString().trim();
tvTaskName.setText("");
etTaskName.setVisibility(View.VISIBLE);
etTaskName.setText(tasksname);
btnSaveTaskName.setVisibility(View.VISIBLE);
}
});
btnNewSubtask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i2 = new Intent(TaskInfo.this, SubtaskActivity.class);
startActivityForResult(i2, ENTER_SUBTASK);
overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up);
}
});
// THE DATABASE PART
btnProceed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = dbHelper.getdata();
while(res != null && res.moveToNext()){
subtname = res.getString(0);
pri = res.getString(1);
time = res.getString(2);
}
if (etWorkingHours.getText().toString().isEmpty())
{
etWorkingHours.setText("0");
}
if (etWorkingMinutes.getText().toString().isEmpty())
{
etWorkingMinutes.setText("0");
}
if (etWorkinghrs.getText().toString().isEmpty())
{
etWorkinghrs.setText("0");
}
if (etWorkingMins.getText().toString().isEmpty())
{
etWorkingMins.setText("0");
}
int working_hours = Integer.parseInt(etWorkinghrs.getText().toString().trim());
int working_minutes = Integer.parseInt(etWorkingMins.getText().toString().trim());
int without_break_hours = Integer.parseInt(etWorkingHours.getText().toString().trim());
int without_break_minutes = Integer.parseInt(etWorkingMinutes.getText().toString().trim());
if (etWorkingHours.getText().toString().isEmpty() || etWorkingMinutes.getText().toString().isEmpty() || etWorkinghrs.getText().toString().isEmpty() || etWorkingMins.getText().toString().isEmpty())
{
Toast.makeText(TaskInfo.this, "Field cannot be empty, please try again.", Toast.LENGTH_SHORT).show();
}
else
{
if (working_hours != 0)
{
if (working_hours > without_break_hours)
{
int breaktime = Integer.parseInt(tvBreakTime.getText().toString());
Intent intent = new Intent(TaskInfo.this, TaskSummary.class);
intent.putExtra("working_hours", working_hours);
intent.putExtra("working_minutes", working_minutes);
intent.putExtra("without_break_hours", without_break_hours);
intent.putExtra("without_break_minutes", without_break_minutes);
intent.putExtra("break_duration", breaktime);
intent.putExtra("subtaskname", taskName);
intent.putExtra("priigh", NpriHigh);
intent.putExtra("primed", NpriMed);
intent.putExtra("prilow", NpriLow);
intent.putExtra("timemore", NtimeMore);
intent.putExtra("timemed", NtimeMed);
intent.putExtra("timeless", NtimeLess);
startActivity(intent);
}
if (working_hours == without_break_hours){
if (working_minutes >= without_break_minutes){
int breaktime = Integer.parseInt(tvBreakTime.getText().toString());
Intent intent = new Intent(TaskInfo.this, TaskSummary.class);
intent.putExtra("working_hours", working_hours);
intent.putExtra("working_minutes", working_minutes);
intent.putExtra("without_break_hours", without_break_hours);
intent.putExtra("without_break_minutes", without_break_minutes);
intent.putExtra("break_duration", breaktime);
intent.putExtra("subtaskname", taskName);
intent.putExtra("priigh", NpriHigh);
intent.putExtra("primed", NpriMed);
intent.putExtra("prilow", NpriLow);
intent.putExtra("timemore", NtimeMore);
intent.putExtra("timemed", NtimeMed);
intent.putExtra("timeless", NtimeLess);
intent.putExtra("subtaskname", subtname);
intent.putExtra("pri", pri);
intent.putExtra("time", time);
startActivity(intent);
}
if (working_minutes < without_break_minutes){
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
if (working_hours < without_break_hours){
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
if (working_hours == 0){
if (without_break_hours == 0)
{
if (working_minutes >= without_break_minutes){
int breaktime = Integer.parseInt(tvBreakTime.getText().toString());
Intent intent = new Intent(TaskInfo.this, TaskSummary.class);
intent.putExtra("working_hours", working_hours);
intent.putExtra("working_minutes", working_minutes);
intent.putExtra("without_break_hours", without_break_hours);
intent.putExtra("without_break_minutes", without_break_minutes);
intent.putExtra("break_duration", breaktime);
intent.putExtra("subtaskname", taskName);
intent.putExtra("prihigh", NpriHigh);
intent.putExtra("primed", NpriMed);
intent.putExtra("prilow", NpriLow);
intent.putExtra("timemore", NtimeMore);
intent.putExtra("timemed", NtimeMed);
intent.putExtra("timeless", NtimeLess);
startActivity(intent);
}
if (working_minutes < without_break_minutes){
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
if (without_break_hours != 0)
{
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
}
}
});
boolean delete = getIntent().getBooleanExtra("deleted", false);
if (delete){
}
}
}
}
}
The problem is that you're creating a new ArrayList while the adapter is left using the old one. That's why notifyDataSetChanged() doesn't work because the adapter's backing list has not changed.
To fix this, update the values list directly
public void addANewSubTask(SubtaskPartTwo newSubTask) {
this.values.add(newSubTask);
notifyDataSetChanged();
}
or, add() through the adapter itself.
public void addANewSubTask(SubtaskPartTwo newSubTask) {
add(newSubTask);
notifyDataSetChanged();
}
Even if I add one item, it shows 2 (both the same)
It seems you're adding the new element twice:
SubtaskPartTwo subtaskPartTwo = new SubtaskPartTwo(subtname, pri, time);
subtaskList.add(subtaskPartTwo);
adapter.addANewSubTask(subtaskPartTwo);
Just add via adapter only as it notifies as well. Check other places too for such duplicates.

unable to make proper ui like playstore

Hi i am developing an app where i have to make a ui like playtstore for that i saw this tutorial but now my problem is that i'm unable to add different
text for different rows and second is that even after setting height and width it doesnt seem to be get affected.
Please if someone can help me out here i'm stuck at this point
my code is as follows
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
int[] images = {R.drawable.vancouver,R.drawable.party,R.drawable.hands_ip,R.drawable.dj};
// Inflate the layout for this fragment
allSampleData = new ArrayList<SectionDataModel>();
createDummyData();
HorizontalAdapter firstAdapter = new HorizontalAdapter(images);
View view = inflater.inflate(R.layout.fragment_home, container, false);
NestedScrollView nestedScrollView = view.findViewById(R.id.scrollView);
llm = new LadderLayoutManager(1.5f, 0.85f, LadderLayoutManager.HORIZONTAL).
setChildDecorateHelper(new LadderLayoutManager
.DefaultChildDecorateHelper(getResources().getDimension(R.dimen.item_max_elevation)));
llm.setChildPeekSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
30, getResources().getDisplayMetrics()));
//llm.setReverse(true);
/*llm.setMaxItemLayoutCount(5);
rcv = (RecyclerView) view.findViewById(R.id.rcv);
rcv.setLayoutManager(llm);
new LadderSimpleSnapHelper().attachToRecyclerView(rcv);
adapter = new HSAdapter();
rcv.setAdapter(adapter);
multi_scroll_recyclerview = (RecyclerView)view.findViewById(R.id.multi_scroll_recyclerview);
multi_scroll_recyclerview.setNestedScrollingEnabled(false);
multi_scroll_layout_manager = new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false);
multi_scroll_recyclerview.setLayoutManager(multi_scroll_layout_manager);
multi_scroll_adapter = new RecyclerViewDataAdapter(getActivity(),allSampleData);
multi_scroll_recyclerview.setAdapter(multi_scroll_adapter);
multi_scroll_recyclerview.setHasFixedSize(true);*/
/* MultiSnapRecyclerView firstRecyclerView = (MultiSnapRecyclerView)view.findViewById(R.id.first_recycler_view);
LinearLayoutManager firstManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
firstRecyclerView.setLayoutManager(firstManager);
firstRecyclerView.setAdapter(firstAdapter);
HorizontalAdapter secondAdapter = new HorizontalAdapter(images);
MultiSnapRecyclerView secondRecyclerView =(MultiSnapRecyclerView) view.findViewById(R.id.second_recycler_view);
LinearLayoutManager secondManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
secondRecyclerView.setLayoutManager(secondManager);
secondRecyclerView.setAdapter(secondAdapter);
HorizontalAdapter thirdAdapter = new HorizontalAdapter(images);
MultiSnapRecyclerView thirdRecyclerView = (MultiSnapRecyclerView)view.findViewById(R.id.third_recycler_view);
LinearLayoutManager thirdManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
thirdRecyclerView.setLayoutManager(thirdManager);
thirdRecyclerView.setAdapter(thirdAdapter);*/
return view;
}
public void createDummyData() {
for (int i = 1; i <= 5; i++) {
SectionDataModel dm = new SectionDataModel();
dm.setHeaderTitle("Clubs");
dm.setHeadertitle2("Lounge");
dm.setHeadertitle3("Cafe");
dm.setHeadertitle4("Rooftop");
ArrayList<SingleItemModel> singleItem = new ArrayList<SingleItemModel>();
for (int j = 0; j <= 5; j++) {
singleItem.add(new SingleItemModel("Item " + j, "URL " + j));
}
dm.setAllItemsInSection(singleItem);
allSampleData.add(dm);//line which is causing issue
}
}
code for adapter
public class SectionListDataAdapter extends RecyclerView.Adapter<SectionListDataAdapter.SingleItemRowHolder> {
private ArrayList<SingleItemModel> itemsList;
private Context mContext;
public SectionListDataAdapter(Context context, ArrayList<SingleItemModel> itemsList) {
this.itemsList = itemsList;
this.mContext = context;
}
#Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_single_card, null);
SingleItemRowHolder mh = new SingleItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(SingleItemRowHolder holder, int i) {
SingleItemModel singleItem = itemsList.get(i);
holder.tvTitle.setText(singleItem.getName());
/* Glide.with(mContext)
.load(feedItem.getImageURL())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.error(R.drawable.bg)
.into(feedListRowHolder.thumbView);*/
}
#Override
public int getItemCount() {
return (null != itemsList ? itemsList.size() : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder {
protected TextView tvTitle;
protected ImageView itemImage;
public SingleItemRowHolder(View view) {
super(view);
this.tvTitle = (TextView) view.findViewById(R.id.tvTitle);
this.itemImage = (ImageView) view.findViewById(R.id.itemImage);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(v.getContext(), tvTitle.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
}
My code for model class
public class SectionDataModel {
private String headerTitle,headertitle2,headertitle3,headertitle4;
private ArrayList<SingleItemModel> allItemsInSection;
public SectionDataModel() {
}
public SectionDataModel(String headerTitle, ArrayList<SingleItemModel> allItemsInSection) {
this.headerTitle = headerTitle;
this.allItemsInSection = allItemsInSection;
}
public String getHeaderTitle() {
return headerTitle;
}
public String getHeadertitle2() {
return headertitle2;
}
public String getHeadertitle3() {
return headertitle3;
}
public String getHeadertitle4() {
return headertitle4;
}
public void setHeaderTitle(String headerTitle) {
this.headerTitle = headerTitle;
}
public void setHeadertitle2(String headertitle2) {
this.headertitle2 = headertitle2;
}
public void setHeadertitle3(String headertitle3) {
this.headertitle3 = headertitle3;
}
public void setHeadertitle4(String headertitle4) {
this.headertitle4 = headertitle4;
}
public ArrayList<SingleItemModel> getAllItemsInSection() {
return allItemsInSection;
}
public void setAllItemsInSection(ArrayList<SingleItemModel> allItemsInSection) {
this.allItemsInSection = allItemsInSection;
}
}
listitem.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:selectableItemBackground"
android:orientation="vertical"
android:padding="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<com.ct.listrtrial.Custom.CustomTextViewMedium
android:id="#+id/itemTitle"
android:layout_width="0dp"
android:layout_weight="8"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical"
android:layout_toLeftOf="#+id/btnMore"
android:text="Sample title"
android:textColor="#android:color/white"
android:textSize="27sp" />
<ImageView
android:id="#+id/btnMore"
android:layout_width="0dp"
android:layout_weight="0.8"
android:layout_marginTop="13dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="#drawable/ic_more_horiz_black_24dp"
android:textColor="#FFF" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view_list"
android:layout_width="match_parent"
android:layout_marginTop="10dp"
android:layout_height="160dp"
android:layout_gravity="center_vertical"
android:orientation="horizontal" />
</LinearLayout>
main fragment.xml
<android.support.v4.widget.NestedScrollView android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/scrollView"
android:fillViewport="true"
android:background="#color/colorPrimary"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/rcv"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:paddingBottom="10dp"
android:paddingTop="10dp" />
<android.support.v7.widget.RecyclerView
android:id="#+id/multi_scroll_recyclerview"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1">
</android.support.v7.widget.RecyclerView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
listsinglecard.xml
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="220dp"
android:layout_marginLeft="18dp"
android:layout_height="200dp"
app:cardCornerRadius="65dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:selectableItemBackground"
android:orientation="vertical">
<ImageView
android:id="#+id/itemImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:scaleType="centerCrop"
android:src="#drawable/vancouver" />
<TextView
android:id="#+id/tvTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/itemImage"
android:gravity="center"
android:padding="5dp"
android:visibility="gone"
android:text="Sample title"
android:textColor="#android:color/black"
android:textSize="18sp" />
</LinearLayout>
</android.support.v7.widget.CardView>

Recycler View and Card View not displaying cards

This is my Activity:
public String id;
public String passPhrase;
public ArrayList<SongCell> songs;
private RecyclerView recyclerView;
private MyAdapter myAdapter;
private RecyclerView.LayoutManager layoutManager;
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.songs_view_layout);
Context context = this.getApplicationContext();
Bundle stateData = getIntent().getExtras();
try
{
id = stateData.getString("id");
passPhrase = stateData.getString("passPhrase");
ArrayList data;
recyclerView = (RecyclerView) findViewById(R.id.song_list);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
data = new ArrayList<SongCell>();
for (int i=0; i<5;i++)
{
data.add(new SongCell("Song "+i,"Artist "+i, null));
}
myAdapter = new MyAdapter(data);
recyclerView.setAdapter(myAdapter);
}
catch(Exception e)
{
Log.d("Error: ", e.toString());
}
}
card.xml
<android.support.v7.widget.CardView android:layout_width="fill_parent"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="6dp"
>
<ImageView
android:layout_width="70dp"
android:layout_height="70dp"
android:id="#+id/song_photo"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginRight="16dp"
android:background="#drawable/error" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/song_name"
android:textSize="30sp"
android:text="Song Name"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textColor="#000000" />
<ImageButton
android:layout_width="60dp"
android:layout_height="60dp"
android:id="#+id/vote_button"
android:layout_alignParentRight="true"
android:layout_marginRight="8dp"
android:background="#drawable/arrow" />
</RelativeLayout>
</android.support.v7.widget.CardView>
Activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="#2d2d2d">
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:paddingBottom="30dp"
android:layout_marginBottom="10dp"
android:background="#222222"></TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:paddingBottom="10dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ImageView
android:layout_width="70dp"
android:layout_height="70dp"
android:id="#+id/featSongImage1"
android:contentDescription="#string/newsongimage"
android:background="#drawable/error" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/songname"
android:id="#+id/featSongName1" />
<ImageButton
android:layout_width="25dp"
android:layout_height="25dp"
android:id="#+id/featSongButt1"
android:background="#drawable/arrow"
android:contentDescription="#string/votearrow" />
</LinearLayout>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:foregroundGravity="fill_horizontal"
android:gravity="fill_horizontal|center">
<android.support.v7.widget.RecyclerView
android:id="#+id/song_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal" />
</TableRow>
</TableLayout>
</LinearLayout>
And this is my custom adapter
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>
{
private ArrayList<SongCell> data;
public MyAdapter(ArrayList<SongCell> dataI)
{
data = dataI;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType)
{
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.song_card,viewGroup,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewholder, int pos) {
viewholder.songName.setText(data.get(pos).getName());
viewholder.artist.setText(data.get(pos).getArtist());
viewholder.image.setImageBitmap(data.get(pos).getArtwork());
}
#Override
public int getItemCount() {
return 0;
}
#Override
public int getItemViewType(int position) {
return 0;
}
public class ViewHolder extends RecyclerView.ViewHolder
{
TextView songName;
TextView artist;
ImageView image;
ImageButton voteButton;
public ViewHolder(View v)
{
super(v);
this.songName = (TextView) v.findViewById(R.id.song_name);
this.image = (ImageView) v.findViewById(R.id.song_photo);
this.voteButton = (ImageButton) v.findViewById(R.id.vote_button);
}
}
}
I have looked at a ton of guides on how to get this working but it still doesn't work. Anyone have any clue what's going on? I'm on version 25.0.1, and have all the modules imported. But it's not adding a single card into the layout.
I thought it would be difficult to debug such a big code you uploaded. But luckily my eye went on this line
#Override
public int getItemCount() {
return 0;
}
return 0; in adapter.
Your list size is always 0.
instead write this
#Override
public int getItemCount() {
return data.size();
}
EDIT-1:
You will also get null pointer exception here
viewholder.artist.setText(data.get(pos).getArtist());
Because you are not initializing the artist variable in ViewHolder class.
Edit-2
#Override
public int getItemCount() {
return 0;
}
you can remove this particular code from your adapter. Because overriding the methods of class that we don't use might sometimes result in errors that you can't even imagine.

Custom ListView is not displayed

Following some tutorials, I managed to make a custom list.
But the whole screen is just a list
And now want to put the list below the form. And to make the whole screen make scroll along with the list (see the last item in the list, the form needs to rise)
The log (Toasty) says that the item was added, but nothing appears. I do not know if the problem is in how I add, or is the way I try to display
This is my layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:fillViewport="true"
android:padding="5dp" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/cliente" />
<EditText
android:id="#+id/venda_form_cliente"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:cursorVisible="false"
android:focusable="false"
android:hint="#string/selecione_um_cliente" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/produto" />
<EditText
android:id="#+id/venda_form_prod"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:cursorVisible="false"
android:focusable="false"
android:hint="#string/selecione_um_produto" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/quantidade" />
<EditText
android:id="#+id/venda_form_qtd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:selectAllOnFocus="true"
android:text="#string/um" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/valor" />
<EditText
android:id="#+id/venda_form_valor"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cursorVisible="false"
android:focusable="false"
android:inputType="none" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/desconto" />
<EditText
android:id="#+id/venda_form_desc"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:selectAllOnFocus="true"
android:text="#string/zero" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/subtotal" />
<EditText
android:id="#+id/venda_form_subtotal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cursorVisible="false"
android:focusable="false"
android:inputType="none" />
</LinearLayout>
</LinearLayout>
<Button
android:id="#+id/venda_form_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="10dp"
android:text="#string/adicionar" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:scrollbars="none" >
</ListView>
</LinearLayout>
</LinearLayout>
</LinearLayout>
And my activity
public class VendaFormActivity extends Activity {
private Cliente cliente;
// private Spinner condicaoSelect;
private Produto produto;
private TextWatcher somar;
private ItemVenda itemVenda;
private ListaAdapter listaAdapter;
private EditText inputQuantidade;
private EditText inputDesconto;
private EditText inputSubTotal;
private EditText inputProduto;
private EditText inputValor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_venda_form);
inputProduto = ((EditText) findViewById(R.id.venda_form_prod));
inputValor = ((EditText) findViewById(R.id.venda_form_valor));
((EditText) findViewById(R.id.venda_form_cliente)).setOnClickListener(new ClickListener(this, ClienteActivity.class, MainActivity.REQUEST_CLIENTE));
inputProduto.setOnClickListener(new ClickListener(this, ProdutoActivity.class, MainActivity.REQUEST_PRODUTO));
//condicaoSelect = (Spinner) findViewById(R.id.venda_form_condicao);
//new CondicaoHelper(this).popular(condicaoSelect);
bindCamposValores();
fazerLista();
bindBtnAdd();
}
private void limparCamposValores() {
inputDesconto.setText("0.00");
inputQuantidade.setText("1");
inputSubTotal.getText().clear();
inputProduto.getText().clear();
}
private void bindBtnAdd() {
((Button) findViewById(R.id.venda_form_btn)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try{
Double quantidade = Double.parseDouble( inputQuantidade.getText().toString() );
Double desconto = Double.parseDouble( inputDesconto.getText().toString() );
itemVenda = new ItemVenda();
itemVenda.setDesconto(desconto);
itemVenda.setProduto(produto);
itemVenda.setQuantidade(quantidade);
listaAdapter.setNotifyOnChange(true);
listaAdapter.getItens().add(itemVenda);
listaAdapter.notifyDataSetChanged();
Toast.makeText(getApplication(), "Foi", Toast.LENGTH_SHORT).show();
limparCamposValores();
} catch (Exception e) {
Toast.makeText(getApplication(), "Invalido", Toast.LENGTH_SHORT).show();
// NPE no produto
// NumberFormat nos valores
}
}
});
}
private void fazerLista() {
listaAdapter = new ListaAdapter(getApplicationContext());
((ListView) findViewById(android.R.id.list)).setAdapter(listaAdapter);
}
static class ViewHolder {
protected TextView descricao;
protected TextView codigo;
protected TextView ean;
protected TextView referencia;
protected TextView quantidade;
protected TextView valor_unit;
protected TextView valor_item;
}
private class ListaAdapter extends ArrayAdapter<ItemVenda>{
private final Context context;
private final List<ItemVenda> itens;
public ListaAdapter(Context context) {
super(context, R.layout.produto_list);
this.context = context;
this.itens = new LinkedList<ItemVenda>();
}
public ListaAdapter(Context context, List<ItemVenda> itens) {
super(context, R.layout.produto_list, itens);
this.context = context;
this.itens = itens;
}
public List<ItemVenda> getItens() {
return itens;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflator.inflate(R.layout.produto_list_item, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.descricao = (TextView) view.findViewById(R.id.descricao);
viewHolder.codigo = (TextView) view.findViewById(R.id.codigo);
viewHolder.ean = (TextView) view.findViewById(R.id.ean);
viewHolder.referencia = (TextView) view.findViewById(R.id.referencia);
viewHolder.quantidade = (TextView) view.findViewById(R.id.quantidade);
viewHolder.valor_unit = (TextView) view.findViewById(R.id.valor_unit);
viewHolder.valor_item = (TextView) view.findViewById(R.id.valor_item);
view.setTag(viewHolder);
} else {
view = convertView;
}
ViewHolder holder = (ViewHolder) view.getTag();
ItemVenda item = itens.get(position);
holder.descricao.setText(item.getProduto().getNome());
holder.codigo.setText(item.getProduto().getCodigo());
holder.ean.setText(item.getProduto().getEan());
holder.referencia.setText(item.getProduto().getReferencia());
holder.quantidade.setText(item.getQuantidade().toString());
holder.valor_unit.setText(item.getProduto().getPreco().toString());
holder.valor_item.setText(item.getSubTotal().toString());
return view;
}
}
private void bindCamposValores() {
inputQuantidade = ((EditText) findViewById(R.id.venda_form_qtd));
inputDesconto = ((EditText) findViewById(R.id.venda_form_desc));
inputSubTotal = ((EditText) findViewById(R.id.venda_form_subtotal));
somar = new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
#Override
public void afterTextChanged(Editable arg0) {
Double sub = 0.0;
try{
itemVenda = new ItemVenda();
itemVenda.setQuantidade(Double.parseDouble(inputQuantidade.getText().toString()));
itemVenda.setDesconto(Double.parseDouble(inputDesconto.getText().toString()));
itemVenda.setProduto(produto);
sub = itemVenda.getSubTotal();
} catch (Exception e) {
// algum campo não é numero/está vazio
}
inputSubTotal.setText(""+sub);
}
};
// Se mudar o valor
inputQuantidade.addTextChangedListener(somar);
inputDesconto.addTextChangedListener(somar);
// quando sair do campo
inputQuantidade.setOnFocusChangeListener(new Focus("1"));
inputDesconto.setOnFocusChangeListener(new Focus("0.00"));
}
private class Focus implements OnFocusChangeListener {
private final String padrao;
public Focus(String padrao){
this.padrao = padrao;
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus){
Editable text = ((EditText) v).getText();
if(null == text || "".equals(text.toString())){
text.append(padrao);
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_venda_form, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_copiar:
copiar();
return true;
case R.id.menu_simulacao:
simulacao();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void copiar() {
Toast.makeText(getApplication(), "Nada ainda", Toast.LENGTH_SHORT).show();
}
private void simulacao() {
Intent intent = new Intent(getApplicationContext(), SimulacaoPagtoActivity.class);
startActivityForResult(intent, MainActivity.REQUEST_SIMULACAO);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == MainActivity.REQUEST_CLIENTE) {
if (resultCode == RESULT_OK) {
cliente = (Cliente) intent.getSerializableExtra(MainActivity.RESULT_MODEL_LIST);
((EditText) findViewById(R.id.venda_form_cliente)).setText(cliente.getNome());
}
} else if (requestCode == MainActivity.REQUEST_PRODUTO) {
if (resultCode == RESULT_OK) {
produto = (Produto) intent.getSerializableExtra(MainActivity.RESULT_MODEL_LIST);
inputProduto.setText(produto.getNome());
inputValor.setText(""+produto.getPreco());
somar.afterTextChanged(null);
}
} else if(requestCode == MainActivity.REQUEST_SIMULACAO){
// o que fazer quando voltar da simulação ?
}
}
}
Finally, my item layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:orientation="vertical"
android:padding="5dp" >
<TextView
android:id="#+id/descricao"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#333"
android:textSize="16sp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/codigo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="CODIGO" />
<TextView
android:id="#+id/ean"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="EAN" />
<TextView
android:id="#+id/referencia"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="REFERENCIA" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/quantidade"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="QUANT." />
<TextView
android:id="#+id/valor_unit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="VLR UNIT" />
<TextView
android:id="#+id/valor_item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="VLR ITEM" />
</LinearLayout>
</LinearLayout>
UPDATE
When I add an item in the list, nothing is shown. But after I click a TextEdit, and the virtual keyboard up, after typing some value, I close the keyboard, then the adapter.getView () is called and the list appears
I think I found your problem. Shouldn't the following code:
((ListView) findViewById(android.R.id.list)).setAdapter(listaAdapter);
Be:
((ListView) findViewById(R.id.list)).setAdapter(listaAdapter);
instead?
You are trying to find a default Android view, rather than the view that you have created, which means that you are not actually setting the adapter for your ListView.
I am not sure about that, but if you want the list to be scrollable with the activity, you should use ScrollView, and then check if you scroll the list or the view itself. Try it
You can also try to see with debugger if the item was actually added to the list. I hope you will find an error.
Found the solution
1) The adapter have 2 constructors, but just 1 with List<ItemVenda> itens, and it isn't called.
I fixed it.
2) To add an item on the list, I need to call adapter.add() and not adapter.getItens().add()`. I think this trigger others methods.
3) Finally, to take the scroll list, and apply the scroll across the screen, I need to increase the size of the list. Then I override the method adapter.add(), and calculate the new height of the list, and add android:scrollbars="none" on ListView
Thanks to all, especially to #Marek

Categories

Resources