How to save points after popup close and avoid repetition from SQLite? - java

I have 36 imageButtons and with each one I call the same popup in which I set random question from sqlite database. When user answers question by clicking one of the 4 possible solutions it closes and goes back to my 36 buttons. Now here I have 2 problems:
I use this code to avoid repeating questions. In activity scope:
LinkedList mAnsweredQuestions = new LinkedList();
private String generateWhereClause(){
StringBuilder result = new StringBuilder();
for (Long l : mAnsweredQuestions){
result.append(" AND _ID <> " + l);
}
return result.toString();
}
and in my question method:
mAnsweredQuestions.add(c.getLong(0));
But this does not work when my activity resumes after popup question close. It's like it loads my activity from scratch. I use this in my other game and it works fine in "normal" activity, but for some reason after popup it does not.
2.I need for each imageButton press to launch this popup activity and after each correct answer to save different number of points. I used startActivityForResult in my other game to start activity and save result, but in that case I was starting different activities with each button. Now I have to start the same activity, and save back different results. How can I do that?
Here's my popup question class:
public class Pitanja_Cigle extends Activity{
public static String tacanOdg;
int counter = 0;
Button b1, b2, b3, b4;
TextView question;
LinkedList<Long> mAnsweredQuestions = new LinkedList<Long>();
private String generateWhereClause(){
StringBuilder result = new StringBuilder();
for (Long l : mAnsweredQuestions){
result.append(" AND _ID <> " + l);
}
return result.toString();
}
Runnable mLaunchTaskFinish = new Runnable() {
public void run() {
finish();
}
};
private class Answer {
public Answer(String opt, boolean correct) {
option = opt;
isCorrect = correct;
}
String option;
boolean isCorrect;
}
Handler mHandler = new Handler();
final OnClickListener clickListener = new OnClickListener() {
public void onClick(View v) {
Answer ans = (Answer) v.getTag();
if (ans.isCorrect) {
Intent i = new Intent("rs.androidaplikacije.toplo_hladno.TACANODGOVOR");
startActivity(i);
mHandler.postDelayed(mLaunchTaskFinish,1200);
}
else{
Intent i = new Intent(getApplicationContext(), PogresanOdgovor.class);
i.putExtra("tacanOdgovor", tacanOdg);
startActivity(i);
mHandler.postDelayed(mLaunchTaskFinish,2200);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.pitanja_cigle);
InicirajVariable();
nextQuestion();
}
private void nextQuestion() {
counter++;
TestAdapter mDbHelper = new TestAdapter(this);
mDbHelper.createDatabase();
try{ //Pokusava da otvori db
mDbHelper.open(); //baza otvorena
Cursor c = mDbHelper.getPitanjaCigle(generateWhereClause());
mAnsweredQuestions.add(c.getLong(0));
List<Answer> labels = new ArrayList<Answer>();
labels.add(new Answer(c.getString(2), true));
labels.add(new Answer(c.getString(3), false));
labels.add(new Answer(c.getString(4), false));
labels.add(new Answer(c.getString(5), false));
tacanOdg = c.getString(2);
Collections.shuffle(labels);
question.setText(c.getString(1));
b1.setText(labels.get(0).option);
b1.setTag(labels.get(0));
b1.setOnClickListener(clickListener);
b2.setText(labels.get(1).option);
b2.setTag(labels.get(1));
b2.setOnClickListener(clickListener);
b3.setText(labels.get(2).option);
b3.setTag(labels.get(2));
b3.setOnClickListener(clickListener);
b4.setText(labels.get(3).option);
b4.setTag(labels.get(3));
b4.setOnClickListener(clickListener);
}
finally{ // kada zavrsi sa koriscenjem baze podataka, zatvara db
mDbHelper.close();
}
}
private void InicirajVariable() {
Typeface naslov = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
Typeface dugmad = Typeface.createFromAsset(getAssets(), "Bebas.ttf");
question = (TextView) findViewById(R.id.tvPitanjeCigle);
b1 = (Button) findViewById(R.id.bOdgCigle1);
b2 = (Button) findViewById(R.id.bOdgCigle2);
b3 = (Button) findViewById(R.id.bOdgCigle3);
b4 = (Button) findViewById(R.id.bOdgCigle4);
b1.setTypeface(dugmad);
b2.setTypeface(dugmad);
b3.setTypeface(dugmad);
b4.setTypeface(dugmad);
question.setTypeface(naslov);
}
}

Related

null value on variable passed from inside a onclick response

Is there any reason why method CreatePlan won't allow me access to variable recipe_name from the onRecipeClicked function which is retrieved from the recyclerview adapter. The Log shows that the value is retrieved from the recyclerview, but I can't seem to pass it to another method.
Any help is appreciated.
Update
Also is there a way of assigning the auto incremented id created from createPlanRecipe to the id variable in createPlan?
public class CreateMealPlan extends MainActivity {
DatePicker datepicker;
Button submit;
List<com.stu54259.plan2cook.Model.Category> listRecipe = new ArrayList<>();
Cursor c;
RecyclerView recipeList;
RecipeListAdapter adapterRecipe;
String recipe_name;
EditText editPlanName;
Integer id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_meal_plan);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
Intent a = new Intent(CreateMealPlan.this,MainActivity.class);
startActivity(a);
break;
case R.id.recipes:
Intent b = new Intent(CreateMealPlan.this,RecipeSearch.class);
startActivity(b);
break;
/*case R.id.shoppingList:
Intent c = new Intent(CreateMealPlan.this, ShoppingList.class);
startActivity(c);
break;*/
case R.id.mealPlan:
Intent d = new Intent(CreateMealPlan.this, MenuPlan.class);
startActivity(d);
break;
/*case R.id.reminder:
Intent e = new Intent(CreateMealPlan.this, Reminder.class);
startActivity(e);
break*/
}
return false;
}
});
datepicker = findViewById(R.id.calendarView);
ListRecipes();
RecipeListAdapter.OnRecipeClickListener listener = new RecipeListAdapter.OnRecipeClickListener() {
public void onRecipeClicked(int position, String recipe_name) {
Log.d("Recipe selected", recipe_name);
}
};
adapterRecipe = new RecipeListAdapter(this, listRecipe, listener);
recipeList = findViewById(R.id.recipes);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false);
recipeList.setLayoutManager(mLayoutManager);
recipeList.setItemAnimator(new DefaultItemAnimator());
recipeList.setAdapter(adapterRecipe);
submit = (Button) findViewById(R.id.create);
// perform click event on submit button
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CreatePlan();
}
});
}
public void ListRecipes() {
listRecipe.clear();
SQLiteDatabase db = (new DatabaseManager(this).getWritableDatabase());
String selectQuery = " SELECT recipe_name, image, image2, category" + " FROM " + DatabaseManager.TABLE_RECIPE + " GROUP BY recipe_name";
c = db.rawQuery(selectQuery, null);
Log.d("Query", selectQuery);
if (c.moveToFirst()) {
do {
com.stu54259.plan2cook.Model.Category category = new com.stu54259.plan2cook.Model.Category();
category.setRecipe_name(c.getString(c.getColumnIndex("recipe_name")));
category.setImage(c.getInt(c.getColumnIndex("image")));
category.setImage2(c.getString(c.getColumnIndex("image2")));
category.setCategory_name(c.getString(c.getColumnIndex("category")));
listRecipe.add(category);
} while (c.moveToNext());
c.close();
}
}
public void CreatePlan(){
editPlanName = findViewById(R.id.editPlanName);
String plan_name = editPlanName.getText().toString();
DatabaseManager db;
int day = datepicker.getDayOfMonth();
int month = datepicker.getMonth();
int year = datepicker.getYear();
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Integer d_name = day;
Log.d("Date", String.valueOf(d_name));
String dayOfTheWeek = sdf.format(d_name);
String date = day + "/" + month + "/" +year;
db = new DatabaseManager(getApplicationContext());
db.createPlanRecipe(d_name, dayOfTheWeek, recipe_name);
db.createPlan(plan_name, id);
}
}

How to say if a button is clicked inside an IF?

I want to make a function in which if a button on a different activity is pressed, then another function which is outside of this one will be invoked. But in case that the button is not pressed the function must not take place.
Here I leave you the code of what I've done so far(java.file:
public class Comida2 extends AppCompatActivity implements Adaptador2.OnRecipeListener {
private RecyclerView recyclerView1;
List<Entidad2> listItems;
Adaptador2 adaptor;
private Entidad2 entidad1,entidad2,entidad3;
Button cambiarmenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_comida);
cambiarmenu = (Button) findViewById(R.id.boton_cambiarmenu);
recyclerView1 = findViewById(R.id.lv_1);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView1.setLayoutManager(layoutManager);
listItems = new ArrayList<>();
entidad1 = new Entidad2(R.drawable.calabacines_3, "Solomillo a la plancha", " 10 min.", 4, 20);
entidad2 = new Entidad2(R.drawable.patatas_deluxe_especiadas_70523_300_150, "Entrecot", " 15 min.", 2, 50);
entidad3 = new Entidad2(R.drawable.tomate, "Hamburguesa", " 2 min.", 5, 100);
listItems.add(entidad1);
listItems.add(entidad2);
listItems.add(entidad3);
adaptor = new Adaptador2(listItems, this);
recyclerView1.setAdapter(adaptor);
adaptor.notifyDataSetChanged();
//Clicado();
}
#Override
public void OnRecipe(int priority) {
if (priority == 20) {
Intent in = new Intent(this, Solomillo.class);
startActivity(in);
}
if (priority == 50) {
Intent in = new Intent(this, Entrecot.class);
startActivity(in);
}
if (priority == 100) {
Intent in = new Intent(this, Hamburguesa.class);
startActivity(in);
}
}
private void Clicado(){
final boolean[] numerillo = new boolean[1];
cambiarmenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
numerillo[0] = true;
}
});
if (numerillo[0]) {
pickEntidad();
}
}
private void pickEntidad(){
final int random = new Random().nextInt(101);
int priority1 = entidad1.getPriority();
int priority2 = entidad2.getPriority();
int priority3 = entidad3.getPriority();
listItems.clear();
if(random < priority1){
listItems.add(entidad1);
}else if(random < priority2){
listItems.add(entidad2);
}else if (random <= priority3){
listItems.add(entidad3);
}
adaptor.notifyDataSetChanged();
}
}
I want that if the button cambiarmenu is pressed, then the function pickEntidad is invoked, but that if its not, then nothing happens. I've had the problem that I had put the method in which if the button is pressed... inside the Oncreate, and then when it was not pressed the app crashed.
The method Clicado is not coded correctly as it is the method I tried to do myself in which I've included the if and the onClickListener.
Any idea of how to do it please?
Thanks.
I did see your another post and now I understand your problem.
"The button called cambaiarmenu is in another activity, not in Comida2" - what you said here Why can't I use a button which is not in the same activity as the java.file?
The moment you called
setContentView(R.layout.activity_comida);
you can only declare all widgets(button ,textview, etc) under that layout and which I believe R.id.boton_cambiarmenu(cambiarmenu button id) does not belong on that layout.
So you need to declare your cambiarmenu button on the activity where you declare its layout and call this inside its onclicklistener
new Comida2().pickEntidad(); //calling function pickEntidad from Comida2 class
Try this. change your pickEntidad like this
private void pickEntidad(){
final int random = new Random().nextInt(101);
List<Entidad2> newlistItems = new ArrayList<>();
Entidad2 entidad1 = new Entidad2(R.drawable.calabacines_3, "Solomillo a la plancha", " 10 min.", 4, 20);
Entidad2 entidad2 = new Entidad2(R.drawable.patatas_deluxe_especiadas_70523_300_150, "Entrecot", " 15 min.", 2, 50);
Entidad2 entidad3 = new Entidad2(R.drawable.tomate, "Hamburguesa", " 2 min.", 5, 100);
int priority1 = entidad1.getPriority();
int priority2 = entidad2.getPriority();
int priority3 = entidad3.getPriority();
if(random < priority1){
newlistItems.add(entidad1);
}else if(random < priority2){
newlistItems.add(entidad2);
}else if (random <= priority3){
newlistItems.add(entidad3);
}
adaptor.notifyDataSetChanged(); //this another activity listview adaptor so it useless to notify it when you are not this activity
}

How can I pass data from a programmatically created button to another class?

I'm currently working on developing an Android app, in which I have an Activity where the user can see all of their current streaks (which were created programmatically with data accessed from Android's SQLite database).
I'm trying to then pass this data when clicked into another activity which displays an individual streak from the list of all streaks. I would need to pass all 4 pieces of information (streak name, streak category, date started, and days kept), and I'm honestly not quite sure where to start. Below is what I have so far, and while I'm not getting errors - this is currently passing either null, 0 or simply nothing to EnlargedActivity.java.
I currently have most of my code in EnlargedActivity's onResume() method, since whenever a new button is clicked, new data has to be passed in - although I'm not sure if that's the best way to do this, I'm still pretty new to Android programming. Thanks!
AllStreaks.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_streaks);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
prefs = getSharedPreferences("carter.streakly", Context.MODE_PRIVATE);
editor = prefs.edit();
db = new DatabaseHelper(this);
mTableLayout = (TableLayout) findViewById(R.id.all_streak_table);
Cursor res = db.getAllData();
if(res.getCount() ==0) {
//show message
showMessage("Error", "Nothing found");
return;
}
idList = new ArrayList<>();
streakList = new ArrayList<>();
categoryList = new ArrayList<>();
dateStartedList = new ArrayList<>();
daysKeptList = new ArrayList<>();
buttonList = new ArrayList<>();
int counter = 0;
//StringBuffer buffer = new StringBuffer();
while (res.moveToNext()){
idList.add(res.getString(0));
//buffer.append("STREAKNAME :"+ res.getString(1)+"\n");
//buffer.append("STREAKCATEGORY :"+res.getString(2)+"\n");
//buffer.append("DATESTARTED :"+res.getString(3)+"\n");;
daysKeptList.add(res.getString(4));
streakList.add(res.getString(1));
counter++;
}
LinearLayout.LayoutParams btnParams = new LinearLayout.LayoutParams(200, 200);
btnParams.setMargins(200, 30, 80, 30);
LinearLayout.LayoutParams tvParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ActionBar.LayoutParams.WRAP_CONTENT);
tvParams.setMargins(100, 0, 0, 0);
i = 0;
while (i < counter){
if(i%2==0){
mTableRow = new TableRow(this);
mTableLayout.addView(mTableRow);
}
ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
mTableRow.addView(ll);
btn = new Button(this);
btn.setText(daysKeptList.get(i));
btn.setId(i);
btn.setBackground(getResources().getDrawable(R.drawable.round_button));
btn.setLayoutParams(btnParams);
buttonList.add(btn);
ll.addView(btn);
tv = new TextView(this);
tv.setText(streakList.get(i));
tv.setId(i);
tv.setGravity(Gravity.CENTER | Gravity.BOTTOM);
tv.setTextSize(20);
tv.setLayoutParams(tvParams);
ll.addView(tv);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(AllStreaks.this, EnlargedActivity.class);
intent.putExtra("enlargeName", streakList.get(i-1));
startActivity(intent);
}
});
i++;
}
}
public void showMessage(String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}
EnlargedActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enlarged);
prefs = getSharedPreferences("carter.streakly", Context.MODE_PRIVATE);
editor = prefs.edit();
Toast.makeText(EnlargedActivity.this, streakIconName, Toast.LENGTH_LONG).show();
}
public void onResume(){
super.onResume();
db = new DatabaseHelper(this);
res = db.getAllData();
if(res.getCount() ==0) {
//show message
showMessage("Error", "Nothing found");
return;
}
idList = new ArrayList<>();
streakList = new ArrayList<>();
categoryList = new ArrayList<>();
dateStartedList = new ArrayList<>();
daysKeptList = new ArrayList<>();
streakIcon = (TextView)findViewById(R.id.activity_enlarge_icon);
streakIcon.setGravity(Gravity.CENTER);
streakIcon.setTextSize(30);
counter = 0;
while (res.moveToNext()){
idList.add(res.getString(0));
streakList.add(res.getString(1));
categoryList.add(res.getString(2));
dateStartedList.add(res.getString(3));
daysKeptList.add(res.getString(4));
if (streakList.get(counter) == getIntent().getStringExtra("enlargeName")){
streakIconName = streakList.get(counter);
daysKept = Integer.parseInt(daysKeptList.get(counter));
streakIcon.setText(streakIconName + "\n" + daysKept);
}
counter++;
}
}
public void onPause(){
super.onPause();
counter = 0;
idList.clear();
streakList.clear();
categoryList.clear();
dateStartedList.clear();
daysKeptList.clear();
}
public void showMessage(String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}

dont go to next activity unless the entire box is fill

I made an app for my use for calculating a string of values appear in an another activity. My app has 3 editTexts and one button. If we press button calculate with the input in edit text and calculated values will displayed in a second activity. I made it successfully but my problem is if the user is leave any of the boxes empty and press the button, the system will Force Close. To avoid this I made editText in graphical layout pre entered with a hint. But if the user accidentally presses button after editing the editText again system shows a Force Close.
I tried many if else methods but it does not work. Some one show me a correct way to check all editText boxes.
public class Screen1 extends Activity {
public static StringBuilder EXTRA_MESSAGE=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen1);
Button bu1= (Button)findViewById(R.id.bu);
bu1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View message)
{ int f1,f3,f4;
String vis;
EditText t1=(EditText)findViewById(R.id.a);
EditText t3=(EditText)findViewById(R.id.c);
EditText t4=(EditText)findViewById(R.id.d);
String e1=t1.getText().toString();
String e3= t3.getText().toString();
String e4= t4.getText().toString();
f1 =Integer.parseInt(e1);
f4=Integer.parseInt(e4);
f3=Integer.parseInt(e3);
StringBuilder sb = new StringBuilder();
for( float i= (float)0.1;i<=5;i=i+(float) .1)
{
sb.append(String.format("%.1f", i)+" mcg = "+(f1*60*i*f4)/(f3*1000)+"\n");
}
vis=sb.toString();
Intent intent = new Intent(message.getContext(),Screen2.class);
intent.putExtra("EXTRA_MESSAGE",vis);
startActivity(intent);
}
});
}
}
Using [TextUtils][1] check isEmpty() text inside your onClick:
#Override
public void onCreate(Bundle savedInstanceState){
EditText t1=(EditText)findViewById(R.id.a);
EditText t3=(EditText)findViewById(R.id.c);
EditText t4=(EditText)findViewById(R.id.d);
Button bu1 = (Button) findViewById(R.id.bu);
bu1.setOnClickListener(this);
}
#Override
public void onClick(View message){
boolean foundEmpty = false;
if(TextUtils.isEmpty(t1.getText())) {
foundEmpty = true;
t1.setError("Please Enter a value");
}
if(TextUtils.isEmpty(t2.getText()){
foundEmpty = true;
t2.setError("Please Enter a value");
}
if(TextUtils.isEmpty(t3.getText()){
foundEmpty = true;
t3.setError("Please enter a value");
}
if(!foundEmpty){
/* none of your text fields are empty */
int f1, f3, f4;
f1 =Integer.parseInt(e1);
f4=Integer.parseInt(e4);
f3=Integer.parseInt(e3);
final StringBuilder sb = new StringBuilder();
for( float i= (float)0.1;i<=5;i=i+(float) .1) {
sb.append(String.format("%.1f", i)+
" mcg = "+
(f1*60*i*f4)/(f3*1000)+"\n");
}
final String vis = sb.toString();
Intent intent = new Intent(message.getContext(), Screen2.class);
intent.putExtra("EXTRA_MESSAGE", vis);
startActivity(intent);
}
}
From what I gather from your question, you're getting an error when bu1 is clicked, and at least one of the EditTexts is empty. This is because you're calling Integer.parseInt() on an empty String. The following code will check if the boxes are empty, and show a Toast if any are. It will also show a Toast if the user enters anything that's not a valid number:
public class Screen1 extends Activity
{
private static final String EXTRA_MESSAGE = "extra_msg";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.screen1);
final EditText t1 = (EditText)findViewById(R.id.a);
final EditText t3 = (EditText)findViewById(R.id.c);
final EditText t4 = (EditText)findViewById(R.id.d);
Button bu1 = (Button)findViewById(R.id.bu);
bu1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View message)
{
int f1,f3,f4;
String e1 = t1.getText().toString();
String e3 = t3.getText().toString();
String e4 = t4.getText().toString();
if (e1.equals("") || e3.equals("") || e4.equals(""))
{
Toast.makeText(Screen1.this, "Please enter all numbers.", Toast.LENGTH_SHORT).show();
return;
}
try
{
f1 = Integer.parseInt(e1);
f4 = Integer.parseInt(e4);
f3 = Integer.parseInt(e3);
StringBuilder sb = new StringBuilder();
for (float i = 0.1f; i <= 5; i = i + .1f)
{
sb.append(String.format("%.1f", i) + " mcg = " + (f1 * 60 * i * f4) / (f3 * 1000) + "\n");
}
Intent intent = new Intent(Screen1.this, Screen2.class);
intent.putExtra(EXTRA_MESSAGE, sb.toString());
startActivity(intent);
}
catch (NumberFormatException e)
{
Toast.makeText(Screen1.this, "Invalid numbers.", Toast.LENGTH_SHORT).show();
}
}
}
);
}
}

How to hide two wrong answers in a quiz?

Like in "Who wants to be a millionaire". When a user press a 50/50 help button I want two wrong answers to hide, therefor to setText to "" for two buttons, BUT not "the answer" one. But I don't know how to do that. I'm using sqlite prepopulated database with questions and answers. My 50/50 help button is bPolaPola. Here's my game class:
public class NeogranicenoPetGresaka extends SwarmActivity implements OnClickListener{
MyCount brojacVremena = new MyCount(16000, 1000);
LinkedList<Long> mAnsweredQuestions = new LinkedList<Long>();
private String generateWhereClause(){
StringBuilder result = new StringBuilder();
for (Long l : mAnsweredQuestions){
result.append(" AND _ID <> " + l);
}
return result.toString();
}
Button bIzlazIzKviza, bOdgovor1, bOdgovor2, bOdgovor3, bOdgovor4, bPolaPola;
TextView question, netacniOdg, score, countdown;
int brojacPogresnihOdgovora = 0;
int brojacTacnihOdgovora = 0;
public static String tacanOdg;
Runnable mLaunchTask = new Runnable() {
public void run() {
nextQuestion();
brojacVremena.start();
}
};
Runnable mLaunchTaskFinish = new Runnable() {
public void run() {
brojacVremena.cancel();
finish();
}
};
private class Answer {
public Answer(String opt, boolean correct) {
option = opt;
isCorrect = correct;
}
String option;
boolean isCorrect;
}
Handler mHandler = new Handler();
final OnClickListener clickListener = new OnClickListener() {
public void onClick(View v) {
Answer ans = (Answer) v.getTag();
if (ans.isCorrect) {
brojacVremena.cancel();
brojacTacnihOdgovora = brojacTacnihOdgovora + 5;
Intent i = new Intent("rs.androidaplikacijekvizopstekulture.TACANODGOVOR");
startActivity(i);
mHandler.postDelayed(mLaunchTask,1200);
}
else{
brojacVremena.cancel();
brojacPogresnihOdgovora++;
Intent i = new Intent(getApplicationContext(), PogresanOdgovor.class);
i.putExtra("tacanOdgovor", tacanOdg);
startActivity(i);
mHandler.postDelayed(mLaunchTask,2200);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.neograniceno);
Typeface dugmad = Typeface.createFromAsset(getAssets(), "Bebas.ttf");
Typeface pitanje = Typeface.createFromAsset(getAssets(), "myriad.ttf");
bIzlazIzKviza = (Button) findViewById(R.id.bIzlazIzKvizaN);
netacniOdg = (TextView) findViewById(R.id.tvBrojPitanjaN);
question = (TextView) findViewById(R.id.tvPitanjeN);
bOdgovor1 = (Button) findViewById(R.id.bOdgovorN1);
bOdgovor2 = (Button) findViewById(R.id.bOdgovorN2);
bOdgovor3 = (Button) findViewById(R.id.bOdgovorN3);
bOdgovor4 = (Button) findViewById(R.id.bOdgovorN4);
bPolaPola = (Button) findViewById(R.id.bPolaPolaN);
score = (TextView) findViewById(R.id.tvSkor2N);
countdown = (TextView) findViewById(R.id.tvCountdownN);
bOdgovor1.setTypeface(dugmad);
bOdgovor2.setTypeface(dugmad);
bOdgovor3.setTypeface(dugmad);
bOdgovor4.setTypeface(dugmad);
bPolaPola.setTypeface(dugmad);
bIzlazIzKviza.setTypeface(dugmad);
netacniOdg.setTypeface(dugmad);
question.setTypeface(pitanje);
score.setTypeface(dugmad);
countdown.setTypeface(dugmad);
nextQuestion(); //startuje prvo pitanje!
brojacVremena.start(); //startuje brojac vremena
}
public class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
Intent i = new Intent(getApplicationContext(), PogresanOdgovor.class);
i.putExtra("tacanOdgovor", tacanOdg);
startActivity(i);
mHandler.postDelayed(mLaunchTask,2200);
brojacPogresnihOdgovora++;
}
#Override
public void onTick(long millisUntilFinished) {
countdown.setText("" + millisUntilFinished / 1000);
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override public void onStop() {
super.onStop();
brojacVremena.cancel();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
public void nextQuestion() {
TestAdapter mDbHelper = new TestAdapter(this);
mDbHelper.createDatabase();
try{ //Pokusava da otvori db
mDbHelper.open(); //baza otvorena
Cursor c = mDbHelper.getTestData(generateWhereClause());
mAnsweredQuestions.add(c.getLong(0));
List<Answer> labels = new ArrayList<Answer>();
labels.add(new Answer(c.getString(2), true));
labels.add(new Answer(c.getString(3), false));
labels.add(new Answer(c.getString(4), false));
labels.add(new Answer(c.getString(5), false));
Collections.shuffle(labels);
tacanOdg = c.getString(2);
if(brojacPogresnihOdgovora < 5){
question.setText(c.getString(1));
bOdgovor1.setText(labels.get(0).option);
bOdgovor1.setTag(labels.get(0));
bOdgovor1.setOnClickListener(clickListener);
bOdgovor2.setText(labels.get(1).option);
bOdgovor2.setTag(labels.get(1));
bOdgovor2.setOnClickListener(clickListener);
bOdgovor3.setText(labels.get(2).option);
bOdgovor3.setTag(labels.get(2));
bOdgovor3.setOnClickListener(clickListener);
bOdgovor4.setText(labels.get(3).option);
bOdgovor4.setTag(labels.get(3));
bOdgovor4.setOnClickListener(clickListener);
netacniOdg.setText("" + brojacPogresnihOdgovora);
score.setText("Score: " + brojacTacnihOdgovora);
}
else{
brojacVremena.cancel();
Intent i = new Intent(getApplicationContext(), Rezultat.class);
i.putExtra("noviRezultat", brojacTacnihOdgovora);
startActivity(i);
mHandler.postDelayed(mLaunchTaskFinish,4000);
SwarmLeaderboard.submitScore(6863, brojacTacnihOdgovora);
}
}
finally{ // kada zavrsi sa koriscenjem baze podataka, zatvara db
mDbHelper.close();
}
bIzlazIzKviza.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
}
OK, as jazzbassrob pointed I need to be more specific. I need to setText to my bPolaPola button to "", empty String, but my main problem is that I don't know after collections shuffle where my answers will end up, so I don't know which buttons to setText to. How to know where my answers end up after shuffle?
I actually did not try anything cause in this specific situation I really don't know where to start.
How about running a query which will find the correct option even before the user clicks on one, then you find the correct button out of the four options. After this, use setText="" on any random two buttons other than the one which points to the correct answer.

Categories