How to create a new card after taking input from dialog box - java

Basically on clicking a button a dialog box opens from which I am capturing information. Once I click on "Done" option present in the Dialog box, I want a new card to be created comprising of that information. I have implemented recycler view for achieving the above but for some reason it is not working. Could someone tell me what's wrong?
Here's the code of my Adapter
package com.example.android.teleconsultation_doctor;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class AdapterManageSlots extends RecyclerView.Adapter<AdapterManageSlots.ManageSlotsViewHolder> {
private ArrayList<CardViewManageSlots> mManageSlots;
public static class ManageSlotsViewHolder extends RecyclerView.ViewHolder{
public TextView mSlots, mTiming;
public ManageSlotsViewHolder(#NonNull View itemView) {
super(itemView);
mTiming = itemView.findViewById(R.id.textViewTimingValue);
mSlots = itemView.findViewById(R.id.textViewSlotValue);
}
}
public AdapterManageSlots(ArrayList<CardViewManageSlots> manageSlots){
mManageSlots = manageSlots;
}
#NonNull
#Override
public ManageSlotsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cardview_manage_slots, viewGroup, false);
ManageSlotsViewHolder evh = new ManageSlotsViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(#NonNull ManageSlotsViewHolder manageSlotsViewHolder, int i) {
CardViewManageSlots currentItem = mManageSlots.get(i);
manageSlotsViewHolder.mSlots.setText(currentItem.getSlot());
manageSlotsViewHolder.mTiming.setText(currentItem.getTiming());
}
#Override
public int getItemCount() {
return mManageSlots.size();
}
}
Here is the JAVA code of the activity
package com.example.android.teleconsultation_doctor;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
public class ManageSlots extends AppCompatActivity implements DatePickerDialog.OnDateSetListener, AdapterView.OnItemSelectedListener {
ImageView imageViewCalender;
TextView textViewDateValue;
String date, spinnerSlotValue, spinnerEndTimeValue, spinnerStartTimeValue;
Button buttonAddSlot;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_slots);
ArrayList<CardViewManageSlots> slotDetails = new ArrayList<>();
imageViewCalender = findViewById(R.id.imageViewCalander);
textViewDateValue = findViewById(R.id.textViewDateValue);
buttonAddSlot = findViewById(R.id.buttonAddSlot);
imageViewCalender.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDatePickerDialog();
}
});
buttonAddSlot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(ManageSlots.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_manage_slots, null);
Spinner mSpinnerSlots = mView.findViewById(R.id.spinnerSlots);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ManageSlots.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.slot_names));
adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
mSpinnerSlots.setAdapter(adapter);
spinnerSlotValue = mSpinnerSlots.getSelectedItem().toString();
Spinner mSpinnerStartTime = mView.findViewById(R.id.spinnerStartTime);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(ManageSlots.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.time));
adapter1.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
mSpinnerStartTime.setAdapter(adapter1);
spinnerStartTimeValue = mSpinnerStartTime.getSelectedItem().toString();
Spinner mSpinnerEndTime = mView.findViewById(R.id.spinnerEndTime);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(ManageSlots.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.time));
adapter2.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
mSpinnerEndTime.setAdapter(adapter2);
spinnerEndTimeValue = mSpinnerEndTime.getSelectedItem().toString();
mBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Toast.makeText(ManageSlots.this, "Slot Created!" + spinnerSlotValue + spinnerEndTimeValue + spinnerStartTimeValue, Toast.LENGTH_LONG).show();
dialogInterface.dismiss();
}
});
mBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
}
});
String finalTime = spinnerStartTimeValue + "-" + spinnerEndTimeValue;
Toast.makeText(this, finalTime, Toast.LENGTH_SHORT).show();
slotDetails.add(new CardViewManageSlots(spinnerSlotValue,finalTime));
//slotDetails.add(new CardViewManageSlots("Morning","diwwodmw"));
mRecyclerView = findViewById(R.id.recyclerViewSlots);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new AdapterManageSlots(slotDetails);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
private void showDatePickerDialog() {
DatePickerDialog datePickerDialog = new DatePickerDialog(
this,
this,
Calendar.getInstance().get(Calendar.YEAR),
Calendar.getInstance().get(Calendar.MONTH),
Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
);
datePickerDialog.show();
}
#Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
int i3=i1;
i3=i3+1;
date = i2 + "/" + i3 + "/" + i;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR,i);
cal.set(Calendar.MONTH,i1);
cal.set(Calendar.DAY_OF_MONTH,i2);
String selectedDate = DateFormat.getDateInstance().format(cal.getTime());
textViewDateValue.setText(selectedDate);
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
Here is the XML code of the activity
<?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"
tools:context=".ManageSlots">
<include
layout="#layout/toolbar_layout"
android:id="#+id/mytoolbar"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Date:"
android:id="#+id/textViewSelectDate"
android:layout_below="#id/mytoolbar"
android:layout_margin="10dp"
android:textSize="20dp"
android:textColor="#000"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageViewCalander"
android:src="#drawable/round_today_black_18dp_2x"
android:layout_toRightOf="#id/textViewSelectDate"
android:layout_below="#id/mytoolbar"
android:layout_marginTop="5dp"
android:clickable="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textViewDateValue"
android:layout_below="#id/imageViewCalander"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:textSize="20dp"
android:text="Aug 21, 2020"
android:textColor="#000"
/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/textViewDateValue"
android:id="#+id/recyclerViewSlots"
android:padding="4dp"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/buttonAddSlot"
android:text="Add Slot"
android:layout_alignParentBottom="true"
android:layout_margin="10dp"
android:background="#color/colorPrimaryDark"
android:textColor="#fff"/>
</RelativeLayout>

If I understand it correctly, you want something like this:
mBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
spinnerSlotValue = mSpinnerSlots.getSelectedItem().toString();
spinnerStartTimeValue = mSpinnerStartTime.getSelectedItem().toString();
spinnerEndTimeValue = mSpinnerEndTime.getSelectedItem().toString();
String finalTime = spinnerStartTimeValue + "-" + spinnerEndTimeValue;
slotDetails.add(new CardViewManageSlots(spinnerSlotValue,finalTime));
mAdapter.notifyDataSetChanged();
dialogInterface.dismiss();
}
});

Related

Having trouble converting an activity into a fragment. Activity contains a DialogueFragment

So I have to convert an activity into a fragment. I followed some basic principles however the app still crashes.
The converted activity code:
package com.example.computerscienceiawithtablayout;
import android.support.annotation.NonNull;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import java.io.File;
import java.util.*;
public class FragmentHome extends Fragment implements AddBookDialogue.AddBookDialogueListener{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onStart() {
super.onStart();
}
public void onBigButtonClick(View w) {
AddBookDialogue addBookDialogue = new AddBookDialogue();
addBookDialogue.show(getChildFragmentManager(), "add book dialogue");
}
#Override
public void getTexts(String bookAuthor, String bookTitle, String bookBarcode, String bookCourse, String selectedBookshelf) {
if(bookAuthor.isEmpty() || bookTitle.isEmpty() || bookBarcode.isEmpty() || bookCourse.isEmpty()){
Toast.makeText(getActivity(), "You didn't enter all necessary data", Toast.LENGTH_LONG).show();
}else{
if(bookBarcode.length()!=8){
Toast.makeText(getActivity(), "Barcodes should be eight digits long", Toast.LENGTH_LONG).show();
}else{ if(selectedBookshelf.equals("Withdrawn")){
Book a = new Book(bookAuthor, bookTitle, bookBarcode, bookCourse, selectedBookshelf);
Toast.makeText(getActivity(), a.toString(), Toast.LENGTH_LONG).show();
}else{
Book a = new Book(bookAuthor, bookTitle, bookBarcode, bookCourse, selectedBookshelf);
Toast.makeText(getActivity(), a.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
}
The fragment call upon an addBookDialogue, which is a dialoguefragment, code here:
package com.example.computerscienceiawithtablayout;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
public class AddBookDialogue extends AppCompatDialogFragment{
private EditText editTextBookAuthor;
private EditText editTextBookTitle;
private EditText editTextBookCourse;
private EditText editTextBookBarcode;
private Spinner spinnerBookshelf;
private AddBookDialogueListener listener;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getParentFragment().getActivity());
LayoutInflater inflater = getParentFragment().getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialogue_addbook, null);
builder.setView(view)
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String bookAuthor = editTextBookAuthor.getText().toString();
String bookTitle = editTextBookTitle.getText().toString();
String bookBarcode = editTextBookBarcode.getText().toString();
String bookCourse = editTextBookCourse.getText().toString();
String seletecBookshelf = spinnerBookshelf.getSelectedItem().toString();
listener.getTexts( bookAuthor, bookTitle, bookBarcode, bookCourse, seletecBookshelf);
}
});
editTextBookAuthor = view.findViewById(R.id.author);
editTextBookTitle= view.findViewById(R.id.bookTitle);
editTextBookBarcode= view.findViewById(R.id.bookBarcode);
editTextBookCourse= view.findViewById(R.id.bookBarcode);
spinnerBookshelf= view.findViewById(R.id.spinnerBookshelf);
ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.addBookBookshelfsAvailable, android.R.layout.simple_spinner_item);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerBookshelf.setAdapter(spinnerAdapter);
return builder.create();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
listener = (AddBookDialogueListener) context;
} catch(ClassCastException e){
throw new ClassCastException(context.toString() + "no listener");
}
}
public interface AddBookDialogueListener{
void getTexts(String bookAuthor, String bookTitle, String bookBarcode, String bookCourse, String selectedBookshelf);
}
}
I am huge newbie and basing some of this code on intuition. The major flaws that I can think of are calling the addBookDialogue with .show(getChildFragmentManager) and in AddBookDialogue file setting the builder to getParentFragment.getActivity This probably isn't the correct approach, but I am having difficulties understanding the interactions between fragments. The book object is a simple java class with a constructor and a few setters/getters
So yeah, idk where to problem is, all help appreciated :)
For more reference here is the xml file for the main activity
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FragmentHome">
<fragment
android:id="#+id/fragmentHome"
android:name="com.example.computerscienceiawithtablayout.FragmentHome"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
</android.support.constraint.ConstraintLayout>
and here is the xml for the fragment
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FragmentHome">
<Button
android:text="#string/Add"
android:textStyle="bold"
android:textColor="#ffffff"
android:background="#drawable/button_states"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:onClick="onBigButtonClick"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="480dp" app:layout_constraintStart_toStartOf="parent"
android:layout_marginStart="164dp" style="#style/Widget.AppCompat.Button"/>
</android.support.constraint.ConstraintLayout>

Can't Update Recyclerview adapter with new list,new list showing blank

I want to get new updated list in Favourite activity,but instead i'm getting no items in favourite list.List getting values from sharedpreference but not updating to recycler view.
DiseaseAdapter
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by admin on 12/4/2017.
*/
public class DiseaseAdapter extends RecyclerView.Adapter<DiseaseAdapter.DiseaseAdapterViewHolder> {
List <String> data;
Context ctx;
SharedPreference sharedPreference;
DiseaseAdapter(List <String> data, Context ctx){
this.data=data;
notifyDataSetChanged();
this.ctx=ctx;
sharedPreference = new SharedPreference();
}
#Override
public DiseaseAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater=LayoutInflater.from(parent.getContext());
View view= inflater.inflate(R.layout.activity_listview,parent,false);
return new DiseaseAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(DiseaseAdapterViewHolder holder, int position) {
final String title=data.get(position);
holder.textView1.setText(title);
if (checkFavoriteItem(title)) {
holder.imageButton.setImageResource(R.drawable.star_colour);
holder.imageButton.setTag("red");
} else {
holder.imageButton.setImageResource(R.drawable.ic_action_name);
holder.imageButton.setTag("grey");
}
}
#Override
public int getItemCount() {
return data.size();
}
class DiseaseAdapterViewHolder extends RecyclerView.ViewHolder {
TextView textView1;
ImageView imageButton;
public DiseaseAdapterViewHolder(View itemView) {
super(itemView);
textView1=(TextView) itemView.findViewById(R.id.textView);
imageButton=(ImageView)itemView.findViewById(R.id.imgbtn_favorite);
}
}
/*Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(String checkProduct) {
boolean check = false;
List<String> favorites = sharedPreference.getFavorites(ctx);
if (favorites != null) {
for (String product : favorites) {
if (product.equals(checkProduct)) {
check = true;
break;
}
}
}
return check;
}
}
MainActivity
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity{
RecyclerView simpleListView;
static Context ctx;
String diseaseList[];
SharedPreference sharedPreference;
DiseaseAdapter da;
List<String> newDiseaseList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ctx=this;
sharedPreference = new SharedPreference();
diseaseList= new String[]{"Abscess",
"Allergies",
"Amnesia",
"Anemia",
"Andropause",
"Angina",
"Weight Loss"};
Arrays.sort(diseaseList);
newDiseaseList = Arrays.asList(diseaseList);
simpleListView= (RecyclerView)findViewById(R.id.simpleListView);
LinearLayoutManager lm=new LinearLayoutManager(MainActivity.this);
simpleListView.setLayoutManager(lm);
/* DividerItemDecoration di=new DividerItemDecoration(MainActivity.this,lm.getOrientation());
simpleListView.addItemDecoration(di);*/
da=new DiseaseAdapter(newDiseaseList,ctx);
simpleListView.setAdapter(da);
simpleListView.setHasFixedSize(true);
simpleListView.addOnItemTouchListener(
new RecyclerItemClickListener(ctx, simpleListView ,new RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
ImageView button = (ImageView) view.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ctx, newDiseaseList.get(position));
Toast.makeText(ctx,
"add to favourites",
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_colour);
} else {
sharedPreference.removeFavorite(ctx, newDiseaseList.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_action_name);
Toast.makeText(ctx,
"removed from favourites",
Toast.LENGTH_SHORT).show();
}
}
#Override public void onLongItemClick(View view, int position) {
}
})
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_favorites:
Intent i=new Intent(this,Favourite.class);
this.startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
}
SharedPreference.java
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.google.gson.Gson;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
public SharedPreference() {
super();
}
// This four methods are used for maintaining favorites.
public void saveFavorites(Context context, List<String> favorites) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
public void addFavorite(Context context, String product) {
List<String> favorites = getFavorites(context);
if (favorites == null)
favorites = new ArrayList<String>();
favorites.add(product);
saveFavorites(context, favorites);
}
public void removeFavorite(Context context, String product) {
List<String> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(product);
saveFavorites(context, favorites);
}
}
public ArrayList<String> getFavorites(Context context) {
SharedPreferences settings;
List<String> favorites ;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
String [] favoriteItems = (gson.fromJson(jsonFavorites,String [].class));
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<String>(favorites);
} else
return null;
return (ArrayList<String>) favorites;
}
}
Favourite.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;
public class Favourite extends AppCompatActivity {
RecyclerView favoriteList;
SharedPreference sharedPreference;
List<String> favorites;
DiseaseAdapter diseaseAdapter;
Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourite);
ctx=this;
sharedPreference = new SharedPreference();
favorites = sharedPreference.getFavorites(ctx);
favoriteList = (RecyclerView)findViewById(R.id.favListView);
if (favorites == null) {
showAlert(getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
} else {
if (favorites.size() == 0) {
showAlert(
getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
}
if (favorites != null) {
diseaseAdapter = new DiseaseAdapter(favorites,ctx);
diseaseAdapter.notifyDataSetChanged();
favoriteList.setAdapter(diseaseAdapter);
favoriteList.invalidate();
favoriteList.addOnItemTouchListener(
new RecyclerItemClickListener(ctx, favoriteList ,new RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
ImageView button = (ImageView) view
.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ctx,
favorites.get(position));
Toast.makeText(
ctx,
ctx.getResources().getString(
R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_colour);
} else {
sharedPreference.removeFavorite(ctx,
favorites.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_action_name);
/* diseaseAdapter.remove(favorites
.get(position));*/
diseaseAdapter.notifyItemRemoved(position);
Toast.makeText(
ctx,
ctx.getResources().getString(
R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
}
#Override public void onLongItemClick(View view, int position) {
}
})
);
}
}
}
public void showAlert(String title, String message) {
if (ctx != null) {
AlertDialog alertDialog = new AlertDialog.Builder(ctx)
.create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
// setting OK Button
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// activity.finish();
getFragmentManager().popBackStackImmediate();
}
});
alertDialog.show();
}
}
}
activity_main.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"
tools:context="com.example.admin.fav.MainActivity">
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/simpleListView"
>
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
activity_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="20dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:textColor="#434b3e"
android:text=""/>
<ImageView
android:id="#+id/imgbtn_favorite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="3dp"
android:background="#null"
/>
</RelativeLayout>
activity_favourite.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"
tools:context="com.example.admin.fav.Favourite">
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/favListView"
>
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
You are missing setLayoutManager() in Favourite.java.
Try calling NotifyDataSetChanged() instead of NotifyItemRemoved() or NotifyItemAdded(). These methods did not work for me either. You just won't get the animations of items being added and removed but you can add your own animations to do the trick!
You should use Room Database to store lists and handle them as it is much easier and makes a lot of sense. SharedPreferences is recommended for storing values such as integers and booleans, not whole lists.

ListView/Adapter is not displaying the last item

this is a small application which asks some questions and then it will show answers. When we finish answering all the questions, new activity appears and shows us the all the answers except the last one. I searched this problem and saw answers but none of them is working in my case. Thanks for any kind of help.
This is my code:
XML code for the main layout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.itrio.iqtest.Result_QA"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Answers"
android:textSize="22sp"
android:textStyle="bold"
android:layout_margin="20dp"/>
<ListView
android:id="#+id/result_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
Another XML custom view.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:padding="10dp">
<TextView
android:id="#+id/question_result"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:textSize="18sp"
android:textStyle="bold">
</TextView>
<View
android:layout_width="match_parent"
android:layout_height="10dp"/>
<TextView
android:textStyle="italic"
android:id="#+id/answer_result"
android:layout_width="fill_parent"
android:textSize="18sp"
android:layout_marginBottom="10dp"
android:layout_height="wrap_content">
</TextView>
</LinearLayout>
Here's the code for questions:
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
public class Genius extends AppCompatActivity {
private TextView question_view;
private Button mNext;
int currentQ = 0;
RadioGroup genius_rg;
RadioButton op1, op2, op3, op4,checked;
private int score;
int turns=0;
boolean check= false, shuffle = true;
String[] questions = new String[8];
String[] answers = new String[8];
//Keys
private static final String Question_Index_key = "Index value of Questions";
private static final String Checked_Radio = "Selected radio Button";
private static final String Is_Radio_Checked = "ISC";
private static final String Do_Not_Shuffle_Again = "Dont' shuffle";
public static final String Result_Questions = "questions to display at result activity";
public static final String Result_Answers = "answers to display at result activity";
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(Question_Index_key,currentQ);
outState.putInt(Checked_Radio,genius_rg.getCheckedRadioButtonId());
outState.putBoolean(Is_Radio_Checked,check);
outState.putBoolean(Do_Not_Shuffle_Again, shuffle);
}
#Override
public void onBackPressed() {
super.onBackPressed();
Dialog alert_exit = new QuizExitAlert(Genius.this);
alert_exit.show();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Changes 'back' button action
if (keyCode == KeyEvent.KEYCODE_BACK) {
Dialog alert_exit = new QuizExitAlert(Genius.this);
alert_exit.show();
}
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_genius);
if (savedInstanceState != null) {
currentQ = savedInstanceState.getInt(Question_Index_key);
if (savedInstanceState.getBoolean(Is_Radio_Checked)) {
checked = (RadioButton) findViewById(savedInstanceState.getInt(Checked_Radio));
checked.setChecked(true);
}
shuffle = savedInstanceState.getBoolean(Do_Not_Shuffle_Again);
}
question_view = (TextView) findViewById(R.id.question_genius);
genius_rg = (RadioGroup) findViewById(R.id.radio_genius);
op1 = (RadioButton) findViewById(R.id.g_op1);
op2 = (RadioButton) findViewById(R.id.g_op2);
op3 = (RadioButton) findViewById(R.id.g_op3);
op4 = (RadioButton) findViewById(R.id.g_op4);
Collections.shuffle(bank);
question_view.setText(bank.get(currentQ).getQ());
op1.setText(bank.get(currentQ).getOp1());
op2.setText(bank.get(currentQ).getOp2());
op3.setText(bank.get(currentQ).getOp3());
op4.setText(bank.get(currentQ).getOp4());
mNext = (Button) findViewById(R.id.next_genius);
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
turns++;
if (turns >= 8) {
new AlertDialog.Builder(Genius.this)
.setTitle("Done!!!")
.setMessage("You have answered all the questions.")
.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent result = new Intent(Genius.this,Result_QA.class);
result.putExtra(Result_Questions, questions);
result.putExtra(Result_Answers, answers);
startActivity(result);
}
}).show();
}else {
if (op1.isChecked() || op2.isChecked() || op3.isChecked() || op4.isChecked()) {
checked = (RadioButton) findViewById(genius_rg.getCheckedRadioButtonId());
if (bank.get(currentQ).getAns() == checked.getText()) {
score += 10;
}
questions[currentQ] = bank.get(currentQ).getQ();
answers[currentQ] = bank.get(currentQ).getAns();
genius_rg.clearCheck();
currentQ++;
question_view.setText(bank.get(currentQ).getQ());
op1.setText(bank.get(currentQ).getOp1());
op2.setText(bank.get(currentQ).getOp2());
op3.setText(bank.get(currentQ).getOp3());
op4.setText(bank.get(currentQ).getOp4());
} else {
Toast.makeText(Genius.this, "Select an option to proceed", Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
Here's the code for LisView Activity:
import android.os.Bundle;
import android.app.Activity;
import android.widget.ListView;
public class Result_QA extends Activity {
ListView result;
ReslutListViewAdapter reslutListViewAdapter;
String[] ques, ans;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result__q);
Bundle b= getIntent().getExtras();
ques = b.getStringArray(new Genius().Result_Questions);
ans = b.getStringArray(new Genius().Result_Answers);
result = (ListView) findViewById(R.id.result_view);
reslutListViewAdapter = new ReslutListViewAdapter(this, ques, ans);
System.out.println("adapter => "+reslutListViewAdapter.getCount());
result.setAdapter(reslutListViewAdapter);
}
}
Code for ListViewAdapter class:
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class ReslutListViewAdapter extends BaseAdapter {
Activity context;
String[] questions;
String[] answers;
public ReslutListViewAdapter(Activity con, String[] ques, String[] ans){
super();
context = con;
questions = ques;
answers = ans;
}
#Override
public int getCount() {
return questions.length;
}
private class ViewHolder {
TextView mQ;
TextView mA;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null)
{
convertView = inflater.inflate(R.layout.result_listadapter, null);
holder = new ViewHolder();
holder.mQ = (TextView) convertView.findViewById(R.id.question_result);
holder.mA = (TextView) convertView.findViewById(R.id.answer_result);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.mQ.setText(questions[position]);
holder.mA.setText(answers[position]);
return convertView;
}
}
First of all listview is old one Recyclerview had came, which makes our work easier and lot more improvements have been done in RecyclerView to make developer work easier.
Coming to this issue, ListView doesn't support wrap_content. So change the height and width of ListView to match_parent. Then in adapter xml file the parent layout height should be wrap_content, but you have mentioned it as match_parent, so change that also to wrap_content. Hopefully, this should solve your problem. If the above solution didn't work, then try by removing the padding and margin in the adapter XML layout(from the parent layout in result_listadapter.xml file).
FYI fill_parent is deprecated and we are supposed to use match_parent instead of that. So avoid using the fill_parent.
Hope this helps:)

Android programming - ListView with button

I am creating this layout where a list of text is displayed with a "delete" button besides each item. I am not able to get the layout right i guess. Can i get some help on this?
Here is the layout file for the list view:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/locationList"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/delete"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FFFFFFFF"
android:text="Delete"
android:onClick="onClickDelete"/>
</ListView>
</RelativeLayout>
Here is the java code:
package com.android.ict.seneca.androidpocketguide;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class Websites extends Activity
implements AdapterView.OnItemClickListener{
private final String CLASS_NAME = "Websites";
DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy, HH:mm");
String date;
String location;
String name;
int counter;
List listName;
private SharedPreferences savedState;
private ListView listView;
private List<RowItem> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_websites);
listName= new ArrayList();
String app_name = "//sdcard//LocoLog.txt";
//int counter = 0, flag = 0;
String temp = "";
savedState = getSharedPreferences( "quantitySaved", MODE_PRIVATE );
rowItems = new ArrayList<RowItem>();
counter = savedState.getInt("counter", -1 );
if(counter!=-1)
{
for (int i = 1; i <= counter; i++)
{
String na;
String da;
String lo;
na = "name" + i;
da = "date" + i;
lo = "location" + i;
name = savedState.getString(na, "na" );
date = savedState.getString(da, "da" );
location = savedState.getString(lo, "lo" );
//Toast.makeText(this, "The data: "+name + " " + location + " " + date,Toast.LENGTH_LONG).show();
listName.add(new RowItem(name, location, date, counter));
}
}
else
{
Toast.makeText(this, "No locations saved yet",Toast.LENGTH_LONG).show();
}
listView = (ListView) findViewById(R.id.locationList);
listView.setAdapter( new CustomListAdapter(this, R.layout.list_item, listName ) );
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String cities = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(this, cities, Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(view.getContext(), SingleListItem.class);
myIntent.putExtra("product", cities);
startActivityForResult(myIntent, 0);
}
public void onClickDelete(View view)
{
//String cities = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(this, "delete ", Toast.LENGTH_LONG).show();
//rowItems.remove(position);
}
public void onClickAdd(View view)
{
Toast.makeText(this, "add ", Toast.LENGTH_LONG).show();
}
public void onStart() {
super.onStart();
Log.d(CLASS_NAME, "onStart invoked!");
}
public void onPause() {
super.onPause();
Log.d(CLASS_NAME, "onPause invoked!!");
}
public void onResume() {
super.onResume();
Log.d(CLASS_NAME, "onResume invoked!!");
}
public void onStop() {
super.onStop();
Log.d(CLASS_NAME, "onStop invoked!!!");
}
public void onDestroy() {
super.onDestroy();
Log.d(CLASS_NAME, "onDestroy INVOKED!!!");
}
public void onRestart() {
super.onRestart();
Log.d(CLASS_NAME, "onRestart invoked!!");
}
}
You cannot add Button like this in listview.Your button should be in separate layout.
mainLayout.xml
<ListView
android:id="#+id/locationList"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
and your listview items layout i.e button in your case
buttons.xml
<Button
android:id="#+id/delete"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FFFFFFFF"
android:text="Delete"
android:onClick="onClickDelete"/>
and then in your Activity
listview.setAdapter(YourAdapter());
and then in your adapter's getView method()
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolderItem viewHolder;
if(convertView==null){
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
convertView = inflater.inflate(R.layout.buttons, parent, false);
viewHolder = new ViewHolderItem();
viewHolder.button = convertView.findViewById(R.id.button);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolderItem) convertView.getTag();
}
viewHolder.button.setOnClickListener(new View.onClickListener(){
public void onClick(){
//handle your on click.
}
});
return convertView;
}
Viewholder class
static class ViewHolderItem{
private Button button;
}
Read this for further information http://www.androidhive.info/2011/10/android-listview-tutorial

EditText losing content after scrolling in RecyclerView

I'm having an issue that I have not been able to solve for a couple weeks now. I have an app that adds two EditTexts and one CheckBox on button click. However, whenever I type some content in the EditTexts, and then scroll down, the content disappears when I scroll back up. I cannot figure out a fix for this. I have found a few other very similar posts, however I have tried all solutions I can find, but none have seemed to do the trick for me yet. Here are a couple similar posts I found:
EditText loses content on scroll in ListView
Saving EditText content in RecyclerView
I've recently done some changes to my program in attempt to fix this as well. I added an ArrayList to my MainActivity and passed it to my adapter. I also made two custom text listeners in which onTextChanged, I add the string to the ArrayList. Then, in onBindViewHolder, I update the position in the text listeners, then set the text to the String in the ArrayList at that position. However, this is giving some strange errors. Now, when I add content to an EditText and scroll down, it adds it to multiple EditTexts, and even changes the content in some of them. I'm not sure how to go about fixing this.
Also, on another note, I have the app enabled for drag and drop and swipe to dismiss. So please take that into account as well if you have a solution. Thank you!
MainActivity
import android.content.ClipData;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ArrayList<ListItems> itemsList;
private RecyclerView mRecyclerView;
private MyRecyclerAdapter adapter;
private List<String> courseStrings = new ArrayList<>();
private List<String> creditStrings = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
courseStrings.add("");
creditStrings.add("");
// Toast variable in order to fix toast queueing issue.
final Toast toast = Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT);
// For the recycler view.
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
itemsList = new ArrayList<>();
adapter = new MyRecyclerAdapter(MainActivity.this, itemsList, courseStrings, creditStrings);
mRecyclerView.setAdapter(adapter);
mRecyclerView.setLayoutManager(linearLayoutManager);
// For the addCourse button.
final Button addCourse = (Button) findViewById(R.id.addCourse);
addCourse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adapter.createListItem(new ListItems(null, null, false), toast);
toast.setText("New course added");
toast.show();
}
});
final Button clearAll = (Button) findViewById(R.id.clearAll);
clearAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// In order to clear the list.
if (itemsList.size() == 0) {
toast.setText("All courses have already been cleared.");
toast.show();
} else {
adapter.clearAdapter();
toast.setText("All courses have been cleared.");
toast.show();
}
}
});
// For the drag and drop/swipe to dismiss.
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(
new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN,
ItemTouchHelper.LEFT) {
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
final int fromPos = viewHolder.getAdapterPosition();
final int toPos = target.getAdapterPosition();
Collections.swap(itemsList, fromPos, toPos);
adapter.notifyItemMoved(fromPos, toPos);
return true;
}
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
adapter.onItemDismiss(viewHolder.getAdapterPosition());
}
});
itemTouchHelper.attachToRecyclerView(mRecyclerView);
} // End of onCreate
} // End of MainActivity
MyRecyclerAdapter
import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.view.LayoutInflater;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.CustomRowViewHolder> {
private ArrayList<ListItems> itemsList;
private Context mContext;
private List<String> courseStrings;
private List<String> creditStrings;
public MyRecyclerAdapter(Context context, ArrayList<ListItems> itemsList, List<String> courseStrings, List<String> creditStrings){
this.itemsList = itemsList;
this.mContext = context;
this.courseStrings = courseStrings;
this.creditStrings = creditStrings;
}
#Override
public MyRecyclerAdapter.CustomRowViewHolder onCreateViewHolder(final ViewGroup viewGroup, int position) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.new_course_row, null);
final CustomRowViewHolder holder = new CustomRowViewHolder(v, new CoursesCustomTextListener(), new CreditsCustomTextListener());
holder.creditsText.setInputType(InputType.TYPE_CLASS_NUMBER);
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(holder.checkBox.isChecked()) {
holder.courseText.setEnabled(false);
holder.courseText.setFocusable(false);
holder.courseText.setInputType(InputType.TYPE_NULL);
holder.creditsText.setEnabled(false);
holder.creditsText.setFocusable(false);
holder.creditsText.setInputType(InputType.TYPE_NULL);
} else {
holder.courseText.setEnabled(true);
holder.courseText.setFocusable(true);
holder.courseText.setFocusableInTouchMode(true);
holder.courseText.setInputType(InputType.TYPE_CLASS_TEXT);
holder.creditsText.setEnabled(true);
holder.creditsText.setFocusable(true);
holder.creditsText.setFocusableInTouchMode(true);
holder.creditsText.setInputType(InputType.TYPE_CLASS_NUMBER);
} // End if else
}
});
return holder;
} // End of onCreateViewHolder
#Override
public void onBindViewHolder(CustomRowViewHolder holder, final int position) {
ListItems listItem = itemsList.get(position);
int focusedItem = 0;
holder.itemView.setSelected(focusedItem == position);
holder.getLayoutPosition();
holder.creditsCustomTextListener.updatePosition(position);
holder.creditsCustomTextListener.updatePosition(position);
holder.courseText.setText(courseStrings.get(position));
holder.creditsText.setText(creditStrings.get(position));
// Set listener to check box.
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
itemsList.get(position).setIsComplete(b);
}
});
holder.checkBox.setChecked( itemsList.get(position).getIsComplete());
} // End of onBindViewHolder
public void clearAdapter() {
itemsList.clear();
notifyDataSetChanged();
} // End of clearAdapter
public int getItemCount() {
return(null != itemsList ? itemsList.size() : 0);
} // End of getItemCount
public void onItemDismiss(int position) {
itemsList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, itemsList.size());
} // End of onItemDismiss
public void createListItem(ListItems listItem, Toast toast) {
itemsList.add(listItem);
int position = itemsList.indexOf(listItem);
notifyItemInserted(position);
} // End of createListItem
///////////////////////////////////// CustomRowViewHolder /////////////////////////////////////
public static class CustomRowViewHolder extends RecyclerView.ViewHolder {
public EditText courseText;
public EditText creditsText;
public CheckBox checkBox;
public RelativeLayout relativeLayout;
public CoursesCustomTextListener coursesCustomTextListener;
public CreditsCustomTextListener creditsCustomTextListener;
public CustomRowViewHolder(View view, CoursesCustomTextListener coursesCustomTextListener, CreditsCustomTextListener creditsCustomTextListener) {
super(view);
this.coursesCustomTextListener = coursesCustomTextListener;
this.creditsCustomTextListener = creditsCustomTextListener;
this.courseText = (EditText) view.findViewById(R.id.course);
this.creditsText = (EditText) view.findViewById(R.id.credits);
this.checkBox = (CheckBox) view.findViewById(R.id.complete);
this.relativeLayout = (RelativeLayout) view.findViewById(R.id.relLayout);
this.courseText.addTextChangedListener(coursesCustomTextListener);
this.creditsText.addTextChangedListener(creditsCustomTextListener);
}
}
////////////////////////////////// CoursesCustomTextListener //////////////////////////////////
private class CoursesCustomTextListener implements TextWatcher {
private int position;
public void updatePosition(int position) {
this.position = position;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// No operation to perform.
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
courseStrings.add(s.toString());
}
#Override
public void afterTextChanged(Editable s) {
// No operation to perform.
}
}
////////////////////////////////// CreditsCustomTextListener //////////////////////////////////
private class CreditsCustomTextListener implements TextWatcher {
private int position;
public void updatePosition(int position) {
this.position = position;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// No operation to perform.
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
creditStrings.add(s.toString());
}
#Override
public void afterTextChanged(Editable s) {
// No operation to perform.
}
}
} // End of MyRecyclerAdapter
ListItems
import java.util.ArrayList;
public class ListItems {
private String course;
private String credits;
private Boolean complete;
public ListItems(String mCourse, String mCredits, Boolean mComplete) {
course = mCourse;
credits = mCredits;
complete = mComplete;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public String getCredits() {
return credits;
}
public void setCredits(String credits) {
this.credits = credits;
}
public Boolean getIsComplete() {
return complete;
}
public void setIsComplete(Boolean complete) {
this.complete = complete;
}
} // End of ListItems
new_course_row.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="wrap_content"
android:id="#+id/relLayout"
android:layout_margin="5dp">
<EditText
android:layout_width="130dp"
android:layout_height="wrap_content"
android:id="#+id/course"
android:hint="Enter Course ID"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="16sp"
android:maxLines="1" />
<EditText
android:layout_width="115dp"
android:layout_height="wrap_content"
android:id="#+id/credits"
android:hint="Enter Credits"
android:layout_alignBottom="#+id/course"
android:textSize="16sp"
android:layout_toRightOf="#+id/course"
android:maxLines="1" />
<CheckBox
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Check if complete"
android:id="#+id/complete"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignBottom="#+id/course"
android:textSize="13sp"
android:paddingBottom="4dp"
android:paddingTop="4dp" />
</RelativeLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingRight="10dp"
android:paddingLeft="10dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:id="#+id/rl"
tools:context=".MainActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Course"
android:id="#+id/addCourse"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:textColor="#FFF"
android:background="#drawable/my_button"
android:textSize="18dp"
android:paddingRight="5dp"
android:paddingLeft="5dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear All"
android:id="#+id/clearAll"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:textColor="#FFF"
android:background="#drawable/my_button"
android:textSize="18dp"
android:paddingRight="5dp"
android:paddingLeft="5dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"/>
<android.support.v7.widget.RecyclerView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/recycler_view"
android:layout_below="#+id/addCourse"
android:layout_marginTop="10dp"
/>
</RelativeLayout>
Thank you in advance for any help! I could REALLY use a solution!
EDIT: I've noticed now that, say I enter "aaaaaaa" in the first EditText, then it will add "a" to an EditText further down the list, then "aa" to the EditText after that one, then "aaa", "aaaa", until it reaches "aaaaaaa". Then there will be a few empty EditText's, and then it will start it over again. Here is a visual:
EDIT x2: Haven't worked on this in a while, and haven't been getting any answers. Even got the "Tumbleweed" badge for this post! Anyone have any ideas?
Though I am not quite sure but I believe this is happening because recycler view regenerates its positons . For your custom edit text you are adding the string ` #Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
courseStrings.add(s.toString());
}
for both edit texts.
In recyler view you have implemented this.courseText.addTextChangedListener(coursesCustomTextListener);
so everytime you scroll the onBind Method is called and as the position changes this must be getting called too. Hence it must be regenerating . I request you to first try
holder.courseText.setTag(position);
in onBindViewHolder().
Try it for both texts individually.If it does work then try
holder.view.setTag(position);

Categories

Resources