How do you start an activity without pressing a button? - android

I have an activity that asks the user a question. Currently it asks questions forever until the user exits the app, but I want it to ask 20 questions, then proceed to a new activity. I thought if I did this:
for(int i = 0;i < 20;i++){
random = new Random();
chooseQuestion();
}
Intent i = new Intent(PlayGame.this, Gamble.class);
startActivity(i);
it would work, but my app is now breaking. Am I opening a new activity incorrectly, and if so how should I proceed?
Ok I'm really new to this and I don't know how much of the code to post in response to a comment so here's all of it, I'm sorry.
public class PlayGame extends Activity implements OnClickListener {
//set up minimum and maximum numbers for different operators and difficulty levels
private int level = 0, answer = 0, operator = 0, operand1 = 0, operand2 = 0;
private final int ADD_OPERATOR = 0, SUBTRACT_OPERATOR = 1, MULTIPLY_OPERATOR = 2, DIVIDE_OPERATOR = 3;
private String[] operators = {"+", "-", "x", "/"};
private int[][] levelMin = {
{1, 11, 21},
{1, 5, 10},
{2, 5, 10},
{2, 3, 5}};
private int[][] levelMax = {
{10, 25, 50},
{10, 20, 30},
{5, 10, 15},
{10, 50, 100}};
private Random random;
private TextView question, answerTxt, scoreTxt, coincountTxt;
private ImageView response;
private Button btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0, enterBtn, clearBtn;
#Override
//tell the buttons to be buttons when the activity is opened
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playgame);
question = (TextView)findViewById(R.id.question);
answerTxt = (TextView)findViewById(R.id.answer);
response = (ImageView)findViewById(R.id.response);
scoreTxt = (TextView)findViewById(R.id.score);
coincountTxt = (TextView)findViewById(R.id.coincount);
response.setVisibility(View.INVISIBLE);
btn1 = (Button)findViewById(R.id.btn1);
btn2 = (Button)findViewById(R.id.btn2);
btn3 = (Button)findViewById(R.id.btn3);
btn4 = (Button)findViewById(R.id.btn4);
btn5 = (Button)findViewById(R.id.btn5);
btn6 = (Button)findViewById(R.id.btn6);
btn7 = (Button)findViewById(R.id.btn7);
btn8 = (Button)findViewById(R.id.btn8);
btn9 = (Button)findViewById(R.id.btn9);
btn0 = (Button)findViewById(R.id.btn0);
enterBtn = (Button)findViewById(R.id.enter);
clearBtn = (Button)findViewById(R.id.clear);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
btn7.setOnClickListener(this);
btn8.setOnClickListener(this);
btn9.setOnClickListener(this);
btn0.setOnClickListener(this);
enterBtn.setOnClickListener(this);
clearBtn.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
if(extras != null)
{
int passedLevel = extras.getInt("level", -1);
if(passedLevel>=0) level = passedLevel;
}
for(int i = 0;i < 20;i++){
random = new Random();
chooseQuestion();
}
Intent i = new Intent(PlayGame.this, Gamble.class);
startActivity(i);
}
//find which button pressed on main menu and set operator accordingly
public int getOperator() {
Bundle extras = getIntent().getExtras();
int type = extras.getInt("type", -1);
if(type==1) operator = ADD_OPERATOR;
else if(type==2) operator = SUBTRACT_OPERATOR;
else if(type==3) operator = MULTIPLY_OPERATOR;
else if(type==4) operator = DIVIDE_OPERATOR;
//randomly finds operator for each successive question
else if(type==5) operator = random.nextInt(operators.length);
return operator;
}
//get random valid question within the parameters defined by operation and difficulty
private void chooseQuestion(){
//get a question
answerTxt.setText("= ?");
operator = getOperator();
operand1 = getOperand();
operand2 = getOperand();
//get new subtraction question if answer is negative
if(operator == SUBTRACT_OPERATOR){
while(operand2>operand1){
operand1 = getOperand();
operand2 = getOperand();
}
}
//get new division question if answer is not whole number
else if(operator==DIVIDE_OPERATOR){
while((((double)operand1/(double)operand2)%1 > 0) || (operand1==operand2))
{
operand1 = getOperand();
operand2 = getOperand();
}
}
//find answer to question
switch(operator)
{
case ADD_OPERATOR:
answer = operand1+operand2;
break;
case SUBTRACT_OPERATOR:
answer = operand1-operand2;
break;
case MULTIPLY_OPERATOR:
answer = operand1*operand2;
break;
case DIVIDE_OPERATOR:
answer = operand1/operand2;
break;
default:
break;
}
//set text to show question on screen
question.setText(operand1+" "+operators[operator]+" "+operand2);
}
//random number generator
private int getOperand(){
//return operand number
return random.nextInt(levelMax[operator][level] - levelMin[operator][level] + 1)
+ levelMin[operator][level];
}
//tell buttons what to do when clicked on
#Override
public void onClick(View view) {
//button clicked
if(view.getId()==R.id.enter){
//enter button
String answerContent = answerTxt.getText().toString();
if(!answerContent.endsWith("?"))
{
//answer has been entered, check if correct
int enteredAnswer = Integer.parseInt(answerContent.substring(2));
int exScore = getScore();
int exCoincount = getCoincount();
if(enteredAnswer==answer){
//correct - show tick and add one to score and coincount
scoreTxt.setText("Score: "+(exScore+1));
response.setImageResource(R.drawable.tick);
response.setVisibility(View.VISIBLE);
coincountTxt.setText(""+(exCoincount+1));
}
else{
//incorrect - show cross and reset score to 0
scoreTxt.setText("Score: 0");
response.setImageResource(R.drawable.cross);
response.setVisibility(View.VISIBLE);
}
//show new question
chooseQuestion();
}
}
//if clear button clicked reset answer text to question mark
else if(view.getId()==R.id.clear){
//clear button
answerTxt.setText("= ?");
}
else if(view.getId()==R.id.help_btn){
//help button
Intent i = new Intent(PlayGame.this, HowToPlay.class);
startActivity(i);
}
//if number clicked:
else {
//number button
response.setVisibility(View.INVISIBLE);
int enteredNum = Integer.parseInt(view.getTag().toString());
//if first number replace question mark
if(answerTxt.getText().toString().endsWith("?"))
answerTxt.setText("= "+enteredNum);
//if subsequent number append to previous
else
answerTxt.append(""+enteredNum);
}
}
//function to calculate score (used above in 'correct' if statement
private int getScore(){
String scoreStr = scoreTxt.getText().toString();
return Integer.parseInt(scoreStr.substring(scoreStr.lastIndexOf(" ")+1));
}
//function to calculate number of coins
private int getCoincount(){
String coincountStr = coincountTxt.getText().toString();
return Integer.parseInt(coincountStr.substring(coincountStr.lastIndexOf(" ")+1));
}
}
The code I was referencing is onCreate() and it calls the function chooseQuestion() from not far below that.

Use a Handler
new Handler().postDelayed(new Runnable(){
public void run(){
//start activity here
}
}, 1000);

Try this:
for(int i = 0;i <= 20;i++){
if(i==20){
Intent i = new Intent(PlayGame.this, Gamble.class);
startActivity(i);
break;
} else {
random = new Random();
chooseQuestion();
}
}

Use a Thread
new Thread(new Runnable() {
#Override
public void run() {
//enter code here
}).start();}

Related

Android: String array

I have a game activity about different alphabet are randomly available user would select some of them that are making a correct word.
i made the string array of word which is answer
but i want to knew how to display this answer word alphabets and adding some randomly other alphabet as a confusion?
like taking the answer for example [World] and divid it's alphabet like that [W , L, D , O] AND make them randomly displayed and the player choose from them ?
TextView guessItTimer;
CountDownTimer timer;
Random r;
String currentWord;
private int presCounter = 0;
private int maxPresCounter = 4;
private String[] keys = {"R", "I", "B", "D", "X"};
String dictionary[] = {
"remember",
"hungry",
"crying",
"sour",
"sleep",
"awesome",
"Seven",
"color",
"began",
"appear",
"weight",
"language"
};
TextView textScreen, textQuestion, textTitle;
Animation smallbigforth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_guess_it);
guessItTimer = findViewById(R.id.guessItTimer);
smallbigforth = AnimationUtils.loadAnimation(this, R.anim.smallbigforth);
keys = shuffleArray(keys);
for (String key : keys) {
addView(( findViewById(R.id.layoutParent)), key, findViewById(R.id.et_guess));
}
maxPresCounter = 4;
resetTimer();
}
//CountdownTimer
void resetTimer() {
timer = new CountDownTimer(30150, 1000) {
#Override
public void onTick(long l) {
guessItTimer.setText(String.valueOf(l / 1000));
}
#Override
public void onFinish() {
Toast.makeText(GuessItActivity.this, "Time is over", Toast.LENGTH_SHORT).show();
startActivity(new Intent(GuessItActivity.this, BossFinalActivity.class));
finish();
}
}.start();
}
private String[] shuffleArray(String[] ar) {
Random rnd = new Random();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
String a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
return ar;
}
private void addView(LinearLayout viewParent, final String text, final EditText editText) {
LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
linearLayoutParams.rightMargin = 30;
final TextView textView = new TextView(this);
textView.setLayoutParams(linearLayoutParams);
textView.setBackground(this.getResources().getDrawable(R.drawable.bgpink));
textView.setTextColor(this.getResources().getColor(R.color.colorPurple));
textView.setGravity(Gravity.CENTER);
textView.setText(text);
textView.setClickable(true);
textView.setFocusable(true);
textView.setTextSize(32);
textQuestion = findViewById(R.id.textQuestionBoss);
textScreen = findViewById(R.id.gametitle);
textTitle = findViewById(R.id.Ammo);
textView.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View v) {
if(presCounter < maxPresCounter) {
if (presCounter == 0)
editText.setText("");
editText.setText(editText.getText().toString() + text);
textView.startAnimation(smallbigforth);
textView.animate().alpha(0).setDuration(300);
presCounter++;
if (presCounter == maxPresCounter)
doValidate();
}
}
});
viewParent.addView(textView);
}
private void doValidate() {
presCounter = 0;
EditText editText = findViewById(R.id.et_guess);
LinearLayout linearLayout = findViewById(R.id.layoutParent);
currentWord = dictionary[r.nextInt(dictionary.length)];
if(editText.getText().toString().equals(currentWord)) {
//Toast.makeText(GuessItActivity.this, "Correct", Toast.LENGTH_SHORT).show();
Intent a = new Intent(GuessItActivity.this,BossFinalActivity.class);
startActivity(a);
editText.setText("");
} else {
Toast.makeText(GuessItActivity.this, "Wrong", Toast.LENGTH_SHORT).show();
editText.setText("");
}
keys = shuffleArray(keys);
linearLayout.removeAllViews();
for (String key : keys) {
addView(linearLayout, key, editText);
}
}
public void onBackPressed() {
timer.cancel();
this.finish();
super.onBackPressed();
}
You can achieve it like this
String a2z = "abcdefghijklmnopqrstuvwxyz";
String answer = "World";
// lets assume you need 16 char to select from
ArrayList<Character> chars = new ArrayList<Character>();
for (int i = 0; i < answer.length(); i++) {
chars.add(answer.charAt(i));
}
int dif = 16 - chars.size();
Random rand = new Random();
for (int i = 0; i < dif; i++) {
int ranIndex = rand.nextInt(a2z.length());
chars.add(a2z.charAt(ranIndex));
}
Collections.sort(chars);
System.out.println("nameArray2" + chars.toString());

use shuffelArray as global variable

We are trying to use this array of integers in other methods. Setting the final shuffled Array to a global variable has become next to impossible. We have set other variable as global. The goal here is to have a new int [] fix array every time a button is clicked. We have been able to generate a random int [] ar but can not utilize the array in other methods. So our questions after making the random int [] ar how can we use it in the onClickBtnOne method? Code with comments below
public class MainActivity extends AppCompatActivity {
Button btn1,btn2,btn3,btn4,btn5,btn6;
String T1,T2,T3,T4,T5,T6;
int test[] = new int[7];
int count = 0;
int v1,v2,v3,v4,v5,v6;
int[] fix = {3,2,1,4,6,5};
// Trying to not use above values
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);
btn3 = findViewById(R.id.btn3);
btn4 = findViewById(R.id.btn4);
btn5 = findViewById(R.id.btn5);
btn6 = findViewById(R.id.btn6);
main(null);
}
// end onCeate
public static void main(String args[]) {
int [] fix = {1,2,3,4,5,6};
shuffleArray(fix);
// Want to USE this fix shuffleArray
//==================================
for (int i = 0; i < fix.length; i++) {
System.out.print(fix[i] + ",");
}
System.out.println();
}
// Implementing Fisher–Yates shuffle
static void shuffleArray(int [] ar) {
// If running on Java 6 or older, use `new Random()` on RHS here
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
public void onClickBtnOne(View view){
btn1.setBackgroundColor(getColor(R.color.color_Red));
btn1.setEnabled(false);
count = count + 1;
v1 = count;
test[v1] = count;
if(fix[0] == test[v1]){
// Need a global fix[] here
// =========================
T1 = "true";
if(T1.matches("true")){
btn1.setBackgroundColor(getColor(R.color.color_Yellow));
}
}else {
T1 = "false";
}
}
The array you are trying to use does not have an add method you need to put the values in from another variable like this ar[i] = a; So if you use this type of Array declaration List value = new ArrayList<>(); where you declared the other global variable life will be much easier. Modified code below
This will do the shuffle NOTICE value.clear() without this the List will grow each time it is initialized
public void shf(View view){
value.clear();
for (int i = 1; i <= 6; i++) {
value.add(i);
}
Collections.shuffle(value);
}
And here is your test method call value.get(index) Arrays are ZERO based
public void on1(View view){
btn1.setBackgroundColor(getColor(R.color.color_Red));
btn1.setEnabled(false);
if(value.get(0) == 1){
T1 = "true";
if(T1.matches("true")){
btn1.setBackgroundColor(getColor(R.color.color_Yellow));
}
}else {
T1 = "false";
}
}

Using AlertDialog.Builder to build custom AlertDialog class

I have a Class FoodDialog that extends AlertDialog that I have customized to how I would like it to look.
I am now wanting to edit the positive/negative buttons using an AlertDialog.Builder, however, when I attempt to build an instance of FoodDialog using a builder, I am facing an 'Incompatible types' error where the builder is asking for AlertDialog instead I am providing it with an extension of AlertDialog - is there a way around this?
If not, is there a way I can edit the positive/negative buttons of my custom AlertDialog class FoodDialog?
Below is my FoodDialog class. The yes/no buttons I have there are ones I have created myself, but I would like the ones that are part of the AlertDialog.Builder to appear instead as these buttons get pushed out of sight when the soft keyboard appears:
public class FoodDialog extends AlertDialog implements OnClickListener {
private TextView foodNameTextView, foodDescTextView, foodPortionTextView, catTextView, qtyText, cal, fat, sFat, carb, sug, prot, salt, imageTxt,
measureText;
private EditText foodQty;
private ImageView foodImage;
private ImageButton yesBtn, noBtn;
private int foodID, totalCal;
private Bitmap image;
private String user, portionType, foodName, foodDesc, cat, totalCalString, totalFatString,
totalSFatString, totalCarbString, totalSugString, totalProtString, totalSaltString, portionBaseString;
private double totalFat, totalSFat, totalCarb, totalSug, totalProt, totalSalt, portionBase;
private Food food;
private Portion portion;
private Nutrients nutrients;
private PortionType pType;
private DBHandler db;
public FoodDialog(Context context){
super(context);
}
public FoodDialog(Context context, int foodID, String imgLocation, final String user) {
super(context, android.R.style.Theme_Holo_Light_Dialog);
this.setTitle("Confirm?");
setContentView(R.layout.dialog_layout);
this.foodID = foodID;
this.user = user;
db = new DBHandler(context);
food = db.getFoodByID(foodID, user);
portion = db.getPortionByFoodID(foodID);
nutrients = db.getNutrientsByFoodIDAndPortionType(foodID, portion.getPortionType());
pType = db.getPortionTypeByName(portion.getPortionType());
//getting object attributes
portionType = portion.getPortionType();
portionBase = portion.getPortionBase();
//food
foodName = food.getName();
foodDesc = food.getDesc();
cat = food.getCat();
//nutrients
totalCal = nutrients.getCal();
totalFat = nutrients.getFat();
totalSFat = nutrients.getSFat();
totalCarb = nutrients.getCarb();
totalSug = nutrients.getSug();
totalProt = nutrients.getProt();
totalSalt = nutrients.getSalt();
//converting to string
totalCalString = String.valueOf(totalCal);
if (totalFat % 1 == 0) {
totalFatString = String.format("%.0f", totalFat);
} else {
totalFatString = String.valueOf(totalFat);
}
if (totalSFat % 1 == 0) {
totalSFatString = String.format("%.0f", totalSFat);
} else {
totalSFatString = String.valueOf(totalSFat);
}
if (totalCarb % 1 == 0) {
totalCarbString = String.format("%.0f", totalCarb);
} else {
totalCarbString = String.valueOf(totalCarb);
}
if (totalSug % 1 == 0) {
totalSugString = String.format("%.0f", totalSug);
} else {
totalSugString = String.valueOf(totalSug);
}
if (totalProt % 1 == 0) {
totalProtString = String.format("%.0f", totalProt);
} else {
totalProtString = String.valueOf(totalProt);
}
if (totalSalt % 1 == 0) {
totalSaltString = String.format("%.0f", totalSalt);
} else {
totalSaltString = String.valueOf(totalSalt);
}
if (portionBase % 1 == 0) {
portionBaseString = String.format("%.0f", portionBase);
} else {
portionBaseString = String.valueOf(portionBase);
}
//textviews
foodNameTextView = (TextView) findViewById(R.id.dialogName);
foodNameTextView.setText(foodName);
foodDescTextView = (TextView) findViewById(R.id.dialogDesc);
foodDescTextView.setText(foodDesc);
foodPortionTextView = (TextView) findViewById(R.id.dialogPortion);
foodPortionTextView.setText("Values based per " + portionBase + " " + portionType);
catTextView = (TextView) findViewById(R.id.dialogCat);
catTextView.setText(cat);
measureText = (TextView) findViewById(R.id.dialogMeasure);
measureText.setText(portionType);
qtyText = (TextView) findViewById(R.id.dialogQtyText);
imageTxt = (TextView) findViewById(R.id.dialogImageText);
cal = (TextView) findViewById(R.id.dialogCal);
cal.setText(totalCalString);
fat = (TextView) findViewById(R.id.dialogFat);
fat.setText(totalFatString + "g");
sFat = (TextView) findViewById(R.id.dialogSFat);
sFat.setText(totalSFatString + "g");
carb = (TextView) findViewById(R.id.dialogCarb);
carb.setText(totalCarbString + "g");
sug = (TextView) findViewById(R.id.dialogSug);
sug.setText(totalSugString + "g");
prot = (TextView) findViewById(R.id.dialogProt);
prot.setText(totalProtString + "g");
salt = (TextView) findViewById(R.id.dialogSalt);
salt.setText(totalSaltString + "g");
//img
foodImage = (ImageView) findViewById(R.id.dialogImage);
imgLocation = food.getImgURL();
image = BitmapFactory.decodeFile(imgLocation);
foodImage.setImageBitmap(image);
if (imgLocation.equals("nourl")) {
imageTxt.setText("No Image");
}
//edit tex
foodQty = (EditText) findViewById(R.id.dialogQty);
//adjusting edittext
foodQty.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
foodQty.setFilters(new InputFilter[]{
new DigitsKeyListener(Boolean.FALSE, Boolean.TRUE) {
int beforeDecimal = 4, afterDecimal = 3;
#Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
String temp = foodQty.getText() + source.toString();
if (temp.equals(".")) {
return "0.";
} else if (temp.toString().indexOf(".") == -1) {
// no decimal point placed yet
if (temp.length() > beforeDecimal) {
return "";
}
} else {
temp = temp.substring(temp.indexOf(".") + 1);
if (temp.length() > afterDecimal) {
return "";
}
}
return super.filter(source, start, end, dest, dstart, dend);
}
}
});
foodQty.setText(portionBaseString);
//btns
yesBtn = (ImageButton) findViewById(R.id.yesBtn);
noBtn = (ImageButton) findViewById(R.id.noBtn);
Bitmap tick = BitmapFactory.decodeResource(context.getResources(),
R.drawable.png_tick);
Bitmap cross = BitmapFactory.decodeResource(context.getResources(),
R.drawable.png_cross);
yesBtn.setImageBitmap(tick);
noBtn.setImageBitmap(cross);
yesBtn.setOnClickListener(this);
noBtn.setOnClickListener(this);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
#Override
public void onClick(View v) {
if (v == yesBtn) {
SimpleDateFormat currentDate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
String date = currentDate.format(new Date());
String time = currentTime.format(new Date());
double qty = 0;
//get quantity amount
// if (portionMeasure.equals("singles")) {
//qty = foodQty.getValue();
// } else {
if (foodQty.getText().length() != 0) {
qty = Double.valueOf(foodQty.getText().toString());
} else {
qty = 0;
}
// }
if (qty == 0 || String.valueOf(qty) == "") {
Toast.makeText(getContext(), "Please enter an amount", Toast.LENGTH_SHORT).show();
} else {
//create new intake
Intake intake = new Intake(0, foodID, portionType, qty, date, time);
//record it and increment food used value
db.recordIntake(intake, user);
db.incrementUsedCount(intake.getFoodID(), 1);
db.close();
cancel();
Toast.makeText(getContext(), foodName + " recorded", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("What next?");
builder.setItems(new CharSequence[]
{"Record another food intake..", "Main Menu..", "View Stats.."},
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
cancel();
break;
case 1:
Intent main = new Intent(getContext(), ProfileActivity.class);
getContext().startActivity(main);
break;
case 2:
Intent stats = new Intent(getContext(), StatsActivity.class);
getContext().startActivity(stats);
break;
}
}
});
AlertDialog choose = builder.create();
choose.show();
}
} else if (v == noBtn) {
cancel();
}
}
}
You can catch your buttons click listener as follows:
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//yes button click code here
}
});
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//no button click code here
}
});
You can use the logcat to see if your listener are being fired.

working with canvas : The specified child already has a parent. You must call removeView() on the child's parent first

I visit so many solutions regarding this issue but can't catch it clearly .When ever I run the project first time it works perfectly but when I run it second time then it fire this error in logCat
The specified child already has a parent. You must call removeView() on the child's parent first
where is the error in that code segment ?where should I change in code. any suggestion is acceptable .Thanks in advance ..
Main.java
public class MainActivity extends Activity {
List<PieDetailsItem> piedata = new ArrayList<PieDetailsItem>(0);
EditText edt3;
Button btnChart;
public String s15;
public String[] strArray;
public ImageView mImageView ;
public LinearLayout finalLayout ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
finalLayout = (LinearLayout) findViewById(R.id.pie_container);
mImageView = new ImageView(this);
edt3 = (EditText) this.findViewById(R.id.editText1);
btnChart = (Button) findViewById(R.id.button1);
btnChart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*if(mImageView != null) {
finalLayout.removeView(mImageView);
}
else {*/
s15 = edt3.getText().toString();
/*System.out.println("value 1 is --->"+s10);
System.out.println("value 2 is --->"+s12);*/
System.out.println("value 3 is --->"+s15);
String domain = s15;
strArray = domain.split("\\,");
for (String str : strArray) {
System.out.println(str);
}
// }
openChart();
}
});
}
private void openChart(){
Integer[] items = new Integer[strArray.length];
//double[] distribution = new double[strArray.length];
for (int i = 0; i < items.length; i++) {
items[i] = Integer.parseInt(strArray[i]);
System.out.println("xxxxxx"+items[i]);
}
PieDetailsItem item;
int maxCount = 0;
int itemCount = 0;
// int items[] = { 20, 40, 10, 15, 5 };
int colors[] = { -6777216, -16776961, -16711681, -12303292, -7829368 };
// String itemslabel[] = { " vauesr ur 100", " vauesr ur 200",
// " vauesr ur 300", " vauesr ur 400", " vauesr ur 500" };
for (int i = 0; i < items.length; i++) {
itemCount = items[i];
item = new PieDetailsItem();
item.count = itemCount;
// item.label = itemslabel[i];
item.color = colors[i];
piedata.add(item);
maxCount = maxCount + itemCount;
}
int size = 200;
int BgColor = 0xffa11b1;
Bitmap mBaggroundImage = Bitmap.createBitmap(size, size,
Bitmap.Config.ARGB_8888);
View_PieChart piechart = new View_PieChart(this);
piechart.setLayoutParams(new LayoutParams(size, size));
piechart.setGeometry(size, size, 2, 2, 2, 2, 2130837504);
piechart.setSkinparams(BgColor);
piechart.setData(piedata, maxCount);
piechart.invalidate();
piechart.draw(new Canvas(mBaggroundImage));
piechart = null;
//ImageView mImageView = new ImageView(this);
mImageView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
mImageView.setBackgroundColor(BgColor);
mImageView.setImageBitmap(mBaggroundImage);
//LinearLayout finalLayout = (LinearLayout) findViewById(R.id.pie_container);
finalLayout.addView(mImageView);
}
}
You're adding mImageView to the layout multiple times. A view can only be part of 1 ViewGroup. You need to either add it only once, or create a second ImageView if you really want 2 of them in the layout.

Make click button generate random numbers without repeating

I want to make an app (just for learning purposes) that generates a random message without repeatition.
I have this code inside the onCreate method:
imgbutton2 = (ImageButton) findViewById(R.id.imgbutton2);
int n=3;
int v1[] = new int[n];
v1[0] = 0;
v1[1] = 0;
v1[2] = 0;
int i, j;
for(i=0;i<n;i++){
for(j=0; ;j++){
Random rn = new Random();
int range = 3;
int r = rn.nextInt(range) 1;
if(r != v1[0] & r != v1[1] & r != v1[2]) {
v1[i] = r v1[i];
textView1=new TextView(this);
switch (r) {
case 1:
textView1 = (TextView) findViewById(R.id.textView1);
textView1.setText("Message 1");
break;
case 2:
textView1 = (TextView) findViewById(R.id.textView1);
textView1.setText("Message 2");
break;
case 3:
textView1 = (TextView) findViewById(R.id.textView1);
textView1.setText("Message 3");
break;
}
break;
}
}
imgbutton2.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent i = null;
}});
}
I put a null function to the imgbutton2 (that's inside the first FOR), just for wait the user click, and continue reading to enter again in the first FOR with the i=1 now), but it's not working.
The idea is generate a new message when the button is clicked.
Can anyone help me?
Android provides the API to get the Random Number: Use this on your button click event and get random number with no repetition.
Random myRandom = new Random();
int randomNumber = myRandom.nextInt();
Log.i("RandomNumber:" + randomNumber);

Categories

Resources