Unable to Modify TextView Inside Custom Adapter - java

ok, I have a custom adapter which will display exercise, time, and whether the exercise is selected or not. When the user clicks on the clock icon inside every element in the adapter a dialogbox will show up, in which the user can modify the time for exercise. Once the time is entered the arraylist containing objects of type exercise will be updated. so the exerciseTime for that exercise object inside the list will be updated. Then the list will be refresh and the new exercise time will be displayed. but that is not the case. I can get the time to be updated. when I first create the arraylist of exercises, which I get from string.xml resource file, the default exercise time is 30min. but after the user updates, is still reflecting the time. any help apprciated.
entry_item.xml for custom adapter
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/backroundColor">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="3dp"
android:layout_marginBottom="3dp">
<ImageView
android:id="#+id/item_icon_imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.10"
android:src="#drawable/ic_running_exercise"/>
<TextView
android:id="#+id/exercise_textview"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.40"
android:textSize="20sp"
android:textColor="#color/textColor"
android:text="Running"/>
<TextView
android:id="#+id/exercise_time_textview"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.20"
android:textSize="18sp"
android:textColor="#color/textColor"
android:text="30 min"/>
<ImageView
android:layout_gravity="center"
android:id="#+id/set_time_imagview"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.20"
android:src="#drawable/ic_timer_black_24dp"/>
<CheckBox
android:id="#+id/exercise_checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.05"
android:buttonTint="#color/textColor"/>
</LinearLayout>
</RelativeLayout>
custom adapter
public class WorkoutAdapter extends ArrayAdapter<Exercise> {
public WorkoutAdapter(Context context, int num, ArrayList<Exercise> exerciseList) {
super(context, 0, exerciseList);
// allExercises = exerciseList;
}
#NonNull
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// Get the data item for this position
final Exercise exercise = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.entry_item, parent, false);
}
// Lookup view for data population
ImageView exerciseImageview = convertView.findViewById(R.id.item_icon_imageview);
TextView exerciseNameTextview = convertView.findViewById(R.id.exercise_textview);
TextView exerTimeTextview = convertView.findViewById(R.id.exercise_time_textview);
final ImageView setTimeImageview = convertView.findViewById(R.id.set_time_imagview);
final CheckBox exerciseCheckbox = convertView.findViewById(R.id.exercise_checkBox);
exerciseNameTextview.setText(exercise.getExerciseName());
exerciseImageview.setImageResource(exercise.getExerciseImage());
//selected exercise checkbox
exerciseCheckbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(exerciseCheckbox.isChecked()) {
exercise.setSelected(true);
}
else {
exercise.setSelected(false);
}
}
});
setTimeImageview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setTimerDialogBox(position);
Toast.makeText(getContext(), position+"", Toast.LENGTH_LONG).show();
}
});
return convertView;
}
/**
* alert dialogbox for add new item to listview
*/
private void setTimerDialogBox(final int position) {
// Creating alert Dialog with one Button
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext(), R.style.dialogBox);
alertDialog.setTitle("Set Time");
final EditText input = new EditText(getContext());
alertDialog.setView(input);
alertDialog.setIcon(R.drawable.ic_timer_black_24dp1);
alertDialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
long time = Long.parseLong(input.getText().toString());
Workout.exerciseList.get(position).setExerciseTime(time);
notifyDataSetChanged();
Toast.makeText(getContext(),"Time added", Toast.LENGTH_SHORT).show();
}
}).create();
alertDialog.setNegativeButton("CANCEL",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).create();
alertDialog.show();
}
}

Related

Opening a dialog box inside adapter returning null values

I have been trying to get this to work without success for about 10 hours now, I have looked all over stack overflow. I am trying to get a simple dialog box to appear and handle some simple input.
It has a TextView as a title, EditText as a input field, and two button continue with the operation or cancel.
For some reason, no matter what I do, I cannot seem to be able to reference ANY view inside my shopping_dialogue xml layout. It gives me this error:
java.lang.NullPointerException: Attempt to invoke virtual method
'void android.widget.TextView.setText(java.lang.CharSequence)' on a
null object reference
I have tried to add an onClick event to the button to see if that works, when I try to reference the button inside the onClick method it gives me the same error. I am using a fragment to do this.
shopping_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/shoppingDialogTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Edit Shopping List Name" />
<EditText
android:id="#+id/shoppingDialogEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="30"
android:inputType="textPersonName"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="#+id/shoppingDialogOk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button" />
<Button
android:id="#+id/shoppingDialogCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="k"
android:text="Button" />
</LinearLayout>
shopping_list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
card_view:cardCornerRadius="4dp"
android:id="#+id/shoppingList_card_view"
android:layout_margin="10dp"
android:layout_height="200dp">
<LinearLayout
android:id="#+id/shoppingListParent"
android:layout_gravity="center"
android:layout_width="match_parent"
android:orientation="vertical"
android:gravity="center"
android:layout_height="match_parent">
<TextView
android:id="#+id/shoppingName"
android:layout_width="wrap_content"
android:gravity="center"
android:textSize="25sp"
android:textColor="#FFF"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/shoppingDate"
android:layout_width="wrap_content"
android:gravity="center"
android:textSize="25sp"
android:textColor="#FFF"
android:layout_height="wrap_content" />
</LinearLayout>
</androidx.cardview.widget.CardView>
fragment_shopping_list.xml
<?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">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/shoppingList_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
ShopingAdapter.java
public class ShoppingAdapter extends RecyclerView.Adapter<ShoppingAdapter.ShoppingViewHolder> {
private List<ShoppingData> shoppingList;
private Context context;
public ShoppingAdapter(List<ShoppingData> shoppingList, Context context){
this.shoppingList = shoppingList;
this.context = context;
}
#NonNull
#Override
public ShoppingViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i){
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.shopping_list_row, viewGroup, false);
return new ShoppingViewHolder(itemView);
}
#Override
public void onBindViewHolder(ShoppingViewHolder viewHolder, int i){
ShoppingData data = shoppingList.get(i);
Random k = new Random();
int color = Color.argb(255,k.nextInt(255),k.nextInt(255),k.nextInt(255));
viewHolder.parent.setBackgroundColor(color);
viewHolder.shoppingName.setText(data.getName());
viewHolder.shoppingDate.setText(data.getDate());
viewHolder.shoppingName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(v.getContext());
builder1.setCancelable(true);
builder1.setView(R.layout.shopping_dialog);
AlertDialog alert = builder1.create();
/*
EditText text = v.findViewById(R.id.shoppingDialogEditText);
text.setText("Some Text");
This causes a null object reference
*/
alert.show();
}
});
}
#Override
public int getItemCount(){return shoppingList.size();}
public class ShoppingViewHolder extends RecyclerView.ViewHolder{
private TextView shoppingName, shoppingDate;
private LinearLayout parent;
public ShoppingViewHolder(View itemView){
super(itemView);
parent = itemView.findViewById(R.id.shoppingListParent);
shoppingName = itemView.findViewById(R.id.shoppingName);
shoppingDate = itemView.findViewById(R.id.shoppingDate);
}
}
}
ShoppingFragment.java
public class ShoppingFragment extends Fragment {
private RecyclerView recyclerView;
private ShoppingAdapter shoppingAdapter;
private List<ShoppingData> shoppingList = new ArrayList<>();
#NonNull
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState){
shoppingList.add(new ShoppingData("k","12/12/12"));
shoppingList.add(new ShoppingData("k","12/12/12"));
shoppingList.add(new ShoppingData("k","12/12/12"));
shoppingList.add(new ShoppingData("k","12/12/12"));
shoppingList.add(new ShoppingData("k","12/12/12"));
shoppingList.add(new ShoppingData("k","12/12/12"));
View rootView = inflater.inflate(R.layout.fragment_shopping_list, container, false);
recyclerView = rootView.findViewById(R.id.shoppingList_recycler_view);
shoppingAdapter = new ShoppingAdapter(shoppingList, getActivity());
RecyclerView.LayoutManager manager = new GridLayoutManager(getActivity(), 2);
recyclerView.setLayoutManager(manager);
recyclerView.setAdapter(shoppingAdapter);
return rootView;
}
public void k(View view){ //the click listern that causes a null object reference when referencing the button
Button button = view.findViewById(R.id.shoppingDialogOk);
button.setText("k");
}
}
ShoppingData.java
package com.uhcl.recipe5nd.helperClasses;
public class ShoppingData {
private String name;
private String date;
public ShoppingData(String name, String date){
this.name = name;
this.date = date;
}
public String getDate(){
return this.date;
}
public String getName(){
return this.name;
}
}
Everything works fine until I try to reference anything inside shopping_dialog.xml.
If you look at my shopping adapter class, what I am trying to do is to add an onClick listener to the "shoppigName" text view inside my onBindViewHolder method. This works, but when I try to reference the shoppingDialogEditText, it causes the app the crash and give me that error.
Like I mentioned I also tried adding a click event method k to a button inside shopping_dialog.xml, and implemented it inside my fragment class to see if that would work, but it still causes the same error.
viewHolder.shoppingName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View dailogView = LayoutInflater.from(mContext).inflate(R.layout.shopping_dialog, null);
AlertDialog.Builder builder1 = new AlertDialog.Builder(v.getContext());
builder1.setCancelable(true);
builder1.setView(dailogView);
AlertDialog alert = builder1.create();
EditText text = dailogView.findViewById(R.id.shoppingDialogEditText);
text.setText("Some Text");
alert.show();
}
});
The view your using to the find the edittext is not the view of that dialog box, therefore it's throwing null pointer.
You are using a wrong view to find the editText. It is not the view of dialog box. It is the view of the item which is being clicked rather than dialog box.
Use this
viewHolder.shoppingName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View dailogView =
LayoutInflater.from(mContext).inflate(R.layout.shopping_dialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
builder.setCancelable(true);
builder.setView(dailogView);
AlertDialog alert = builder.create();
EditText text = dailogView.findViewById(R.id.shoppingDialogEditText);
text.setText("Shopping Dialog Text");
alert.show();
}
});
}

Android - ArrayAdapter toggle ImageButton src between Play and Pause in ListView

I am still learning android. Here I need help to toggle between Play and Pause source in ImageButton in the ListView.
There should be only one song in Play state at a time. So if clicked other should stop.
SongAdapter.java
public class SongAdapter extends ArrayAdapter<Song> {
public SongAdapter(#NonNull Context context, int resource, #NonNull List<Song> objects) {
super(context, resource, objects);
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View playlistItemView = convertView;
if (playlistItemView == null) {
playlistItemView = LayoutInflater.from(getContext()).inflate(R.layout.playlist_item, parent, false);
}
Song currentSong = getItem(position);
// get list item elements
ImageView albumCoverThumbnail = playlistItemView.findViewById(R.id.playlist_album_thumbnail);
TextView songTitle = playlistItemView.findViewById(R.id.playlist_song_title);
TextView songAlbumTitle = playlistItemView.findViewById(R.id.playlist_song_album_title);
TextView songArtist = playlistItemView.findViewById(R.id.playlist_song_artist);
final ImageButton songPlayButton = playlistItemView.findViewById(R.id.playlist_play_button);
// set data to the list item
assert currentSong != null;
albumCoverThumbnail.setImageResource(currentSong.getSongAlbumCoverId());
songTitle.setText(currentSong.getSongTitle());
songAlbumTitle.setText(currentSong.getSongAlbumTitle());
songArtist.setText(currentSong.getSongSingers());
// set song button action
songPlayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
songPlayButton.setImageResource(R.drawable.ic_pause_black_24dp);
Toast.makeText(getContext(), "Button clicked for item " + position, Toast.LENGTH_LONG).show();
}
});
return playlistItemView;
}
}
Song.java
public class Song {
private String songAlbumTitle;
private String songTitle;
private String songSingers;
private int songAlbumCoverId;
public Song(String albumTitle, String title, String singers, int albumCoverId) {
songAlbumTitle = albumTitle;
songTitle = title;
songSingers = singers;
songAlbumCoverId = albumCoverId;
}
public String getSongAlbumTitle() {
return songAlbumTitle;
}
public String getSongTitle() {
return songTitle;
}
public String getSongSingers() {
return songSingers;
}
public int getSongAlbumCoverId() {
return songAlbumCoverId;
}
}
Activity.java
public class DreamVoyage extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dream_voyage);
// get view ids
ImageView albumCoverImage = findViewById(R.id.album_cover);
// get intent extras
Bundle bundle = getIntent().getExtras();
// check if bundle in not null and containing value
if (bundle != null) {
String albumTitle = bundle.getString("album_one_title");
String albumBand = bundle.getString("album_one_band");
int albumCover = bundle.getInt("album_one_cover");
albumCoverImage.setImageResource(albumCover);
TextView albumTitleText = findViewById(R.id.album_title);
TextView albumBandText = findViewById(R.id.album_band);
albumTitleText.setText(albumTitle);
albumBandText.setText(albumBand);
ArrayList<Song> songs = new ArrayList<Song>();
songs.add(new Song(albumTitle, "I do it for you", "Bryn Adams", albumCover));
songs.add(new Song(albumTitle, "Here I am", "Bryn Adams", albumCover));
SongAdapter songAdapter = new SongAdapter(this, 0, songs);
ListView listView = findViewById(R.id.playlist_view);
listView.setAdapter(songAdapter);
}
}
}
playlist_item.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="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:background="#drawable/border_bottom"
android:orientation="horizontal">
<ImageView
android:id="#+id/playlist_album_thumbnail"
android:layout_width="32dp"
android:layout_height="32dp"
android:src="#drawable/album_three"
android:scaleType="centerCrop"
android:contentDescription="#string/album_thumbnail_desc"/>
<android.support.constraint.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:id="#+id/playlist_song_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Mon voyage de rĂªve"
android:layout_marginLeft="8dp"
android:textColor="#000000"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
<TextView
android:id="#+id/playlist_song_album_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dream Voyage"
android:textSize="10sp"
android:textColor="#666666"
app:layout_constraintTop_toBottomOf="#+id/playlist_song_title"
app:layout_constraintStart_toStartOf="#id/playlist_song_title"/>
<TextView
android:id="#+id/playlist_song_credit_separator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" - "
android:textSize="10sp"
android:textColor="#666666"
app:layout_constraintTop_toBottomOf="#+id/playlist_song_title"
app:layout_constraintStart_toEndOf="#id/playlist_song_album_title"/>
<TextView
android:id="#+id/playlist_song_artist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" - John Doen, Jane Doe"
android:textSize="10sp"
android:textColor="#666666"
app:layout_constraintTop_toBottomOf="#+id/playlist_song_title"
app:layout_constraintStart_toEndOf="#id/playlist_song_credit_separator"/>
</android.support.constraint.ConstraintLayout>
<ImageButton
android:id="#+id/playlist_play_button"
android:layout_width="24dp"
android:layout_height="24dp"
android:padding="0dp"
android:layout_gravity="center_vertical"
android:background="#00FFFFFF"
android:src="#drawable/ic_play_arrow_black_24dp"
android:scaleType="centerCrop"/>
</LinearLayout>
Use a variable to store current playing items index
SongAdapter {
int playingIndex = -1 //-1 means no song is playing
.
.
.
}
Set play/pause drawable based on playingIndex and set the playingIndex in the songPlayButton.setOnClickListener
public View getView(final int position, ...) {
if(playingIndex == position)
songPlayButton.setImageResource(R.drawable.ic_play_black_24dp);
else
songPlayButton.setImageResource(R.drawable.ic_pause_black_24dp);
songPlayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(position == playIndex)
playIndex = -1;
else
playIndex = position;
notifyDataSetChanged();
}
});
}
It should get the job done. But it forces a redraw of all rows. In RecyclerView there is the notifyItemChanged method which can force redraw on single item.
You may try using the method here to update single row https://stackoverflow.com/a/3727813/4907678
My suggestion is migrating to RecyclerView and using notifyItemChanged.
cheers!

Do not show again checkbox on a DialogFragment

So the title explains it all. I have a dialogfragment that currently pops up and I want to add a do not show checkbox to it and then obviously implement that check and not show if it was checked. I know there is a .setSingleChoiceItems, but I am not entirely sure on what would be going in there as it isn't really an item I would add somewhere. But then again I could probably be wrong as I am just getting into Android development.
Dialogfragment java
public class WifivsDataDialog extends DialogFragment {
#
Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_box)
.setPositiveButton(R.string.WiFi, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES!
}
})
.setNegativeButton(R.string.Cell_Data, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
Here is the code calling it in my MainActivity.java
WifivsDataDialog myDiag = new WifivsDataDialog();
myDiag.show(getFragmentManager(), "dialog_layout");
myDiag.setCancelable(false);
The accepted answer works, but it doesn't look like the normal material design system dialog, which is what I wanted.
Here's an option using a custom view layout to hold just the text and checkbox (with padding that matches material design), and allow the AlertDialog to manage the buttons.
no_location_dialog.xml layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="24dp"
android:paddingRight="12dp">
<TextView
android:id="#+id/no_location_text"
style="?android:attr/textAppearance"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="14dp"
android:paddingBottom="6dp"
android:text="#string/main_nolocation"
android:textSize="16sp"
android:autoLink="all"
android:linksClickable="true"></TextView>
<CheckBox
android:id="#+id/location_never_ask_again"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/main_never_ask_again" />
</LinearLayout>
And the code for setting up the AlertDialog:
private Dialog createNoLocationDialog() {
View view = getActivity().getLayoutInflater().inflate(R.layout.no_location_dialog, null);
CheckBox neverShowDialog = (CheckBox) view.findViewById(R.id.location_never_ask_again);
neverShowDialog.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
// Save the preference
PreferenceUtils.saveBoolean(getString(R.string.preference_key_never_show_location_dialog), isChecked);
}
});
Drawable icon = getResources().getDrawable(android.R.drawable.ic_dialog_map);
DrawableCompat.setTint(icon, getResources().getColor(R.color.theme_primary));
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
.setTitle(R.string.main_nolocation_title)
.setIcon(icon)
.setCancelable(false)
.setView(view)
.setPositiveButton(R.string.rt_yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivityForResult(
new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS),
REQUEST_NO_LOCATION);
}
}
)
.setNegativeButton(R.string.rt_no,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Ok, I suppose we can just try looking from where we
// are.
mMapFragment.mController.onLocation();
}
}
);
return builder.create();
}
It looks like this:
Here's the full code in a commit on Github - https://github.com/OneBusAway/onebusaway-android/commit/98135b66b0be5b73187e0148bef5d308c42a9fbe.
The DialogFragment class
public class WifivsDataDialog extends DialogFragment implements View.OnClickListener {
private CheckBox checkBox;
private Button button1;
private Button button2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View mainView = inflater.inflate(R.layout.wifi_dialog, container);
checkBox = (CheckBox) mainView.findViewById(R.id.checkBox);
button1 = (Button) mainView.findViewById(R.id.button1);
button2 = (Button) mainView.findViewById(R.id.button2);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
// Store the isChecked to Preference here
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("DONT_SHOW_DIALOG", isChecked);
editor.commit();
}
});
return mainView;
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
// Do wifi stuff here
break;
case R.id.button2:
// Do cellular stuff here
break;
}
}
}
The Layout xml wifi_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Some information to be displayed to human"
android:id="#+id/textView" android:textSize="30dp"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Do now show this dialog again."
android:id="#+id/checkBox"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" android:gravity="center">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="WiFi"
android:id="#+id/button1" android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CELL"
android:id="#+id/button2"/>
</LinearLayout>
</LinearLayout>
And on your Activity or where ever you display the dialog, check the preference set by user before displaying the dialog. Something like below.
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
boolean dontShowDialog = sharedPref.getBoolean("DONT_SHOW_DIALOG", false);
if (!dontShowDialog) {
new WifivsDataDialog().show(getFragmentManager(), "WiFi");
}

Uncheck CheckTextView from ListView so there are only two checked boxes at any time

I have a list view from which the user must choose two teams by checking the boxes and then validate by pressing the OK button. The problem is I want to make it so that there can only be two checked boxes at any time
Example :
if the user picks team 1 and 2 then the boxes for 1 and 2 should be checked but if the user then picks team 3, 1 should un-check automatically.
I've already managed to isolate and store the position of the box that needs to be unchecked but I don't know what to do with it.
Thanks!!
heres the listView
<Button
android:id="#+id/btnConfirm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ok"
/>
<ListView
android:id="#+id/listEquipe"
android:layout_below="#+id/btnConfirm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
and the following layout :
<?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="wrap_content"
android:orientation="horizontal"
>
<TextView
android:id="#+id/txtIdEquipe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"/>
<CheckedTextView
android:id="#+id/txtNomEquipe"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:padding="5dp"
android:textSize="12pt"
android:textColor="#000000"
/>
</LinearLayout>
This is one way to achieve it (I used stupid data in the adapter):
public class MainActivity extends AppCompatActivity {
private List<Integer> selectedItems = new ArrayList<>();
private String[] teams = new String[]{ "Team A", "Team B", "Team C"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView lv = (ListView) findViewById(R.id.listEquipe);
final BaseAdapter adapter = new BaseAdapter() {
#Override
public int getCount() {
return teams.length;
}
#Override
public Object getItem(int position) {
return teams[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = getLayoutInflater().inflate(R.layout.item, null);
((TextView) view.findViewById(R.id.txtIdEquipe)).setText((String) getItem(position));
CheckedTextView ctv = (CheckedTextView) view.findViewById(R.id.txtNomEquipe);
ctv.setChecked(selectedItems.contains(position));
return view;
}
};
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(selectedItems.contains(position)) {
selectedItems.remove(position);
}
else {
selectedItems.add(position);
if(selectedItems.size() > 2) {
selectedItems.remove(0);
}
}
adapter.notifyDataSetChanged();
}
});
}
}

RecyclerView Item Click Listener

I'm trying to replace a ListView with a RecyclerView. The click listeners I had set up for it look like this (this is from the Activity):
//Road Trip selection
roadTripList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
RoadTrip trip = trips.get(i);
Intent intent= new Intent(RoadTripListActivity.this, RoadTripActivity.class);
intent.putExtra("startLocation", trip.getStart());
intent.putExtra("endLocation", trip.getEnd());
intent.putExtra("routeType", trip.getType());
setResult(RoadTripActivity.ROADTRIP_LIST_INTENT_RESULT, intent);
finish();
overridePendingTransition(R.anim.in_right, R.anim.out_left);
}
});
//Road Trip deletion
roadTripList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int i, long l) {
new AlertDialog.Builder(RoadTripListActivity.this)
.setTitle("Delete this Road Trip?")
.setMessage("Are you sure you want to delete this road trip from your saved trips?")
.setCancelable(true)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
trips.remove(i);
tripStrings.remove(i);
tinyDB.putListString("roadtrips", tripStrings);
//roadTripList.setAdapter(adapter);
adapter.updateAdapter(trips);
}
}).setNegativeButton("Cancel", null)
.create().show();
return true;
}
});
Adapter looks like this:
public class RoadTripListAdapter extends RecyclerView.Adapter<RoadTripListAdapter.ViewHolder> {
protected ArrayList<RoadTrip> trips;
protected Context context;
public RoadTripListAdapter(Context context, ArrayList<RoadTrip> trips) {
this.context = context;
this.trips = trips;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private final TextView startTextView;
private final TextView endTextView;
private final ImageView imageView;
private final LinearLayout itemLayout;
public ViewHolder(View v) {
super(v);
startTextView = (TextView) v.findViewById(R.id.roadtrip_list_start);
endTextView = (TextView) v.findViewById(R.id.roadtrip_list_end);
imageView = (ImageView) v.findViewById(R.id.roadtrip_list_icon);
itemLayout = (LinearLayout) v.findViewById(R.id.roadtrip_list_item_layout);
}
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
//Get the corresponding step
final RoadTrip trip = trips.get(position);
holder.startTextView.setText(trip.getStart());
holder.endTextView.setText(trip.getEnd());
if (trip.getType().equals(SearchType.walking.name())) {
holder.imageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_directions_walk_24dp));
} else {
holder.imageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_directions_car_24dp));
}
}
#Override
public int getItemCount() {
return trips.size();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.road_trip_list_item, parent, false);
return new ViewHolder(v);
}
public void updateAdapter(ArrayList<RoadTrip> trips) {
this.trips = trips;
this.notifyDataSetChanged();
}
}
And the list item xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/roadtrip_list_item_layout"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/roadtrip_list_icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_gravity="center_vertical"
android:layout_margin="5dp"
android:src="#drawable/ic_directions_car_24dp"/>
<LinearLayout
android:layout_width="wrap_content"
android:orientation="vertical"
android:layout_height="wrap_content">
<TextView
android:id="#+id/roadtrip_list_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textColor="#color/black"
android:text="Start: "/>
<TextView
android:id="#+id/roadtrip_list_end"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textColor="#color/black"
android:text="End: "/>
</LinearLayout>
</LinearLayout>
How can I set up the equivalent for a RecyclerView? Everything I can find on the subject says to set it up inside the adapter, but that won't work in this case... Is there a way to set it up in the Activity?
In onBindViewHolder, add OnClickListener and OnLongClickListener like this :
itemLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RoadTrip trip = trips.get(position);
Intent intent= new Intent(RoadTripListActivity.this, RoadTripActivity.class);
intent.putExtra("startLocation", trip.getStart());
intent.putExtra("endLocation", trip.getEnd());
intent.putExtra("routeType", trip.getType());
setResult(RoadTripActivity.ROADTRIP_LIST_INTENT_RESULT, intent);
finish();
overridePendingTransition(R.anim.in_right, R.anim.out_left);
}
});
//Road Trip deletion
itemLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
new AlertDialog.Builder(RoadTripListActivity.this)
.setTitle("Delete this Road Trip?")
.setMessage("Are you sure you want to delete this road trip from your saved trips?")
.setCancelable(true)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
trips.remove(position);
tripStrings.remove(position);
tinyDB.putListString("roadtrips", tripStrings);
notifyItemRemoved(position);
notifyItemRangeChanged(position, trips.size());
}
}).setNegativeButton("Cancel", null)
.create().show();
return true;
}
});
I figured it out:
((Activity) context).setResult(RoadTripActivity.ROADTRIP_LIST_INTENT_RESULT, intent);
((Activity) context).finish();
((Activity) context).overridePendingTransition(R.anim.in_right, R.anim.out_left);
I had been using getApplicationContext to pass as the context for the adapter, so I changed it to
adapter = new RoadTripListAdapter(this, trips);
in the activity.
out_marginLeft="50dp"
android:layout_marginTop="50dp"
android:layout_marginRight="50dp"
android:gravity="center"
android:orientation="vertical">
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/txtProgress"
android:layout_centerHorizontal="true"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:progress="50"
android:progressTint="#android:color/black" />
<TextView
android:id="#+id/txtProgress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Progress"
android:textColor="#android:color/black" />
</LinearLayout>
Java

Categories

Resources