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();
}
}
}
}
Related
Here is a video of what I trying to do and explanation of the issue that I am having. Go to the following link below.
https://file.re/2021/09/12/2021-09-1210-43-21/
Here is the XML, Java, and Manifest Code Video. Go to the following link below.
https://file.re/2021/09/12/2021-09-1211-32-13/
Answer worked, but now I have two new problems. Here is the video link below.
https://file.re/2021/09/12/2021-09-1212-08-04/
I am creating an app that lists CardView layouts to a RecyclerView.
My app will add the CardView layout to the RecyclerView list, but it only lists one. I want it to add multiples of the same CardView when the user clicks on the button to add the card (basically cloning the CardView layout one under the other).
Here is what I have in my Button Click...
ftocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ArrayList<RecyclerItem> addFahToCelCard = new ArrayList<>();
addFahToCelCard.add(new RecyclerItem());
recyclerView = findViewById(R.id.recycler_item_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerItemAdapter = new RecyclerItemAdapter(addFahToCelCard);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerItemAdapter);
}
}
});
I've tried putting the ArrayList<RecyclerItem> addFahToCelCard = new ArrayList<>(); under the MainActivity extends AppCompatActivity class just before the onCreate like this...
public class MainActivity extends AppCompatActivity {
final private ArrayList<RecyclerItem> addFahToCelCard = new ArrayList<>();
That didn't work.
If I don't keep ArrayList<RecyclerItem> addFahToCelCard = new ArrayList<>(); in the button click listener, and I add a new CardView it will add a new one behind the original one each time the button is clicked, and if I delete the card it keep popping back up until I delete them all off. How do I fix this the way I want it to behave? I hope this all makes sense.
I appreciate the help!
Here is everything in the java class..
public class MainActivity extends AppCompatActivity {
ArrayList<RecyclerItem> addFahToCelCard;
private Animation fromBottom;
private Animation toBottom;
private Boolean clicked = false;
private RecyclerView recyclerView;
private RecyclerItemAdapter recyclerItemAdapter;
private RecyclerView.LayoutManager layoutManager;
public FloatingActionButton mainConverterMenuFloatBtn;
public TextView chooseConverterLabel, ftocConverterLabelBtn, ftokConverterLabelBtn, ctofConverterLabelBtn, ctokConverterLabelBtn, ktofConverterLabelBtn, ktocConverterLabelBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fromBottom = AnimationUtils.loadAnimation(MainActivity.this, R.anim.from_bottom_animation);
toBottom = AnimationUtils.loadAnimation(MainActivity.this, R.anim.to_bottom_animation);
mainConverterMenuFloatBtn = findViewById(R.id.add_temp_converter_float_btn);
chooseConverterLabel = findViewById(R.id.choose_converter_label);
ftocConverterLabelBtn = findViewById(R.id.add_f_to_c_converter_label_btn);
ftokConverterLabelBtn = findViewById(R.id.add_f_to_k_converter_label_btn);
ctofConverterLabelBtn = findViewById(R.id.add_c_to_f_converter_label_btn);
ctokConverterLabelBtn = findViewById(R.id.add_c_to_k_converter_label_btn);
ktofConverterLabelBtn = findViewById(R.id.add_k_to_f_converter_label_btn);
ktocConverterLabelBtn = findViewById(R.id.add_k_to_c_converter_label_btn);
addFahToCelCard = new ArrayList<>();
recyclerView = findViewById(R.id.recycler_item_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerItemAdapter = new RecyclerItemAdapter(addFahToCelCard);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerItemAdapter);
mainConverterMenuFloatBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mainConverterMenu();
}
});
ftocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
addFahToCelCard.add(new RecyclerItem());
recyclerItemAdapter.notifyDataSetChanged();
closeActionButton();
}
}
});
ftokConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
closeActionButton();
}
}
});
ctofConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
closeActionButton();
}
}
});
ctokConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
closeActionButton();
}
}
});
ktofConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
closeActionButton();
}
}
});
ktocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
closeActionButton();
}
}
});
}
private void addFahToCelCard() {
}
private void mainConverterMenu() {
setVisibility(clicked);
setClickable(clicked);
setAnimation(clicked);
clicked = !clicked;
}
private void setVisibility(Boolean clicked) {
if (!clicked) {
chooseConverterLabel.setVisibility(View.VISIBLE);
ftocConverterLabelBtn.setVisibility(View.VISIBLE);
ftokConverterLabelBtn.setVisibility(View.VISIBLE);
ctofConverterLabelBtn.setVisibility(View.VISIBLE);
ctokConverterLabelBtn.setVisibility(View.VISIBLE);
ktofConverterLabelBtn.setVisibility(View.VISIBLE);
ktocConverterLabelBtn.setVisibility(View.VISIBLE);
} else {
chooseConverterLabel.setVisibility(View.GONE);
ftocConverterLabelBtn.setVisibility(View.GONE);
ftokConverterLabelBtn.setVisibility(View.GONE);
ctofConverterLabelBtn.setVisibility(View.GONE);
ctokConverterLabelBtn.setVisibility(View.GONE);
ktofConverterLabelBtn.setVisibility(View.GONE);
ktocConverterLabelBtn.setVisibility(View.GONE);
}
}
private void setClickable(Boolean clicked) {
if (!clicked) {
chooseConverterLabel.setClickable(true);
ftocConverterLabelBtn.setClickable(true);
ftokConverterLabelBtn.setClickable(true);
ctofConverterLabelBtn.setClickable(true);
ctokConverterLabelBtn.setClickable(true);
ktofConverterLabelBtn.setClickable(true);
ktocConverterLabelBtn.setClickable(true);
} else {
chooseConverterLabel.setClickable(false);
ftocConverterLabelBtn.setClickable(false);
ftokConverterLabelBtn.setClickable(false);
ctofConverterLabelBtn.setClickable(false);
ctokConverterLabelBtn.setClickable(false);
ktofConverterLabelBtn.setClickable(false);
ktocConverterLabelBtn.setClickable(false);
}
}
private void setAnimation(Boolean clicked) {
if (!clicked) {
chooseConverterLabel.startAnimation(fromBottom);
ftocConverterLabelBtn.startAnimation(fromBottom);
ftokConverterLabelBtn.startAnimation(fromBottom);
ctofConverterLabelBtn.startAnimation(fromBottom);
ctokConverterLabelBtn.startAnimation(fromBottom);
ktofConverterLabelBtn.startAnimation(fromBottom);
ktocConverterLabelBtn.startAnimation(fromBottom);
} else {
chooseConverterLabel.startAnimation(toBottom);
ftocConverterLabelBtn.startAnimation(toBottom);
ftokConverterLabelBtn.startAnimation(toBottom);
ctofConverterLabelBtn.startAnimation(toBottom);
ctokConverterLabelBtn.startAnimation(toBottom);
ktofConverterLabelBtn.startAnimation(toBottom);
ktocConverterLabelBtn.startAnimation(toBottom);
}
}
private void closeActionButton() {
setVisibility(clicked);
setClickable(clicked);
setAnimation(clicked);
clicked = !clicked;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.app_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.show_hide_float_convert_btn) {
if (mainConverterMenuFloatBtn.isShown()) {
mainConverterMenuFloatBtn.setVisibility(View.GONE);
item.setIcon(R.drawable.ic_baseline_visibility_off_32);
} else if (!mainConverterMenuFloatBtn.isShown()) {
mainConverterMenuFloatBtn.setVisibility(View.VISIBLE);
item.setIcon(R.drawable.ic_baseline_visibility_32);
}
} else if (id == R.id.app_help) {
} else if (id == R.id.tip_developer) {
} else if (id == R.id.premium_features) {
} else if (id == R.id.about_app) {
} else if (id == R.id.exit_app) {
}
return super.onOptionsItemSelected(item);
}
public static class RecyclerItemAdapter extends RecyclerView.Adapter<RecyclerItemAdapter.RecyclerViewHolder> {
public ArrayList<RecyclerItem> recyclerItemList;
public AdapterView.OnItemClickListener recyclerItemListener;
public interface OnItemClickListener {
void onItemClick (int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
recyclerItemListener = (AdapterView.OnItemClickListener) listener;
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder {
EditText inputFahValueET;
TextView fahtoCelResult;
ImageView tempIconAndConvertBtn;
ImageView deleteCardBtn;
String shortResult, longResult;
public RecyclerViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
inputFahValueET = itemView.findViewById(R.id.input_fahrenheit_value_to_convert);
fahtoCelResult = itemView.findViewById(R.id.output_result_ftc);
tempIconAndConvertBtn = itemView.findViewById(R.id.temp_icon_convert_btn);
deleteCardBtn = itemView.findViewById(R.id.remove_card);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
}
}
public RecyclerItemAdapter(ArrayList<RecyclerItem> rList) {
recyclerItemList = rList;
}
#NonNull
#Override
public RecyclerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fahrenheit_to_celsius_converter_layout, parent, false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(v, (OnItemClickListener) recyclerItemListener);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewHolder holder, int position) {
RecyclerItem currentItem = recyclerItemList.get(position);
final String[] result = new String[1];
holder.tempIconAndConvertBtn.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View view) {
String getIputFahValue = holder.inputFahValueET.getText().toString();
NumberFormat nf = new DecimalFormat("0.000");
if(!getIputFahValue.isEmpty()) {
double d = Double.parseDouble(getIputFahValue);
double dd = d - 32;
double ddd = dd * 5;
double dddd = ddd / 9;
result[0] = Double.toString(dddd);
holder.fahtoCelResult.setText(nf.format(dddd) + "°C");
holder.fahtoCelResult.setVisibility(View.VISIBLE);
holder.shortResult = nf.format(dddd) + "°C";
holder.longResult = getIputFahValue + "°F is " + nf.format(dddd) + "°C";
if (result[0].contains(".0")) {
result[0] = result[0].replace(".0", "");
holder.fahtoCelResult.setText(result[0] + "°C");
holder.fahtoCelResult.setVisibility(View.VISIBLE);
holder.shortResult = result[0] + "°C";
holder.longResult = getIputFahValue + "°F is " + result[0] + "°C";
}else if (result[0].contains(".000")) {
result[0] = result[0].replace(".000", "");
holder.fahtoCelResult.setText(result[0] + "°C");
holder.fahtoCelResult.setVisibility(View.VISIBLE);
holder.shortResult = result[0] + "°C";
holder.longResult = getIputFahValue + "°F is " + result[0] + "°C";
}
}else {
Toast.makeText(view.getContext(), "Fahrenheit Value Field Cannot Be Blank!", Toast.LENGTH_LONG).show();
}
}
});
holder.fahtoCelResult.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
AlertDialog.Builder adb = new AlertDialog.Builder(view.getContext());
adb.setIcon(R.drawable.ic_baseline_file_copy_32);
adb.setTitle("Copy Result");
adb.setMessage("You can copy the result to your clipboard if you would like. Choose if you want the short or long result copied to your clipboard.\n\nExample of Short and Long Result:\nShort Result: 32°C\nLong Result: 0°F is 32°C");
adb.setPositiveButton("Short", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ClipboardManager cbm = (ClipboardManager) view.getContext().getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Copy", holder.shortResult);
cbm.setPrimaryClip(clip);
Toast.makeText(view.getContext(), "Result Copied!", Toast.LENGTH_SHORT).show();
}
});
adb.setNegativeButton("Long", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ClipboardManager cbm = (ClipboardManager) view.getContext().getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Copy", holder.longResult);
cbm.setPrimaryClip(clip);
Toast.makeText(view.getContext(), "Result Copied!", Toast.LENGTH_SHORT).show();
}
});
adb.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {}});
adb.create();
adb.show();
return false;
}
});
holder.deleteCardBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
recyclerItemList.remove(position);
notifyItemRemoved(position);
}
});
}
#Override
public int getItemCount() {
return recyclerItemList.size();
}
}
public class RecyclerItem {
public RecyclerItem() {
}
}
}
The recyclerView should be listing the CardViews and also allowing duplicates.
Well, I think you are just using the RecyclerView the wrong way.
In your code snippet, you are initializing the RecyclerView as well as the adapter and all other components every time the user clicks the button.
First of all you will have to create the insert method in the RecyclerItemAdapter class.
RecyclerItemAdapter.java
class RecyclerItemAdapter extends RecyclerView.Adapter<YourViewHolder> {
private ArrayList<RecyclerItem> items;
RecyclerItemAdapter(ArrayList<RecyclerItem> recyclerItems) {
this.items = recyclerItems;
}
//...
public void addItem(RecyclerItem item) {
items.add(item);
notifyDataSetChanged();
}
}
Then, you have ton initialize the RecyclerView only once. The best place to do that is in the onCreate method.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ArrayList<RecyclerItem> addFahToCelCard;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addFahToCelCard = new ArrayList<>();
setupRecyclerView();
setupClickListener();
}
private void setupRecyclerView() {
recyclerView = findViewById(R.id.recycler_item_view);
recyclerItemAdapter = new RecyclerItemAdapter(addFahToCelCard);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.setAdapter(recyclerItemAdapter);
}
}
Now add your onClickListener which will only add the card to the list.
private void setupClickListener() {
ftocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
recyclerItemAdapter.addItem(new RecyclerItem());
}
});
}
What is your xml layout for this cardview ? It looks like this cardview is in another layout that has match parent as width and height.
If thats the case items are too big to show.
Okay so try making first reletive layout height = 100dp to match the card view in fahrenheit_to_celsius_converter_layout.xml
well I didn't understand the problem very well but from what I understood here's what you should do :
first you shouldn't be creating a new recycler view on every button click, instead you should put the code that initializes the recycler view in onCreate method that exist in the activity class and just keep a reference to the arraylist that holds the data and the adapter as global variables.
whenever the user clicks the button you should add a new item to the arraylist of data and use adapter.notifyDataItemSetChanged to tell the recycle view to check if there's any change happened to the recycle view and take action if necessary
here's a part of code that explains what I'm saying and I hope you that even if that doesn't answer your question, you catch a glimpse of how to deal with recyclerview :
first as I said you should keep a reference to the arraylist that holds the data and the adapter as global variables so put those outside any method in the activity
RecyclerItemAdapter recyclerItemAdapter ;
ArrayList <RecyclerItem>addFahToCelCard ;
and then put this code instead of the button code
addFahToCelCard = new ArrayList<>();
recyclerView = findViewById(R.id.recycler_item_view);
layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerItemAdapter = new RecyclerItemAdapter(addFahToCelCard);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerItemAdapter);
ftocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addFahToCelCard.add(new RecyclerItem());
recyclerItemAdapter.notifyDataSetChanged();
}
}
});
that way whenever you want to edit the recyclerView data anytime you can add/remove items from the global arraylist and notify the adapter just like the code inside the button OnClickListener
update to the last video posted about the exception
this problem raises when you delete some items, try to use holder.getAbsoluteAdapterPosition(), instead of getAdapterPosition or the old final position value.
whenever you use a value inside a listener I guess it takes the value that exists right now and hold it as final, so if you have 5 items and deleted the first 3, the last two will still have their position stored as 4 and 5 instead of 1 and 2, thats why you should call the holder.getAbsoluteAdapterPosition() to get the current position instead of the final stored one, that way he stores the holder as final instead of storing a const int value.
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();
}
}
});
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) {
}
Hello need help with a class trying to figure out how to create a first and last button in a fragment that will jump to the first item in a ViewPager and the last item in a ViewPager I'm a bit lost with how to implement. Here is the fragment.
public class CrimeFragment extends Fragment {
private static final String ARG_CRIME_ID = "crime_id";
private static final String DIALOG_DATE = "DialogDate";
private static final int REQUEST_DATE = 0;
private Crime mCrime;
private EditText mTitleField;
private Button mDateButton;
private CheckBox mSolvedCheckBox;
private Spinner mSpinner;
private Button mFirstButton;
private Button mLastButton;
public static CrimeFragment newInstance(UUID crimeId) {
Bundle args = new Bundle();
args.putSerializable(ARG_CRIME_ID, crimeId);
CrimeFragment fragment = new CrimeFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
if (requestCode == REQUEST_DATE) {
Date date =
(Date) data.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
mCrime.setDate(date);
updateDate();
}
}
private void updateDate() {
mDateButton.setText(mCrime.getDate().toString());
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID crimeId = (UUID) getArguments().getSerializable(ARG_CRIME_ID);
mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_crime, container, false);
mTitleField = (EditText)v.findViewById(R.id.crime_title);
mTitleField.setText(mCrime.getTitle());
mTitleField.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(
CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(
CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
mDateButton = (Button) v.findViewById(R.id.crime_date);
updateDate();
mDateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager = getFragmentManager();
DatePickerFragment dialog = DatePickerFragment.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
dialog.show(manager, DIALOG_DATE);
}
});
mSpinner = (Spinner) v.findViewById(R.id.crime_severity);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),
R.array.severity_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
mCrime.setSeverity((String) mSpinner.getSelectedItem());
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
mSolvedCheckBox = (CheckBox) v.findViewById(R.id.crime_solved);
mSolvedCheckBox.setChecked(mCrime.isSolved());
mSolvedCheckBox.setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
mCrime.setSolved(isChecked);
}
});
mFirstButton = (Button) v.findViewById(R.id.first_crime_button);
mFirstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mLastButton = (Button) v.findViewById(R.id.last_crime_button);
mLastButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return v;
}
}
Here is the Activity with the ViewPager.
public class CrimePagerActivity extends FragmentActivity{
private static final String EXTRA_CRIME_ID = "com.martin.android.criminalintent.crime_id";
private ViewPager mViewPager;
private List<Crime> mCrimes;
public static Intent newIntent(Context packageContext, UUID crimeId) {
Intent intent = new Intent(packageContext, CrimePagerActivity.class);
intent.putExtra(EXTRA_CRIME_ID, crimeId);
return intent;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime_pager);
UUID crimeId = (UUID) getIntent().getSerializableExtra(EXTRA_CRIME_ID);
mViewPager = (ViewPager) findViewById(R.id.activity_crime_pager_view_pager);
mCrimes = CrimeLab.get(this).getCrimes();
FragmentManager fragmentManager = getSupportFragmentManager();
mViewPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {
#Override
public Fragment getItem(int position) {
Crime crime = mCrimes.get(position);
return CrimeFragment.newInstance(crime.getId());
}
#Override
public int getCount() {
return mCrimes.size();
}
});
for (int i = 0; i < mCrimes.size(); i++) {
if (mCrimes.get(i).getId().equals(crimeId)) {
mViewPager.setCurrentItem(i);
break;
}
}
}
}
For the First button Im pretty sure I just need to set item to 0? For last button I need to set item to size - 1 just not sure how to do that.
In your CrimePagerActivity, write two method's to jump to the ViewPager first page and last page.
CrimePagerActivity.java:
public void jumpToFirstPage() {
mViewPager.setCurrentItem(0);
}
public void jumpToLastPage() {
mViewPager.setCurrentItem(mCrimes.size() - 1);
}
Call those method's from mFirstButton and mLastButton click listener method:
CrimeFragment.java:
mFirstButton = (Button) v.findViewById(R.id.first_crime_button);
mFirstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((CrimePagerActivity)getActivity()).jumpToFirstPage();
}
});
mLastButton = (Button) v.findViewById(R.id.last_crime_button);
mLastButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((CrimePagerActivity)getActivity()).jumpToLastPage();
}
});
Hope this will work perfectly.
Ok this was a answer that I was given by the teacher incase anyone is interested.
mFirstButton = (Button) v.findViewById(R.id.first_crime_button);
mFirstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ViewPager pager = (ViewPager) getActivity().findViewById(R.id.activity_crime_pager_view_pager);
pager.setCurrentItem(0);
}
});
mLastButton = (Button) v.findViewById(R.id.last_crime_button);
mLastButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ViewPager pager = (ViewPager) getActivity().findViewById(R.id.activity_crime_pager_view_pager);
pager.setCurrentItem(CrimeLab.get(getActivity()).getCrimes().size()-1);
}
});
Create two button and on click set
viewPager.setCurrentItem(0); // for top
and
viewPager.setCurrentItem(mCrimes.size()); // for last
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;
}
}