I'm trying to call my alertdialog from another class in same file. Where do i have wrong here? Just trying to extends the AlertDialog, but i'm not sure how to do this, i don't want to be in my public main class, trying that and work but i need to be in separable class if this is possible.
class MyDialog extends AlertDialog {
public static Context context;
public static int theme;
protected MyDialog(Context context, int theme) {
super(context, theme);
MyDialog.context = context;
theme = THEME_HOLO_DARK;
MyDialog.theme = theme;
}
public void onCreateAlertDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Auto Start")
.setMessage("Start playing after: 30 sec")
.setIcon(R.drawable.info)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(context, "Auto start cancaled!", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
}
);
alertDialog.show();
}
}
I call it from main class like this:
Context context = MyDialog.context;
int i = MyDialog.theme;
MyDialog md = new MyDialog(context, i);
md.onCreateAlertDialog();
I think that it comes from the context variable that you didn't initialize it.
You should get it from the activity your are calling the dialog from :
class MyActivity extends Activity{
...
Context context = this;
MyDialog md = new MyDialog(context, i);
...
}
You are using AlertDialog.Builder which will always return an instance of the AlertDialog class when you build it. You would have to override the static builder to return an instance of your class but this is not really possible.
What you want to do is extend the Dialog class and create your own AlertDialog implementation as demonstrated in the HoloEverywhere library.
https://github.com/ChristopheVersieux/HoloEverywhere/blob/master/library/src/com/WazaBe/HoloEverywhere/app/AlertDialog.java
public class AlertDialog extends Dialog implements DialogInterface {
public static class Builder {
private final AlertController.AlertParams P;
public Builder(Context context) {
this(context, resolveDialogTheme(context, 0));
}
public Builder(Context context, int theme) {
P = new AlertController.AlertParams(new ContextThemeWrapper(
context, resolveDialogTheme(context, theme)));
P.mTheme = theme;
}
public AlertDialog create() {
final AlertDialog dialog = new AlertDialog(P.mContext, P.mTheme);
P.apply(dialog.mAlert);
dialog.setCancelable(P.mCancelable);
if (P.mCancelable) {
dialog.setCanceledOnTouchOutside(true);
}
dialog.setOnCancelListener(P.mOnCancelListener);
if (P.mOnKeyListener != null) {
dialog.setOnKeyListener(P.mOnKeyListener);
}
return dialog;
}
public Context getContext() {
return P.mContext;
}
public Builder setAdapter(final ListAdapter adapter,
final OnClickListener listener) {
P.mAdapter = adapter;
P.mOnClickListener = listener;
return this;
}
public Builder setCancelable(boolean cancelable) {
P.mCancelable = cancelable;
return this;
}
public Builder setCheckedItem(int checkedItem) {
P.mCheckedItem = checkedItem;
return this;
}
public Builder setCursor(final Cursor cursor,
final OnClickListener listener, String labelColumn) {
P.mCursor = cursor;
P.mLabelColumn = labelColumn;
P.mOnClickListener = listener;
return this;
}
public Builder setCustomTitle(View customTitleView) {
P.mCustomTitleView = customTitleView;
return this;
}
public Builder setIcon(Drawable icon) {
P.mIcon = icon;
return this;
}
public Builder setIcon(int iconId) {
P.mIconId = iconId;
return this;
}
public Builder setIconAttribute(int attrId) {
TypedValue out = new TypedValue();
P.mContext.getTheme().resolveAttribute(attrId, out, true);
P.mIconId = out.resourceId;
return this;
}
public Builder setInverseBackgroundForced(boolean useInverseBackground) {
P.mForceInverseBackground = useInverseBackground;
return this;
}
public Builder setItems(CharSequence[] items,
final OnClickListener listener) {
P.mItems = items;
P.mOnClickListener = listener;
return this;
}
public Builder setItems(int itemsId, final OnClickListener listener) {
P.mItems = P.mContext.getResources().getTextArray(itemsId);
P.mOnClickListener = listener;
return this;
}
public Builder setMessage(CharSequence message) {
P.mMessage = message;
return this;
}
public Builder setMessage(int messageId) {
P.mMessage = P.mContext.getText(messageId);
return this;
}
public Builder setMultiChoiceItems(CharSequence[] items,
boolean[] checkedItems,
final OnMultiChoiceClickListener listener) {
P.mItems = items;
P.mOnCheckboxClickListener = listener;
P.mCheckedItems = checkedItems;
P.mIsMultiChoice = true;
return this;
}
public Builder setMultiChoiceItems(Cursor cursor,
String isCheckedColumn, String labelColumn,
final OnMultiChoiceClickListener listener) {
P.mCursor = cursor;
P.mOnCheckboxClickListener = listener;
P.mIsCheckedColumn = isCheckedColumn;
P.mLabelColumn = labelColumn;
P.mIsMultiChoice = true;
return this;
}
public Builder setMultiChoiceItems(int itemsId, boolean[] checkedItems,
final OnMultiChoiceClickListener listener) {
P.mItems = P.mContext.getResources().getTextArray(itemsId);
P.mOnCheckboxClickListener = listener;
P.mCheckedItems = checkedItems;
P.mIsMultiChoice = true;
return this;
}
public Builder setNegativeButton(CharSequence text,
final OnClickListener listener) {
P.mNegativeButtonText = text;
P.mNegativeButtonListener = listener;
return this;
}
public Builder setNegativeButton(int textId,
final OnClickListener listener) {
P.mNegativeButtonText = P.mContext.getText(textId);
P.mNegativeButtonListener = listener;
return this;
}
public Builder setNeutralButton(CharSequence text,
final OnClickListener listener) {
P.mNeutralButtonText = text;
P.mNeutralButtonListener = listener;
return this;
}
public Builder setNeutralButton(int textId,
final OnClickListener listener) {
P.mNeutralButtonText = P.mContext.getText(textId);
P.mNeutralButtonListener = listener;
return this;
}
public Builder setOnCancelListener(OnCancelListener onCancelListener) {
P.mOnCancelListener = onCancelListener;
return this;
}
public Builder setOnItemSelectedListener(
final AdapterView.OnItemSelectedListener listener) {
P.mOnItemSelectedListener = listener;
return this;
}
public Builder setOnKeyListener(OnKeyListener onKeyListener) {
P.mOnKeyListener = onKeyListener;
return this;
}
public Builder setOnPrepareListViewListener(
OnPrepareListViewListener listener) {
P.mOnPrepareListViewListener = listener;
return this;
}
public Builder setPositiveButton(CharSequence text,
final OnClickListener listener) {
P.mPositiveButtonText = text;
P.mPositiveButtonListener = listener;
return this;
}
public Builder setPositiveButton(int textId,
final OnClickListener listener) {
P.mPositiveButtonText = P.mContext.getText(textId);
P.mPositiveButtonListener = listener;
return this;
}
public Builder setRecycleOnMeasureEnabled(boolean enabled) {
P.mRecycleOnMeasure = enabled;
return this;
}
public Builder setSingleChoiceItems(CharSequence[] items,
int checkedItem, final OnClickListener listener) {
P.mItems = items;
P.mOnClickListener = listener;
P.mCheckedItem = checkedItem;
P.mIsSingleChoice = true;
return this;
}
public Builder setSingleChoiceItems(Cursor cursor, int checkedItem,
String labelColumn, final OnClickListener listener) {
P.mCursor = cursor;
P.mOnClickListener = listener;
P.mCheckedItem = checkedItem;
P.mLabelColumn = labelColumn;
P.mIsSingleChoice = true;
return this;
}
public Builder setSingleChoiceItems(int itemsId, int checkedItem,
final OnClickListener listener) {
P.mItems = P.mContext.getResources().getTextArray(itemsId);
P.mOnClickListener = listener;
P.mCheckedItem = checkedItem;
P.mIsSingleChoice = true;
return this;
}
public Builder setSingleChoiceItems(ListAdapter adapter,
int checkedItem, final OnClickListener listener) {
P.mAdapter = adapter;
P.mOnClickListener = listener;
P.mCheckedItem = checkedItem;
P.mIsSingleChoice = true;
return this;
}
public Builder setTitle(CharSequence title) {
P.mTitle = title;
return this;
}
public Builder setTitle(int titleId) {
P.mTitle = P.mContext.getText(titleId);
return this;
}
public Builder setView(View view) {
P.mView = view;
P.mViewSpacingSpecified = false;
return this;
}
public Builder setView(View view, int viewSpacingLeft,
int viewSpacingTop, int viewSpacingRight, int viewSpacingBottom) {
P.mView = view;
P.mViewSpacingSpecified = true;
P.mViewSpacingLeft = viewSpacingLeft;
P.mViewSpacingTop = viewSpacingTop;
P.mViewSpacingRight = viewSpacingRight;
P.mViewSpacingBottom = viewSpacingBottom;
return this;
}
public AlertDialog show() {
AlertDialog dialog = create();
dialog.show();
return dialog;
}
}
public static final int THEME_HOLO_DARK = 1;
public static final int THEME_HOLO_LIGHT = 2;
static int resolveDialogTheme(Context context, int resid) {
if (resid == THEME_HOLO_DARK) {
return R.style.Holo_Theme_Dialog_Alert;
} else if (resid == THEME_HOLO_LIGHT) {
return R.style.Holo_Theme_Dialog_Alert_Light;
} else if (resid >= 0x01000000) {
return resid;
} else {
TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(R.attr.alertDialogTheme,
outValue, true);
return outValue.resourceId;
}
}
private final AlertController mAlert;
protected AlertDialog(Context context) {
this(context, false, null, resolveDialogTheme(context, 0));
}
protected AlertDialog(Context context, boolean cancelable,
OnCancelListener cancelListener) {
this(context, cancelable, cancelListener,
resolveDialogTheme(context, 0));
}
protected AlertDialog(Context context, boolean cancelable,
OnCancelListener cancelListener, int theme) {
super(context, resolveDialogTheme(context, theme));
setCancelable(cancelable);
setOnCancelListener(cancelListener);
mAlert = new AlertController(context, this, getWindow());
}
protected AlertDialog(Context context, int theme) {
this(context, false, null, theme);
}
public Button getButton(int whichButton) {
return mAlert.getButton(whichButton);
}
public ListView getListView() {
return mAlert.getListView();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAlert.installContent();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mAlert.onKeyDown(keyCode, event)) {
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (mAlert.onKeyUp(keyCode, event)) {
return true;
}
return super.onKeyUp(keyCode, event);
}
#Deprecated
public void setButton(CharSequence text, Message msg) {
setButton(BUTTON_POSITIVE, text, msg);
}
#Deprecated
public void setButton(CharSequence text, final OnClickListener listener) {
setButton(BUTTON_POSITIVE, text, listener);
}
public void setButton(int whichButton, CharSequence text, Message msg) {
mAlert.setButton(whichButton, text, null, msg);
}
public void setButton(int whichButton, CharSequence text,
OnClickListener listener) {
mAlert.setButton(whichButton, text, listener, null);
}
#Deprecated
public void setButton2(CharSequence text, Message msg) {
setButton(BUTTON_NEGATIVE, text, msg);
}
#Deprecated
public void setButton2(CharSequence text, final OnClickListener listener) {
setButton(BUTTON_NEGATIVE, text, listener);
}
#Deprecated
public void setButton3(CharSequence text, Message msg) {
setButton(BUTTON_NEUTRAL, text, msg);
}
#Deprecated
public void setButton3(CharSequence text, final OnClickListener listener) {
setButton(BUTTON_NEUTRAL, text, listener);
}
public void setCustomTitle(View customTitleView) {
mAlert.setCustomTitle(customTitleView);
}
public void setIcon(Drawable icon) {
mAlert.setIcon(icon);
}
public void setIcon(int resId) {
mAlert.setIcon(resId);
}
public void setIconAttribute(int attrId) {
TypedValue out = new TypedValue();
getContext().getTheme().resolveAttribute(attrId, out, true);
mAlert.setIcon(out.resourceId);
}
public void setInverseBackgroundForced(boolean forceInverseBackground) {
mAlert.setInverseBackgroundForced(forceInverseBackground);
}
public void setMessage(CharSequence message) {
mAlert.setMessage(message);
}
#Override
public void setTitle(CharSequence title) {
super.setTitle(title);
mAlert.setTitle(title);
}
public void setView(View view) {
mAlert.setView(view);
}
public void setView(View view, int viewSpacingLeft, int viewSpacingTop,
int viewSpacingRight, int viewSpacingBottom) {
mAlert.setView(view, viewSpacingLeft, viewSpacingTop, viewSpacingRight,
viewSpacingBottom);
}
}
Related
I tried all the possible options that I just found.
I can’t send ArrayList to another activity via the Parcelable interface.
To implement a media player
String format information it sends.
I would be very grateful, maybe there are some other options. This is the first time I'm asking a question here
Here is my activity that I use to send, the code is still very raw
public class MainActivity extends AppCompatActivity {
ScheduledExecutorService scheduledExecutorService;
public MediaPlayer mediaPlayer;
private SeekBar seekBar;
private ImageView btn_Play;
private ImageView btn_Next;
private ImageView btn_Pre;
private TextView setCurrentDuration, setTotalDuration;
private ArrayList<SoundInfo> audioList = new ArrayList<>();
SoundAdapter adapter = new SoundAdapter();
public Handler handler = new Handler();
AudioEffect audioEffect;
private int currentPosition = 0;
private SoundInfo soundInfo = new SoundInfo(this);
SoundEffects soundEffects;
boolean mediaPauseStat = false;
Context context;
PageFragmentOne pageFragmentOne;
//public MainActivity(PageFragmentOne pageFragmentOne) {
// this.pageFragmentOne = pageFragmentOne;
//}
MediaManager mediaManager = new MediaManager(this, adapter, audioList);
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Старт сервиса
//Intent i = new Intent(this, MediaPlaybackService.class);
//i.putExtra("play", "письмо от главного активити");
//startService(i);
//mediaManager.LoadSounds();
/**
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
**/
////////////////////////////////////////////////////////////////////////////////////////////
setCurrentDuration = findViewById(R.id.current_Duration);
setTotalDuration = findViewById(R.id.total_Duration);
seekBar = findViewById(R.id.seekBar);
RecyclerView list = findViewById(R.id.my_recycler_view);
list.setAdapter(adapter);
list.setLayoutManager(new LinearLayoutManager(this));
// Оформление отображения адаптера
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, LinearLayout.VERTICAL);
dividerItemDecoration.setDrawable(getResources().getDrawable(R.drawable.list_item_divider, null));
list.addItemDecoration(dividerItemDecoration);
///////////////////////////////////////////////
soundInfo.setMassive(audioList);
adapter.setOnItemClickListener(new SoundAdapter.OnItemClickListener() {
#Override
public void onClick(View v, final SoundInfo obj, final int position, final ImageView onNext) {
final SoundInfo path = audioList.get(position);
String audioPath = obj.getData();
prepareMedia(position);
// Задаем текующию позицию трека
currentPosition = position;
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
// TODO Auto-generated method stub
mediaPlayer.start();
// Всегда должен быть после старта плеера, что бы не вылазило 238
updateProgressBar();
//seekBar.setProgress(0);
seekBar.setMax(mediaPlayer.getDuration());
btn_Play.setImageResource(R.drawable.btn_pause);
}
});
// Перемотка аудио
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// Слишком часто обновляет
}
#Override
public void onStartTrackingTouch(final SeekBar seekBar) {
if (mediaPlayer != null) {
soundInfo.setMediaPauseStat(false);
soundInfo.setMediaRewind(false);
mediaPlayer.pause();
seekBar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
mediaPlayer.seekTo(seekBar.getProgress());
return false;
}
});
}
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (mediaPlayer != null) {
soundInfo.setMediaPauseStat(true);
//soundInfo.setMediaRewind(true);
mediaPlayer.start();
}
}
});
// Кнопка проигрывания и паузы
btn_Play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!mediaPlayer.isPlaying()) {
onPlay();
} else {
onPaused();
}
}
});
// Следующий трек
btn_Next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onNext();
}
});
// Предыдущий трек
btn_Pre.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onPre();
}
});
}
});
init();
}
private MyBroadcastReceiver myReceiver;
#Override
public void onResume() {
super.onResume();
myReceiver = new MyBroadcastReceiver();
final IntentFilter intentFilter = new IntentFilter("YourAction");
LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, intentFilter);
}
#Override
public void onPause() {
super.onPause();
if (myReceiver != null)
LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver);
myReceiver = null;
}
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// String yourValue = b.getString("ser");
Bundle bundle = intent.getExtras();
}
}
public void onMainMediaPlayList(View view) {
final Intent intent2 = new Intent(getApplicationContext(), MainMediaPlayList.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("MEDIA_MASSIVE", audioList);
intent2.putExtras(bundle);
startActivity(intent2);
//Intent i = new Intent(MainActivity.this, MediaPlaybackService.class);
//startService(i);
////////////////////////////////////////////////////////////////////////////////////////////
}
public void init() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Разрешение не предоставляется
// Должны ли мы показать объяснение?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Показать объяснение пользователю * асинхронно* -- не блокировать
// этот поток ждет ответа пользователя! После пользователя
// увидев объяснение, попробуйте еще раз запросить разрешение.
} else {
// Никаких объяснений не требуется; запросить разрешение
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.MODIFY_AUDIO_SETTINGS,
Manifest.permission.RECORD_AUDIO},
101);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS является
// app-определенная константа int. Метод обратного вызова получает
// результат запроса.
}
} else {
// Разрешение уже предоставлено
//loadSounds();
mediaManager.LoadSounds();
}
//bPlayPause = findViewById(R.id.bPlayPause);
//lv = (ListView) findViewById(R.id.lvPlayList);
btn_Play = findViewById(R.id.btn_Play);
btn_Next = findViewById(R.id.btn_Next);
btn_Pre = findViewById(R.id.btn_Pre);
}
Here is my SoundInfo
public class SoundInfo implements Parcelable {
private String data, artist, title;
private Context context;
private String pathData;
public SoundInfo(MainActivity context) {
this.context = context;
}
public SoundInfo() {
}
public SoundInfo(MainMediaPlayList context) {
this.context = context;
}
public SoundInfo(MediaPlaybackService mediaPlaybackService, String star) {
this.context = mediaPlaybackService;
this.star = star;
}
protected SoundInfo(Parcel in) {
data = in.readString();
artist = in.readString();
title = in.readString();
pathData = in.readString();
mediaPauseStat = in.readByte() != 0;
ismediaRewind = in.readByte() != 0;
audioList = in.createTypedArrayList(SoundInfo.CREATOR);
star = in.readString();
}
public static final Creator<SoundInfo> CREATOR = new Creator<SoundInfo>() {
#Override
public SoundInfo createFromParcel(Parcel in) {
return new SoundInfo(in);
}
#Override
public SoundInfo[] newArray(int size) {
return new SoundInfo[size];
}
};
public void SoundInfo(String data, String artist, String title) {
this.data = data;
this.artist = artist;
this.title = title;
}
public SoundInfo(String data, String artist, String title) {
this.data = data;
this.artist = artist;
this.title = title;
}
public String getData() {
return data;
}
public String getArtist() {
return artist;
}
public String getTitle() {
return title;
}
public void setData(String artist) {
this.data = data;
}
public void setArtist(String artist) {
this.artist = artist;
}
public void setTitle(String title) {
this.title = title;
}
public void setpathData(String pathData) {
this.pathData = pathData;
}
public String getpathData() {
return pathData;
}
// Запись в память для отображения времени
boolean mediaPauseStat = true;
boolean ismediaRewind = true;
public void setMediaPauseStat(boolean mediaPauseStat) {
this.mediaPauseStat = mediaPauseStat;
}
public boolean getMediaPauseStat() {
return mediaPauseStat;
}
public void setMediaRewind(boolean isMediaRewind) {
this.ismediaRewind = ismediaRewind;
}
public boolean getMediaRewind() {
return ismediaRewind;
}
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
// Массив
private ArrayList<SoundInfo> audioList = new ArrayList<SoundInfo>();
public ArrayList<SoundInfo> getMassive() {
return audioList;
}
public void setMassive(ArrayList<SoundInfo> audioList) {
this.audioList = audioList;
}
private String star;
public String getStar() {
return star;
}
public void setStar(String star) {
this.star = star;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(data);
dest.writeString(artist);
dest.writeString(title);
dest.writeString(pathData);
dest.writeByte((byte) (mediaPauseStat ? 1 : 0));
dest.writeByte((byte) (ismediaRewind ? 1 : 0));
dest.writeTypedList(audioList);
dest.writeString(star);
}
}
Here is my adater which I use
public class SoundAdapter extends RecyclerView.Adapter<SoundAdapter.ViewHolder> {
private ArrayList<SoundInfo> audioList = new ArrayList<SoundInfo>();
Context context;
//private String[] items;
private OnItemClickListener onItemClickListener;
public void setItems(Context context, ArrayList<SoundInfo> audioList) {
this.context = context;
this.audioList = audioList;
//audioList.addAll(items);
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_audio, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
holder.bind(audioList.get(position));
holder.clickFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final SoundInfo path = audioList.get(position);
onItemClickListener.onClick(view, path, position, holder.onNext);
}
});
}
#Override
public int getItemCount() {
return audioList == null ? 0 : audioList.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
private TextView data, title, artist;
private ImageView onNext;
private View clickFile;
ViewHolder(View view) {
super(view);
title = view.findViewById(R.id.tvSoundTitle);
artist = view.findViewById(R.id.tvSoundArtist);
clickFile = view.findViewById(R.id.clickFile);
//data = view.findViewById(R.id.item_title);
//onNext = view.findViewById(R.id.imageNext);
}
public void bind(SoundInfo soundInfo) {
title.setText(soundInfo.getTitle());
artist.setText(soundInfo.getArtist());
//clickFile.setText(soundInfo.getData());
}
}
// Передача данных в основной активити
public interface OnItemClickListener {
void onClick(View view, SoundInfo obj, int position, ImageView onNext);
}
}
Here is the second activity that an ArrayList gets.
Bundle bundle = getIntent().getExtras();
ArrayList<SoundInfo> audioList = bundle.getParcelableArrayList("MEDIA_MASSIVE");
adapter.setItems(MainMediaPlayList.this, audioList);
adapter.notifyDataSetChanged();
// загрузка адаптера
RecyclerView list = findViewById(R.id.my_recycler_view);
list.setAdapter(adapter);
list.setLayoutManager(new LinearLayoutManager(MainMediaPlayList.this));
When you open a new activity, the application crashes
does not display any errors in the log, the problem is as I understand that intent can not find
audioList as it seems to me
If I remove the method everything loads
public void onMainMediaPlayList(View view) {
final Intent intent2 = new Intent(getApplicationContext(), MainMediaPlayList.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("MEDIA_MASSIVE", audioList);
intent2.putExtras(bundle);
startActivity(intent2);
Here I took off the launch log, it may somehow help
2020-03-08 18:09:43.406 15730-15730/com.shimmer.myapplication W/r.myapplicatio: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
2020-03-08 18:09:43.406 15730-15730/com.shimmer.myapplication W/r.myapplicatio: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
2020-03-08 18:09:43.431 15730-15730/com.shimmer.myapplication I/OverScrollerOptimization: start init SmartSlideOverScroller and get the overscroller config
2020-03-08 18:09:43.431 15730-15730/com.shimmer.myapplication I/OverScrollerOptimization: get the overscroller config
2020-03-08 18:09:43.466 15730-15730/com.shimmer.myapplication D/HwFrameworkSecurityPartsFactory: HwFrameworkSecurityPartsFactory in.
2020-03-08 18:09:43.466 15730-15730/com.shimmer.myapplication I/HwFrameworkSecurityPartsFactory: add HwFrameworkSecurityPartsFactory to memory.
2020-03-08 18:09:43.506 15730-15730/com.shimmer.myapplication D/ActivityThread: add activity client record, r= ActivityRecord{e3185e4 token=android.os.BinderProxy#837d3d7 {com.shimmer.myapplication/com.shimmer.myapplication.MainActivity}} token= android.os.BinderProxy#837d3d7
I don't think so, You can send an ArrayList like this.
I recommend you sending Class instead of sending an Arraylist.
So, just create a class like AudiolistHolder and put your ArrayList inside this class and don't forget to implement Parcelable interface for this class, too, and send this class between activities this should solve your problem. I always use this way.
EDIT:
You can use this to send your data
Intent intent2 = new Intent(this, MainMediaPlayList.class);
MassiveAudioList m = new MassiveAudioList(audioList);
intent2.putExtra("MEDIA_MASSIVE”, m);
startActivity(intent2);
and you can use this in your second activity to retrieve data
MassiveAudioList massiveAudio=getIntent().getParcelableExtra("MEDIA_MASSIVE");
ArrayList<SoundInfo> audioList = massiveAudio.getMassiveAudioList();
Have you tried like this with arraylist
I think it can be,
In MainActivity.java
ArrayList<String> audioList= new ArrayList<>();
audioList.add("ChipThrills");
Intent i = new Intent(MainActivity.this, Secondactivity.class);
i.putExtra("Musickey", audioList);
startActivity(i);
In SecondActivity.java
ArrayList<String> audioList = (ArrayList<String>) getIntent().getSerializableExtra("Musickey");
I am writing to you here because I did not understand how to add code to the comment
And how do I extract data by adding it to an array. If of course I did the right thing, I'm new to this field. Thanks.
public class MassiveAudioList implements Parcelable {
private ArrayList<SoundInfo> audioList = new ArrayList<>();
private Context context;
public MassiveAudioList(Context context) {
this.context = context;
}
public MassiveAudioList(ArrayList audioList) {
this.audioList = audioList;
}
protected MassiveAudioList(Parcel in) {
audioList = in.createTypedArrayList(SoundInfo.CREATOR);
}
public static final Creator<MassiveAudioList> CREATOR = new Creator<MassiveAudioList>() {
#Override
public MassiveAudioList createFromParcel(Parcel in) {
return new MassiveAudioList(in);
}
#Override
public MassiveAudioList[] newArray(int size) {
return new MassiveAudioList[size];
}
};
public ArrayList<SoundInfo> getMassiveAudioList() {
return audioList;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeTypedList(audioList);
}
}
public void onMainMediaPlayList(View view) {
Log.d("TAG", "soundinfo" + soundInfo.getData());
final Intent intent2 = new Intent(getApplicationContext(), MainMediaPlayList.class);
massiveAudioList = new MassiveAudioList(this);
MassiveAudioList m = new MassiveAudioList(audioList);
Bundle bundle = new Bundle();
bundle.putParcelable("MEDIA_MASSIVE", m);
intent2.putExtras(bundle);
startActivity(intent2);
}
I'm not able to see the recycle view, not sure where It has gone wrong. It would be great if you can help me.
Fragment
public class CallDurationFragment extends Fragment {
final FirebaseDatabase database = FirebaseDatabase.getInstance();
ArrayList<CallHistroy> callList = new ArrayList<>();
ArrayList<CallHistroy> callListTemp = new ArrayList<>();
ArrayList<CallHistroy> callObject = new ArrayList<>();
ArrayList<CallHistroy> callListText = new ArrayList<>();
private CallDurationFragment.OnFragmentInteractionListener mListener;
private RecyclerView rvCall;
private RecyclerView.Adapter callAdaptor;
private RecyclerView.LayoutManager eLayoutManager;
private EditText phoneNumber;
private static final int DIALOG_DATE_PICKER = 100;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_callduration_list, container, false);
phoneNumber = (EditText) getActivity().findViewById(editTextSearchKeyPhoneNo);
Context context = getActivity();
rvCall = (RecyclerView) rootView.findViewById(R.id.rvCallDuration);
rvCall.setHasFixedSize(true);
rvCall.setLayoutManager(eLayoutManager);
eLayoutManager = new LinearLayoutManager(getActivity());
phoneNumber.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
callListTemp = getAllCallRecords();
for(int i = 0 ; i < callListTemp.size() ; i++)
if(callListTemp.get(i).getPhoneNumber().contains(s.toString()) )
callListText.add(callListTemp.get(i));
callList = calculateIncomingOutgoing();
callAdaptor = new CallDurationAdapter(getActivity(), callList);
rvCall.setAdapter(callAdaptor);
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
}
});
callList = calculateIncomingOutgoing();
callAdaptor = new CallDurationAdapter(getActivity(), callList);
rvCall.setAdapter(callAdaptor);
return rootView;
}
public ArrayList<CallHistroy> getAllCallRecords(){
DatabaseReference ref = database.getReference();
ref.child("Call").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
callObject.clear();
HashMap<String,Object> call = null;
Iterator<DataSnapshot> items = dataSnapshot.getChildren().iterator();
while(items.hasNext()){
DataSnapshot item = items.next();
Log.e("Listener",item.toString() );
call =(HashMap<String, Object>) item.getValue();
callObject.add(new CallHistroy(call.get("phoneNumber").toString(),call.get("mode").toString(),call.get("duration").toString(), call.get("date").toString(),item.getKey()));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return callObject;
}
public ArrayList<CallHistroy> calculateIncomingOutgoing(){
if(callListText.size() > 0){
callList = callListText;
}else {
callList = getAllCallRecords();
}
ArrayList<CallHistroy> callHistroyIncomingOutgoing = new ArrayList<>();
if(callList.size() > 0){
if(callList.get(0).getMode().equals("Outgoing")) {
callHistroyIncomingOutgoing.add(new CallHistroy(callList.get(0).getPhoneNumber(), "0", callList.get(0).getDuration()));
}else{
callHistroyIncomingOutgoing.add(new CallHistroy(callList.get(0).getPhoneNumber(), callList.get(0).getDuration(), "0"));
}
}
for( int i = 1 ; i < callList.size() ; i++){
boolean setValue = false;
for (int j = 0; j < callHistroyIncomingOutgoing.size() ;j++){
if( callHistroyIncomingOutgoing.get(j).getPhoneNumber().equals(callList.get(i).getPhoneNumber())){
setValue = true;
int incoming = Integer.parseInt(callHistroyIncomingOutgoing.get(j).getIncomingDuration());
int outgoing = Integer.parseInt( callHistroyIncomingOutgoing.get(j).getOutgoingDuration());
int duration = Integer.parseInt( callList.get(i).getDuration());
if(callList.get(i).getMode().equals("Outgoing")) {
callHistroyIncomingOutgoing.get(j).updateDuration(String.valueOf(incoming), String.valueOf(outgoing + duration));
}else{
callHistroyIncomingOutgoing.get(j).updateDuration(String.valueOf(incoming + duration), String.valueOf(outgoing));
}
}
}
if(!setValue) {
if(callList.get(i).getMode() == "Outgoing") {
callHistroyIncomingOutgoing.add(new CallHistroy(callList.get(i).getPhoneNumber(), "0", callList.get(i).getDuration()));
}else{
callHistroyIncomingOutgoing.add(new CallHistroy(callList.get(i).getPhoneNumber(), callList.get(i).getDuration(), "0"));
}
}
}
return callHistroyIncomingOutgoing;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof CallListFragment.OnFragmentInteractionListener) {
mListener = (CallDurationFragment.OnFragmentInteractionListener) context;
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onPause(){
super.onPause();
}
#Override
public void onDestroyView(){
super.onDestroyView();
}
#Override
public void onDestroy(){
super.onDestroy();
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Adaptor
RecyclerView.Adapter<CallDurationAdapter.ViewHolder> {
private List<CallHistroy> mCalls;
private Context mContext;
public CallDurationAdapter(Context context, List<CallHistroy> calls) {
mCalls = calls;
mContext = context;
}
private Context getContext() {
return mContext;
}
#Override
public CallDurationAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View callDurationView = inflater.inflate(R.layout.item_call_duration_details, parent, false);
// Return a new holder instance
ViewHolder viewHolder = new ViewHolder(callDurationView);
return viewHolder;
}
#Override
public void onBindViewHolder(CallDurationAdapter.ViewHolder viewHolder, final int position) {
// Get the data model based on position
final CallHistroy ch = mCalls.get(position);
// Set item views based on your views and data model
viewHolder._phoneNoTextView.setText(ch.getPhoneNumber());
viewHolder._incomingTextView.setText(ch.getIncomingDuration());
viewHolder._outgoingTextView.setText(ch.getOutgoingDuration());
final String key = ch.getKey();
}
#Override
public int getItemCount() {
return mCalls.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView _phoneNoTextView;
public TextView _incomingTextView;
public TextView _outgoingTextView;
public ViewHolder(View itemView) {
super(itemView);
_phoneNoTextView = (TextView) itemView.findViewById(R.id.rvs_duration_phone_no);
_incomingTextView = (TextView) itemView.findViewById(R.id.rvs_duration_outing_total_call);
_outgoingTextView = (TextView) itemView.findViewById(R.id.rvs_duration_incoming_total_call);
}
}
}
Activity
public class CallDurationActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call_duration);
CallDurationFragment newFragment = new CallDurationFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.recordFragmentContainer, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
public void refreshCallDuration(View v) {
Intent intent = new Intent(this, CallDurationActivity.class);
startActivity(intent);
}
protected void onPause() {
super.onPause();
}
protected void onStop() {
super.onStop();
}
protected void onDestroy() {
super.onDestroy();
}
public void onBackCallDuration(View v) {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
}
Object
public class CallHistroy implements Comparable<CallHistroy> {
String phoneNumber;
String mode;
String duration;
String date;
String key;
String incomingDuration;
String outgoingDuration;
int totalIncoming;
int totalOutgoing;
public CallHistroy(String _phontNumber, String _incomingDuration, String _outgoingDuration ){
setPhoneNumber( _phontNumber );
setIncomingDuration( _incomingDuration );
setOutgoingDuration( _outgoingDuration );
}
public CallHistroy(String _date, int _totalIncoming, int _totalOutgoing ){
setDate(_date);
setTotalIncoming( _totalIncoming );
setTotalOutgoing( _totalOutgoing );
}
public void updateCall(int _totalIncoming, int _totalOutgoing){
setTotalIncoming( _totalIncoming );
setTotalOutgoing( _totalOutgoing );
}
public void updateDuration(String _incomingDuration, String _outgoingDuration){
setOutgoingDuration( _incomingDuration );
setIncomingDuration( _outgoingDuration );
}
public CallHistroy(String _phoneNumber, String _mode, String _duration, String _date ){
setPhoneNumber( _phoneNumber );
setDuration( _duration );
setDate( _date );
setMode( _mode );
}
public CallHistroy(String _phoneNumber, String _mode, String _duration, String _date, String _key ){
setPhoneNumber( _phoneNumber );
setDuration( _duration );
setDate( _date );
setMode( _mode );
setKey( _key );
}
public String getIncomingDuration() {
return incomingDuration;
}
public String getOutgoingDuration() {
return outgoingDuration;
}
public int getTotalIncoming() {
return totalIncoming;
}
public int getTotalOutgoing() {
return totalOutgoing;
}
public void setIncomingDuration(String incomingDuration) {
this.incomingDuration = incomingDuration;
}
public void setOutgoingDuration(String outgoingDuration) {
this.outgoingDuration = outgoingDuration;
}
public void setTotalIncoming(int totalIncoming) {
this.totalIncoming = totalIncoming;
}
public void setTotalOutgoing(int totalOutgoing) {
this.totalOutgoing = totalOutgoing;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getDate() {
return date;
}
public String getMode() {
return mode;
}
public String getDuration() {
return duration;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setDate(String date) {
this.date = date;
}
public void setDuration(String duration) {
this.duration = duration;
}
public void setMode(String mode) {
this.mode = mode;
}
#Override
public int compareTo(#NonNull CallHistroy callHistroyObject) {
String[] part = callHistroyObject.date.split("/");
String[] part1 = date.split("/");
int date = Integer.parseInt(part[0]);
int month = Integer.parseInt(part[1]);
String _year = part[2];
int year = Integer.parseInt(_year.substring(0,4));
int date1 = Integer.parseInt(part1[0]);
int month1 = Integer.parseInt(part1[1]);
String _year1 = part1[2];
int year1 = Integer.parseInt(_year1.substring(0,4));
if(year > year1)
return -1;
else if(month > month1)
return -1;
else if(date >date1)
return -1;
else
return 0;
}
}
You're setting your layout manager before it's created
rvCall.setLayoutManager(eLayoutManager);
eLayoutManager = new LinearLayoutManager(getActivity());
should be
eLayoutManager = new LinearLayoutManager(getActivity());
rvCall.setLayoutManager(eLayoutManager);
I want to use this from the material-dialog library without using the library in my build.gradle file.
Is there a way to do that?
Thanks to Abderrahim Soubai Elidrissi deleted answer I used LovelyDialog and implemented the following classes in my project:
AbsLovelyDialog.java
#SuppressWarnings({"unchecked", "WeakerAccess"})
public abstract class AbsLovelyDialog<T extends AbsLovelyDialog> {
private static final String KEY_SAVED_STATE_TOKEN = "key_saved_state_token";
private Dialog dialog;
private View dialogView;
private ImageView iconView;
private TextView topTitleView;
private TextView titleView;
private TextView messageView;
public AbsLovelyDialog(Context context) {
init(new AlertDialog.Builder(context));
}
public AbsLovelyDialog(Context context, int theme) {
init(new AlertDialog.Builder(context, theme));
}
private void init(AlertDialog.Builder dialogBuilder) {
dialogView = LayoutInflater.from(dialogBuilder.getContext()).inflate(getLayout(), null);
dialog = dialogBuilder.setView(dialogView).create();
iconView = findView(R.id.ld_icon);
titleView = findView(R.id.ld_title);
messageView = findView(R.id.ld_message);
topTitleView = findView(R.id.ld_top_title);
}
#LayoutRes
protected abstract int getLayout();
public T setMessage(#StringRes int message) {
return setMessage(string(message));
}
public T setMessage(CharSequence message) {
messageView.setVisibility(View.VISIBLE);
messageView.setText(message);
return (T) this;
}
public T setTitle(#StringRes int title) {
return setTitle(string(title));
}
public T setTopTitle(#StringRes int title) {
return setTopTitle(string(title));
}
public T setTitle(CharSequence title) {
titleView.setVisibility(View.VISIBLE);
titleView.setText(title);
return (T) this;
}
public T setTopTitle(CharSequence title) {
topTitleView.setVisibility(View.VISIBLE);
topTitleView.setText(title);
return (T) this;
}
public T setTopTitleColor(int color) {
topTitleView.setTextColor(color);
return (T) this;
}
public T setIcon(Bitmap bitmap) {
iconView.setVisibility(View.VISIBLE);
iconView.setImageBitmap(bitmap);
return (T) this;
}
public T setIcon(Drawable drawable) {
iconView.setVisibility(View.VISIBLE);
iconView.setImageDrawable(drawable);
return (T) this;
}
public T setIcon(#DrawableRes int iconRes) {
iconView.setVisibility(View.VISIBLE);
iconView.setImageResource(iconRes);
return (T) this;
}
public T setIconTintColor(int iconTintColor) {
iconView.setColorFilter(iconTintColor);
return (T) this;
}
public T setTitleGravity(int gravity) {
titleView.setGravity(gravity);
return (T) this;
}
public T setMessageGravity(int gravity) {
messageView.setGravity(gravity);
return (T) this;
}
public T setTopColor(#ColorInt int topColor) {
findView(R.id.ld_color_area).setBackgroundColor(topColor);
return (T) this;
}
public T setTopColorRes(#ColorRes int topColoRes) {
return setTopColor(color(topColoRes));
}
/*
* You should call method saveInstanceState on handler object and then use saved info to restore
* your dialog in onRestoreInstanceState. Static methods wasDialogOnScreen and getDialogId will
* help you in this.
*/
public T setInstanceStateHandler(int id, LovelySaveStateHandler handler) {
handler.handleDialogStateSave(id, this);
return (T) this;
}
public T setCancelable(boolean cancelable) {
dialog.setCancelable(cancelable);
return (T) this;
}
public T setSavedInstanceState(Bundle savedInstanceState) {
if (savedInstanceState != null) {
boolean hasSavedStateHere =
savedInstanceState.keySet().contains(KEY_SAVED_STATE_TOKEN) &&
savedInstanceState.getSerializable(KEY_SAVED_STATE_TOKEN) == getClass();
if (hasSavedStateHere) {
restoreState(savedInstanceState);
}
}
return (T) this;
}
public Dialog show() {
dialog.show();
return dialog;
}
public Dialog create() {
return dialog;
}
public void dismiss() {
dialog.dismiss();
}
void onSaveInstanceState(Bundle outState) {
outState.putSerializable(KEY_SAVED_STATE_TOKEN, getClass());
}
void restoreState(Bundle savedState) {
}
boolean isShowing() {
return dialog != null && dialog.isShowing();
}
protected String string(#StringRes int res) {
return dialogView.getContext().getString(res);
}
protected int color(#ColorRes int colorRes) {
return ContextCompat.getColor(getContext(), colorRes);
}
protected Context getContext() {
return dialogView.getContext();
}
protected <ViewClass extends View> ViewClass findView(int id) {
return (ViewClass) dialogView.findViewById(id);
}
protected class ClickListenerDecorator implements View.OnClickListener {
private View.OnClickListener clickListener;
private boolean closeOnClick;
protected ClickListenerDecorator(View.OnClickListener clickListener, boolean closeOnClick) {
this.clickListener = clickListener;
this.closeOnClick = closeOnClick;
}
#Override
public void onClick(View v) {
if (clickListener != null) {
if (clickListener instanceof LovelyDialogCompat.DialogOnClickListenerAdapter) {
LovelyDialogCompat.DialogOnClickListenerAdapter listener =
(LovelyDialogCompat.DialogOnClickListenerAdapter) clickListener;
listener.onClick(dialog, v.getId());
} else {
clickListener.onClick(v);
}
}
if (closeOnClick) {
dismiss();
}
}
}
}
LovelyChoiceDialog.java
public class LovelyChoiceDialog extends AbsLovelyDialog<LovelyChoiceDialog> {
private static final String KEY_ITEM_CHECKED_STATES = "key_item_checked_states";
private ListView choicesList;
private TextView confirmButton;
{
choicesList = findView(R.id.ld_choices);
}
public LovelyChoiceDialog(Context context) {
super(context);
}
public LovelyChoiceDialog(Context context, int theme) {
super(context, theme);
}
public <T> LovelyChoiceDialog setItems(T[] items, OnItemSelectedListener<T> itemSelectedListener) {
return setItems(Arrays.asList(items), itemSelectedListener);
}
public <T> LovelyChoiceDialog setItems(List<T> items, OnItemSelectedListener<T> itemSelectedListener) {
ArrayAdapter<T> adapter = new ArrayAdapter<>(getContext(),
R.layout.dialog_item_simple_text, android.R.id.text1,
items);
return setItems(adapter, itemSelectedListener);
}
public <T> LovelyChoiceDialog setItems(ArrayAdapter<T> adapter, OnItemSelectedListener<T> itemSelectedListener) {
choicesList.setOnItemClickListener(new ItemSelectedAdapter<>(itemSelectedListener));
choicesList.setAdapter(adapter);
return this;
}
public <T> LovelyChoiceDialog setItemsMultiChoice(T[] items, OnItemsSelectedListener<T> itemsSelectedListener) {
return setItemsMultiChoice(items, null, itemsSelectedListener);
}
public <T> LovelyChoiceDialog setItemsMultiChoice(T[] items, boolean[] selectionState, OnItemsSelectedListener<T> itemsSelectedListener) {
return setItemsMultiChoice(Arrays.asList(items), selectionState, itemsSelectedListener);
}
public <T> LovelyChoiceDialog setItemsMultiChoice(List<T> items, OnItemsSelectedListener<T> itemsSelectedListener) {
return setItemsMultiChoice(items, null, itemsSelectedListener);
}
public <T> LovelyChoiceDialog setItemsMultiChoice(List<T> items, boolean[] selectionState, OnItemsSelectedListener<T> itemsSelectedListener) {
ArrayAdapter<T> adapter = new ArrayAdapter<>(getContext(),
R.layout.dialog_item_simple_text_multichoice, android.R.id.text1,
items);
return setItemsMultiChoice(adapter, selectionState, itemsSelectedListener);
}
public <T> LovelyChoiceDialog setItemsMultiChoice(ArrayAdapter<T> adapter, OnItemsSelectedListener<T> itemsSelectedListener) {
return setItemsMultiChoice(adapter, null, itemsSelectedListener);
}
public <T> LovelyChoiceDialog setItemsMultiChoice(ArrayAdapter<T> adapter, boolean[] selectionState, OnItemsSelectedListener<T> itemsSelectedListener) {
LayoutInflater inflater = LayoutInflater.from(getContext());
View confirmBtnContainer = inflater.inflate(R.layout.dialog_item_footer_confirm, null);
confirmButton = (TextView) confirmBtnContainer.findViewById(R.id.ld_btn_confirm);
confirmButton.setOnClickListener(new ItemsSelectedAdapter<>(itemsSelectedListener));
choicesList.addFooterView(confirmBtnContainer);
ListView choicesList = findView(R.id.ld_choices);
choicesList.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
choicesList.setAdapter(adapter);
if (selectionState != null) {
for (int i = 0; i < selectionState.length; i++) {
choicesList.setItemChecked(i, selectionState[i]);
}
}
return this;
}
public LovelyChoiceDialog setConfirmButtonText(#StringRes int text) {
return setConfirmButtonText(string(text));
}
public LovelyChoiceDialog setConfirmButtonText(String text) {
if (confirmButton == null) {
throw new IllegalStateException(string(R.string.ex_msg_dialog_choice_confirm));
}
confirmButton.setText(text);
return this;
}
public LovelyChoiceDialog setConfirmButtonColor(int color) {
if (confirmButton == null) {
throw new IllegalStateException(string(R.string.ex_msg_dialog_choice_confirm));
}
confirmButton.setTextColor(color);
return this;
}
#Override
void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (isMultiChoiceList()) {
ListAdapter adapter = choicesList.getAdapter();
boolean[] checkedStates = new boolean[adapter.getCount()];
SparseBooleanArray checkedPositions = choicesList.getCheckedItemPositions();
for (int i = 0; i < checkedPositions.size(); i++) {
if (checkedPositions.valueAt(i)) {
checkedStates[checkedPositions.keyAt(i)] = true;
}
}
outState.putBooleanArray(KEY_ITEM_CHECKED_STATES, checkedStates);
}
}
#Override
void restoreState(Bundle savedState) {
super.restoreState(savedState);
if (isMultiChoiceList()) {
boolean[] checkedStates = savedState.getBooleanArray(KEY_ITEM_CHECKED_STATES);
if (checkedStates == null) {
return;
}
for (int index = 0; index < checkedStates.length; index++) {
choicesList.setItemChecked(index, checkedStates[index]);
}
}
}
#Override
protected int getLayout() {
return R.layout.dialog_choice;
}
private boolean isMultiChoiceList() {
return choicesList.getChoiceMode() == AbsListView.CHOICE_MODE_MULTIPLE;
}
public interface OnItemSelectedListener<T> {
void onItemSelected(int position, T item);
}
public interface OnItemsSelectedListener<T> {
void onItemsSelected(List<Integer> positions, List<T> items);
}
private class ItemSelectedAdapter<T> implements AdapterView.OnItemClickListener {
private OnItemSelectedListener<T> adaptee;
private ItemSelectedAdapter(OnItemSelectedListener<T> adaptee) {
this.adaptee = adaptee;
}
#Override
#SuppressWarnings("unchecked")
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (adaptee != null) {
adaptee.onItemSelected(position, (T) parent.getItemAtPosition(position));
}
dismiss();
}
}
private class ItemsSelectedAdapter<T> implements View.OnClickListener {
private OnItemsSelectedListener<T> adaptee;
private ItemsSelectedAdapter(OnItemsSelectedListener<T> adaptee) {
this.adaptee = adaptee;
}
#Override
#SuppressWarnings("unchecked")
public void onClick(View v) {
if (adaptee != null) {
SparseBooleanArray checkedItemPositions = choicesList.getCheckedItemPositions();
List<T> selectedItems = new ArrayList<>(checkedItemPositions.size());
List<Integer> selectedPositions = new ArrayList<>(checkedItemPositions.size());
ListAdapter adapter = choicesList.getAdapter();
for (int index = 0; index < adapter.getCount(); index++) {
if (checkedItemPositions.get(index)) {
selectedPositions.add(index);
selectedItems.add((T) adapter.getItem(index));
}
}
adaptee.onItemsSelected(selectedPositions, selectedItems);
}
dismiss();
}
}
}
LovelyDialogCompat.java
public class LovelyDialogCompat {
/**
* If you don't want to change implemented interfaces when migrating from standard dialogs
* to LovelyDialogs - use this method.
*/
public static View.OnClickListener wrap(Dialog.OnClickListener listener) {
return new DialogOnClickListenerAdapter(listener);
}
static class DialogOnClickListenerAdapter implements View.OnClickListener {
private Dialog.OnClickListener adapted;
DialogOnClickListenerAdapter(DialogInterface.OnClickListener adapted) {
this.adapted = adapted;
}
public void onClick(DialogInterface dialogInterface, int which) {
if (adapted != null) {
adapted.onClick(dialogInterface, which);
}
}
#Override
public void onClick(View v) {
}
}
}
LovelySaveStateHandler.java
public class LovelySaveStateHandler {
private static final String KEY_DIALOG_ID = "id";
private SparseArray<WeakReference<AbsLovelyDialog<?>>> handledDialogs;
public LovelySaveStateHandler() {
handledDialogs = new SparseArray<>();
}
public static boolean wasDialogOnScreen(Bundle savedInstanceState) {
return savedInstanceState.keySet().contains(KEY_DIALOG_ID);
}
public static int getSavedDialogId(Bundle savedInstanceState) {
return savedInstanceState.getInt(KEY_DIALOG_ID, -1);
}
public void saveInstanceState(Bundle outState) {
for (int index = handledDialogs.size() - 1; index >= 0; index--) {
WeakReference<AbsLovelyDialog<?>> dialogRef = handledDialogs.valueAt(index);
if (dialogRef.get() == null) {
handledDialogs.remove(index);
continue;
}
AbsLovelyDialog<?> dialog = dialogRef.get();
if (dialog.isShowing()) {
dialog.onSaveInstanceState(outState);
outState.putInt(KEY_DIALOG_ID, handledDialogs.keyAt(index));
return;
}
}
}
void handleDialogStateSave(int id, AbsLovelyDialog<?> dialog) {
handledDialogs.put(id, new WeakReference<AbsLovelyDialog<?>>(dialog));
}
}
I need a guide to add data from my add button of my fragment and show the list in another fragment..Everything in memory
This is my entity
public class Incidencia implements Parcelable {
private Integer id_incidencia;
private String FechaRegistroIncidencia;
private String NomRegistro;
private String FechaRegistro;;
private String HoraRegistro;
private int CodEstacion;
private String NomEstacion;
private int CodEquipo;
private String NomEquipo;
private String TipoFalla;
private int AtoramientoMoneda;
private int AtoramientoBillete;
private String HoraLlegadaEstacion;
private String Estado;
private String Observaciones;
private String FechaSolucion;
private String HoraSolucion;
public Integer getId_incidencia() {
return id_incidencia;
}
public void setId_incidencia(Integer id_incidencia) {
this.id_incidencia = id_incidencia;
}
public String getFechaRegistroIncidencia() {
return FechaRegistroIncidencia;
}
public void setFechaRegistroIncidencia(String fechaRegistroIncidencia) {
FechaRegistroIncidencia = fechaRegistroIncidencia;
}
public String getNomRegistro() {
return NomRegistro;
}
public void setNomRegistro(String nomRegistro) {
NomRegistro = nomRegistro;
}
public String getFechaRegistro() {
return FechaRegistro;
}
public void setFechaRegistro(String fechaRegistro) {
FechaRegistro = fechaRegistro;
}
public String getHoraRegistro() {
return HoraRegistro;
}
public void setHoraRegistro(String horaRegistro) {
HoraRegistro = horaRegistro;
}
public Integer getCodEstacion() {
return CodEstacion;
}
public void setCodEstacion(Integer codEstacion) {
CodEstacion = codEstacion;
}
public String getNomEstacion() {
return NomEstacion;
}
public void setNomEstacion(String nomEstacion) {
NomEstacion = nomEstacion;
}
public Integer getCodEquipo() {
return CodEquipo;
}
public void setCodEquipo(Integer codEquipo) {
CodEquipo = codEquipo;
}
public String getNomEquipo() {
return NomEquipo;
}
public void setNomEquipo(String nomEquipo) {
NomEquipo = nomEquipo;
}
public String getTipoFalla() {
return TipoFalla;
}
public void setTipoFalla(String tipoFalla) {
TipoFalla = tipoFalla;
}
public Integer getAtoramientoMoneda() {
return AtoramientoMoneda;
}
public void setAtoramientoMoneda(Integer atoramientoMoneda) {
AtoramientoMoneda = atoramientoMoneda;
}
public Integer getAtoramientoBillete() {
return AtoramientoBillete;
}
public void setAtoramientoBillete(Integer atoramientoBillete) {
AtoramientoBillete = atoramientoBillete;
}
public String getHoraLlegadaEstacion() {
return HoraLlegadaEstacion;
}
public void setHoraLlegadaEstacion(String horaLlegadaEstacion) {
HoraLlegadaEstacion = horaLlegadaEstacion;
}
public String getEstado() {
return Estado;
}
public void setEstado(String estado) {
Estado = estado;
}
public String getObservaciones() {
return Observaciones;
}
public void setObservaciones(String observaciones) {
Observaciones = observaciones;
}
public String getFechaSolucion() {
return FechaSolucion;
}
public void setFechaSolucion(String fechaSolucion) {
FechaSolucion = fechaSolucion;
}
public String getHoraSolucion() {
return HoraSolucion;
}
public void setHoraSolucion(String horaSolucion) {
HoraSolucion = horaSolucion;
}
public Incidencia(){}
protected Incidencia(Parcel in){
this.id_incidencia=in.readInt();;
this.FechaRegistroIncidencia=in.readString();
this.NomRegistro=in.readString();
this.FechaRegistro=in.readString();
this.HoraRegistro=in.readString();
this.CodEstacion=in.readInt();
this.NomEstacion=in.readString();
this.CodEquipo=in.readInt();
this.NomEquipo=in.readString();
this.TipoFalla=in.readString();
this.AtoramientoMoneda=in.readInt();
this.AtoramientoBillete=in.readInt();
this.HoraLlegadaEstacion=in.readString();
this.Estado=in.readString();
this.Observaciones=in.readString();
this.FechaSolucion=in.readString();
this.HoraSolucion=in.readString();
}
public static final Parcelable.Creator<Incidencia> CREATOR = new Parcelable.Creator<Incidencia>() {
#Override
public Incidencia createFromParcel(Parcel source) {
return new Incidencia(source);
}
#Override
public Incidencia[] newArray(int size) {
return new Incidencia[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.FechaRegistro);
dest.writeString(this.HoraRegistro);
dest.writeString(this.TipoFalla);
dest.writeString(this.FechaSolucion);
dest.writeString(this.HoraSolucion);
dest.writeString(this.NomEstacion);
}
}
This is my adapter
public class ListaIncidenciasTroncalAdapter extends RecyclerView.Adapter<ListaIncidenciasTroncalAdapter.ListaIncidenciasTroncalAdapterViewHolder>
{
private List<Incidencia> mLstIncidencia = new ArrayList<>();
private OnItemClickListener listener;
public void add(Incidencia incidencia){
mLstIncidencia.add(incidencia);
notifyItemInserted(mLstIncidencia.size()-1);
}
#Override
public ListaIncidenciasTroncalAdapter.ListaIncidenciasTroncalAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listaincidencias_item,parent,false);
ListaIncidenciasTroncalAdapterViewHolder mlistaIncidenciasTroncalAdapterViewHolder = new ListaIncidenciasTroncalAdapterViewHolder(view);
return mlistaIncidenciasTroncalAdapterViewHolder;
}
#Override
public void onBindViewHolder(ListaIncidenciasTroncalAdapter.ListaIncidenciasTroncalAdapterViewHolder holder, final int position) {
final Incidencia incidencia= mLstIncidencia.get(position);
holder.tv_FechaRegistro.setText("Registro: "+incidencia.getFechaRegistro()+" - "+incidencia.getHoraRegistro());
holder.tv_Falla.setText(incidencia.getTipoFalla());
holder.tv_Estacion.setText(incidencia.getNomEstacion());
holder.tv_FechaSolucion.setText("Solucion: "+incidencia.getFechaSolucion()+" - "+incidencia.getHoraSolucion());
}
#Override
public int getItemCount() {
return mLstIncidencia.size();
}
static class ListaIncidenciasTroncalAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private OnItemClickListener listener;
TextView tv_FechaRegistro, tv_Falla, tv_Estacion,tv_FechaSolucion;
LinearLayout linearLayout;
public DetalleIncidencia detalleincidencia;
public ListaIncidenciasTroncalAdapterViewHolder(View itemView) {
super(itemView);
tv_FechaRegistro= (TextView) itemView.findViewById(R.id.tvRegistro);
tv_Falla= (TextView) itemView.findViewById(R.id.tvFalla);
tv_Estacion= (TextView) itemView.findViewById(R.id.tvEstacion);
tv_FechaSolucion= (TextView) itemView.findViewById(R.id.tvSolucion);
final Context context = itemView.getContext();
// detalleincidencia=(DetalleIncidencia) itemView.findViewById(R.id.)
linearLayout=(LinearLayout) itemView.findViewById(R.id.linearItem);
}
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
}
}
public void setOnItemClickListener(OnItemClickListener listener){
this.listener = listener;
}
public interface OnItemClickListener{
public void onItemClick(String textName, String textViewBrief);
}
}
I want to add an Incidencia Object from this fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
*Inflate ingresoincidenciastroncal and setup Views.
*/
final View x = inflater.inflate(R.layout.ingresoincidenciastroncal,null);
context = x.getContext();
//BOTON DE AGREGAR INCIDENCIA
botonAgregaIncidencia=(Button) x.findViewById(R.id.btnAgregarIncidencia);
botonAgregaIncidencia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Incidencia incidencia = new Incidencia();
incidencia.setFechaRegistro(mDateDisplay.getText().toString());
incidencia.setHoraSolucion(mTimeDisplay.getText().toString());
Toast toast = Toast.makeText(getContext(), "Registrado", Toast.LENGTH_SHORT);
toast.show();
}
});
return x;
}
And I want to see the list in this fragment
public class ListaIncidenciasTroncalFragment extends Fragment {
Context context;
GestureDetector detector;
private RecyclerView rvListaIncidencias;
private ListaIncidenciasTroncalAdapter mlistaIncidenciasTroncalAdapter;
public ListaIncidenciasTroncalFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View x = inflater.inflate(R.layout.listaincidenciastroncalfragment,null);
context = x.getContext();
detector = new GestureDetector(getActivity(), new RecyclerViewOnGestureListener());
rvListaIncidencias=(RecyclerView)x.findViewById(R.id.rv_listaIncidenciasTroncal);
rvListaIncidencias.setLayoutManager(new LinearLayoutManager(getContext()));
mlistaIncidenciasTroncalAdapter = new ListaIncidenciasTroncalAdapter();
rvListaIncidencias.setAdapter(mlistaIncidenciasTroncalAdapter);
//I ADD THIS ONE FOR TEST AND ITS SUCCESFULL BUT I DONT KNOW HOW TO ADD IT BY THE BUTTON IN ANOTHER FRAGMENT
Incidencia incidencia = new Incidencia();
incidencia.setFechaRegistro("06/06/2017");
incidencia.setHoraRegistro("10:30");
incidencia.setTipoFalla("Atasco Moneda");
incidencia.setNomEstacion("Javier Prado");
incidencia.setFechaSolucion("07/06/2017");
incidencia.setHoraSolucion("9:20");
mlistaIncidenciasTroncalAdapter.add(incidencia);
return x;
}
In your first fragment, define an interface which would pass your Incidencia object to the host activity. The interface method is called in your button's onClick():
public class YourFirstFragment extends Fragment {
private OnButtonClickedListener mListener;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
botonAgregaIncidencia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
...
mListener.onButtonClicked(incidencia);
}
});
}
public interface OnButtonClickedListener {
void onButtonClicked(Incidencia incidencia);
}
}
Then, in your activity, implement this interface. The overridden method will also bundle the object and pass to your next fragment as the fragment argument:
public class YourActivity implements YourFirstFragment.OnButtonClicked {
.
.
.
#Override
public void onButtonClicked(Incidencia incidencia){
ListaIncidenciasTroncalFragment fragment = new ListaIncidenciasTroncalFragment();
Bundle args = new Bundle();
args.putParcelable("yourKey", incindencia);
fragement.setArguments(args);
getSupportFragmentManager().beginTransaction().replace(R.id.yourFragmentContainer, fragment).commit();
}
}
Finally, in your second fragment, extract the bundle or arguments like so and use it however you want:
Bundle args = getArguments();
Incidencia incidencia = args.getParcelable("yourKey");
I want to customize TITLE color of V7 AlertDialog. SetCustomTitle() doesnt seems to be working with android.support.v7.app.AlertDialog. I can see a blank TITLE like below
But expected AlertDialog is below
Creating Alert Dialog
private void createDialog() {
ContextThemeWrapper ctw = new ContextThemeWrapper( mContext, R.style.TooltipTheme);
AlertDialog.Builder builder = new CustomAlertDialogBuilder(ctw);
builder.setTitle(mTitle);
builder.setMessage(mMsg);
builder.setPositiveButton(mOkButton,null);
AlertDialog alert11 = builder.create();
alert11.show();
Button positiveButton = alert11.getButton(DialogInterface.BUTTON_POSITIVE);
positiveButton.setTextColor(mContext.getResources().getColor(R.color.BNPP_Color_Palette_PrimaryBtn));
}
style.xml
<style name="TooltipTheme" parent="Theme.AppCompat.Dialog.Alert"></style>
CustomAlertDialogBuilder
public class CustomAlertDialogBuilder extends AlertDialog.Builder {
private final Context mContext;
private TextView mTitle;
private ImageView mIcon;
private TextView mMessage;
public CustomAlertDialogBuilder(Context context) {
super(context);
mContext = context;
View customTitle = View.inflate(mContext, R.layout.alert_dialog_title, null);
mTitle = (TextView) customTitle.findViewById(R.id.alertTitle);
mIcon = (ImageView) customTitle.findViewById(R.id.icon);
setCustomTitle(customTitle);
View customMessage = View.inflate(mContext, R.layout.alert_dialog_message, null);
mMessage = (TextView) customMessage.findViewById(R.id.message);
setView(customMessage);
}
#NonNull
#Override
public AlertDialog.Builder setPositiveButton(CharSequence text, DialogInterface.OnClickListener listener) {
return super.setPositiveButton(text, listener);
}
#NonNull
#Override
public AlertDialog.Builder setPositiveButton(int textId, DialogInterface.OnClickListener listener) {
return super.setPositiveButton(textId, listener);
}
#Override
public CustomAlertDialogBuilder setTitle(int textResId) {
mTitle.setText(textResId);
return this;
}
#Override
public CustomAlertDialogBuilder setTitle(CharSequence text) {
mTitle.setText(text);
return this;
}
#Override
public CustomAlertDialogBuilder setMessage(int textResId) {
mMessage.setText(textResId);
return this;
}
#Override
public CustomAlertDialogBuilder setMessage(CharSequence text) {
mMessage.setText(text);
return this;
}
#Override
public CustomAlertDialogBuilder setIcon(int drawableResId) {
mIcon.setImageResource(drawableResId);
return this;
}
#Override
public CustomAlertDialogBuilder setIcon(Drawable icon) {
mIcon.setImageDrawable(icon);
return this;
}
}
You could disable the standard title with
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
and through
builder.setView(inflater.inflate(R.layout.dialog_signin, null))
Have a view with custom title.