Android Studio quiz app saving score - android

I'm currently making a flag quiz app, and want to add scores. Below you can see a picture of it; each flag is a fragment, and when you press them, the right hand side allows you to submit an answer.
When you enter the right answer, a "correct" message appears, and you can go to the next flag. I want a right answer to give a score of 1, and a wrong one (or when pressed skip or hint) to give a score of zero. At the end, the score is summarized. However, I'm unsure how to do this. I've created a ScoreActivity.java file where the scores will be registered (though it's currently empty), and I've tried writing the code shown below.
Play.java
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.app.FragmentManager;
import android.view.View;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.view.View.OnClickListener;
import android.view.LayoutInflater;
import android.widget.Button;
import android.widget.ImageButton;
import android.view.ViewGroup;
import layout.FragmentOne;
import layout.FragmentTwo;
import layout.FragmentThree;
import layout.FragmentDefault;
public class Play extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
final ImageButton imageBtn10 = (ImageButton) findViewById(R.id.imageButton10);
final ImageButton imageBtn9 = (ImageButton) findViewById(R.id.imageButton9);
final ImageButton imageBtn8 = (ImageButton) findViewById(R.id.imageButton8);
final ImageButton imageBtn7 = (ImageButton) findViewById(R.id.imageButton7);
final ImageButton imageBtn6 = (ImageButton) findViewById(R.id.imageButton6);
final ImageButton imageBtn5 = (ImageButton) findViewById(R.id.imageButton5);
final ImageButton imageBtn4 = (ImageButton) findViewById(R.id.imageButton4);
final ImageButton imageBtn3 = (ImageButton) findViewById(R.id.imageButton3);
FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTrans = fragMan.beginTransaction();
FragmentDefault fd = new FragmentDefault();
fragTrans.replace(R.id.fragment_place, fd);
fragTrans.commit();
fragTrans.hide(new FragmentOne());
fragTrans.hide(new FragmentTwo());
fragTrans.hide(new FragmentThree());
imageBtn10.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTrans = fragMan.beginTransaction();
fragTrans.replace(R.id.fragment_place, new FragmentOne());
fragTrans.commit();
imageBtn10.setEnabled(false);
}
});
imageBtn9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTrans = fragMan.beginTransaction();
fragTrans.replace(R.id.fragment_place, new FragmentTwo());
fragTrans.commit();
}
});
imageBtn8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTrans = fragMan.beginTransaction();
fragTrans.replace(R.id.fragment_place, new FragmentThree());
fragTrans.commit();
}
});
imageBtn7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTrans = fragMan.beginTransaction();
fragTrans.replace(R.id.fragment_place, new FragmentThree());
fragTrans.commit();
}
});
imageBtn6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTrans = fragMan.beginTransaction();
fragTrans.replace(R.id.fragment_place, new FragmentThree());
fragTrans.commit();
}
});
imageBtn5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTrans = fragMan.beginTransaction();
fragTrans.replace(R.id.fragment_place, new FragmentThree());
fragTrans.commit();
}
});
imageBtn4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTrans = fragMan.beginTransaction();
fragTrans.replace(R.id.fragment_place, new FragmentThree());
fragTrans.commit();
//imageBtn4.setEnabled(false);
}
});
imageBtn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTrans = fragMan.beginTransaction();
fragTrans.replace(R.id.fragment_place, new FragmentThree());
fragTrans.commit();
}
});
Button button_score = (Button)findViewById(R.id.scoreButton);
button_score.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentPlay = new Intent(Play.this, ScoreActivity.class);
startActivity(intentPlay);
}
});
}
}
FragmentOne.java (this is the fragment for the German flag)
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
//import android.widget.TextView;
public class FragmentOne extends Fragment {
EditText theAnswer;
Button ScoreButton;
private EditText userAnswer;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_fragment_one, null);
userAnswer = (EditText)v.findViewById(R.id.editText);
final TextView tv = (TextView)v.findViewById(R.id.showCorrect);
final TextView hintv = (TextView)v.findViewById(R.id.textHint);
final Button submit = (Button)v.findViewById(R.id.submitBtn1);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String theAnswer = (userAnswer.getText().toString());
if (theAnswer.equalsIgnoreCase("Germany")) {
//TextView tv = (TextView)v.findViewById(R.id.showCorrect);
tv.setText("Correct!");
} else {
}
submit.setEnabled(false);
// updateScore();
}
});
final Button skip = (Button)v.findViewById(R.id.skipBtn);
skip.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
submit.setEnabled(false);
}
});
final Button hint = (Button)v.findViewById(R.id.hintBtn);
hint.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
hintv.setText("The capital is Berlin \n The country is in Europe \n It starts with G... ");
//submit.setEnabled(false);
}
});
return v;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ScoreButton = (Button)getView().findViewById(R.id.scoreButton);
final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
ScoreButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences.Editor editor = app_preferences.edit();
if (userAnswer.isChecked()){
editor.putInt("answer_value", 1);
}
else {
editor.putInt("answer_value", 0);
}
editor.commit();
}
});
}
}
.isChecked() appears in red. Do I need to import something?

First of all: why are you using all of these fragment? Can't you use a single fragment updating its data to alternate between questions?
The problem is that EditText class does not have isChecked() method.
To use that method you need to use a CheckBox class.
You are using a widget to catch user input, like a text type HTML input.
Is checked is logically a property of an item that can ben checked, like an HTML checkbox
You are putting a text into your EditText (user answer) and then you are asking to a string container field if it's checked. It does not make sense.
What you really needs is store if user answer match right answer (like in a boolean). You can set this value when you set "correct" in result TextView, someting like this:
final Button submit = (Button)v.findViewById(R.id.submitBtn1);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String theAnswer = (userAnswer.getText().toString());
if (theAnswer.equalsIgnoreCase("Germany")) {
//TextView tv = (TextView)v.findViewById(R.id.showCorrect);
tv.setText("Correct!");
// keep trace of user answer result
wellAnswered = true;
} else {
}
submit.setEnabled(false);
// updateScore();
}
});
Then you can update your FragmentOne code as follows:
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ScoreButton = (Button)getView().findViewById(R.id.scoreButton);
final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
ScoreButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences.Editor editor = app_preferences.edit();
if (wellAnswered){
editor.putInt("answer_value", 1);
// remember to reset your variable for next question
wellAnswered = false;
}
else {
editor.putInt("answer_value", 0);
}
editor.commit();
}
});
}

To save the Scores , you can use SharedPreferences. As per the docs:
If you have a relatively small collection of key-values that you'd like to save, you should use the SharedPreferences APIs. A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them. Each SharedPreferences file is managed by the framework and can be private or shared.
How do I use SharedPreferences to store my Score?
Every time the user clicks the submit button, inside the onClickListener() retrieve the existing value from the SharedPreferences file and increment it by one.
So, How do I do it?
Well First, create an instance of SharedPreferences:
private SharedPreferences sharedpreferences;
then initialize it:
sharedpreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);
then inside the onClickListener() :
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("SCORE", sharedpreferences.getInt("SCORE",0)+1);
editor.apply();
So what this does is , it creates a Key value pair, where the key is SCORE, and putInt() method inserts a value associated with the key, in this case SCORE.
NOTE : sharedpreferences.getInt("SCORE",0)+1) what this does is it increments, the score by one. And finally apply() saves the data to the SharedPreferences file.
How do I retrieve the Score ?
sharedpreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);
int score = sharedpreferences.getInt("SCORE",0)
Where, the 0 is the default value.
Hope it helps!

So I have amended the code in FragmentOne.java, and now it looks like this:
public class FragmentOne extends Fragment {
private EditText userAnswer;
private boolean wellAnswered;
private Button ScoreButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_fragment_one, null);
userAnswer = (EditText)v.findViewById(R.id.editText);
final TextView tv = (TextView)v.findViewById(R.id.showCorrect);
final TextView hintv = (TextView)v.findViewById(R.id.textHint);
final Button submit = (Button)v.findViewById(R.id.submitBtn1);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String theAnswer = (userAnswer.getText().toString());
if (theAnswer.equalsIgnoreCase("Germany")) {
//TextView tv = (TextView)v.findViewById(R.id.showCorrect);
tv.setText("Correct!");
wellAnswered = true;
} else {
}
submit.setEnabled(false);
// updateScore();
}
});
final Button skip = (Button)v.findViewById(R.id.skipBtn);
skip.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
submit.setEnabled(false);
}
});
final Button hint = (Button)v.findViewById(R.id.hintBtn);
hint.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
hintv.setText("The capital is Berlin \n The country is in Europe \n It starts with G... ");
//submit.setEnabled(false);
}
});
return v;}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ScoreButton = (Button)getView().findViewById(R.id.scoreButton);
final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
ScoreButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences.Editor editor = app_preferences.edit();
if (wellAnswered){
editor.putInt("answer_value", 1);
// remember to reset your variable for next question
wellAnswered = false;
}
else {
editor.putInt("answer_value", 0);
}
editor.commit();
}
});
}
}
I have used the suggestions from your answers and I get no errors, however, the app crashes when I press the flags. Any idea what I'm doing wrong?
STACKTRACE:
01-06 20:08:18.152 3912-3912/? I/art: Not late-enabling -Xcheck:jni (already on)
01-06 20:08:18.153 3912-3912/? W/art: Unexpected CPU variant for X86 using defaults: x86
01-06 20:08:18.189 3912-3919/? I/art: Debugger is no longer active
01-06 20:08:18.189 3912-3919/? I/art: Starting a blocking GC Instrumentation
01-06 20:08:18.294 3912-3912/? W/System: ClassLoader referenced unknown path: /data/app/com.example.karolinawullum.quizapp-1/lib/x86
01-06 20:08:18.299 3912-3912/? I/InstantRun: Instant Run Runtime started. Android package is com.example.karolinawullum.quizapp, real application class is null.
[ 01-06 20:08:18.311 1560: 1583 D/ ]
HostConnection::get() New Host Connection established 0x8d661580, tid 1583
01-06 20:08:18.378 3912-3912/? W/System: ClassLoader referenced unknown path: /data/app/com.example.karolinawullum.quizapp-1/lib/x86
01-06 20:08:18.487 3912-3912/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
01-06 20:08:18.608 3912-3933/? I/OpenGLRenderer: Initialized EGL, version 1.4
01-06 20:08:18.610 3912-3933/? D/OpenGLRenderer: Swap behavior 1
01-06 20:08:18.637 3912-3933/? E/EGL_emulation: tid 3933: eglSurfaceAttrib(1174): error 0x3009 (EGL_BAD_MATCH)
01-06 20:08:18.637 3912-3933/? W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x90557900, error=EGL_BAD_MATCH

Related

Sharedprefrences not saving?

When i try to save a variable to shared preferences then call it in an editext it is not being saved? I've been looking around for hours but i cannot find anything on it. I know that sharedPrefrences acts like a dictionary in a way but other than that i don't understand why this is not working :(
package com.example.gatorblocks;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.wearable.activity.WearableActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class block1Settings extends WearableActivity{
private TextView mTextView;
Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_block1_settings);
configureBackButton();
configureColor();
Button addTextButton = (Button) findViewById(R.id.Apply);
TextView simpleEditText = findViewById(R.id.simpleEditText);
SharedPreferences prefs = getSharedPreferences("classes.txt", 0);
simpleEditText.setText(prefs.getString("classes1","1-1")); //set textbox to equal current class
final EditText vEditText = (EditText) findViewById(R.id.simpleEditText);
mTextView = (TextView) findViewById(R.id.text);
// Enables Always-on
setAmbientEnabled();
addTextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String enteredText = vEditText.getText().toString(); //sets the array value of block to the editText
test(enteredText);
}
});
}
private void configureColor() {
Button Block1 = (Button) findViewById(R.id.colorButton);
Block1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(block1Settings.this, colorBlock1.class));
overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
}
});
}
private void configureBackButton(){
Button backbutton = (Button) findViewById(R.id.backButton);
backbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(block1Settings.this, classes.class));
overridePendingTransition(R.anim.slide_in_left,R.anim.slide_out_right);
finish();
}
});
}
public void test(String enteredText){
SharedPreferences pref = getSharedPreferences("classes.txt", 0);
SharedPreferences.Editor editor = pref.edit();
editor.putString("class1", enteredText);
editor.apply();
}
}
How did you get data from SharedPreferences which is not saved? You saved data using key class1 and want to get it by classes1 which is not correct way. You have to use same key. Try using
SharedPreferences prefs = getSharedPreferences("classes.txt", 0);
simpleEditText.setText(prefs.getString("class1","1-1"));

Android Updating Last ListView After Fragment Change

I have 2 different Fragments and in first Fragment, I am adding a new student entry to my custom Student ArrayList. I also have a ListView to show my student list in my second Fragment. However, when I go to my second Fragment, it doesn't update the latest ListView. So my question is that how can I update my ListView after I change my Fragment tab?
registerBtn simply adds a new entry to my studentsArrayList.
At first, I tried to use "Get" button to update my ListView but it didn't work. What I want to do is that refreshing my ListView whenever I pass to my StudentsFragment.
RegisterFragment.java:
package com.rawsly.android.schoolprogram;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Random;
public class RegisterFragment extends Fragment {
private static final String TAG = "RegisterFragment";
public ArrayList<Students> studentsArrayList = new ArrayList<>();
private ArrayList<Long> idList = new ArrayList<>();
private TextView studentID;
private Button registerBtn, clearBtn, exitBtn;
private EditText editName, editLastName, editGender, editFaculty, editDepartment, editAdvisor;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.register_fragment, container, false);
studentID = (TextView) view.findViewById(R.id.studentID);
studentID.setText(String.valueOf(generateID()));
editName = (EditText) view.findViewById(R.id.editName);
editLastName = (EditText) view.findViewById(R.id.editLastName);
editGender = (EditText) view.findViewById(R.id.editGender);
editFaculty = (EditText) view.findViewById(R.id.editFaculty);
editDepartment = (EditText) view.findViewById(R.id.editDepartment);
editAdvisor = (EditText) view.findViewById(R.id.editAdvisor);
registerBtn = (Button) view.findViewById(R.id.registerBtn);
registerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String id = studentID.getText().toString();
String name = editName.getText().toString();
String lastName = editLastName.getText().toString();
String gender = editGender.getText().toString();
String faculty = editFaculty.getText().toString();
String department = editDepartment.getText().toString();
String advisor = editAdvisor.getText().toString();
studentsArrayList.add(new Students(id, name, lastName, gender, faculty, department, advisor));
Toast.makeText(getContext(), "New entry added.", Toast.LENGTH_SHORT).show();
}
});
clearBtn = (Button) view.findViewById(R.id.clearBtn);
clearBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editName.setText(null);
editLastName.setText(null);
editGender.setText(null);
editFaculty.setText(null);
editDepartment.setText(null);
editAdvisor.setText(null);
studentID.setText(String.valueOf(generateID()));
}
});
exitBtn = (Button) view.findViewById(R.id.exitBtn);
exitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.exit(1);
}
});
return view;
}
// Generates a random ID.
public long generateID() {
Random rnd = new Random();
char [] digits = new char[11];
digits[0] = (char) (rnd.nextInt(9) + '1');
for(int i=1; i<digits.length; i++) {
digits[i] = (char) (rnd.nextInt(10) + '0');
}
long result = Long.parseLong(new String(digits));
if(idList.contains(result)) {
return generateID();
} else {
return result;
}
}
}
StudentsFragment.java:
package com.rawsly.android.schoolprogram;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class StudentsFragment extends Fragment {
private static final String TAG = "StudentsFragment";
private EditText txtSearch;
private ListView studentsListView;
private Button getStudents, updateStudent, deleteStudent, exitBtn;
public StudentsAdapter adapter;
public ArrayList<Students> studentsArrayList = new ArrayList<>();;
public int selectedItem = -1; // to update or delete the data
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.students_fragment, container, false);
// Dummy Data
studentsArrayList.add(new Students("1122334455", "Ahmet", "Özdemir", "Male", "Mühendislik ve Doğa Bilimleri", "Bilgisayar Mühendisliği", "Tuğba Yıldız"));
studentsArrayList.add(new Students("1234567890", "Ezgi", "İmamoğlu", "Female", "Mühendislik ve Doğa Bilimleri", "Bilgisayar Mühendisliği", "Tuğba Yıldız"));
studentsArrayList.add(new Students("0123456789", "Enise", "Usta", "Female", "Sosyal ve Beşeri Bilimler Fakültesi", "Uluslararası İlişkiler", "Murat Orhun"));
studentsArrayList.add(new Students("1122445588", "Sinem", "Ünver", "Female", "Mühendislik ve Doğa Bilimleri", "Endüstri Mühendisliği", "Zehra Yılmaz"));
studentsArrayList.add(new Students("2546882547", "Zehra", "Gürçay", "Female", "Mühendislik ve Doğa Bilimleri", "Endüstri Mühendisliği", "Şule Gündüz"));
adapter = new StudentsAdapter(getContext(), studentsArrayList);
studentsListView = (ListView) view.findViewById(R.id.studentsListView);
studentsListView.setAdapter(adapter);
studentsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
selectedItem = position;
Toast.makeText(getContext(), "Selected entry: " + (selectedItem+1), Toast.LENGTH_LONG).show();
}
});
// Opens a dialog window
getStudents = (Button) view.findViewById(R.id.getStudents);
getStudents.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
adapter.notifyDataSetChanged();
studentsListView.invalidate();
}
}); // end of the add action
// To delete the selected School object
deleteStudent = (Button) view.findViewById(R.id.deleteStudent);
deleteStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(selectedItem == -1) {
Toast.makeText(getContext(), "Please, select an entry first.", Toast.LENGTH_SHORT).show();
} else {
studentsArrayList.remove(selectedItem);
selectedItem = -1;
adapter.notifyDataSetChanged();
Toast.makeText(getContext(), "Selected entry is deleted.", Toast.LENGTH_SHORT).show();
}
}
}); // end of the delete action
// To exit the program
exitBtn = (Button) view.findViewById(R.id.exitBtn);
exitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.exit(1);
}
}); // end of the exit action
// To update the selected School object
updateStudent = (Button) view.findViewById(R.id.updateStudent);
updateStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(selectedItem == -1) {
Toast.makeText(getContext(), "Please, select an entry first.", Toast.LENGTH_SHORT).show();
} else {
final Dialog dialog = new Dialog(getContext());
dialog.setContentView(R.layout.update_student);
dialog.setTitle("Update An Entry");
// Dialog components - EditText, Button
String id = studentsArrayList.get(selectedItem).id;
String name = studentsArrayList.get(selectedItem).name;
String lastName = studentsArrayList.get(selectedItem).lastName;
String gender = studentsArrayList.get(selectedItem).gender;
String faculty = studentsArrayList.get(selectedItem).faculty;
String department = studentsArrayList.get(selectedItem).department;
String advisor = studentsArrayList.get(selectedItem).advisor;
final TextView studentID = (TextView) dialog.findViewById(R.id.studentID);
final EditText editName = (EditText) dialog.findViewById(R.id.editName);
final EditText editLastName = (EditText) dialog.findViewById(R.id.editLastName);
final EditText editGender = (EditText) dialog.findViewById(R.id.editGender);
final EditText editFaculty = (EditText) dialog.findViewById(R.id.editFaculty);
final EditText editDepartment = (EditText) dialog.findViewById(R.id.editDepartment);
final EditText editAdvisor = (EditText) dialog.findViewById(R.id.editAdvisor);
studentID.setText(id);
editName.setText(name);
editLastName.setText(lastName);
editGender.setText(gender);
editFaculty.setText(faculty);
editDepartment.setText(department);
editAdvisor.setText(advisor);
Button updateStudent = (Button) dialog.findViewById(R.id.updateStudent);
Button clearStudent = (Button) dialog.findViewById(R.id.clearStudent);
Button cancelStudent = (Button) dialog.findViewById(R.id.cancelStudent);
// Updates the selected School object
updateStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String id = studentID.getText().toString();
String name = editName.getText().toString();
String lastName = editLastName.getText().toString();
String gender = editGender.getText().toString();
String faculty = editFaculty.getText().toString();
String department = editDepartment.getText().toString();
String advisor = editAdvisor.getText().toString();
studentsArrayList.get(selectedItem).setId(id);
studentsArrayList.get(selectedItem).setName(name);
studentsArrayList.get(selectedItem).setLastName(lastName);
studentsArrayList.get(selectedItem).setGender(gender);
studentsArrayList.get(selectedItem).setFaculty(faculty);
studentsArrayList.get(selectedItem).setDepartment(department);
studentsArrayList.get(selectedItem).setAdvisor(advisor);
adapter.notifyDataSetChanged();
Toast.makeText(getContext(), "An entry is updated.", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
// Clears all fields
clearStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editName.setText(null);
editLastName.setText(null);
editGender.setText(null);
editFaculty.setText(null);
editDepartment.setText(null);
editAdvisor.setText(null);
}
});
// Dismisses the dialog
cancelStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
adapter.notifyDataSetChanged(); // notifying adapter about changes
}
}
}); // end of the update action
return view;
}
}
"Troubleshooting
If calling notifyDataSetChanged() doesn't work all the layout methods won't help either. Believe me the ListView was properly updated. If you fail to find the difference you need to check where the data in your adapter comes from.
If this is just a collection you're keeping in memory check that you actually deleted from or added the item(s) to the collection before calling the notifyDataSetChanged().
If you're working with a database or service backend you'll have to call the method to retrieve the information again (or manipulate the in memory data) before calling the notifyDataSetChanged().
The thing is this notifyDataSetChanged only works if the dataset has changed. So that is the place to look if you don't find changes coming through. Debug if needed."
duplicate: How to refresh Android listview?

I'm having trouble implementing the fragment (imageButton) and make it work with my mainActivity

I am working on Android Studio, creating an ad, or banner for an existing application. I cannot use AdMob or anything similar. Therefore I created a fragment with an ImageButton that once I click on it takes me to a website. I am having issues trying to implement the ImageButton fragment.
mainActivy.java:
package com.android.nancysarmiento.assignmenttwo;
import android.os.ParcelFileDescriptor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
ImageView pic;
Button toggleBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pic = (ImageView) findViewById(R.id.imgDisplay);
toggleBtn = (Button)(findViewById(R.id.toggleBtn));
}
public void toggleImage(View view){
if(toggleBtn.getText().toString().equals("show me a nole")){
pic.setImageResource(R.mipmap.nole);
toggleBtn.setText("show me a gator");
toggleBtn = (Button)(findViewById(R.id.toggleBtn));
} else {
pic.setImageResource(R.mipmap.gator);
toggleBtn.setText("show me a nole");
}
}
}
banner.java
public class BannerAd extends Fragment {
private static ImageButton bannerad;
bannerSection activityCommander;
public interface bannerSection {
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable
ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.banner, container, false);
bannerad = (ImageButton) view.findViewById(R.id.cs_ad);
bannerad.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri uri = Uri.parse("http://www.cs.fsu.edu/");
Intent intent = new Intent(Intent.ACTION_VIEW,
uri);
startActivity(intent);
}
}
);
return view;
}
}
Your fragment is not started. Add this method to your Fragment NEW
public void startFragment(Fragment fragment) {
FragmentManager fm = getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.fragment, fragment);
transaction.commit();
}

Passing Boolean value from fragments to activity

I am new to android development and I am trying to pass a Boolean value from dialog fragment to the activity.
the boolean value is supposed to be decided by the user(depends on which button user clicked). However, the boolean immediately turned to false without clicking any button.
I have tried various method recommended I found on internet but none of them works for me(I guess I have some part screwed up...), these method include:
-broadcasting
-implementing interface
-intent.putExtra
and below is the code that I have came up with, could anyone help me take a look? Any help is appreciated.
Stage:
package com.example.fuj.valorsafeworldbytrade;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import static com.example.fuj.valorsafeworldbytrade.LosingDialogFragment.LOSING_FRAGMENT;
public class Stage extends AppCompatActivity {
String stage;
FragmentManager fragmentManager = getSupportFragmentManager();
LosingDialogFragment losingDialogFragment = new LosingDialogFragment();
BasicInfo basicInfo = new BasicInfo();
public void setText(){
TextView cpuReputation = (TextView) findViewById(R.id.cpu_reputation);
TextView cpuGold = (TextView) findViewById(R.id.cpu_gold);
TextView pGoldText = (TextView) findViewById(R.id.player_gold);
TextView pRepText = (TextView) findViewById(R.id.player_reputation);
cpuReputation.setText(String.valueOf(basicInfo.cRep));
cpuGold.setText(String.valueOf(basicInfo.cGold));
pGoldText.setText(String.valueOf(basicInfo.pGold));
pRepText.setText(String.valueOf(basicInfo.pRep));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stage);
setText();
}
protected void onStart() {
super.onStart();
stage = getIntent().getStringExtra(StageChoosingMenu.STAGE);
}
public void playerChoice(View view) {
boolean deceiveEnabled;
switch (view.getId()) {
case R.id.cooperate_button:
deceiveEnabled = false;
break;
case R.id.deceive_button:
deceiveEnabled = true;
break;
default:
throw new RuntimeException("Unknown Button ID");
}
switch (stage){
case "xumo":
xuMo(deceiveEnabled);
break;
}
}
public void xuMo(boolean playerDeceiveEnabled){
boolean cpuDeceiveEnabled;
cpuDeceiveEnabled = (Math.random() - basicInfo.faith > 0);
if (cpuDeceiveEnabled){
if (playerDeceiveEnabled){
basicInfo.playerDvsCpuD();
// faith changes to be amend w/ proper value, need record on the change of status
}
if (!playerDeceiveEnabled){
basicInfo.playerCvsCpuD();
}
}
if (!cpuDeceiveEnabled){
if (playerDeceiveEnabled){
basicInfo.playerDvsCpuC();
}
if (!playerDeceiveEnabled){
basicInfo.playerCvsCpuC();
}
}
if(basicInfo.pGold <= 0 || basicInfo.cGold <= 0 || basicInfo.pRep <= 0 || basicInfo.cRep <= 0){
//to be changed
setText();
losingDialogFragment.show(fragmentManager,LOSING_FRAGMENT);
//trying to show a alert dialog fragment
Log.d("True", String.valueOf(losingDialogFragment.tryAgainEnabled));
if(losingDialogFragment.tryAgainEnabled){//tryAgainEnabled is always false
//This is the part that I wanted to retrieve data from the user(if they want to try again or not)
basicInfo.reset();
losingDialogFragment.dismiss();
}else{
losingDialogFragment.dismiss();
}
}
setText();
// to be changed
}
}
LosingDialogFragment:
package com.example.fuj.valorsafeworldbytrade;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
/**
* Created by fuj on 20/1/2017.
*/
public class LosingDialogFragment extends DialogFragment{
public static final String LOSING_FRAGMENT = "LOSING";
public boolean tryAgainEnabled;
Intent intent = new Intent();
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_lose, container, false);;
//the following code is used to set the boolean value after the user click the button
final Button tryAgainButton = (Button)rootView.findViewById(R.id.try_again_button);
tryAgainButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tryAgainEnabled = true;
}
});
Button giveUpButton =(Button)rootView.findViewById(R.id.give_up_button);
giveUpButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tryAgainEnabled = false;
}
});
getDialog().setTitle(LOSING_FRAGMENT);
return rootView;
}
}
I am also sorry that I am not the best with English, if any things is not clear or not polite because of my poor English, please kindly let me know. I apologize in advance for any mistakes I have made.
It's because you check the value of tryAgainEnabled exactly right after showing the Dialog. Dialog starts Asynchronously, It means that it starts in diffrent Thread and your current thread doesn't wait for dismissing Dialog, So this line of your code if(losingDialogFragment.tryAgainEnabled){ runs exactly after you show dialog, befor you set value to tryAgainEnabled. Because the default value of boolean is always false, you will get false everytime.
I suggest that use listener for this:
Dialog:
public class LosingDialogFragment extends DialogFragment {
public static final String LOSING_FRAGMENT = "LOSING";
public boolean tryAgainEnabled;
Intent intent = new Intent();
private View.OnClickListener onTryAgainButtonClickLisnter;
private View.OnClickListener onGiveUpButtonClickLisnter;
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_lose, container, false);;
final Button tryAgainButton = (Button)rootView.findViewById(R.id.try_again_button);
tryAgainButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(onTryAgainButtonClickLisnter!=null)
onTryAgainButtonClickLisnter.onClick(v);
}
});
Button giveUpButton =(Button)rootView.findViewById(R.id.give_up_button);
giveUpButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(onGiveUpButtonClickLisnter!=null)
onGiveUpButtonClickLisnter.onClick(v);
}
});
getDialog().setTitle(LOSING_FRAGMENT);
return rootView;
}
public void setOnTryAgainButtonClickLisnter(View.OnClickListener onTryAgainButtonClickLisnter) {
this.onTryAgainButtonClickLisnter = onTryAgainButtonClickLisnter;
}
public void setOnGiveUpButtonClickLisnter(View.OnClickListener onGiveUpButtonClickLisnter) {
this.onGiveUpButtonClickLisnter = onGiveUpButtonClickLisnter;
}
}
In your activity call dialog like this:
LosingDialogFragment losingDialogFragment = new LosingDialogFragment();
losingDialogFragment.setOnTryAgainButtonClickLisnter(new View.OnClickListener() {
#Override
public void onClick(View v) {
tryAgain();
losingDialogFragment.dismiss();
}
});
losingDialogFragment.setOnGiveUpButtonClickLisnter(new View.OnClickListener() {
#Override
public void onClick(View v) {
giveUp();
losingDialogFragment.dismiss();
}
});
losingDialogFragment.show(fragmentManager, "");
Declare public boolean tryAgainEnabled; in your Stage Activity and youd can update that variable using ((Stage)context).tryAgainEnabled.
package com.example.fuj.valorsafeworldbytrade;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import static com.example.fuj.valorsafeworldbytrade.LosingDialogFragment.LOSING_FRAGMENT;
public class Stage extends AppCompatActivity {
String stage;
FragmentManager fragmentManager = getSupportFragmentManager();
LosingDialogFragment losingDialogFragment = new LosingDialogFragment();
BasicInfo basicInfo = new BasicInfo();
public boolean tryAgainEnabled;
public void setText(){
TextView cpuReputation = (TextView) findViewById(R.id.cpu_reputation);
TextView cpuGold = (TextView) findViewById(R.id.cpu_gold);
TextView pGoldText = (TextView) findViewById(R.id.player_gold);
TextView pRepText = (TextView) findViewById(R.id.player_reputation);
cpuReputation.setText(String.valueOf(basicInfo.cRep));
cpuGold.setText(String.valueOf(basicInfo.cGold));
pGoldText.setText(String.valueOf(basicInfo.pGold));
pRepText.setText(String.valueOf(basicInfo.pRep));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stage);
setText();
}
protected void onStart() {
super.onStart();
stage = getIntent().getStringExtra(StageChoosingMenu.STAGE);
}
public void playerChoice(View view) {
boolean deceiveEnabled;
switch (view.getId()) {
case R.id.cooperate_button:
deceiveEnabled = false;
break;
case R.id.deceive_button:
deceiveEnabled = true;
break;
default:
throw new RuntimeException("Unknown Button ID");
}
switch (stage){
case "xumo":
xuMo(deceiveEnabled);
break;
}
}
public void xuMo(boolean playerDeceiveEnabled){
boolean cpuDeceiveEnabled;
cpuDeceiveEnabled = (Math.random() - basicInfo.faith > 0);
if (cpuDeceiveEnabled){
if (playerDeceiveEnabled){
basicInfo.playerDvsCpuD();
// faith changes to be amend w/ proper value, need record on the change of status
}
if (!playerDeceiveEnabled){
basicInfo.playerCvsCpuD();
}
}
if (!cpuDeceiveEnabled){
if (playerDeceiveEnabled){
basicInfo.playerDvsCpuC();
}
if (!playerDeceiveEnabled){
basicInfo.playerCvsCpuC();
}
}
if(basicInfo.pGold <= 0 || basicInfo.cGold <= 0 || basicInfo.pRep <= 0 || basicInfo.cRep <= 0){
//to be changed
setText();
losingDialogFragment.show(fragmentManager,LOSING_FRAGMENT);
Log.d("True", String.valueOf(losingDialogFragment.tryAgainEnabled));
if(losingDialogFragment.tryAgainEnabled){//tryAgainEnabled is always false
basicInfo.reset();
losingDialogFragment.dismiss();
}else{
losingDialogFragment.dismiss();
}
}
setText();
// to be changed
}
}
And in Fragment
package com.example.fuj.valorsafeworldbytrade;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
/**
* Created by fuj on 20/1/2017.
*/
public class LosingDialogFragment extends DialogFragment{
public static final String LOSING_FRAGMENT = "LOSING";
Context context;
Intent intent = new Intent();
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_lose, container, false);;
final Button tryAgainButton = (Button)rootView.findViewById(R.id.try_again_button);
tryAgainButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((Stage)context).tryAgainEnabled = true;
}
});
Button giveUpButton =(Button)rootView.findViewById(R.id.give_up_button);
giveUpButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((Stage)context).tryAgainEnabled = false;
}
});
getDialog().setTitle(LOSING_FRAGMENT);
return rootView;
}
}

Android Main Activity is too slow

I have 9 buttons on my main activity which navigates to particular fragment on clicking. but it is to heavy on main thread. how can reduce the code size. can i use switch instead of defining 9 buttons
here is the main activity code
MainActivity
package com.gowarbaam.baluchistannationalparty;
import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.gowarbaam.baluchistannationalparty.Fragments.AboutApp;
import com.gowarbaam.baluchistannationalparty.Fragments.AboutParty;
import com.gowarbaam.baluchistannationalparty.Fragments.Aims;
import com.gowarbaam.baluchistannationalparty.Fragments.CityList;
import com.gowarbaam.baluchistannationalparty.Fragments.Events;
import com.gowarbaam.baluchistannationalparty.Fragments.History;
import com.gowarbaam.baluchistannationalparty.Fragments.Martyrs;
import com.gowarbaam.baluchistannationalparty.Fragments.TwitterMain;
public class MainActivity extends AppCompatActivity {
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
final Button HistoryBtn = (Button) findViewById(R.id.historyBtn);
HistoryBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new History()).commit();
}
});
final Button AimsBtn = (Button) findViewById(R.id.aimsBtn);
AimsBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new Aims()).commit();
}
});
final Button MembersBtn = (Button) findViewById(R.id.membersBtn);
MembersBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new CityList()).commit();
}
});
final Button PhotoBtn = (Button) findViewById(R.id.martyrsBtn);
PhotoBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new Martyrs()).commit();
}
});
final Button TweetBtn = (Button) findViewById(R.id.tweetsBtn);
TweetBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new TwitterMain()).commit();
}
});
final Button AboutParty = (Button) findViewById(R.id.aboutParty);
AboutParty.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new AboutParty()).commit();
}
});
final Button b = (Button) findViewById(R.id.eventsBtn);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new Events()).commit();
}
});
final Button AboutApp = (Button) findViewById(R.id.aboutApp);
AboutApp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new AboutApp()).commit();
}
});
}
#Override
public void onBackPressed() {
Intent myIntent = new Intent(this, MainActivity.class);
this.startActivity(myIntent);
}
}
One reason why your application might be getting slower is the way you treat the onBackPressed() event. Every time you hit the back press button anywhere in the app you are creating a new MainActivity, but you never finish the previous one and since that's your MainActivity you are pretty much recreating your whole application on every back press.
Your problem doesn't seem to be something due to your activity class, but rather your XML files.
If anything, I would recommend creating an activity for each fragment an put them on it, just for tests. You can see how below.
AboutAppActivity
package com.gowarbaam.baluchistannationalparty;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.gowarbaam.baluchistannationalparty.Fragments.AboutApp;
public class AboutAppActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction()
.replace(R.id.containerView, new AboutApp())
.commit();
}
}
And on your MainActivity
public class MainActivity extends AppCompatActivity {
// This is not for performance, just DRY
private View.OnClickListener btnOnClickListener(final Class activityClass) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), activityClass);
startActivity(i);
}
};
}
#Override
protected void onCreate(Bundle savedInstanceState) {
(...)
final Button AboutApp = (Button) findViewById(R.id.aboutApp);
AboutApp.setOnClickListener(this.btnOnClickListener(AboutAppActivity.class));
}
}

Categories

Resources