Can't determine the clicked item in android ViewGroup - android

I am working with ViewGroup . I want to make a click effect on the item of the group so that User can detect which item is currently clicked. Can anyone please help me?
private View getSubCategoryListItemView(final SubCategoryItem si, double dwPercentage, final int cat_id)
{
LayoutInflater li = LayoutInflater.from(this);
View vv = li.inflate(R.layout.sub_cat_list_item, llCatListHolder, false);
ImageView ivIcon = (ImageView) vv.findViewById(R.id.iv_sub_cat_icon);
final TextView tvName = (TextView) vv.findViewById(R.id.tv_sub_cat_name);
ivIcon.setImageResource(AppConstants.ALL_CAT_MARKER_ICONS[cat_id-1]);
ViewGroup.LayoutParams lpIv = ivIcon.getLayoutParams();
lpIv.width = (int) (primaryIconWidth * dwPercentage);
ivIcon.setLayoutParams(lpIv);
tvName.setText(si.getSubcatHeader());
tvName.setTextSize((float) (VIEW_WIDTH * .10 * dwPercentage));
/**************************
*
* This OnClickListener will be called for clicking subcategory items from the top list
*
* Toast.makeText(getApplicationContext(), "Entertainment ", Toast.LENGTH_SHORT).show();
* ************************/
// tvName.setTextColor(Color.WHITE);
Toast.makeText(getApplicationContext(), "BackTrack ", Toast.LENGTH_SHORT).show();
vv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<SubCategoryItem> subCategoryItems;
subCategoryItems = getSubCategoryList(cat_id);
for(SubCategoryItem si : subCategoryItems)
{
// tvName.setTextColor(Color.WHITE);
}
tvName.setTextColor(Color.RED);
/*code for category*/
/*following code will be different for each category*/
/*category id 1 means education.
* category id 2 means health
* category id 3 means entertainment
* category id 4 means government
* category id 5 means legal
* category id 6 means financial
* category id 7 means job*/
// tvName.setTextColor(Color.WHITE);
switch (currentCategoryID) {
case AppConstants.EDUCATION:
Toast.makeText(getApplicationContext(), "Education Entrance ", Toast.LENGTH_SHORT).show();
ArrayList<EducationServiceProviderItem> eduItem;
eduItem = constructEducationListItemForHeader(cat_id, si.getSubcatHeader());
callMapFragmentWithEducationInfo(si.getSubcatHeader(), cat_id, eduItem);
break;
case AppConstants.HEALTH:
Toast.makeText(getApplicationContext(), "Helath Entrance ", Toast.LENGTH_SHORT).show();
//TODO write necessary codes for health
ArrayList<HealthServiceProviderItem> healthItem;
healthItem = constructHealthListItemForHeader(cat_id, si.getSubcatHeader());
callMapFragmentWithHealthInfo(si.getSubcatHeader(), cat_id, healthItem);
break;
case AppConstants.ENTERTAINMENT:
tvName.setTextColor(Color.GREEN);
Toast.makeText(getApplicationContext(), "Entertainment ", Toast.LENGTH_SHORT).show();
ArrayList<EntertainmentServiceProviderItem> entItem;
entItem = constructEntertainmentListItemForHeader(cat_id, si.getSubcatHeader());
callMapFragmentWithEntertainmentInfo(si.getSubcatHeader(), cat_id, entItem);
break;
//TODO write necessary codes for entertainment
case AppConstants.GOVERNMENT:
//TODO write necessary codes for government
break;
case AppConstants.LEGAL:
Toast.makeText(getApplicationContext(), "Legal ", Toast.LENGTH_SHORT).show();
ArrayList<LegalAidServiceProviderItem>legalItem;
legalItem = constructlegalaidListItemForHeader(cat_id,si.getSubcatHeader());
callMapFragmentWithLegalAidInfo(si.getSubcatHeader(),cat_id,legalItem);
break;
case AppConstants.FINANCIAL:
ArrayList<FinancialServiceProviderItem>financialItem;
financialItem = constructfinancialListItemForHeader(cat_id, si.getSubcatHeader());
callMapFragmentWithFinancialInfo(si.getSubcatHeader(), cat_id, financialItem);
break;
case AppConstants.JOB:
ArrayList<JobServiceProviderItem>jobItem;
jobItem = constructjobListItemForHeader(cat_id, si.getSubcatHeader());
callMapFragmentWithJobInfo(si.getSubcatHeader(), cat_id, jobItem);
break;
default:
break;
}
/*code for all*/
}
});
return vv;
}
flag
I have set an OnclickListener. But I can not detect which TextView is clicked now? I have tried to make Text color changed. Suppose I set Text color orange and commmon color black. When the first item has clicked then the text color is orange. When the another item clicked it has become also make be orange. Then two item is orange color. But previous item should be black after clicking next item and only current item should be orange.

Related

Deleting child view from first position and adding it to last position

I have a custom view called TinderStackLayout.
At a certain part of the code I am deleting a child view of it and re-adding it back at the last position possible -
private void handleViewAfterAnimation(View view, boolean shouldSkipView) {
Log.d("card view - ", "inside handleViewAfterAnimation");
isCardAnimating = false;
TinderStackLayout tinderStackLayout = (TinderStackLayout) view.getParent();
if (tinderStackLayout == null)
return;
tinderStackLayout.removeView(view);
if (shouldSkipView)
tinderStackLayout.addCard((TinderCardView) view, tinderStackLayout.getChildCount() - 1);
//this part is for debugging purpose
for (int i = 0; i < tinderStackLayout.getChildCount(); i++) {
View childAt = tinderStackLayout.getChildAt(i);
if (childAt instanceof TinderCardView)
Log.d("card view - ", "child cards after deletion - " + (((TinderCardView) childAt).usernameTextView.getText()));
}
}
here is my addCard() method -
public void addCard(TinderCardView tinderCardView, int addToPosition) {
View topCard = getChildAt(0);
if (topCard != null && topCard.equals(tinderCardView)) {
return;
}
topCardOnStack = tinderCardView;
ViewGroup.LayoutParams layoutParams;
layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
addView(tinderCardView, addToPosition, layoutParams);
// tinderCardView.animate()
// .x(0)
// .setInterpolator(new AnticipateOvershootInterpolator());
}
What I don't understand is what I get in the UI -
I have 3 cards.
I press the button, one card is being animated away, the second one is being shown. I press the button again, the second one animates away. I press the last one and the button does not work anymore. What I want to achieve is the first card appearing now behind the last one.
Here is what I get when logging the values out -
seems correct, it was before clicking 3 2 1 and now 2 3 1. The next one should be 1 2 3, but this is what I get for the next one -
goes back to 3 2 1 instead of 1 2 3. I can't figure out why. ?
Edit:
found the reason why this is happening, I am giving a view which should always be the top card on the stack but I am actually not giving the top card because I am always adding a new card. Here is the method -
public void handleButtonPressed(int buttonTag) {
Log.d("card view - ", "inside handleButtonPressed");
TinderStackLayout tinderStackLayout = ((TinderStackLayout) this.getParent());
TinderCardView topCard = (TinderCardView) tinderStackLayout.getChildAt(tinderStackLayout.getChildCount() - 1);
if (isCardAnimating) {
return;
}
switch (buttonTag) {
case DELETE_BUTTON_PRESSED:
isCardAnimating = true;
deleteCard(topCard);
break;
case PASS_BUTTON_PRESSED:
Log.d("card view - ", "inside pass button pressed");
isCardAnimating = true;
passCard(topCard);
Log.d("card view - ", "top card Value before pass - " + topCard.displayNameTextView.getText());
Log.d("card view - ", "child count - " + tinderStackLayout.getChildCount());
for (int i = 0; i < tinderStackLayout.getChildCount(); i++) {
View childAt = tinderStackLayout.getChildAt(i);
if (childAt instanceof TinderCardView)
Log.d("card view - ", "child cards before deletion - " + (((TinderCardView) childAt).usernameTextView.getText()));
}
break;
case APPROVE_BUTTON_PRESSED:
showLawyerContactDetailsFragment(topCard);
break;
}
}
I am trying to do TinderCardView topCard = (TinderCardView) tinderStackLayout.getChildAt(tinderStackLayout.getChildCount() - 1) in order to get the top card in my stack, which would be correct if I delete the cards and not re-add them to my stack but that is not the case when re-adding them. What should be the solution for always getting the top card when I am adding new views all the time?
If you want to shuffle cards, then you don't need to delete and re-add them. You simply need a data structure, which will do it for you. For your use case you can use Circular Array.
private CircularArray cardArray; //declaration
Now when you are adding your views, add it to your card array also.
cardArray.addLast(tinderCardView);
addView(tinderCardView); // add to your layout.
Then use this code to check.
int shuffleCount = 3;
for (int i = 1; i <= shuffleCount; i++)
shuffleTopCard(i);
Finally shuffleTopCard() method.
private void shuffleTopCard(int shuffleID) {
Log.d(TAG, "shuffleTopCard: cards before shuffle");
for (int i = 0; i < cardCount; i++)
Log.d(TAG, "shuffleTopCard: " + ((TinderCardView) cardArray.get(i)).getTag());
TinderCardView cardView = (TinderCardView) cardArray.popLast();
Log.e(TAG, "shuffleTopCard: top cardID = " + cardView.getTag());
cardArray.addFirst(cardView);
Log.d(TAG, "shuffleTopCard: cards after shuffling " + shuffleID + " time");
for (int i = 0; i < cardArray.size(); i++)
Log.d(TAG, "shuffleTopCard: " + ((TinderCardView) cardArray.get(i)).getTag());
Log.e(TAG, "shuffleTopCard: after shuffle top card = " + ((TinderCardView) cardArray.getLast()).getTag());
}
Use of CircularArray will free you from head-ache of maintaining card position manually and also separates your CustomViewGroup and card shuffling logic thereby resulting in loosely-coupled code.

How to Double Score the point for a word?

I have my first Android app and I am having difficulty on how can I double the point for a word/words whenever a player click an imageview. Basically, I want it to function like this: If the player hasn't click the imageview, the pointing system stays the same. If the player clicks the imageview the a message will pop-out (a toast perhaps telling the player that the points for the next 3 words will be doubled). How can I make this happen? How can I double the points for the 3 consecutive words without exceeding?
Here's my code for searching and calculation
//CALCULATE SCORE
private int optionTxtView = 0 ; //which textview to use for addition purposes
private int addClick = 0 ; //No. of clicks for search for calculation
private void calculate(){
x = Integer.parseInt(tv3.getText().toString().replaceAll("\\s",""));
y = Integer.parseInt(tv2.getText().toString().replaceAll("\\s",""));
z = x + y;
score.setText(Integer.toString(z));
}
//SEARCH WORD, DISPLAYING SCORE
public void viewWord(View view)
{
String s1= search.getText().toString(); //What word to search
String s2= dbHelper.getData(s1); // If in db, display equivalent score
if(optionTxtView == 0){
//display the score on textview1
tv2.setText(s2);
optionTxtView = 1;
}
else{
if(optionTxtView == 1){
//display the score on textview2
tv3.setText(s2);
optionTxtView = 0;
}
}
//Display search word/s
adapter.add(text.getText().toString());
adapter.notifyDataSetChanged();
if(addClick ==0){
calculate();
addClick = 1;
text.setText("");
generatedString="";
}
else{
if(addClick == 1){
calculate();
addClick = 2;
text.setText("");
generatedString="";
}}
boolean sDouble = false
imgView.setOnClickListener(new View.OnClickListener() {
//#Override
public void onClick(View v) {
// Show your Toast message
// double = true;
}
});
and where you are running your game code check the value of sDouble, if its true then double the scoring system inside a for loop, or set an integer value to 0 and increment it for next 3 words, after that set the value of sDouble back to false.
You may also need to make sure that the user doesn't click on the image for the next 3 tries after clicking it once.
Update:
Since your score is a String, you need to parse it to an Integer before performing any mathematical operation, use Integer.parseInt(s2).

The difference between onratingbarchanged and onratingbarclicked android

I've got a rating bar in my android application which is in a custom adapter. I've set the ratingbar to listen for a change and on that change, update the database through a cient/server architecture. I then use the custom adapter in a master/details view. The problem is, everytime I load the details page on click of the left-hand list item, it updates the rating bar. This is not what I want. I only want to update the rating bar once it's been clicked, not everytime the adapter is used.
Is there way to only fire an event when it is clicked and not changed. Is there a major difference between onratingbarchanged (which it is currently) and onratingbarclicked (which I'm assuming is what I should be doing?)
My code is as follows:
//Should this rather be setOnClickListener()???
ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener()
{
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser)
{
questions.get(position).TotalRating = rating;
String newRating = "" + rating;
ratingBar.setRating(rating);
Toast.makeText(getContext(),
"Rating set to: " + rating + " for the position: " + position, Toast.LENGTH_SHORT).show();
String question = questions.get(position).Question;
//Create XML with both position/question to send to doAsyncTask
serverUpdateRating update = new serverUpdateRating();
Document doc;
try
{
//Create an XML document with question from the selected position as well as the new rating
doc = x.createDoc();
Element tutor = doc.createElement("Update");
tutor.appendChild(x.UpdateRating(doc, newRating, question));
doc.appendChild(tutor);
//Create a string
String s = x.getStringFromDocument(doc);
String result = update.execute(s).get();
//return either true (updated correctly) or false (problem)
if (result.equals("true"))
{
Toast.makeText(getContext(),
"Rating successfully updated", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getContext(),
"Rating update unsuccessful", Toast.LENGTH_LONG).show();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
I don't know if there is a workaround for this, but if there is, I would be extremely grateful!
You could use fromUser in onRatingChanged
onRatingChanged :
[...] fromUser True if the rating change was initiated by a user's touch
gesture or arrow key/horizontal trackbell movement.

Infinite loop somewhere in a CYOA game

Why is the code breaking?
Intro: trying to make a "Choose Your Own Adventure" game.
Layout is composed by:
bPage = button saying what page the user is on. Click to manually change page (not implemented yet)
bOne: go through first path
bTwo: go through second path
tvPageTitle: page title, at the top
mainText: main text body (story explained here)
there's also a splash screen, which works perfectly, but when you click on "start", it loads this layout, which hangs (possible infinite loop)
Can someone tell me why? Tried to put as many comments as I could, so it should be self explanatory
Please ask as many questions as you want :)
package com.assignement.cyoa;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Remember extends Activity {
// Declaring variables
TextView mainText;
int page = 1;
MediaPlayer pageflip;
Boolean gameOver = false;
int currentPage = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.remember);
// Enable manual scrolling text
mainText = (TextView) findViewById(R.id.mainText);
mainText.setMovementMethod(new ScrollingMovementMethod());
// Enable sound when choosing path
pageflip = MediaPlayer.create(Remember.this, R.raw.pageflip);
//TODO: customise story to insert player name. Remember to import method
//EditText userName = LoginActivity.userName;
// Link XML Views with Java
final TextView mainText = (TextView) findViewById(R.id.mainText);
final TextView tvPageTitle = (TextView) findViewById(R.id.tvPageTitle);
final Button bOne = (Button) findViewById(R.id.bOne);
final Button bTwo = (Button) findViewById(R.id.bTwo);
final Button bPage = (Button) findViewById(R.id.bPage);
// Array creation
final String[] storyText = new String[22];
final String[] pageTitle = new String[22];
final CharSequence[] pathA = new CharSequence[22];
final CharSequence[] pathB = new CharSequence[22];
///// MAIN TEXT AND POSSIBLE PATHS ARRAYS \\\\\
// Page 0 - Error
storyText[0] = "Path broken";
pageTitle[0] = "Path broken";
pathA[0]= "Path broken";
pathB[0]= "Path broken";
// Page 1
storyText[1] = "\tYou lift open your eyes. All you can see is a bright light. You get up and take a look around you. You are in a very tight room, with no windows and one door. Everything is painted in white. Beside the door is a small walkie talkie which looks brand new.\n\tYou begin to think, where are you? Who are you? You steady yourself and stumble towards the door. You tightly grab the knob and begin to twist it open. It's locked. Damn. You take another spin around the place. You don't know where you are, you don't know who you are, and you are trapped inside this small room. You pace slowly around the room with your mind thinking intensely on what to do.\n\tYou pick up the walkie talkie. You press the button for the microphone and speak.\n\t''Hello? Is anyone there?''\n\tThe room remains silent until a voice springs out of the device.\n\t''Ahh yes, hello!'' The voice is very high pitched, seemingly happy, yet, sinister. ''Do you remember who you are?''\n\tYou think once more, trying to remember who you are, but nothing manages to spring up.\n\t''Hello? Do you remember-''\n\t''No,'' you answer unhappily. ''I don't''\n\tSilence fills the room once more, but the voice comes back.\n\t''Good, this should make things much more interesting.''\n\tYou don't know whether you should be scared or happy. Questions pop up in your mind.";
pageTitle[1] = "Your New Home";
pathA[1]= "You brush it off and go anyway";
pathB[1]= "Decide it's not worth it and leave";
// Page 2
storyText[2] = "Test";
pageTitle[2] = "Not worth it";
pathA[2]= "Go back";
pathB[2]= "";
// Page 3
storyText[3] = "Test";
pageTitle[3] = "You brush it off";
pathA[3]= "Go upstairs and explore the mysterious shadow";
pathB[3]= "Go to the kitchen to start unpacking";
// Page 4
storyText[4] = "Test";
pageTitle[4] = "You go upstairs";
pathA[4]= "Check it out";
pathB[4]= "Go to the kitchen to start unpacking";
// Page 5 - End
storyText[5] = "Test";
pageTitle[5] = "Checking it out";
pathA[5]= "Try Again";
pathB[5]= "";
// Page 6
storyText[6] = "Test";
pageTitle[6] = "The Kitchen";
pathA[6]= "It's probably just a cat, continue unpacking";
pathB[6]= "Check it out";
// Page 7
storyText[7] = "Test";
pageTitle[7] = "Unpacking";
pathA[7]= "Check out the basement";
pathB[7]= "";
// Page 8
storyText[8] = "Test";
pageTitle[8] = "Checking it out";
pathA[8]= "Check out the basement";
pathB[8]= "";
// Page 9
storyText[9] = "Test";
pageTitle[9] = "The Basement";
pathA[9]= "Forget the light! Get out of here!";
pathB[9]= "Turn the light on anyways";
// Page 10 - End
storyText[10] = "Test";
pageTitle[10] = "Leaving";
pathA[10]= "Try Again";
pathB[10]= "";
// Page 11
storyText[11] = "Test";
pageTitle[11] = "Lights on";
pathA[11]= "Chase the mysterious shadow";
pathB[11]= "Scream and run upstairs";
// Page 12
storyText[12] = "Test";
pageTitle[12] = "The Mysterious Shadow";
pathA[12]= "News report";
pathB[12]= "";
// Page 13 - END
storyText[13] = "Test";
pageTitle[13] = "News Report";
pathA[13]= "Try Again";
pathB[13]= "";
// Page 14
storyText[14] = "Test";
pageTitle[14] = "Upstairs";
pathA[14]= "Just stay where you are";
pathB[14]= "Answer the door";
// Page 15 - End
storyText[15] = "Test";
pageTitle[15] = "Stay where you are";
pathA[15]= "Try Again";
pathB[15]= "";
// Page 16
storyText[16] = "Test";
pageTitle[16] = "The Door";
pathA[16]= "Go to the Attic";
pathB[16]= "";
// Page 17
storyText[17] = "Test";
pageTitle[17] = "The Attic";
pathA[17]= "Leave it alone";
pathB[17]= "Play with the Ouija Board";
// Page 18
storyText[18] = "Test";
pageTitle[18] = "Left Alone";
pathA[18]= "Jump out of the window";
pathB[18]= "Accept your fate";
// Page 19
storyText[19] = "Test";
pageTitle[19] = "The Ouija Board";
pathA[19]= "Jump out of the window";
pathB[19]= "Accept your fate";
// Page 20 - End
storyText[20] = "Test";
pageTitle[20] = "Out the Window";
pathA[20]= "Try Again";
pathB[20]= "";
// Page 21 - End
storyText[21] = "Test";
pageTitle[21] = "Fate Accepted";
pathA[21]= "Try Again";
pathB[21]= "";
// Loop until Game Over
do {
// Populate fields and play page flip sound
mainText.setText(storyText[page]);
tvPageTitle.setText(pageTitle[page]);
bOne.setText(pathA[page]);
bTwo.setText(pathB[page]);
bPage.setText("" + page);
pageflip.start();
currentPage = page;
// Hide button 2 if it doesn't have a possible option
if (pathB[page] == "")
bTwo.setVisibility(View.INVISIBLE);
else
bTwo.setVisibility(View.VISIBLE);
/*
TODO: Enable debug. Manually change page when clicking on the page button
bPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
???
}
});
*/
// Operate first path
bOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (currentPage) {
case 1: page = 3;
break;
case 2: page = 1;
break;
case 3: page = 4;
break;
case 4: page = 5;
break;
case 5: page = 1;
break;
case 6: page = 7;
break;
case 7: page = 9;
break;
case 8: page = 9;
break;
case 9: page = 10;
break;
case 10: page = 1;
break;
case 11: page = 12;
break;
case 12: page = 13;
break;
case 13: page = 1;
break;
case 14: page = 15;
break;
case 15: page = 1;
break;
case 16: page = 17;
break;
case 17: page = 18;
break;
case 18: page = 20;
break;
case 19: page = 20;
break;
case 20: page = 1;
break;
case 21: page = 1;
break;
default: page = 0;
}
}
});
// Operate second path
bTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (currentPage) {
case 1: page = 2;
break;
case 2: page = 0;
break;
case 3: page = 6;
break;
case 4: page = 6;
break;
case 5: page = 0;
break;
case 6: page = 8;
break;
case 7: page = 0;
break;
case 8: page = 0;
break;
case 9: page = 11;
break;
case 10: page = 0;
break;
case 11: page = 14;
break;
case 12: page = 0;
break;
case 13: page = 0;
break;
case 14: page = 16;
break;
case 15: page = 0;
break;
case 16: page = 0;
break;
case 17: page = 19;
break;
case 18: page = 21;
break;
case 19: page = 21;
break;
case 20: page = 0;
break;
case 21: page = 0;
break;
default: page = 0;
}
}
});
} while (gameOver == false);
//TODO: Game Over screen
}
}
EDIT2: adopted new suggestion, made according changes. now layout loads, but clicking a button makes the app crash
package com.assignement.cyoa;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Remember extends Activity {
// Declaring variables
int page;
int currentPage;
MediaPlayer pageflip;
TextView mainText;
TextView tvPageTitle;
Button bOne;
Button bTwo;
Button bPage;
// Array creation
String[] storyText = new String[22];
String[] pageTitle = new String[22];
CharSequence[] pathA = new CharSequence[22];
CharSequence[] pathB = new CharSequence[22];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.remember);
// Link XML Views with Java
TextView mainText = (TextView) findViewById(R.id.mainText);
TextView tvPageTitle = (TextView) findViewById(R.id.tvPageTitle);
Button bOne = (Button) findViewById(R.id.bOne);
Button bTwo = (Button) findViewById(R.id.bTwo);
Button bPage = (Button) findViewById(R.id.bPage);
// Enable manual scrolling text
mainText = (TextView) findViewById(R.id.mainText);
mainText.setMovementMethod(new ScrollingMovementMethod());
// Enable sound when choosing path
pageflip = MediaPlayer.create(Remember.this, R.raw.pageflip);
///// MAIN TEXT AND POSSIBLE PATHS ARRAYS \\\\\
// Page 0 - Error
storyText[0] = "Path broken";
pageTitle[0] = "Path broken";
pathA[0]= "Path broken";
pathB[0]= "Path broken";
// Page 1
storyText[1] = "\tYou lift open your eyes. All you can see is a bright light. You get up and take a look around you. You are in a very tight room, with no windows and one door. Everything is painted in white. Beside the door is a small walkie talkie which looks brand new.\n\tYou begin to think, where are you? Who are you? You steady yourself and stumble towards the door. You tightly grab the knob and begin to twist it open. It's locked. Damn. You take another spin around the place. You don't know where you are, you don't know who you are, and you are trapped inside this small room. You pace slowly around the room with your mind thinking intensely on what to do.\n\tYou pick up the walkie talkie. You press the button for the microphone and speak.\n\t''Hello? Is anyone there?''\n\tThe room remains silent until a voice springs out of the device.\n\t''Ahh yes, hello!'' The voice is very high pitched, seemingly happy, yet, sinister. ''Do you remember who you are?''\n\tYou think once more, trying to remember who you are, but nothing manages to spring up.\n\t''Hello? Do you remember-''\n\t''No,'' you answer unhappily. ''I don't''\n\tSilence fills the room once more, but the voice comes back.\n\t''Good, this should make things much more interesting.''\n\tYou don't know whether you should be scared or happy. Questions pop up in your mind.";
pageTitle[1] = "Your New Home";
pathA[1]= "You brush it off and go anyway";
pathB[1]= "Decide it's not worth it and leave";
// Page 2
storyText[2] = "Test";
pageTitle[2] = "Not worth it";
pathA[2]= "Go back";
pathB[2]= "";
// Page 3
storyText[3] = "Test";
pageTitle[3] = "You brush it off";
pathA[3]= "Go upstairs and explore the mysterious shadow";
pathB[3]= "Go to the kitchen to start unpacking";
// Page 4
storyText[4] = "Test";
pageTitle[4] = "You go upstairs";
pathA[4]= "Check it out";
pathB[4]= "Go to the kitchen to start unpacking";
// Page 5 - End
storyText[5] = "Test";
pageTitle[5] = "Checking it out";
pathA[5]= "Try Again";
pathB[5]= "";
// Page 6
storyText[6] = "Test";
pageTitle[6] = "The Kitchen";
pathA[6]= "It's probably just a cat, continue unpacking";
pathB[6]= "Check it out";
// Page 7
storyText[7] = "Test";
pageTitle[7] = "Unpacking";
pathA[7]= "Check out the basement";
pathB[7]= "";
// Page 8
storyText[8] = "Test";
pageTitle[8] = "Checking it out";
pathA[8]= "Check out the basement";
pathB[8]= "";
// Page 9
storyText[9] = "Test";
pageTitle[9] = "The Basement";
pathA[9]= "Forget the light! Get out of here!";
pathB[9]= "Turn the light on anyways";
// Page 10 - End
storyText[10] = "Test";
pageTitle[10] = "Leaving";
pathA[10]= "Try Again";
pathB[10]= "";
// Page 11
storyText[11] = "Test";
pageTitle[11] = "Lights on";
pathA[11]= "Chase the mysterious shadow";
pathB[11]= "Scream and run upstairs";
// Page 12
storyText[12] = "Test";
pageTitle[12] = "The Mysterious Shadow";
pathA[12]= "News report";
pathB[12]= "";
// Page 13 - END
storyText[13] = "Test";
pageTitle[13] = "News Report";
pathA[13]= "Try Again";
pathB[13]= "";
// Page 14
storyText[14] = "Test";
pageTitle[14] = "Upstairs";
pathA[14]= "Just stay where you are";
pathB[14]= "Answer the door";
// Page 15 - End
storyText[15] = "Test";
pageTitle[15] = "Stay where you are";
pathA[15]= "Try Again";
pathB[15]= "";
// Page 16
storyText[16] = "Test";
pageTitle[16] = "The Door";
pathA[16]= "Go to the Attic";
pathB[16]= "";
// Page 17
storyText[17] = "Test";
pageTitle[17] = "The Attic";
pathA[17]= "Leave it alone";
pathB[17]= "Play with the Ouija Board";
// Page 18
storyText[18] = "Test";
pageTitle[18] = "Left Alone";
pathA[18]= "Jump out of the window";
pathB[18]= "Accept your fate";
// Page 19
storyText[19] = "Test";
pageTitle[19] = "The Ouija Board";
pathA[19]= "Jump out of the window";
pathB[19]= "Accept your fate";
// Page 20 - End
storyText[20] = "Test";
pageTitle[20] = "Out the Window";
pathA[20]= "Try Again";
pathB[20]= "";
// Page 21 - End
storyText[21] = "Test";
pageTitle[21] = "Fate Accepted";
pathA[21]= "Try Again";
pathB[21]= "";
/*
TODO: Enable debug. Manually change page when clicking on the page button
bPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
???
}
});
*/
// Populate fields according to first page
page = 1;
currentPage = page;
mainText.setText(storyText[page]);
tvPageTitle.setText(pageTitle[page]);
bOne.setText(pathA[page]);
bTwo.setText(pathB[page]);
bPage.setText("" + page);
pageflip.start();
// Hide button 2 if it doesn't have a possible option
if (pathB[page] == "")
bTwo.setVisibility(View.INVISIBLE);
else
bTwo.setVisibility(View.VISIBLE);
// Operate first path
bOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (currentPage) {
case 1: page = 3;
break;
case 2: page = 1;
break;
case 3: page = 4;
break;
case 4: page = 5;
break;
case 5: page = 1;
break;
case 6: page = 7;
break;
case 7: page = 9;
break;
case 8: page = 9;
break;
case 9: page = 10;
break;
case 10: page = 1;
break;
case 11: page = 12;
break;
case 12: page = 13;
break;
case 13: page = 1;
break;
case 14: page = 15;
break;
case 15: page = 1;
break;
case 16: page = 17;
break;
case 17: page = 18;
break;
case 18: page = 20;
break;
case 19: page = 20;
break;
case 20: page = 1;
break;
case 21: page = 1;
break;
default: page = 0;
}
setPage(page);
}
});
// Operate second path
bTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (currentPage) {
case 1: page = 2;
break;
case 2: page = 0;
break;
case 3: page = 6;
break;
case 4: page = 6;
break;
case 5: page = 0;
break;
case 6: page = 8;
break;
case 7: page = 0;
break;
case 8: page = 0;
break;
case 9: page = 11;
break;
case 10: page = 0;
break;
case 11: page = 14;
break;
case 12: page = 0;
break;
case 13: page = 0;
break;
case 14: page = 16;
break;
case 15: page = 0;
break;
case 16: page = 0;
break;
case 17: page = 19;
break;
case 18: page = 21;
break;
case 19: page = 21;
break;
case 20: page = 0;
break;
case 21: page = 0;
break;
default: page = 0;
}
}
});
}
private void setPage(int curPage)
{
// Populate fields and play page flip sound
page = curPage;
mainText.setText(storyText[page]);
tvPageTitle.setText(pageTitle[page]);
bOne.setText(pathA[page]);
bTwo.setText(pathB[page]);
bPage.setText("" + page);
pageflip.start();
currentPage = page;
// Hide button 2 if it doesn't have a possible option
if (pathB[page] == "")
bTwo.setVisibility(View.INVISIBLE);
else
bTwo.setVisibility(View.VISIBLE);
}
}
Part of your problem is definitely an infinite loop. You have
} while (gameOver == false);
but you never make gameOver == true. But I would reconsider your design. Instead of having this in a loop, it looks like you could have a function that sets the text of your TextViews and do that work and call that from your onClicks passing the function the int that it needs to select the right pages, etc... There is no reason to continually set your OnClickListeners in a loop. It can be done once in onCreate().
Edit
private void setPage(int curPage)
{
page = curPage;
mainText.setText(storyText[page]);
tvPageTitle.setText(pageTitle[page]);
bOne.setText(pathA[page]);
bTwo.setText(pathB[page]);
bPage.setText("" + page);
pageflip.start();
currentPage = page;
// Hide button 2 if it doesn't have a possible option
if (pathB[page] == "")
bTwo.setVisibility(View.INVISIBLE);
else
bTwo.setVisibility(View.VISIBLE);
}
then in your onClick() call the function
bOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (currentPage) {
case 1: page = 3;
break;
case 2: page = 1;
break;
case 3: page = 4;
break;
...
}
setPage(page);
Declare your variables as member variables before (onCreate()) but initialize them in onCreate()
public class Remember extends Activity {
TextView mainText;
TextView tvPageTitle;
Button bOne;
Button bTwo;
Button bPage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.remember);
mainText = (TextView) findViewById(R.id.mainText);
tvPageTitle = (TextView) findViewById(R.id.tvPageTitle);
bOne = (Button) findViewById(R.id.bOne);
bTwo = (Button) findViewById(R.id.bTwo);
bPage = (Button) findViewById(R.id.bPage);
You can't initialize your Views before you have inflated the layout with setContentView()
You have
TextView mainText = (TextView) findViewById(R.id.mainText);
inside onCreate(). Change that to
mainText = (TextView) findViewById(R.id.mainText);
remove the TextView otherwise you are creating a local variable and your member variables don't have a value so you will get NPE. Do the same with all of your Views.
If i followed your code correctly, it seems you start on page 1, and then just loop.
Your seem to be relying on break; to exit the do-while, but you are just setting the onclicklistener. Are you actually clicking anything? bOne or bTwo i mean. If you dont click them, infinite loop.

Delete selected item from List view

I have developed a code in which i have populated list view dynamically.
now i want to delete the selected item from list view on button click(on pressing delete button)
I have searched out this in this site but didn't got any exact solution so i am posting this question
please help me how to do this :
code on delete buttons onClickListener is as shown below :
DeleteButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
if (idx >= 0) {
Log.v("Item index deleted", idx + "");
idx = OdrLst.getCheckedItemPosition();
String delete = (String) ((OdrLst.getAdapter())
.getItem(idx));
// Long deteteId = OdrLst.getAdapter().getItemId(idx);
Log.d("Item deleted", delete);
Log.d("adapter count before", adapter.getCount() + "");
Log.d("lv count before", OdrLst.getCount() + "");
// Log.d("listitems count before", listItems.+"");
adapter.remove(delete);
//listItems.remove(idx);
adapter.notifyDataSetChanged();
OdrLst.setAdapter(adapter);
// OdrLst.removeViewAt(idx);
// adapter.clear();
Log.d("adapter count after", adapter.getCount() + "");
Log.d("lv count after", OdrLst.getCount() + "");
//adapter.notifyDataSetChanged();
// Log.v("adapter count after 1", adapter.getCount()+"");
}
// cleared = false; // <--- nope, we did not clear the value yet
// delItem();
}
});
This code shows exact position and item to be deleted but the item not gets removed from the listview...
Try adding this after removing the item.
adapter.notifyDataSetChanged();
You can make a customized Listview containing check boxes or imageview and then use Arraylist to get the items which were clicked in the list.
refer these link:
Remove item from the listview in Android

Categories

Resources