I have a custom Dialog Fragment and I need to display an Alert dialog inside it.
Is it possible to do without closing the Dialog fragment?
When I do it with the context provided for the Dialog fragment it just closes the Dialog fragment and open the Alert dialog.
case R.id.deleteButton:
new AlertDialog.Builder(context)
.setTitle(context.getResources().getString(R.string.discard_changes))
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, (dialog, whichButton) -> {
onItemClickListener.onItemClick(Device, DELETE_DOC);
dismiss();
})
.setNegativeButton(android.R.string.no, null).show();
break;
EDIT
As requested, the whole Dialog code:
public class InstallationDocumentDeviceAddFormDialog extends Dialog implements View.OnClickListener {
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
private Context context;
private Button btn_cancel;
NavBar navBar;
Button addDeviceButton;
ImageButton deleteButton;
boolean isEditMode;
public static int EDIT_INSTALLATIONDOC = 1;
public static int DELETE_INSTALLATIONDOC = 2;
private InstallationDocumentDevice installationDocumentDevice;
public interface OnItemClickListener {
void onItemClick(InstallationDocumentDevice installationDocumentDevice, int action);
}
#NonNull
private OnItemClickListener onItemClickListener;
public InstallationDocumentDeviceAddFormDialog(#NonNull Context context, InstallationDocumentDevice installationDocumentDevice, boolean isEditMode, #NonNull OnItemClickListener onItemClickListener) {
super(context);
this.context = context;
this.onItemClickListener = onItemClickListener;
this.installationDocumentDevice = installationDocumentDevice;
this.isEditMode = isEditMode;
Log.i("DocumentController", "dialog device: " + installationDocumentDevice.toString());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_new_device_form);
RecyclerView accessoriesRecyclerView = (RecyclerView) findViewById(R.id.addNewDeviceAccessoriesRecycler);
RecyclerView guidancesRecyclerView = (RecyclerView) findViewById(R.id.addNewDeviceGuidancesRecycler);
RecyclerView testsRecyclerView = (RecyclerView) findViewById(R.id.addNewDeviceTestsRecycler);
navBar = findViewById(R.id.navBar);
if(isEditMode) navBar.setTitle(context.getResources().getString(R.string.editing_device) + " " + installationDocumentDevice.getLocalizedDeviceName());
else navBar.setTitle(context.getResources().getString(R.string.adding_new_device) + " " + installationDocumentDevice.getLocalizedDeviceName());
addDeviceButton = findViewById(R.id.btnAddNewDevice);
addDeviceButton.setOnClickListener(this);
deleteButton = (ImageButton) findViewById(R.id.deleteButton);
if(isEditMode){
deleteButton.setVisibility(View.VISIBLE);
deleteButton.setOnClickListener(this);
addDeviceButton.setText(context.getResources().getString(R.string.add_new_device_title));
} else {
deleteButton.setVisibility(View.GONE);
}
// navBar.getBackButton().setOnClickListener(view -> dismiss());
accessoriesRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
guidancesRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
testsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
accessoriesRecyclerView.setAdapter(new InstallationDocumentDeviceAddFormAdapter(installationDocumentDevice, this::onClick, InstallationDocumentDeviceAddFormAdapter.ACCESSORIES));
guidancesRecyclerView.setAdapter(new InstallationDocumentDeviceAddFormAdapter(installationDocumentDevice, this::onClick, InstallationDocumentDeviceAddFormAdapter.GUIDANCES));
testsRecyclerView.setAdapter(new InstallationDocumentDeviceAddFormAdapter(installationDocumentDevice, this::onClick, InstallationDocumentDeviceAddFormAdapter.TESTS));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnAddNewDevice:
onItemClickListener.onItemClick(installationDocumentDevice, EDIT_INSTALLATIONDOC);
dismiss();
break;
case R.id.deleteButton:
new AlertDialog.Builder(context)
.setTitle(context.getResources().getString(R.string.datapick_discard_changes))
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, (dialog, whichButton) -> {
onItemClickListener.onItemClick(installationDocumentDevice, DELETE_INSTALLATIONDOC);
dismiss();
})
.setNegativeButton(android.R.string.no, null).show();
// onItemClickListener.onItemClick(installationDocumentDevice, DELETE_INSTALLATIONDOC);
// dismiss();
break;
}
dismiss();
}
private void onClick(int position, int tag) {
switch (tag) {
//Case Accessory
case 1:
// Toast.makeText(context, "Accessory pos: " + position + ". Is checked: " + installationDocumentDevice.getAccessories().get(position).isChecked(), Toast.LENGTH_SHORT).show();
break;
//Case Guidance
case 2:
// Toast.makeText(context, "Guidances pos: " + position, Toast.LENGTH_SHORT).show();
break;
//Case Tests
case 3:
// Toast.makeText(context, "Tests pos: " + position, Toast.LENGTH_SHORT).show();
break;
}
}
}
/* Yes This is Possible You Can Grow through Below My Code which I Use In Recycler Adapter in Holder View Click Event.*/
holder.calendar_day_gridcell.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v1) {
// holder.txt_InTime.setText("Helllo");
try {
// Date parsedDate = dateFormatter.parse(date_month_year);
//Log.d(tag, "Parsed Date: " + parsedDate.toString());
DoubleClickPerform.preventTwoClick(v1);
final Dialog dialog = new Dialog(context,R.style.Theme_AppCompat_Dialog_Alert);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Calendar calendar;
int currentHour;
int currentMinute;
TextView txt_dialog_InTime,txt_dialog_OutTime,txt_dialog_SaveInTime,/*txt_dialog_Delete_InTime*/txt_dialog_SaveOutTime/*txt_dialog_Delete_OutTime*/;
ImageView img_clean_in_time,img_clean_out_time;
Button btn_close;
View view1 = context.getLayoutInflater().inflate(R.layout.in_out_time_dialog, null);
txt_dialog_InTime = view1.findViewById(R.id.txt_dialog_InTime);
txt_dialog_OutTime = view1.findViewById(R.id.txt_dialog_OutTime);
txt_dialog_SaveInTime = view1.findViewById(R.id.txt_dialog_SaveInTime);
// txt_dialog_Delete_InTime = view1.findViewById(R.id.txt_dialog_Delete_InTime);
txt_dialog_SaveOutTime = view1.findViewById(R.id.txt_dialog_SaveOutTime);
// txt_dialog_Delete_OutTime = view1.findViewById(R.id.txt_dialog_Delete_OutTime);
img_clean_in_time = view1.findViewById(R.id.img_clean_in_time);
img_clean_out_time = view1.findViewById(R.id.img_clean_out_time);
btn_close = view1.findViewById(R.id.btn_close);
calendar = Calendar.getInstance();
currentHour = calendar.get(Calendar.HOUR_OF_DAY);
currentMinute = calendar.get(Calendar.MINUTE);
txt_dialog_InTime.setText(holder.txt_InTime.getText().toString());
if(txt_dialog_InTime.getText().toString().equals(""))
{
txt_dialog_OutTime.setEnabled(false);
}
else
{
txt_dialog_OutTime.setEnabled(true);
}
btn_close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
txt_dialog_InTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TimePickerDialog timePickerDialog= new TimePickerDialog(context,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int hour, int minute) {
Time time = new Time(hour, minute, 0);
//little h uses 12 hour format and big H uses 24 hour format
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm aa");
//format takes in a Date, and Time is a sublcass of Date
String s = simpleDateFormat.format(time);
txt_dialog_InTime.setText(s);
}
}, currentHour, currentMinute, false);
timePickerDialog.show();
}
});
dialog.setContentView(view1);
dialog.show();
img_clean_in_time.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txt_dialog_InTime.setText("");
}
});
img_clean_out_time.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txt_dialog_OutTime.setText("");
}
});
txt_dialog_OutTime.setText(holder.txt_OutTime.getText().toString());
txt_dialog_OutTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TimePickerDialog timePickerDialog= new TimePickerDialog(context,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int hour, int minute) {
Time time = new Time(hour, minute, 0);
//little h uses 12 hour format and big H uses 24 hour format
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm aa");
//format takes in a Date, and Time is a sublcass of Date
String s = simpleDateFormat.format(time);
txt_dialog_OutTime.setText(s);
}
}, currentHour, currentMinute, false);
timePickerDialog.show();
}
});
dialog.setContentView(view1);
dialog.show();
/* txt_dialog_Delete_InTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.txt_InTime.setText("");
dialog.dismiss();
}
});
txt_dialog_Delete_OutTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.txt_OutTime.setText("");
dialog.dismiss();
}
});
*/
txt_dialog_SaveInTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.txt_InTime.setText(txt_dialog_InTime.getText().toString());
apiforSaveTime(txt_dialog_InTime.getText().toString(),txt_dialog_OutTime.getText().toString(), finalRevereseDate);
dialog.dismiss();
}
});
txt_dialog_SaveOutTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.txt_OutTime.setText(txt_dialog_OutTime.getText().toString());
if(!txt_dialog_InTime.getText().toString().equals(""))
{
apiforSaveTime(txt_dialog_InTime.getText().toString(),txt_dialog_OutTime.getText().toString(), finalRevereseDate);
dialog.dismiss();
}
else
{
Snackbar snackbar = Snackbar
.make(holder.itemView, "In Time Is Required", Snackbar.LENGTH_LONG);
snackbar.show();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
Related
I developing a Quiz program it's displaying questions in fragments.
For true/false questions 1st Fragment
For MCQ 2nd Fragment
MainActivity (From main I send qs list to mcq fragment and another one)
These 2 Fragments displayed randomly while the quiz is over.
But I need to add a Timer to every Fragment. How can I achieve this?
I have posted the code of MCQ Fragment, Other one is the same like that. (only interfaces differ) I want to know where exactly I need to put the Timer in this.
ActivityMCQ.java (MCQ - Fragment)
public class ActivityMCQ extends Fragment implements View.OnClickListener {
private ImageView iv_yellow_bin, iv_red_bin, iv_black_bin, iv_blue_sharp_box, iv_white_sharp_box, iv_question_image;
private TextView tv_name_of_image;
private int current_questionMCQ,current_questionTrueFalse;
private int score;
private ArrayList<Question> mSQSList = new ArrayList<>();
private ArrayList<Question> trueFalseQsList = new ArrayList<>();
private boolean isFirstMCQ,isFirstTrueFalse;
private static final int TOTAL_NO_OF_QS = 13;
private TextView timer;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.activity_mcq, container, false);
tv_name_of_image = root.findViewById(R.id.tv_name_of_image);
iv_yellow_bin = root.findViewById(R.id.iv_yellow_bin);
iv_red_bin = root.findViewById(R.id.iv_red_bin);
iv_black_bin = root.findViewById(R.id.iv_black_bin);
iv_blue_sharp_box = root.findViewById(R.id.iv_blue_sharp_box);
iv_white_sharp_box = root.findViewById(R.id.iv_white_sharp_box);
timer = root.findViewById(R.id.timer);
iv_yellow_bin.setOnClickListener(this);
iv_red_bin.setOnClickListener(this);
iv_black_bin.setOnClickListener(this);
iv_blue_sharp_box.setOnClickListener(this);
iv_white_sharp_box.setOnClickListener(this);
iv_question_image = root.findViewById(R.id.iv_question_image);
trueFalseQsList = (ArrayList<Question>)getArguments().getSerializable("trueFalseQsList");
mSQSList = (ArrayList<Question>)getArguments().getSerializable("mSQSList");
current_questionMCQ = getArguments().getInt("current_questionMCQ");
current_questionTrueFalse = getArguments().getInt("current_questionTrueFalse");
score = getArguments().getInt("score");
isFirstTrueFalse = getArguments().getBoolean("isFirstTrueFalse");
isFirstMCQ = getArguments().getBoolean("isFirstMCQ");
if(isFirstMCQ){
iv_question_image.setImageDrawable(getResources().getDrawable(mSQSList.get(0).getImageId()));
tv_name_of_image.setText(mSQSList.get(0).getQuestion());
isFirstMCQ = false;
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
timer.setText("Seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
move();
}
}.start();
}else{
moveToNextQuestion();
}
return root;
}
public void checkAnswer(String markedAnswer){
if(mSQSList.get(current_questionMCQ).getColor().equals(markedAnswer)){
score++;
showAnswerDetail(true);
}else{
showAnswerDetail(false);
}
}
public void moveToNextQuestion(){
Log.w("LOGs","CURRENT QS animateQuestion : "+current_questionMCQ);
if (current_questionMCQ+current_questionTrueFalse<TOTAL_NO_OF_QS){
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
timer.setText("Seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
animateQuestion(getActivity(), iv_question_image, BitmapFactory.decodeResource(getResources(), mSQSList.get(current_questionMCQ).getImageId()) , tv_name_of_image, mSQSList.get(current_questionMCQ).getQuestion());
}
}.start();
}else {
showDialogue();
}
}
public void showDialogue(){
androidx.appcompat.app.AlertDialog.Builder alertDialog2 = new androidx.appcompat.app.AlertDialog.Builder(getActivity());
alertDialog2.setTitle("Finished!");
final LinearLayout linearLayout = new LinearLayout(getActivity());
linearLayout.setOrientation(LinearLayout.VERTICAL);
final TextView total_questions = new TextView(getActivity());
LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
total_questions.setText("Your Score = " + score + "/5.");
alertDialog2.setPositiveButton("Exit & Go to Dashboard",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
startActivity(new Intent(getActivity(), ActivityHomepage.class));
}
});
alertDialog2.setNegativeButton("Retry This Test",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
startActivity(new Intent(getActivity(), Quiz_Main.class));
}
});
total_questions.setPadding(100, 30,0,0);
total_questions.setLayoutParams(lp2);
linearLayout.addView(total_questions);
alertDialog2.setView(linearLayout);
alertDialog2.setCancelable(false);
alertDialog2.show();
}
public static void animateQuestion(Context c, final ImageView iv_question, final Bitmap question_image, final TextView tv_question, final String question_text) {
iv_question.setImageBitmap(question_image);
tv_question.setText(question_text);
/*final Animation anim_out = AnimationUtils.loadAnimation(c, android.R.anim.fade_out);
final Animation anim_in = AnimationUtils.loadAnimation(c, android.R.anim.fade_in);
anim_out.setAnimationListener(new Animation.AnimationListener() {
#Override public void onAnimationStart(Animation animation) {}
#Override public void onAnimationRepeat(Animation animation) {}
#Override public void onAnimationEnd(Animation animation)
{
iv_question.setImageBitmap(question_image);
tv_question.setText(question_text);
anim_in.setAnimationListener(new Animation.AnimationListener() {
#Override public void onAnimationStart(Animation animation) {}
#Override public void onAnimationRepeat(Animation animation) {}
#Override public void onAnimationEnd(Animation animation) {}
});
iv_question.startAnimation(anim_in);
tv_question.startAnimation(anim_in);
}
});
iv_question.startAnimation(anim_out);
tv_question.startAnimation(anim_out);*/
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.iv_yellow_bin:
checkAnswer("Yellow");
break;
case R.id.iv_red_bin:
checkAnswer("Red");
break;
case R.id.iv_black_bin:
checkAnswer("Black");
break;
case R.id.iv_blue_sharp_box:
checkAnswer("Blue");
break;
case R.id.iv_white_sharp_box:
checkAnswer("White");
break;
}
}
public void showAnswerDetail(boolean isCorrect){
AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(getActivity());
alertDialog2.setTitle(isCorrect ? "Correct Answer!" : "Wrong Answer!");
final LinearLayout linearLayout = new LinearLayout(getActivity());
linearLayout.setOrientation(LinearLayout.VERTICAL);
final TextView total_questions = new TextView(getActivity());
LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
total_questions.setText("Your Score = " + score + "/15.");
alertDialog2.setPositiveButton("Next Question",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Log.w("LOGs","CURRENT TRUEFALS QS : "+current_questionTrueFalse);
Log.w("LOGs","CURRENT MCQ QS : "+current_questionMCQ);
move();
}
});
total_questions.setPadding(100, 30,0,0);
total_questions.setLayoutParams(lp2);
linearLayout.addView(total_questions);
alertDialog2.setView(linearLayout);
alertDialog2.setCancelable(false);
alertDialog2.show();
}
private void move(){
if(new Random().nextBoolean()){
if (current_questionMCQ<mSQSList.size()-1){
current_questionMCQ++;
moveToNextQuestion();
}else if (current_questionTrueFalse<trueFalseQsList.size()-1) {
current_questionTrueFalse++;
FragmentManager fm = getActivity().getSupportFragmentManager();
Bundle mbundle = new Bundle();
mbundle.putSerializable("trueFalseQsList", trueFalseQsList);
mbundle.putSerializable("mSQSList", mSQSList);
mbundle.putInt("current_questionMCQ", current_questionMCQ);
mbundle.putInt("current_questionTrueFalse", current_questionTrueFalse);
mbundle.putInt("score", score);
mbundle.putBoolean("isFirstMCQ", isFirstMCQ);
mbundle.putBoolean("isFirstTrueFalse", isFirstTrueFalse);
ActivityTrueFalse homeFragment = new ActivityTrueFalse();
homeFragment.setArguments(mbundle);
fm.beginTransaction()
.replace(R.id.container, homeFragment)
.commit();
}else{
showDialogue();
}
}else{
if (current_questionTrueFalse<trueFalseQsList.size()-1) {
current_questionTrueFalse++;
FragmentManager fm = getActivity().getSupportFragmentManager();
Bundle mbundle = new Bundle();
mbundle.putSerializable("trueFalseQsList", trueFalseQsList);
mbundle.putSerializable("mSQSList", mSQSList);
mbundle.putInt("current_questionMCQ", current_questionMCQ);
mbundle.putInt("current_questionTrueFalse", current_questionTrueFalse);
mbundle.putInt("score", score);
mbundle.putBoolean("isFirstMCQ", isFirstMCQ);
mbundle.putBoolean("isFirstTrueFalse", isFirstTrueFalse);
ActivityTrueFalse homeFragment = new ActivityTrueFalse();
homeFragment.setArguments(mbundle);
fm.beginTransaction()
.replace(R.id.container, homeFragment)
.commit();
}else if (current_questionMCQ<mSQSList.size()-1){
current_questionMCQ++;
moveToNextQuestion();
}else{
showDialogue();
}
}
}
}
public class fragment_oneway_flight extends Fragment {
private Spinner spinner1 ;
Context thiscontext;
private int mYear, mMonth, mDay, mHour, mMinute;
int countadult= 1;
int countchild= 0;
int countinfant= 0;
private ProgressDialog pDialog,pDialog1;
TextView quantity_adult_textview, quantity_child_textview, quantity_infant_textview, textview_city_slct_from_oneway, textview_city_slct_to_oneway;
private ImageButton increment_adult_Button, decrement_adult_Button, increment_child_Button, decrement_child_Button, increment_infant_Button, decrement_infant_Button;
private Button prcdtoonwyrslt;
public fragment_oneway_flight() {
// Required empty public constructor
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
thiscontext = container.getContext();
View rootView = inflater.inflate(R.layout.fragment_oneway_flight, container, false);
LinearLayout select_dep_date = (LinearLayout) rootView.findViewById(R.id.date_from_select_oneway);
select_dep_date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment dFragment = new DatePickerFragment();
// Show the date picker dialog fragment
dFragment.show(getFragmentManager(), "Date Picker");
}
});
LinearLayout city_slct_from_oneway = (LinearLayout) rootView.findViewById(R.id.city_slct_from_oneway);
city_slct_from_oneway.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogBoxFragment DialogBoxFragment = new DialogBoxFragment ();
DialogBoxFragment.show(getFragmentManager(),"dialog");
}
});
LinearLayout city_slct_to_oneway = (LinearLayout) rootView.findViewById(R.id.city_slct_to_oneway);
city_slct_to_oneway.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogBoxFragment2 DialogBoxFragment2 = new DialogBoxFragment2 ();
DialogBoxFragment2.show(getFragmentManager(),"dialog2");
}
});
prcdtoonwyrslt = (Button) rootView.findViewById( R.id.prcdtoonwyrslt );
prcdtoonwyrslt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), activity_flight_result_oneway.class);
pDialog1 = new ProgressDialog(getActivity());
pDialog1.setMessage("Please Wait...");
pDialog1.setCancelable(false);
String countadult = quantity_adult_textview.getText().toString();
String countchild = quantity_child_textview.getText().toString();
String countinfant = quantity_infant_textview.getText().toString();
String selectedfromcity = textview_city_slct_from_oneway.getText().toString();
String selectedtocity = textview_city_slct_to_oneway.getText().toString();
intent.putExtra("adultsnos", countadult);
intent.putExtra("childsnos", countchild);
intent.putExtra("infantsnos", countinfant);
intent.putExtra("fromcity", selectedfromcity);
intent.putExtra("tocity", selectedtocity);
startActivity(intent);
}
});
// button function start
increment_adult_Button = (ImageButton) rootView.findViewById( R.id.increment_adult_Button );
decrement_adult_Button = (ImageButton) rootView.findViewById( R.id.decrement_adult_Button );
increment_child_Button = (ImageButton) rootView.findViewById( R.id.increment_child_Button );
decrement_child_Button = (ImageButton) rootView.findViewById( R.id.decrement_child_Button );
increment_infant_Button = (ImageButton) rootView.findViewById( R.id.increment_infant_Button );
decrement_infant_Button = (ImageButton) rootView.findViewById( R.id.decrement_infant_Button );
quantity_adult_textview = (TextView) rootView.findViewById(R.id.quantity_adult_textview);
quantity_child_textview = (TextView) rootView.findViewById(R.id.quantity_child_textview);
quantity_infant_textview = (TextView) rootView.findViewById(R.id.quantity_infant_textview);
increment_adult_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countadult++;
if(countadult>7){
countadult=7;
}
display(countadult);
}
});
decrement_adult_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countadult--;
if(countadult<1){
countadult=1;
}
display(countadult);
}
});
increment_child_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countchild++;
if(countchild>5){
countchild=5;
}
display(countchild);
}
});
decrement_child_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countchild--;
if(countchild<0){
countchild=0;
}
display(countchild);
}
});
increment_infant_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countinfant++;
if(countinfant>5){
countinfant=5;
}
display(countinfant);
}
});
decrement_infant_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countinfant--;
if(countinfant<0){
countinfant=0;
}
display(countinfant);
}
});
// button function end
setSpinnerContent( rootView );
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> id, View rootView, int pos, long arg3) {
if (pos == 0) {
Toast.makeText(getActivity().getApplicationContext(),
"Select Class", Toast.LENGTH_SHORT)
.show();
} else if (pos == 1) {
Toast.makeText(getActivity().getApplicationContext(),
"You have selected Economy", Toast.LENGTH_SHORT)
.show();
} else if (pos == 2) {
Toast.makeText(getActivity().getApplicationContext(),
"You have selected Premium Economy", Toast.LENGTH_SHORT)
.show();
} else if (pos == 3) {
Toast.makeText(getActivity().getApplicationContext(),
"You have selected Business", Toast.LENGTH_SHORT)
.show();
}else if (pos == 4) {
Toast.makeText(getActivity().getApplicationContext(),
"You have selected First Class", Toast.LENGTH_SHORT)
.show();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
Toast.makeText(getActivity().getApplicationContext(), "Nothing to select", Toast.LENGTH_LONG).show();
}
});
return rootView;
}
private void setSpinnerContent( View rootView ) {
spinner1 = (Spinner) rootView.findViewById( R.id.spinner_flight );
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.flight_class_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter( adapter );
}
public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
final Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
/*
Initialize a new DatePickerDialog
DatePickerDialog(Context context, DatePickerDialog.OnDateSetListener callBack,
int year, int monthOfYear, int dayOfMonth)
*/
DatePickerDialog dpd = new DatePickerDialog(getActivity(), R.style.DateDialog,this,year,month,day);
return dpd;
}
public void onDateSet(DatePicker view, int year, int month, int day){
// Do something with the chosen date
TextView dep_date_flight = (TextView) getActivity().findViewById(R.id.text_dep_date);
// Create a Date variable/object with user chosen date
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(0);
cal.set(year, month, day, 0, 0, 0);
Date chosenDate = cal.getTime();
// Format the date using style and locale
DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US);
String formattedDate = df.format(chosenDate);
// Display the chosen date to app interface
dep_date_flight.setText(formattedDate);
}
}
private void display(int number) {
quantity_adult_textview.setText(String.valueOf(countadult));
quantity_child_textview.setText(String.valueOf(countchild));
quantity_infant_textview.setText(String.valueOf(countinfant));
}
public static class DialogBoxFragment extends DialogFragment {
//declaring variables
private ListView listviewforresults;
//Adapter for listview
ArrayAdapter<String> list1adapter;
//Edittext for search
EditText searchdata;
//ArrayList for listview
ArrayList<String> data=new ArrayList<String>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView1 = inflater.inflate(R.layout.fragment_city_select_flight, container, false);
prepareDummyData();
listviewforresults=(ListView)rootView1.findViewById(R.id.showdata);
searchdata=(EditText)rootView1.findViewById(R.id.searchdata);
//set data to Adapter
list1adapter=new ArrayAdapter<String>(getActivity(), country_list,R.id.results,data);
listviewforresults.setAdapter(list1adapter);
//search data when text changes in edittext
searchdata.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
list1adapter.getFilter().filter(s);
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
listviewforresults.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
String selectedFromList = (String) listviewforresults.getItemAtPosition(position).toString();
TextView textview_city_slct_from_oneway = (TextView) getActivity().findViewById(R.id.textview_city_slct_from_oneway);
textview_city_slct_from_oneway.setText(selectedFromList);
getDialog().dismiss();
}
});
getDialog().setTitle("dialog");
return rootView1;
}
public void prepareDummyData()
{
data.add("Chennai");
data.add("Mumbai");
data.add("Bangalore");
data.add("Madurai");
data.add("Coimbatore");
data.add("Newdelhi");
}
}
public static class DialogBoxFragment2 extends DialogFragment {
//declaring variables
private ListView listviewforresults2;
//Adapter for listview
ArrayAdapter<String> list2adapter;
//Edittext for search
EditText searchdata;
//ArrayList for listview
ArrayList<String> data=new ArrayList<String>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView2 = inflater.inflate(R.layout.fragment_city_select_flight2, container, false);
prepareDummyData2();
listviewforresults2=(ListView)rootView2.findViewById(R.id.showdata);
searchdata=(EditText)rootView2.findViewById(R.id.searchdata);
//set data to Adapter
list2adapter=new ArrayAdapter<String>(getActivity(), country_list,R.id.results,data);
listviewforresults2.setAdapter(list2adapter);
//search data when text changes in edittext
searchdata.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
list2adapter.getFilter().filter(s);
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
listviewforresults2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
String selectedFromList2 = (String) listviewforresults2.getItemAtPosition(position).toString();
TextView textview_city_slct_to_oneway = (TextView) getActivity().findViewById(R.id.textview_city_slct_to_oneway);
textview_city_slct_to_oneway.setText(selectedFromList2);
getDialog().dismiss();
}
});
getDialog().setTitle("dialog2");
return rootView2;
}
public void prepareDummyData2() {
data.add("Chennai");
data.add("Mumbai");
data.add("Bangalore");
data.add("Madurai");
data.add("Coimbatore");
data.add("Newdelhi");
}
}
}
the above code is full fragment code with gialog innerclass too. im a beginner can you gys help me out of it?
and actually what i need is i have to click the from and to area in tab view fragment. after slecting it opens a dialog with search filter and listview. after clicking any list item it should diaplay in textview on parent fragment and after that i should be able wo pass the value to next fragment using put intent method.
currently im getting null value when i pass it to the next fragment.
i dont know why.
i have attached an image to get you the clear view. please check it.see here
I try to google play subscription billing. Code is working doing payment. But I want to try when a payment successfull ı want to catch payment cost,time(montly,yearly) and I send my php API for example with an ID or Token. How can i do this.
I tried overriding onPurchasesUpdated
public void onPurchasesUpdated(BillingResult billingResult, #Nullable List<Purchase> purchases) {
}
but it didn't work . I tried show a toast. But method didn't work.
Can I do this with this method If I can how can I run this method ?
public void openPayment(final Context mContext){
final List<String> skuList = new ArrayList<>();
//valueof1MonthMoney,valueof3MonthsMoney,valueof6MonthsMoney,valueof1YearMoney;
skuList.add("com.yeniasya.enewspaper.subscription.onemonth");
skuList.add("com.yeniasya.enewspaper.subscription.threemonth");
skuList.add("com.yeniasya.enewspaper.subscription.sixmonth");
skuList.add("com.yeniasya.enewspaper.subscription.oneyear");
SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(mContext,android.R.style.Theme_DeviceDefault_Light_NoActionBar_Fullscreen);
LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View mView = li.inflate(R.layout.popup_payment, null);
ImageView imvClose=(ImageView)mView.findViewById(R.id.imvClose);
final TextView tv1MonthMoney = (TextView) mView.findViewById(R.id.tv1MonthMoney);
final TextView tv3MonthsMoney = (TextView) mView.findViewById(R.id.tv3MonthsMoney);
final TextView tv6MonthsMoney = (TextView) mView.findViewById(R.id.tv6MonthsMoney);
final TextView tv1YearMoney = (TextView) mView.findViewById(R.id.tv1YearMoney);
final TextView tvOpenPrivacy = (TextView) mView.findViewById(R.id.tvOpenPrivacy);
final LinearLayout linLay1Year = (LinearLayout) mView.findViewById(R.id.linLay1Year);
final LinearLayout linLay6Months = (LinearLayout) mView.findViewById(R.id.linLay6Months);
final LinearLayout linLay3Months = (LinearLayout) mView.findViewById(R.id.linLay3Months);
final LinearLayout linLay1Month = (LinearLayout) mView.findViewById(R.id.linLay1Month);
mBuilder.setView(mView);
dialog = mBuilder.create();
dialog.setCanceledOnTouchOutside(false);
final SkuDetails[] s = new SkuDetails[4];
params.setSkusList(skuList).setType(BillingClient.SkuType.SUBS);
billingClient.querySkuDetailsAsync(params.build(),
new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(BillingResult billingResult,
List<SkuDetails> skuDetailsList) {
// Process the result.
s[0] =skuDetailsList.get(0);
s[1] =skuDetailsList.get(1);
s[2] =skuDetailsList.get(2);
s[3] =skuDetailsList.get(3);
// Toast.makeText(mContext, "listeye girdi", Toast.LENGTH_SHORT).show();
try {
tv1MonthMoney.setText(skuDetailsList.get(0).getPrice());
tv1YearMoney.setText(skuDetailsList.get(1).getPrice());
tv6MonthsMoney.setText(skuDetailsList.get(2).getPrice());
tv3MonthsMoney.setText(skuDetailsList.get(3).getPrice());
/* if(skuDetailsList.get(i).getSku().equals("com.yeniasya.enewspaper.subscription.onemonth"));
tv1MonthMoney.setText(skuDetailsList.get(i).getPrice()+"");
if(skuDetailsList.get(i).getSku().equals("com.yeniasya.enewspaper.subscription.threemonth"));
tv3MonthsMoney.setText(skuDetailsList.get(i).getPrice()+"");
if(skuDetailsList.get(i).getSku().equals("com.yeniasya.enewspaper.subscription.sixmonth"));
tv6MonthsMoney.setText(skuDetailsList.get(i).getPrice()+"");
if(skuDetailsList.get(i).getSku().equals("com.yeniasya.enewspaper.subscription.oneyear"));
tv1YearMoney.setText(skuDetailsList.get(i).getPrice()+""); */
// Toast.makeText(mContext, skuDetailsList.get(i).getSku()+"", Toast.LENGTH_SHORT).show();
}catch (Exception e){
}
}
});
dialog.show();
imvClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
linLay1Year.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takeMoney(s[1]);
}
});
linLay1Month.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takeMoney(s[0]);
}
});
linLay3Months.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takeMoney(s[3]);
}
});
linLay6Months.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takeMoney(s[2]);
}
});
tvOpenPrivacy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
Intent i = new Intent(Intent.ACTION_VIEW);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setData(Uri.parse(mcontext.getString(R.string.PrivacyPolicyUrl)));
mcontext.startActivity(i);}catch (Exception e){}
}
});
}
private void takeMoney(SkuDetails skuDetails){
BillingFlowParams flowParams = BillingFlowParams.newBuilder()
.setSkuDetails(skuDetails)
.build();
billingClient.launchBillingFlow(MainActivity.mActivity,flowParams);
// Toast.makeText(mContext, "bastın3", Toast.LENGTH_SHORT).show();
}
#Override
public void onPurchasesUpdated(BillingResult billingResult, #Nullable List<Purchase> purchases) {
}
This question already has answers here:
how to pass value data between classes/activity in Android?
(6 answers)
Closed 5 years ago.
I want to pass the value of textview1 of Income.java onClick of btn_save to the MainActivity. And also want to sum the value of MainActivity.java when again new value passed Please help me...
Income.java
public class Income extends AppCompatActivity implements AdapterView.OnItemSelectedListener,Calculator.OnDialogReturnListener,View.OnClickListener{
Spinner spinner1;
String[] name,name1;
Button btn_cancel, btn_save,acc_btn,button,updatebtn;
TextView textView1,textView2,accountTV,wantupdate,income;
//EditText textView1;
int yy,mm,dd;
private Income_class i_class;
DatabaseHandler mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.income);
textView1 = (TextView) findViewById(R.id.income_tv);
textView2 = (TextView) findViewById(R.id.date_tv);
accountTV = (TextView) findViewById(R.id.acc_tv);
income = (TextView) findViewById(R.id.incometv);
wantupdate = (TextView) findViewById(R.id.notupdate);
btn_cancel = (Button) findViewById(R.id.cancel_btn);
updatebtn = (Button) findViewById(R.id.up_btn);
acc_btn = (Button) findViewById(R.id.account_btn);
btn_save = (Button) findViewById(R.id.save_btn);
button = (Button) findViewById(R.id.btn);
final AlertDialog.Builder dialog = new AlertDialog.Builder(Income.this);
final AlertDialog.Builder dialog1 = new AlertDialog.Builder(Income.this);
final AlertDialog.Builder dialog2 = new AlertDialog.Builder(Income.this);
final AlertDialog.Builder dialog3 = new AlertDialog.Builder(Income.this);
final EditText editText = new EditText(Income.this);
dialog.setView(editText);
final DatabaseHandler db = new DatabaseHandler(Income.this);
mydb = new DatabaseHandler(this);
button.setOnClickListener(this);
// for calculator
final Calculator cdd = new Calculator(Income.this);
cdd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
//cdd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
cdd.setOnDialogReturnListener(this);
cdd.show();
// for displaying date
final Calendar c = Calendar.getInstance();
yy = c.get(Calendar.YEAR);
mm = c.get(Calendar.MONTH);
dd = c.get(Calendar.DAY_OF_MONTH);
//set current date into text..
textView2.setText(new StringBuilder()
//month os 0 based. Just add 1
.append(dd).append("-").append(mm + 1).append("-").append(yy));
btn_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Income.this,MainActivity.class);
startActivity(intent);
finish();
}
});
acc_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Income.this,Account_detail.class);
startActivity(intent);
finish();
}
});
updatebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String cat = button.getText().toString();
String acc = accountTV.getText().toString();
String text = textView1.getText().toString();
if(text.equals("0")){
dialog3.setTitle("You must enter amount.");
dialog3.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface ialog, int which) {
}
});
dialog3.show();
}
else if(cat.equals("Select Category")){
dialog1.setTitle("Please Select category");
dialog1.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/*Intent intent = new Intent(Income.this, Income.class);
startActivity(intent);
finish();*/
button.requestFocus();
}
});
dialog1.show();
}
else if(acc.equals("")){
dialog2.setTitle("Please Select Account");
dialog2.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
acc_btn.requestFocus();
}
});
dialog2.show();
}
else {
String value = accountTV.getText().toString();
String value2 = textView1.getText().toString();
String value3 = button.getText().toString();
db.update_income(value, value2, value3);
Toast.makeText(getBaseContext(), "Updated Successfully...", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Income.this, Acc_income.class);
startActivity(intent);
finish();
}
}
});
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String cat = button.getText().toString();
String acc = accountTV.getText().toString();
String text = textView1.getText().toString();
if(text.equals("0")){
dialog3.setTitle("You must enter amount.");
dialog3.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface ialog, int which) {
}
});
dialog3.show();
}
else if(cat.equals("Select Category")){
dialog1.setTitle("Please Select category");
dialog1.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/*Intent intent = new Intent(Income.this, Income.class);
startActivity(intent);
finish();*/
button.requestFocus();
}
});
dialog1.show();
}
else if(acc.equals("")){
dialog2.setTitle("Please Select Account");
dialog2.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
acc_btn.requestFocus();
}
});
dialog2.show();
}
else {
String balance2 = textView1.getText().toString();
String name = accountTV.getText().toString();
String category = button.getText().toString();
db.income_insert(name, category, balance2);
Toast.makeText(getBaseContext(), "Account Added...",
Toast.LENGTH_SHORT).show();
}
}
});
wantupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder dialog = new AlertDialog.Builder(Income.this);
dialog.setTitle("Enter Income");
final EditText editText = new EditText(Income.this);
dialog.setView(editText);
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String value1 = textView1.getText().toString();
String value2 = editText.getText().toString();
if(textView1.equals("0")){
String a = editText.getText().toString();
textView1.setText(a);
}
else if(value2.equals("")){
Toast.makeText(Income.this,"Please Enter Amount.",Toast.LENGTH_LONG).show();
}
else {
int a = Integer.parseInt(value1);
int b = Integer.parseInt(value2);
int sum = a + b;
textView1.setText(Integer.toString(sum));
}
}
});
dialog.show();
}
});
Intent intent = getIntent();
accountTV.setText(intent.getStringExtra("ppp"));
}
public void addnumber(){
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String name2 = name[position];
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onReturn(String data) {
textView1.setText(data);
}
#Override
public void onClick(View v) {
/*String cat = button.getText().toString();
if(cat.equals("Select Category")){
button.setError("Please Select category");
button.requestFocus();
}
else */
final CharSequence[] items = {"Automobile", "Entertainment", "Family", "Food And Drinks", "Gasoline", "Gifts And Donations",
"Groceries", "Health And Fitness", "Housing", "Medical", "Other", "Parking", "Shopping", "Utilities"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Make your selection");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
button.setText(items[item]);
}
});
AlertDialog alert = builder.create();
alert.show();
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(Income.this,MainActivity.class);
startActivity(intent);
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button expance,income,account,budget,calander,report,more,transfer;
TextView incomeTv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
incomeTv = (TextView)findViewById(R.id.incometv);
expance = (Button)findViewById(R.id.button_expanse);
income = (Button)findViewById(R.id.button_income);
account = (Button)findViewById(R.id.button_account);
budget = (Button)findViewById(R.id.button_budget);
transfer = (Button)findViewById(R.id.button_moneytransfer);
calander = (Button)findViewById(R.id.button_calander);
report = (Button)findViewById(R.id.button_report);
more = (Button)findViewById(R.id.button_more);
expance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Expense.class);
startActivity(intent);
finish();
}
});
income.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Income.class);
startActivity(intent);
finish();
}
});
account.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Account_detail.class);
startActivity(intent);
finish();
}
});
transfer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Account_Transfer.class);
startActivity(intent);
finish();
}
});
budget.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Acc_income.class);
startActivity(intent);
finish();
}
});
calander.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Account_detail_2.class);
startActivity(intent);
finish();
}
});
more.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Update.class);
startActivity(intent);
finish();
}
});
}
You can use
intent.putExtra("key", value);
I have a problem with my app about schedule SMS. If I schedule SMS in order by time for example first SMS at 12:00 and the second at 13:00, my app works. But if I schedule SMS first at 13:00 and then 12:00, my app doesn't work.
I used a sorting algorithm but it doesn’t work!
Here's my code:
MAIN ACTIVITY:
public class MainActivity extends Activity {
private static final int PERMS_REQUEST_CODE = 123;
private static final int REQUEST_CODE = 1;
TextView textViewTime;
TimePicker timePicker;
Button button;
String name2=null;
String sms2=null;
long tempo2;
int hour;
int minutee;
//int hour;
//int minute;
final int TIME_DIALOG_ID = 999;
public String sPhone, sSms;
public EditText etPhone, etSms;
public Button bStart, bCancel, bTimeSelect, bPhone;
ArrayList<Sms> dataSms;
ListView listView;
public static CustomAdapter adapter;
private static MainActivity ins;
EditText et1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ins = this;
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, 1);
listView = (ListView) findViewById(R.id.listView1);
/*listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
Toast.makeText(MainActivity.this, "Item has been added into your list", Toast.LENGTH_LONG)
.show();
//dataSms.remove(position);
//adapter.notifyDataSetChanged();
Sms dataModel= dataSms.get(position);
//dataModel.setTesto();
}
});*/
dataSms = new ArrayList<Sms>();
adapter = new CustomAdapter(dataSms, getApplicationContext());
listView.setAdapter(adapter);
//Button b=(Button) findViewById(R.id.button1);
//Button button=(Button) findViewById(R.id.button);
bStart = (Button) findViewById(R.id.bStart);
et1=(EditText)findViewById(R.id.editText1);
//bCancel = (Button)findViewById(R.id.bCancel);
//bTimeSelect = (Button) findViewById(R.id.bTime);
bPhone = (Button) findViewById(R.id.bCPhone);
bStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* if (hasPermissions()) {
// our app has permissions.
scheduleAlarm(v);
} else {
//our app doesn't have permissions, So i m requesting permissions.
requestPerms();
}*/
try {
scheduleAlarm(v);
} catch (ParseException e) {
e.printStackTrace();
}
}
});
et1.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onClick(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "TimePicker");
}
});
/* bTimeSelect.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onClick(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "TimePicker");
}
});*/
//};
bPhone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Uri uri = Uri.parse("content://contacts");
Intent intent = new Intent(Intent.ACTION_PICK, uri);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, REQUEST_CODE);
}
});
}
public static MainActivity getInstace(){
return ins;
}
public void updateTheTextView() {
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
// for(int i=0;i<adapter.getCount();i++)
// {
dataSms.remove(0);
adapter.notifyDataSetChanged();
// }
adapter.notifyDataSetChanged();
}
});
//adapter.notifyDataSetChanged();
//Toast.makeText(this, "COUNT DELETE: "+adapter.getCount(), Toast.LENGTH_LONG).show();
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#SuppressLint("ValidFragment")
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
//TimePicker timePicker;
//int hour;
//int minutee;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//Use the current time as the default values for the time picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
//Create and return a new instance of TimePickerDialog
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
//onTimeSet() callback method
#TargetApi(Build.VERSION_CODES.M)
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
hour = hourOfDay;
minutee = minute;
et1.setText( hour + ":" + minutee);
}
}
#TargetApi(Build.VERSION_CODES.M)
public void scheduleAlarm(View V) throws ParseException {
EditText et1 = (EditText) findViewById(R.id.etPhone);
EditText et2 = (EditText) findViewById(R.id.etSms);
String name = et1.getText().toString();
String sms = et2.getText().toString();
//PendingIntent pendingIntent;
//Long time= new GregorianCalendar().getTimeInMillis()+24*60*60*1000;
//Long time = new GregorianCalendar().getTimeInMillis() + 10000;
//Long time= System.currentTimeMillis() + 10000;
/*Intent intentAlarm = new Intent(this, AlarmReceiver.class);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Bundle bundle = new Bundle();
bundle.putCharSequence("Number", name);
bundle.putCharSequence("Message", sms);*/
//intentAlarm.putExtras(bundle);
final Calendar c = Calendar.getInstance();
c.setTimeInMillis(System.currentTimeMillis());
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, minutee);
long tempo=c.getTimeInMillis();
//Toast.makeText(this, "TEMPO: " + tempo, Toast.LENGTH_LONG).show();
//for(int i=0;i<dataSms.size();i++) {
adapter.add(new Sms(name, sms, tempo));
// Sms dataModel= dataSms.get(i);
// adapter.sortByNameAsc();
//Toast.makeText(this, "NOME: " + dataModel.getNome() +"TESTO "+dataModel.getTesto(), Toast.LENGTH_LONG).show();
//}
Toast.makeText(this, "COUNT: " + adapter.getCount(), Toast.LENGTH_LONG).show();
adapter.sortByNameAsc();
for(int i=0;i<dataSms.size();i++) {
//adapter.sortByNameAsc();
Sms dataModel= dataSms.get(i);
name2=dataModel.getNome();
sms2=dataModel.getTesto();
Intent intentAlarm = new Intent(this, AlarmReceiver.class);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// Bundle bundle = new Bundle();
// bundle.putCharSequence("Number", name);
// bundle.putCharSequence("Message", sms);
/*
Sms dataModel= dataSms.get(i);
name2=dataModel.getNome();
sms2=dataModel.getTesto();*/
//tempo2=dataModel.getTempo();
Bundle bundle = new Bundle();
bundle.putCharSequence("Number", name2);
bundle.putCharSequence("Message", sms2);
intentAlarm.putExtras(bundle);
alarmManager.set(AlarmManager.RTC_WAKEUP, dataModel.getTempo(), PendingIntent.getBroadcast(this, i, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
}
//alarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), PendingIntent.getBroadcast(this, 1, intentAlarm.putExtras(bundle), PendingIntent.FLAG_UPDATE_CURRENT));
Toast.makeText(this, "Messaggio programmato!", Toast.LENGTH_LONG).show();
}
}
CUSTOM ADAPTER:
public class CustomAdapter extends ArrayAdapter<Sms> {
public static CustomAdapter adapter;
private ArrayList<Sms> dataSms;
Context mContext;
Sms sms2;
Bundle getBundle = null;
//ArrayList<Location> data = new ArrayList<Location>();
// View lookup cache
private static class ViewHolder {
TextView txtNome;
TextView txtTesto;
TextView txtOre;
TextView txtMinuti;
}
public CustomAdapter(ArrayList<Sms> data, Context context) {
super(context, R.layout.row_item, data);
this.dataSms = data;
this.mContext=context;
}
public void sortByNameAsc() {
Comparator<Sms> comparator = new Comparator<Sms>() {
#Override
public int compare(Sms object1, Sms object2) {
//return (int) (object1.getTempo() - object2.getTempo());
return Long.valueOf(object1.getTempo()).compareTo(Long.valueOf(object2.getTempo()));
//return Double.compare(object1.getPrice(), object2.getPrice());
//return compare(object1.getTempo() - object2.getTempo());
}
};
Collections.sort(dataSms, comparator);
notifyDataSetChanged();
}
/* #Override
public void onClick(View v) {
int position=(Integer) v.getTag();
Object object= getItem(position);
DataModel dataModel=(DataModel)object;
switch (v.getId())
{
case R.id.item_info:
Snackbar.make(v, "Release date " +dataModel.getFeature(), Snackbar.LENGTH_LONG)
.setAction("No action", null).show();
break;
}
}*/
//private int lastPosition = -1;
//dataSms = new ArrayList<Sms>();
//adapter = new CustomAdapter(dataSms, context);
#Override
public int getCount() {
return dataSms.size();
}
/* #Override
public Object getItem(int pos) {
return dataSms.get(pos);
}*/
#Override
public long getItemId(int position) {
return position;
}
// #Override
public long getTime(long c,int position) {
return c;
}
#Override
public void add(Sms sms) {
dataSms.add(sms);
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Sms sms = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.row_item, parent, false);
viewHolder.txtNome = (TextView) convertView.findViewById(R.id.nome);
viewHolder.txtTesto = (TextView) convertView.findViewById(R.id.testo);
viewHolder.txtOre = (TextView) convertView.findViewById(R.id.ore);
viewHolder.txtMinuti = (TextView) convertView.findViewById(R.id.minuti);
result=convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result=convertView;
}
/*Animation animation = AnimationUtils.loadAnimation(mContext, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
result.startAnimation(animation);*/
// lastPosition = position;
viewHolder.txtNome.setText(sms.getNome());
viewHolder.txtTesto.setText(sms.getTesto());
// viewHolder.txtTempo.setText(String.valueOf(sms.getTempo()));
//viewHolder.txtOre.setText(String.valueOf(sms.getOre())+":");
// viewHolder.txtMinuti.setText(String.valueOf(sms.getMinuti()));
/*viewHolder.info.setOnClickListener(this);
viewHolder.info.setTag(position);*/
// Return the completed view to render on screen
return convertView;
}
}
MODEL CLASS:
public class Sms {
long tempo;
String nome;
String testo;
public Sms(String nome, String testo, long tempo) {
this.nome=nome;
this.testo=testo;
this.tempo=tempo;
//this.ore=ore;
// this.minuti=minuti;
}
public void setNome(String nome) {
this.nome = nome;
}
//int ore;
//public int getMinuti() {
// return minuti;
// }
//public void setMinuti(int minuti) {
// this.minuti = minuti;
// }
// public int getOre() {
// return ore;
// }
// public void setOre(int ore) {
// this.ore = ore;
// }
//int minuti;
public void setTesto(String testo) {
this.testo = testo;
}
//int indice;
public long getTempo() {
return tempo;
}
public void setTempo(long tempo) {
this.tempo = tempo;
}
public String getNome() {
return nome;
}
public String getTesto() {
return testo;
}
}