Hi there i've been constructing this code for a week but i still cant get it to work. It has no errors but when i run it on the AVD it terminates suddenly.
package com.tryout.sample;
import java.util.Random;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity implements View.OnClickListener{
Random number = new Random();
int Low = 1;
int High = 13;
int RandomNumber = number.nextInt(High-Low) + Low;
int current = 0;
int points=0;
final Integer[] cardid = { R.drawable.card1,
R.drawable.card10,
R.drawable.card11,
R.drawable.card12,
R.drawable.card13,
R.drawable.card2,
R.drawable.card3,
R.drawable.card4,
R.drawable.card5,
R.drawable.card6,
R.drawable.card7,
R.drawable.card8,
R.drawable.card9,
};
ImageView pic2 = (ImageView) findViewById(R.id.imageView1);
final TextView score = (TextView) findViewById(R.id.textView2);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView score = (TextView) findViewById(R.id.textView2);
Button high = (Button) findViewById(R.id.button1);
Button low = (Button) findViewById(R.id.button2);
final ImageView pic = (ImageView) findViewById(R.id.imageView1);
low.setOnClickListener(new view.OnClickListener() {
public void onClick(View v) {
int resource = cardid[RandomNumber];
if(current < RandomNumber){
points = points + 1;
score.setText(points);
pic.setImageResource(resource);
}else{
score.setText("Game Over");
}
}
});
high.setOnClickListener(new View.OnClickListener() {
public void higher(View v) {
int resource = cardid[RandomNumber];
if(current > RandomNumber){
points = points + 1;
score.setText(points);
pic.setImageResource(resource);
}else{
score.setText("Game Over");
}
}
});
int resource = cardid[RandomNumber];
pic.setImageResource(resource);
current = RandomNumber;
}
}
I cant figure out where my problem is, kindly check out my code. THanks for any help
put this:
ImageView pic2 = (ImageView) findViewById(R.id.imageView1);
final TextView score = (TextView) findViewById(R.id.textView2);
in you onCreate method after the call setContentView(R.layout.activity_main);.
How should R.id.imageView1 assigned if the content is not specified like in your case?
ImageView pic2;
TextView score;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pic2 = (ImageView) findViewById(R.id.imageView1);
score = (TextView) findViewById(R.id.textView2);
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
public class minigame_cardpairing extends Activity implements View.OnClickListener {
private static final int TOTAL_CARD_NUM = 16;
private int[] cardId = {R.id.card01, R.id.card02, R.id.card03, R.id.card04, R.id.card05, R.id.card06, R.id.card07, R.id.card08,
R.id.card09, R.id.card10, R.id.card11, R.id.card12, R.id.card13, R.id.card14, R.id.card15, R.id.card16};
private Card[] cardArray = new Card[TOTAL_CARD_NUM];
private int CLICK_CNT = 0;
private Card first, second;
private int SUCCESS_CNT = 0;
private boolean INPLAY = false;
//----------- Activity widget -----------//
private Button start;
//-----------------------------------//
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.minigame_cardpairing);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
for(int i=0; i<TOTAL_CARD_NUM; i++) {
cardArray[i] = new Card(i/2);
findViewById(cardId[i]).setOnClickListener(this);
cardArray[i].card = (ImageButton) findViewById(cardId[i]); // Card assignment
cardArray[i].onBack();
}
start = (Button) findViewById(R.id.start);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startGame();
//start.setBackgroundDrawable(background);
}
});
findViewById(R.id.exit).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setResult(RESULT_OK);
finish();
}
});
} // end of onCreate
protected void startDialog() {
AlertDialog.Builder alt1 = new AlertDialog.Builder(this);
alt1.setMessage("The match-card game. Please remember to flip the cards two by two card hand is a pair Hit. Hit all pairs are completed.")
.setCancelable(false)
.setPositiveButton("close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alt2 = alt1.create();
alt2.setTitle("Game Description");
alt2.show();
}
protected void clearDialog() {
AlertDialog.Builder alt1 = new AlertDialog.Builder(this);
alt1.setMessage("It fits all the cards in pairs. Congratulations.")
.setCancelable(false)
.setPositiveButton("close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alt2 = alt1.create();
alt2.setTitle("Match-complete");
alt2.show();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
startDialog();
}
public void onClick(View v) {
if (INPLAY) {
switch (CLICK_CNT) {
case 0:
for (int i=0; i<TOTAL_CARD_NUM; i++) {
if (cardArray[i].card == (ImageButton) v) {
first = cardArray[i];
break;
}
}
if (first.isBack) {
first.onFront();
CLICK_CNT = 1;
}
break;
case 1:
for (int i=0; i<TOTAL_CARD_NUM; i++) {
if (cardArray[i].card == (ImageButton) v) {
second = cardArray[i];
break;
}
}
if (second.isBack) {
second.onFront();
if (first.value == second.value) {
SUCCESS_CNT++;
Log.v("SUCCESS_CNT", "" + SUCCESS_CNT);
if (SUCCESS_CNT == TOTAL_CARD_NUM/2) {
clearDialog();
}
}
else {
Timer t = new Timer(0);
t.start();
}
CLICK_CNT = 0;
}
break;
}
}
}
void startGame() {
int[] random = new int[TOTAL_CARD_NUM];
int x;
for (int i=0; i<TOTAL_CARD_NUM; i++) {
if (!cardArray[i].isBack)
cardArray[i].onBack();
}
boolean dup;
for (int i=0; i<TOTAL_CARD_NUM; i++) {
while(true) {
dup = false;
x = (int) (Math.random() * TOTAL_CARD_NUM);
for (int j=0; j<i; j++) {
if (random[j] == x) {
dup = true;
break;
}
}
if (!dup) break;
}
random[i] = x;
}
start.setClickable(false);
for (int i=0; i<TOTAL_CARD_NUM; i++) {
cardArray[i].card = (ImageButton) findViewById(cardId[random[i]]);
cardArray[i].onFront();
}
Log.v("timer", "start");
Timer t = new Timer(1);
//flag = false;
t.start();
/*
while(true) {
if (flag) break;
//Log.v("flag", "" + flag);
}
Log.v("timer", "end");
*/
SUCCESS_CNT = 0;
CLICK_CNT = 0;
INPLAY = true;
}
class Timer extends Thread {
int kind;
Timer (int kind) {
super();
this.kind = kind;
}
#Override
public void run() {
INPLAY = false;
// TODO Auto-generated method stub
try {
if (kind == 0) {
Thread.sleep(1000);
mHandler.sendEmptyMessage(0);
}
else if (kind == 1) {
Thread.sleep(3000);
mHandler.sendEmptyMessage(1);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
INPLAY = true;
}
}
Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 0) {
first.onBack();
second.onBack();
first.isBack = true;
second.isBack = true;
}
else if (msg.what == 1) {
//flag = true;
for (int i=0; i<TOTAL_CARD_NUM; i++) {
cardArray[i].onBack();
}
start.setClickable(true);
}
}
};
}
class Card { // start of Card class
private final static int backImageID = R.drawable.cardback;
private final static int[] frontImageID = {R.drawable.card1, R.drawable.card2,
R.drawable.card3, R.drawable.card4,
R.drawable.card5, R.drawable.card6,
R.drawable.card7, R.drawable.card8};
int value;
boolean isBack;
ImageButton card;
Card(int value) {
this.value = value;
}
public void onBack() {
if (!isBack) {
card.setBackgroundResource(backImageID);
isBack = true;
}
}
public void flip() {
if (!isBack) {
card.setBackgroundResource(backImageID);
isBack = true;
}
else {
card.setBackgroundResource(frontImageID[value]);
isBack = false;
}
}
public void onFront() {
if (isBack) {
card.setBackgroundResource(frontImageID[value]);
isBack = false;
}
}
} // end of Card class
Related
I am working on a side project in android studio and need to store some long term data to a file that can be written and readable, I am able to do this outside of android studio, but when I try to do it within, it sows a error saying
public void onClick(View v) 'onClick(View)' in 'Anonymous class derived from android.view.View.OnClickListener' clashes with 'onClick(View)' in 'android.view.View.OnClickListener'; overridden method does not throw 'java.io.FileNotFoundException'{
I have a function in a separate file that writes to a string from a file, but when I try to access that string from one of my main view pages, its asking for an exception, but will not work with said exception, I've tried try and catch but with no success
File being initialized and written:
package com.example.stellarisspeciesrandomizer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import androidx.appcompat.app.AppCompatActivity;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
public class DLCPage extends AppCompatActivity {
public static int[] DLCArray;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
setContentView(R.layout.dlc_page);
try {
File myObj = new File("hasDLC.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
DLCArray = new int[1];
Button doneButton = (Button) findViewById(R.id.button_done);
doneButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) throws IOException {
writeToFile();
finish();
}});
ImageButton aquaticsCheckbox = (ImageButton) findViewById(R.id.aquatic_checkbox);
aquaticsCheckbox.setTag("1");
//hello
aquaticsCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (aquaticsCheckbox.getTag() == "1") {
aquaticsCheckbox.setImageResource(R.drawable.checked);
aquaticsCheckbox.setTag("2");
DLCArray[0] = 1;
} else if (aquaticsCheckbox.getTag() == "2") {
aquaticsCheckbox.setImageResource(R.drawable.checkmark);
aquaticsCheckbox.setTag("1");
DLCArray[0] = 0;
}
}
});
ImageButton humanoidCheckbox = (ImageButton) findViewById(R.id.humanoid_checkbox);
humanoidCheckbox.setTag("1");
humanoidCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (humanoidCheckbox.getTag() == "1") {
humanoidCheckbox.setImageResource(R.drawable.checked);
humanoidCheckbox.setTag("2");
DLCArray[1] = 1;
} else if (humanoidCheckbox.getTag() == "2") {
humanoidCheckbox.setImageResource(R.drawable.checkmark);
humanoidCheckbox.setTag("1");
DLCArray[1] = 0;
}
}
});
ImageButton plantoidCheckbox = (ImageButton) findViewById(R.id.plantoid_checkbox);
plantoidCheckbox.setTag("1");
plantoidCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (plantoidCheckbox.getTag() == "1") {
plantoidCheckbox.setImageResource(R.drawable.checked);
plantoidCheckbox.setTag("2");
DLCArray[2] = 1;
} else if (plantoidCheckbox.getTag() == "2") {
plantoidCheckbox.setImageResource(R.drawable.checkmark);
plantoidCheckbox.setTag("1");
DLCArray[2] = 0;
}
}
});
ImageButton syntheticCheckbox = (ImageButton) findViewById(R.id.synthetic_checkbox);
syntheticCheckbox.setTag("1");
syntheticCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (syntheticCheckbox.getTag() == "1") {
syntheticCheckbox.setImageResource(R.drawable.checked);
syntheticCheckbox.setTag("2");
DLCArray[3] = 1;
} else if (syntheticCheckbox.getTag() == "2") {
syntheticCheckbox.setImageResource(R.drawable.checkmark);
syntheticCheckbox.setTag("1");
DLCArray[3] = 0;
}
}
});
ImageButton necroidCheckbox = (ImageButton) findViewById(R.id.necroids_checkbox);
necroidCheckbox.setTag("1");
necroidCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (necroidCheckbox.getTag() == "1") {
necroidCheckbox.setImageResource(R.drawable.checked);
necroidCheckbox.setTag("2");
DLCArray[4] = 1;
} else if (necroidCheckbox.getTag() == "2") {
necroidCheckbox.setImageResource(R.drawable.checkmark);
necroidCheckbox.setTag("1");
DLCArray[4] = 0;
}
}
});
ImageButton lithoidCheckbox = (ImageButton) findViewById(R.id.lithoids_checkbox);
lithoidCheckbox.setTag("1");
lithoidCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (lithoidCheckbox.getTag() == "1") {
lithoidCheckbox.setImageResource(R.drawable.checked);
lithoidCheckbox.setTag("2");
DLCArray[5] = 1;
} else if (lithoidCheckbox.getTag() == "2") {
lithoidCheckbox.setImageResource(R.drawable.checkmark);
lithoidCheckbox.setTag("1");
DLCArray[5] = 0;
}
}
});
ImageButton ancientCheckbox = (ImageButton) findViewById(R.id.ancient_checkbox);
ancientCheckbox.setTag("1");
ancientCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (ancientCheckbox.getTag() == "1") {
ancientCheckbox.setImageResource(R.drawable.checked);
ancientCheckbox.setTag("2");
DLCArray[6] = 1;
} else if (ancientCheckbox.getTag() == "2") {
ancientCheckbox.setImageResource(R.drawable.checkmark);
ancientCheckbox.setTag("1");
DLCArray[6] = 0;
}
}
});
ImageButton federationsCheckbox = (ImageButton) findViewById(R.id.federations_checkbox);
federationsCheckbox.setTag("1");
federationsCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (federationsCheckbox.getTag() == "1") {
federationsCheckbox.setImageResource(R.drawable.checked);
federationsCheckbox.setTag("2");
DLCArray[7] = 1;
} else if (federationsCheckbox.getTag() == "2") {
federationsCheckbox.setImageResource(R.drawable.checkmark);
federationsCheckbox.setTag("1");
DLCArray[7] = 0;
}
}
});
ImageButton apocalypseCheckbox = (ImageButton) findViewById(R.id.apocalypse_checkbox);
apocalypseCheckbox.setTag("1");
apocalypseCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (apocalypseCheckbox.getTag() == "1") {
apocalypseCheckbox.setImageResource(R.drawable.checked);
apocalypseCheckbox.setTag("2");
DLCArray[8] = 1;
} else if (apocalypseCheckbox.getTag() == "2") {
apocalypseCheckbox.setImageResource(R.drawable.checkmark);
apocalypseCheckbox.setTag("1");
DLCArray[8] = 0;
}
}
});
ImageButton utopiaCheckbox = (ImageButton) findViewById(R.id.utopia_checkbox);
utopiaCheckbox.setTag("1");
utopiaCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (utopiaCheckbox.getTag() == "1") {
utopiaCheckbox.setImageResource(R.drawable.checked);
utopiaCheckbox.setTag("2");
DLCArray[9] = 1;
} else if (utopiaCheckbox.getTag() == "2") {
utopiaCheckbox.setImageResource(R.drawable.checkmark);
utopiaCheckbox.setTag("1");
DLCArray[9] = 0;
}
}
});
}
public static void writeToFile() throws IOException {
int len = DLCArray.length;
for (int i = 0; i < len; i++) {
FileWriter writer = new FileWriter("hasDLC.txt");
writer.write(DLCArray[i] + "\t"+ "");
}
}
}
second page
package com.example.stellarisspeciesrandomizer;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Randomizer {
private static int[] tall= new int[3] ;
public static String RandomSpecies(String origin) throws FileNotFoundException {
readFile();
Random random = new Random();
ArrayList<String> originArray = new ArrayList<String>();
String origins1 = "Prosperous Unification";
String origins2 = "Galactic Doorstep";
String origins3 = "Lost Colony";
String origins4 = "Here Be Dragons";
String origins5 = "Ocean Paradise";
String origins6 = "Clone Army";
String origins7 = "Necrophage";
String origins18 = "Resource Consolidation";
String origins19 = "Remnants";
String origins16 = "Life Seeded";
String origins17 = "Post-Apocalyptic";
String origins8 = "Remnants";
String origins9 = "Shattered Ring";
String origins10 = "Void Dwellers";
String origins11 = "Scion";
String origins12 = "On The Shoulders of Giants";
String origins13 = "Common Ground";
String origins14 = "Hegemon";
String origins15 = "Doomsday";
String origin20 = "Syncretic Evolution";
String origin21 = "Mechanist";
String origin22 = "String of Life";
originArray.add(origins4);
originArray.add(origins5);
originArray.add(origins6);
originArray.add(origins7);
originArray.add(origins18);
originArray.add(origins19);
originArray.remove(origins17);
originArray.remove(origins16);
originArray.add(origins8);
originArray.add(origins9);
originArray.add(origins10);
originArray.add(origins11);
originArray.add(origins12);
originArray.add(origins13);
originArray.add(origins14);
originArray.add(origins15);
originArray.add(origin20);
originArray.add(origin21);
originArray.add(origin22);
originArray.add(origins1);
originArray.add(origins2);
originArray.add(origins3);
origin = originArray.get(random.nextInt(originArray.size()));
return origin;
}
public static void readFile() throws FileNotFoundException {
Scanner scanner = new Scanner(new File("hasDLC.txt"));
tall = new int [100];
int i = 0;
while(scanner.hasNextInt()){
tall[i++] = scanner.nextInt();
}
System.out.println(tall);
}
}
last page
package com.example.stellarisspeciesrandomizer;
import static com.example.stellarisspeciesrandomizer.Randomizer.RandomSpecies;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
import java.io.FileNotFoundException;
public class RandomizerHome extends AppCompatActivity {
String hi = "hi";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
setContentView(R.layout.randomizer_layout);
ImageView originImageView =(ImageView) findViewById(R.id.originImageView);
Intent dlcIntent = new Intent(this, DLCPage.class);
Button dlcButton = (Button) findViewById(R.id.dlc_button);
dlcButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(dlcIntent);
}
});
Button randomizeButton = (Button) findViewById(R.id.randomize_button);
randomizeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) throws FileNotFoundException {
String originTrue = "hi";
originTrue = RandomSpecies(hi);
switch(originTrue){
case ("Prosperous Unification"): originImageView.setImageResource(R.drawable.prosperousunification);break;
case ("Galactic Doorstep"): originImageView.setImageResource(R.drawable.galacticdoorstep);break;
case ("Lost Colony"): originImageView.setImageResource(R.drawable.lostcolony);break;
case ("Here Be Dragons"): originImageView.setImageResource(R.drawable.here_be_dragons);break;
case ("Ocean Paradise"): originImageView.setImageResource(R.drawable.ocean_paradise);break;
case ("Clone Army"): originImageView.setImageResource(R.drawable.clones);break;
case ("Necrophage"): originImageView.setImageResource(R.drawable.necrophage);break;
case ("Resource Consolidation"): originImageView.setImageResource(R.drawable.resource_consolidation);break;
case ("Remnants"): originImageView.setImageResource(R.drawable.remnant);break;
case ("Life Seeded"): originImageView.setImageResource(R.drawable.life_seeded);break;
case ("Post-Apocalyptic"): originImageView.setImageResource(R.drawable.post_apocalyptic);break;
case ("Shattered Ring"): originImageView.setImageResource(R.drawable.shattered_ring);break;
case ("Void Dwellers"): originImageView.setImageResource(R.drawable.void_dwellers);break;
case ("Scion"): originImageView.setImageResource(R.drawable.scion);break;
case ("On The Shoulders of Giants"): originImageView.setImageResource(R.drawable.on_the_shoulders_of_giant);break;
case ("Common Ground"): originImageView.setImageResource(R.drawable.common_ground);break;
case ("Hegemon"): originImageView.setImageResource(R.drawable.hegemon);break;
case ("Doomsday"): originImageView.setImageResource(R.drawable.doomsday);break;
case ("Syncretic Evolution"): originImageView.setImageResource(R.drawable.syncretic_evolution);break;
case ("Mechanist"): originImageView.setImageResource(R.drawable.mechanist);break;
case ("Tree of Life"): originImageView.setImageResource(R.drawable.tree_of_life);break;
}
System.out.println(originTrue);
}
});
}
}
Here:
randomizeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) throws FileNotFoundException {
What you are doing here: define an anonymous subclass of View.OnClickListener. And when you check the documentation for that class, it says:
public abstract void onClick (View v)
Now read the compiler message again you got. overridden method does not throw 'java.io.FileNotFoundException'
Thus the real answer here is: A) you have to understand what you are doing and B) you have to read compiler error messages really carefully.
Long story short, you can not override an inherited method and add checked exceptions such as FileNotFoundException to the signature of your method. So, the solution is to step back and to really learn/understand how exception handling works in Java. One possibility here: use try/catch in your readFile(), catch the FileNotFoundException and rethrow it as (unchecked) RuntimeException. Then you do not need to have throws FileNotFoundException on your method signatures, and the compiler won't complain any more.
Currently having an issue having an image button open to another activity when we try the app closes. What we are trying to create is a tic tac toe game that has a splash screen, main activity, and new activity that is the actual game. The splash screen opens to the main but when we try to open the main activity to the board game it closes on us. Any advice?
Here is the current code:
Activity1 :
package com.example.tictactoe_game;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class MainActivity extends AppCompatActivity {
ImageButton newActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
newActivity = (ImageButton) findViewById(R.id.imageButton_play);
newActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, GameBoard.class);
startActivity(intent);
}
});
}
}
Activity 2:
package com.example.tictactoe_game;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class GameBoard extends AppCompatActivity implements View.OnClickListener {
private Button[][] buttons = new Button[3][3];
private boolean player1Turn = true;
private int roundCount;
private int player1Points;
private int player2Points;
private TextView textViewPlayer1;
private TextView textViewPlayer2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_board);
textViewPlayer1 = findViewById(R.id.text_viewp1);
textViewPlayer2 = findViewById(R.id.text_viewp2);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
String buttonID = "button_" + i + j;
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i][j] = findViewById(resID);
buttons[i][j].setOnClickListener(this);
}
}
}
#Override
public void onClick(View v) {
if (!((Button) v).getText().toString().equals("")) {
return;
}
if (player1Turn) {
((Button) v).setText("X");
} else {
((Button) v).setText("O");
}
roundCount++;
if (checkForWin()) {
if (player1Turn) {
player1Wins();
} else {
player2Wins();
}
} else if (roundCount == 9) {
draw();
} else {
player1Turn = !player1Turn;
}
}
private boolean checkForWin() {
String[][] field = new String[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
field[i][j] = buttons[i][j].getText().toString();
}
}
for (int i = 0; i < 3; i++) {
if (field[i][0].equals(field[i][1])
&& field[i][0].equals(field[i][2])
&& !field[i][0].equals("")) {
return true;
}
}
for (int i = 0; i < 3; i++) {
if (field[0][i].equals(field[1][i])
&& field[0][i].equals(field[2][i])
&& !field[0][i].equals("")) {
return true;
}
}
if (field[0][0].equals(field[1][1])
&& field[0][0].equals(field[2][2])
&& !field[0][0].equals("")) {
return true;
}
if (field[0][2].equals(field[1][1])
&& field[0][2].equals(field[2][0])
&& !field[0][2].equals("")) {
return true;
}
return false;
}
private void player1Wins() {
player1Points++;
Toast.makeText(this, "Player 1 Wins!", Toast.LENGTH_SHORT).show();
updatePointsText();
resetBoard();
}
private void player2Wins() {
player2Points++;
Toast.makeText(this, "Player 2 Wins!", Toast.LENGTH_SHORT).show();
updatePointsText();
resetBoard();
}
private void draw() {
Toast.makeText(this, "Draw!", Toast.LENGTH_SHORT).show();
resetBoard();
}
private void updatePointsText() {
textViewPlayer1.setText("Player 1: " + player1Points);
textViewPlayer2.setText("Player 2: " + player2Points);
}
private void resetBoard() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
buttons[i][j].setText("");
}
}
roundCount = 0;
player1Turn = true;
}
}
I'm not android studio developer or java developer but regarding for my graduation project I need to make an android app that connects to HC-05 Bluetooth module "Arduino", then starts to transmit and receive bytes ... I have found a lot of projects that connects to the Bluetooth module by showing you a list of Bluetooth devices then you can choose which one you want to connect ...
but I don't want to use this method I want to find a method that searches for a specific Bluetooth mac address and if it available, start connecting to it, if it not available, the app will continue searching ...
I don't have any experience how can programmatically make this.
so please be patient :D
I have done the XML design...
I want to add the mac address connecting code here
package mdluex.smartx;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class ActivityControlCenter extends AppCompatActivity {
private int room1_str = 1;
private int room2_str = 0;
private int room3_str = 1;
private int room4_str = 1;
private int room5_str = 1;
private int room6_str = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_control_center);
final RelativeLayout room1_btn = (RelativeLayout) this.findViewById(R.id.room1_btn);
final TextView room1_st = (TextView) this.findViewById(R.id.room1_st);
final ImageView room1_img = (ImageView) this.findViewById(R.id.room1_img);
room1_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room1_str == 0){
room1_str = 1;
room1_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room1_st.setText("ON");
room1_img.setImageResource(R.drawable.lamp_on);
}
else {
room1_str = 0;
room1_btn.setBackgroundResource(R.drawable.btn_grid_off);
room1_st.setText("OFF");
room1_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room2_btn = (RelativeLayout) this.findViewById(R.id.room2_btn);
final TextView room2_st = (TextView) this.findViewById(R.id.room2_st);
final ImageView room2_img = (ImageView) this.findViewById(R.id.room2_img);
room2_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room2_str == 0){
room2_str = 1;
room2_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room2_st.setText("ON");
room2_img.setImageResource(R.drawable.lamp_on);
}
else {
room2_str = 0;
room2_btn.setBackgroundResource(R.drawable.btn_grid_off);
room2_st.setText("OFF");
room2_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room3_btn = (RelativeLayout) this.findViewById(R.id.room3_btn);
final TextView room3_st = (TextView) this.findViewById(R.id.room3_st);
final ImageView room3_img = (ImageView) this.findViewById(R.id.room3_img);
room3_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room3_str == 0){
room3_str = 1;
room3_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room3_st.setText("ON");
room3_img.setImageResource(R.drawable.lamp_on);
}
else {
room3_str = 0;
room3_btn.setBackgroundResource(R.drawable.btn_grid_off);
room3_st.setText("OFF");
room3_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room4_btn = (RelativeLayout) this.findViewById(R.id.room4_btn);
final TextView room4_st = (TextView) this.findViewById(R.id.room4_st);
final ImageView room4_img = (ImageView) this.findViewById(R.id.room4_img);
room4_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room4_str == 0){
room4_str = 1;
room4_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room4_st.setText("ON");
room4_img.setImageResource(R.drawable.lamp_on);
}
else {
room4_str = 0;
room4_btn.setBackgroundResource(R.drawable.btn_grid_off);
room4_st.setText("OFF");
room4_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room5_btn = (RelativeLayout) this.findViewById(R.id.room5_btn);
final TextView room5_st = (TextView) this.findViewById(R.id.room5_st);
final ImageView room5_img = (ImageView) this.findViewById(R.id.room5_img);
room5_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room5_str == 0){
room5_str = 1;
room5_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room5_st.setText("ON");
room5_img.setImageResource(R.drawable.lamp_on);
}
else {
room5_str = 0;
room5_btn.setBackgroundResource(R.drawable.btn_grid_off);
room5_st.setText("OFF");
room5_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room6_btn = (RelativeLayout) this.findViewById(R.id.room6_btn);
final TextView room6_st = (TextView) this.findViewById(R.id.room6_st);
final ImageView room6_img = (ImageView) this.findViewById(R.id.room6_img);
room6_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room6_str == 0){
room6_str = 1;
room6_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room6_st.setText("ON");
room6_img.setImageResource(R.drawable.lamp_on);
}
else {
room6_str = 0;
room6_btn.setBackgroundResource(R.drawable.btn_grid_off);
room6_st.setText("OFF");
room6_img.setImageResource(R.drawable.lamp_off);
}
}
});
}
}
this is the XML design
Activity Design
the full project code on GitHub
I found the solution :D
thanks, guys ...
My full project contains this code:
package mdluex.smartx;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class ActivityControlCenter extends AppCompatActivity {
private int room1_str = 1;
private int room2_str = 0;
private int room3_str = 1;
private int room4_str = 1;
private int room5_str = 1;
private int room6_str = 1;
String deviceName = "HC-05";
BluetoothDevice result = null;
BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
private BluetoothSocket socket;
private OutputStream outputStream;
private InputStream inputStream;
private final UUID PORT_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//Serial Port Service ID
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_control_center);
if (bluetoothAdapter == null) {
Toast.makeText(getApplicationContext(),"Device doesnt Support Bluetooth",Toast.LENGTH_SHORT).show();
}
if(!bluetoothAdapter.isEnabled())
{
Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableAdapter, 0);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices();
if (devices != null) {
for (BluetoothDevice device : devices) {
if (deviceName.equals(device.getName())) {
Toast.makeText(getApplicationContext(),"SamrtX is available ",Toast.LENGTH_SHORT).show();
result = device;
boolean connected=true;
try {
socket = result.createRfcommSocketToServiceRecord(PORT_UUID);
socket.connect();
Toast.makeText(getApplicationContext(),"Connected",Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
connected=false;
Toast.makeText(getApplicationContext(),"SamrtX is not available ",Toast.LENGTH_SHORT).show();
}
if(connected)
{
try {
outputStream=socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream=socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
}
}
final RelativeLayout room1_btn = (RelativeLayout) this.findViewById(R.id.room1_btn);
final TextView room1_st = (TextView) this.findViewById(R.id.room1_st);
final ImageView room1_img = (ImageView) this.findViewById(R.id.room1_img);
room1_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room1_str == 0){
room1_str = 1;
if (socket!=null)
{
try
{
socket.getOutputStream().write("a".toString().getBytes());
}
catch (IOException e)
{
Toast.makeText(getApplicationContext(),"Error ",Toast.LENGTH_SHORT).show();
}
}
room1_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room1_st.setText("ON");
room1_img.setImageResource(R.drawable.lamp_on);
}
else {
room1_str = 0;
if (socket!=null)
{
try
{
socket.getOutputStream().write("b".toString().getBytes());
}
catch (IOException e)
{
Toast.makeText(getApplicationContext(),"Error ",Toast.LENGTH_SHORT).show();
}
}
room1_btn.setBackgroundResource(R.drawable.btn_grid_off);
room1_st.setText("OFF");
room1_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room2_btn = (RelativeLayout) this.findViewById(R.id.room2_btn);
final TextView room2_st = (TextView) this.findViewById(R.id.room2_st);
final ImageView room2_img = (ImageView) this.findViewById(R.id.room2_img);
room2_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room2_str == 0){
room2_str = 1;
room2_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room2_st.setText("ON");
room2_img.setImageResource(R.drawable.lamp_on);
}
else {
room2_str = 0;
room2_btn.setBackgroundResource(R.drawable.btn_grid_off);
room2_st.setText("OFF");
room2_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room3_btn = (RelativeLayout) this.findViewById(R.id.room3_btn);
final TextView room3_st = (TextView) this.findViewById(R.id.room3_st);
final ImageView room3_img = (ImageView) this.findViewById(R.id.room3_img);
room3_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room3_str == 0){
room3_str = 1;
room3_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room3_st.setText("ON");
room3_img.setImageResource(R.drawable.lamp_on);
}
else {
room3_str = 0;
room3_btn.setBackgroundResource(R.drawable.btn_grid_off);
room3_st.setText("OFF");
room3_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room4_btn = (RelativeLayout) this.findViewById(R.id.room4_btn);
final TextView room4_st = (TextView) this.findViewById(R.id.room4_st);
final ImageView room4_img = (ImageView) this.findViewById(R.id.room4_img);
room4_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room4_str == 0){
room4_str = 1;
room4_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room4_st.setText("ON");
room4_img.setImageResource(R.drawable.lamp_on);
}
else {
room4_str = 0;
room4_btn.setBackgroundResource(R.drawable.btn_grid_off);
room4_st.setText("OFF");
room4_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room5_btn = (RelativeLayout) this.findViewById(R.id.room5_btn);
final TextView room5_st = (TextView) this.findViewById(R.id.room5_st);
final ImageView room5_img = (ImageView) this.findViewById(R.id.room5_img);
room5_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room5_str == 0){
room5_str = 1;
room5_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room5_st.setText("ON");
room5_img.setImageResource(R.drawable.lamp_on);
}
else {
room5_str = 0;
room5_btn.setBackgroundResource(R.drawable.btn_grid_off);
room5_st.setText("OFF");
room5_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room6_btn = (RelativeLayout) this.findViewById(R.id.room6_btn);
final TextView room6_st = (TextView) this.findViewById(R.id.room6_st);
final ImageView room6_img = (ImageView) this.findViewById(R.id.room6_img);
room6_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room6_str == 0){
room6_str = 1;
room6_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room6_st.setText("ON");
room6_img.setImageResource(R.drawable.lamp_on);
}
else {
room6_str = 0;
room6_btn.setBackgroundResource(R.drawable.btn_grid_off);
room6_st.setText("OFF");
room6_img.setImageResource(R.drawable.lamp_off);
}
}
});
}
}
Im following the tutorial of In-app Billing from the following link:
Android Studio Google Play In-app Billing Tutorial.
Im implementing this logic in a Contact Adapter class which extends Base Adapter. In tutorial it is implemented in a class which extends Activity.
Error comes on onActivityResult(). I read several questions on this and I understand this method should be written in class which extends Activity but in my case the scenario is different.
Is there any way to solve this without writing onActivityResult method in MainActivity class.. and if not what should I do?
Heres ContactAdapter.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import com.neirx.myco.smsproject.util.IabHelper;
import com.neirx.myco.smsproject.util.IabResult;
import com.neirx.myco.smsproject.util.Inventory;
import com.neirx.myco.smsproject.util.Purchase;
import java.util.List;
public class ContactAdapter extends BaseAdapter {
private static final java.lang.String CLASS_NAME = "<ContactAdapter> ";
Context context;
List<Contact> objects;
LayoutInflater lInflater;
MainActivity activity;
static final String ITEM_SKU = "android.test.purchased";
IabHelper mHelper;
int count = 0;
int get_limit;
private int limit_counter = 0;
private int max_limit = 2;
boolean testbool = true;
public ContactAdapter(Context context, List<Contact> contact) {
this.context = context;
objects = contact;
lInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
activity = (MainActivity) context;
}
#Override
public int getCount() {
int selectedCount = 0;
int nonSelectedCount = 0;
int size = 0;
for(Contact contact : objects){
if(contact.isChecked()) selectedCount++;
else nonSelectedCount++;
}
if(activity.isShowSelected()) size += selectedCount;
if(activity.isShowNonSelected()) size += nonSelectedCount;
return size;
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void buyClick() {
mHelper.launchPurchaseFlow(activity, ITEM_SKU, 10001, mPurchaseFinishedListener, "mypurchasetoken");
}
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent data)
{
if (!mHelper.handleActivityResult(requestCode,resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result,Purchase purchase)
{
if (result.isFailure()) {
// Handle error
Log.d("----FAILURE 1---", "FAIL 1");
return;
}
else if (purchase.getSku().equals(ITEM_SKU)) {
consumeItem();
//buyButton.setEnabled(false);
}
}
};
public void consumeItem() {
mHelper.queryInventoryAsync(mReceivedInventoryListener);
}
IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result,Inventory inventory) {
if (result.isFailure()) {
// Handle failure
Log.d("----FAILURE 2---", "FAIL 2");
} else {
mHelper.consumeAsync(inventory.getPurchase(ITEM_SKU),mConsumeFinishedListener);
}
}
};
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
public void onConsumeFinished(Purchase purchase,IabResult result) {
if (result.isSuccess()) {
//clickButton.setEnabled(true);
Log.d("----Success ----", "Success");
} else {
// handle error
Log.d("----FAILURE 3---", "FAIL 3");
}
}
};
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
String base64EncodedPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxW650UixX2dLFECVdOpTh5OpBTqHwsznQAKd/cVcqKhrXROy4+Gj6B7M6wbkhTaloNSzTOf+nw9t1LZZ19Vlr6kcwmtxP+V/HOFwjf/NB69StOONogXtGKDyRrxtVaPM5es3yGy/aP/LXWfTLFQYJvur4AePonuRXz33iufBq5ITDQJ0+0D/o/mGtadJv0ZMsP9LV/qrMqruoqpSdaIiw5TGXdzYlJTuoP3GwS9kRyZKDeG/70KZ28W/ZclVWAdnZ7aCeDURYDV3a4pmGp5/cIvKwbex6Y7KbQYENX5ObSgNoFHLdyPTdkYaeuU9O6pet2TjGUCKr8n4M5KUMZVm8QIDAQAB";
mHelper = new IabHelper(context, base64EncodedPublicKey);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result)
{
if (!result.isSuccess()) {
Log.d("---MY TAG---", "In-app Billing setup failed: " +
result);
} else {
Log.d("---MY TAG---", "In-app Billing is set up OK");
}
}
});
SharedPreferences limit_pref = context.getSharedPreferences(Statical.PREF_LIMIT, Context.MODE_PRIVATE);
get_limit = limit_pref.getInt("LIMIT_KEY",0);
//Log.d("----- STORED VALUE-----", "Value is: "+get_limit);
Log.d("----- Max VALUE-----", "Value is: "+max_limit);
if (view == null) {
view = lInflater.inflate(R.layout.view_contact, parent, false);//create view file
}
if (position == 0) {
count = 0;
}
if (!activity.isShowSelected()) {
while (objects.get(position + count).isChecked()) {
count++;
}
}
if (!activity.isShowNonSelected()) {
while (!objects.get(position + count).isChecked()) {
count++;
}
}
final Contact contact = objects.get(position + count);
String contactFirstName = contact.getFirstName();
String contactSecondName = contact.getSecondName();
String contactMiddleName = contact.getMiddleName();
String[] contactNumbers = contact.getNumbers();
TextView tvName = (TextView) view.findViewById(R.id.tvName);
TextView tvNumber = (TextView) view.findViewById(R.id.tvNumber);
final CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox);
if(get_limit == max_limit)
{
//checkBox.setChecked(contact.isChecked());
//testbool = false;
limit_counter = get_limit;
}
else if (get_limit == 1)
{
limit_counter = 1;
}
String fullName;
switch (MainActivity.sortMode) {
case Contact.COMPARE_SECOND_NAME:
fullName = getFullName(contactSecondName, contactFirstName);
break;
case Contact.COMPARE_MIDDLE_NAME:
fullName = getFullName(contactMiddleName, contactFirstName, contactSecondName);
break;
default:
fullName = getFullName(contactFirstName, contactSecondName);
break;
}
tvName.setText(fullName);
StringBuilder sbNumber = new StringBuilder();
for (int i = 0; i < contactNumbers.length; i++) {
sbNumber.append(contactNumbers[i]);
if (i < contactNumbers.length - 1) {
sbNumber.append(", ");
}
}
tvNumber.setText(sbNumber);
if (testbool) {
//Log.d("Check Boolean Tag 2 ", "testbool: "+testbool);
checkBox.setChecked(contact.isChecked());
}
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences selected = context.getSharedPreferences(Statical.CONTACTS_SELECTED, Context.MODE_PRIVATE);
SharedPreferences.Editor editSelected = selected.edit();
SharedPreferences limit_pref = context.getSharedPreferences(Statical.PREF_LIMIT, Context.MODE_PRIVATE);
SharedPreferences.Editor edit_limit_pref = limit_pref.edit();
int k = 0;
if(limit_counter == max_limit)
{
checkBox.setChecked(false);
//Toast.makeText(context,"Limit reached !! ", Toast.LENGTH_SHORT).show();
Log.d("-------LIMIT REACH-----", "value: "+limit_counter);
edit_limit_pref.putInt("LIMIT_KEY",limit_counter);
showAlertDialog();
}
if (contact.isChecked() && limit_counter <= max_limit && limit_counter >= 0) {
limit_counter = limit_counter - 1;
editSelected.putBoolean(contact.getContactId(), false);
edit_limit_pref.putInt("LIMIT_KEY",limit_counter);
contact.setChecked(false);
Log.d("-------UN CHECKED-----", "Un Checked value: "+limit_counter);
k = -1;
}
else if(!contact.isChecked() && limit_counter < max_limit){
limit_counter = limit_counter + 1;
editSelected.putBoolean(contact.getContactId(), true);
edit_limit_pref.putInt("LIMIT_KEY",limit_counter);
contact.setChecked(true);
Log.d("------- CHECKED -----", "Checked value: "+limit_counter);
k = 1;
}
editSelected.apply();
edit_limit_pref.apply();
activity.updateCount(k);
}
});
return view;
}
public void showAlertDialog()
{
Log.d("-------VALUE-----", "value: "+limit_counter);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Limit Reached!");
alertDialog.setMessage("Buy Pro Version");
alertDialog.setIcon(R.drawable.action_bar_logo);
alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
buyClick();
Log.d("-------OK PRESSED -----", "value: " + limit_counter);
dialog.cancel();
}
});
alertDialog.setNegativeButton("Later", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d("----LATER PRESSED -----", "value: " + limit_counter);
dialog.cancel();
}
});
alertDialog.show();
}
private String getFullName(String first, String second, String third) {
StringBuilder sbName = new StringBuilder();
if (!first.isEmpty()) {
sbName.append(first).append(" ");
}
if (!second.isEmpty()) {
sbName.append(second).append(" ");
}
if (!third.isEmpty()) {
sbName.append(third);
}
return sbName.toString();
}
private String getFullName(String first, String second) {
StringBuilder sbName = new StringBuilder();
if (!first.isEmpty()) {
sbName.append(first).append(" ");
}
if (!second.isEmpty()) {
sbName.append(second);
}
return sbName.toString();
}
}
I recommend you to create an activity just to process this payment and then you can back to your normal flow.
i'm using youtubeApi (https://developers.google.com/youtube/android/player/downloads/), I'm looking for a solution for put an onclick listener on the videos on the VideoWall..
package com.android.youbho.Activities;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.PlayerStyle;
import com.google.android.youtube.player.YouTubePlayerFragment;
import com.google.android.youtube.player.YouTubeThumbnailLoader;
import com.google.android.youtube.player.YouTubeThumbnailView;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Pair;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.Toast;
import com.android.youbho.Utils.Constant;
import com.android.youbho.Utils.FlippingView;
import com.android.youbho.Utils.ImageWallView;
#SuppressLint("NewApi") public class VideoWallActivity extends Activity implements
FlippingView.Listener,
YouTubePlayer.OnInitializedListener,
YouTubeThumbnailView.OnInitializedListener{
private static final int RECOVERY_DIALOG_REQUEST = 1;
/** The player view cannot be smaller than 110 pixels high. */
private static final float PLAYER_VIEW_MINIMUM_HEIGHT_DP = 110;
private static final int MAX_NUMBER_OF_ROWS_WANTED = 4;
// Example playlist from which videos are displayed on the video wall
private static final String PLAYLIST_ID = "PLBA95EAD360E2B0D1";
private static final int INTER_IMAGE_PADDING_DP = 5;
// YouTube thumbnails have a 16 / 9 aspect ratio
private static final double THUMBNAIL_ASPECT_RATIO = 16 / 9d;
private static final int INITIAL_FLIP_DURATION_MILLIS = 100;
private static final int FLIP_DURATION_MILLIS = 500;
private static final int FLIP_PERIOD_MILLIS = 2000;
private ImageWallView imageWallView;
private Handler flipDelayHandler;
private FlippingView flippingView;
private YouTubeThumbnailView thumbnailView;
private YouTubeThumbnailLoader thumbnailLoader;
private YouTubePlayerFragment playerFragment;
private View playerView;
private YouTubePlayer player;
private Dialog errorDialog;
private int flippingCol;
private int flippingRow;
private int videoCol;
private int videoRow;
private boolean nextThumbnailLoaded;
private boolean activityResumed;
private State state;
private static final int id_videoPlayer=99;
private enum State {
UNINITIALIZED,
LOADING_THUMBNAILS,
VIDEO_FLIPPED_OUT,
VIDEO_LOADING,
VIDEO_CUED,
VIDEO_PLAYING,
VIDEO_ENDED,
VIDEO_BEING_FLIPPED_OUT,
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
Toast.makeText(getApplicationContext(), "lol:" + position, Toast.LENGTH_LONG).show();
return view;
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB) #SuppressLint("NewApi") #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
state = State.UNINITIALIZED;
ViewGroup viewFrame = new FrameLayout(this);
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int maxAllowedNumberOfRows = (int) Math.floor((displayMetrics.heightPixels / displayMetrics.density) / PLAYER_VIEW_MINIMUM_HEIGHT_DP);
int numberOfRows = Math.min(maxAllowedNumberOfRows, MAX_NUMBER_OF_ROWS_WANTED);
int interImagePaddingPx = (int) displayMetrics.density * INTER_IMAGE_PADDING_DP;
int imageHeight = (displayMetrics.heightPixels / numberOfRows) - interImagePaddingPx;
int imageWidth = (int) (imageHeight * THUMBNAIL_ASPECT_RATIO);
imageWallView = new ImageWallView(this, imageWidth, imageHeight, interImagePaddingPx);
viewFrame.addView(imageWallView, MATCH_PARENT, MATCH_PARENT);
thumbnailView = new YouTubeThumbnailView(this);
thumbnailView.initialize(Constant.DEVELOPER_KEY, this);
flippingView = new FlippingView(this, this, imageWidth, imageHeight);
flippingView.setFlipDuration(INITIAL_FLIP_DURATION_MILLIS);
viewFrame.addView(flippingView, imageWidth, imageHeight);
playerView = new FrameLayout(this);
playerView.setId(id_videoPlayer);
playerView.setVisibility(View.INVISIBLE);
viewFrame.addView(playerView, imageWidth, imageHeight);
playerFragment = YouTubePlayerFragment.newInstance();
playerFragment.initialize(Constant.DEVELOPER_KEY, this);
getFragmentManager().beginTransaction().add(id_videoPlayer, playerFragment).commit();
flipDelayHandler = new FlipDelayHandler();
setContentView(viewFrame);
}
#Override
public void onInitializationSuccess(YouTubeThumbnailView thumbnailView, YouTubeThumbnailLoader thumbnailLoader) {
thumbnailView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "lol! ", Toast.LENGTH_LONG).show();
}
});
this.thumbnailLoader = thumbnailLoader;
thumbnailLoader.setOnThumbnailLoadedListener(new ThumbnailListener());
maybeStartDemo();
}
#Override
public void onInitializationFailure(YouTubeThumbnailView thumbnailView, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
if (errorDialog == null || !errorDialog.isShowing()) {
errorDialog = errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST);
errorDialog.show();
}
} else {
String errorMessage = String.format( errorReason.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasResumed) {
VideoWallActivity.this.player = player;
player.setPlayerStyle(PlayerStyle.CHROMELESS);
player.setPlayerStateChangeListener(new VideoListener());
maybeStartDemo();
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
if (errorDialog == null || !errorDialog.isShowing()) {
errorDialog = errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST);
errorDialog.show();
}
} else {
String errorMessage = String.format( errorReason.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
private void maybeStartDemo() {
if (activityResumed && player != null && thumbnailLoader != null && state.equals(State.UNINITIALIZED)) {
thumbnailLoader.setPlaylist(PLAYLIST_ID); // loading the first thumbnail will kick off demo
state = State.LOADING_THUMBNAILS;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
// Retry initialization if user performed a recovery action
if (errorDialog != null && errorDialog.isShowing()) {
errorDialog.dismiss();
}
errorDialog = null;
playerFragment.initialize(Constant.DEVELOPER_KEY, this);
thumbnailView.initialize(Constant.DEVELOPER_KEY, this);
}
}
#Override
protected void onResume() {
super.onResume();
activityResumed = true;
if (thumbnailLoader != null && player != null) {
if (state.equals(State.UNINITIALIZED)) {
maybeStartDemo();
} else if (state.equals(State.LOADING_THUMBNAILS)) {
loadNextThumbnail();
} else {
if (state.equals(State.VIDEO_PLAYING)) {
player.play();
}
flipDelayHandler.sendEmptyMessageDelayed(0, FLIP_DURATION_MILLIS);
}
}
}
#Override
protected void onPause() {
flipDelayHandler.removeCallbacksAndMessages(null);
activityResumed = false;
super.onPause();
}
#Override
protected void onDestroy() {
if (thumbnailLoader != null) {
thumbnailLoader.release();
}
super.onDestroy();
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB) private void flipNext() {
if (!nextThumbnailLoaded || state.equals(State.VIDEO_LOADING)) {
return;
}
if (state.equals(State.VIDEO_ENDED)) {
flippingCol = videoCol;
flippingRow = videoRow;
state = State.VIDEO_BEING_FLIPPED_OUT;
} else {
Pair<Integer, Integer> nextTarget = imageWallView.getNextLoadTarget();
flippingCol = nextTarget.first;
flippingRow = nextTarget.second;
}
flippingView.setX(imageWallView.getXPosition(flippingCol, flippingRow));
flippingView.setY(imageWallView.getYPosition(flippingCol, flippingRow));
flippingView.setFlipInDrawable(thumbnailView.getDrawable());
flippingView.setFlipOutDrawable(imageWallView.getImageDrawable(flippingCol, flippingRow));
imageWallView.setImageDrawable(flippingCol, flippingRow, thumbnailView.getDrawable());
imageWallView.hideImage(flippingCol, flippingRow);
flippingView.setVisibility(View.VISIBLE);
flippingView.flip();
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB) #Override
public void onFlipped(FlippingView view) {
imageWallView.showImage(flippingCol, flippingRow);
flippingView.setVisibility(View.INVISIBLE);
if (activityResumed) {
loadNextThumbnail();
if (state.equals(State.VIDEO_BEING_FLIPPED_OUT)) {
state = State.VIDEO_FLIPPED_OUT;
} else if (state.equals(State.VIDEO_CUED)) {
videoCol = flippingCol;
videoRow = flippingRow;
playerView.setX(imageWallView.getXPosition(flippingCol, flippingRow));
playerView.setY(imageWallView.getYPosition(flippingCol, flippingRow));
imageWallView.hideImage(flippingCol, flippingRow);
playerView.setVisibility(View.VISIBLE);
player.play();
state = State.VIDEO_PLAYING;
} else if (state.equals(State.LOADING_THUMBNAILS) && imageWallView.allImagesLoaded()) {
state = State.VIDEO_FLIPPED_OUT; // trigger flip in of an initial video
flippingView.setFlipDuration(FLIP_DURATION_MILLIS);
flipDelayHandler.sendEmptyMessage(0);
}
}
}
private void loadNextThumbnail() {
nextThumbnailLoaded = false;
if (thumbnailLoader.hasNext()) {
thumbnailLoader.next();
} else {
thumbnailLoader.first();
}
}
/**
* A handler that periodically flips an element on the video wall.
*/
#SuppressLint("HandlerLeak")
private final class FlipDelayHandler extends Handler {
#Override
public void handleMessage(Message msg) {
flipNext();
sendEmptyMessageDelayed(0, FLIP_PERIOD_MILLIS);
}
}
/**
* An internal listener which listens to thumbnail loading events from the
* {#link YouTubeThumbnailView}.
*/
private final class ThumbnailListener implements YouTubeThumbnailLoader.OnThumbnailLoadedListener {
#Override
public void onThumbnailLoaded(YouTubeThumbnailView thumbnail, String videoId) {
nextThumbnailLoaded = true;
if (activityResumed) {
if (state.equals(State.LOADING_THUMBNAILS)) {
flipNext();
} else if (state.equals(State.VIDEO_FLIPPED_OUT)) {
// load player with the video of the next thumbnail being flipped in
state = State.VIDEO_LOADING;
player.cueVideo(videoId);
}
}
}
#Override
public void onThumbnailError(YouTubeThumbnailView thumbnail, YouTubeThumbnailLoader.ErrorReason reason) {
loadNextThumbnail();
}
}
private final class VideoListener implements YouTubePlayer.PlayerStateChangeListener {
#Override
public void onLoaded(String videoId) {
state = State.VIDEO_CUED;
}
#Override
public void onVideoEnded() {
state = State.VIDEO_ENDED;
imageWallView.showImage(videoCol, videoRow);
playerView.setVisibility(View.INVISIBLE);
}
#Override
public void onError(YouTubePlayer.ErrorReason errorReason) {
if (errorReason == YouTubePlayer.ErrorReason.UNEXPECTED_SERVICE_DISCONNECTION) {
// player has encountered an unrecoverable error - stop the demo
flipDelayHandler.removeCallbacksAndMessages(null);
state = State.UNINITIALIZED;
thumbnailLoader.release();
thumbnailLoader = null;
player = null;
} else {
state = State.VIDEO_ENDED;
}
}
// ignored callbacks
#Override
public void onVideoStarted() { }
#Override
public void onAdStarted() { }
#Override
public void onLoading() { }
}
}
In this way, there are a list of videos in the playlist, each video will start automatically when the first is finished. I need to click each video in the wall for start it
You can add an onClickListener to the ImageViews in the ImageWallView.java class, something like this:
for (int col = 0; col < numberOfColumns; col++) {
for (int row = 0; row < numberOfRows; row++) {
int elementIdx = getElementIdx(col, row);
if (images[elementIdx] == null) {
ImageView thumbnail = new ImageView(context);
thumbnail.setLayoutParams(new LayoutParams(imageWidth, imageHeight));
images[elementIdx] = thumbnail;
unInitializedImages.add(elementIdx);
thumbnail.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ImageWallView.this.context.startActivity(YouTubeIntents.createPlayVideoIntentWithOptions(
ImageWallView.this.context, (String)v.getTag(), true, false));
}
});
}
addView(images[elementIdx]);
}
}
Then you will need to add the video id as the tag in YouTubeThumbnailView in VideoWallActivity.java
Hope that helps
You can use ImageView OnClickListener as suggested in previous answer: (onSizeChanged in ImageWallView.java)
for (int col = 0; col < numberOfColumns; col++) {
for (int row = 0; row < numberOfRows; row++) {
int elementIdx = getElementIdx(col, row);
if (images[elementIdx] == null) {
ImageView thumbnail = new ImageView(context);
thumbnail.setLayoutParams(new LayoutParams(imageWidth, imageHeight));
images[elementIdx] = thumbnail;
unInitializedImages.add(elementIdx);
thumbnail.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ImageWallView.this.context.startActivity(YouTubeIntents.createPlayVideoIntentWithOptions(
ImageWallView.this.context, (String)v.getTag(), true, false));
}
});
}
addView(images[elementIdx]);
}
}
Then you need to store video id to the calling view of ImageWallView . (set and get tag is also used to store objects between views).
To get the child view of ImageWallView, use imageWallView.getChildAt(index). index is the position of ImageView which is clicked on ImageWallView. to get this index, use getElementIdx(col,row). You need to make this method public in ImageWallView.java.
EDITED
To use the Video ID of current thumbnail, Store the VideoID in onFlipped event. This is because onThumbnailLoaded the VideoID of next thumbnail available which immediately get Flipped and available on IamgeWallView. As VideoID is not available in onFlipped event, use it from onThumbnailLoaded event
Here it is:
Declare below string in class
private String strThumbnailVideoId;
set VideoID in onThumbnailLoaded event (in VideoWallActivity.java) into strThumbnailVideoId. This video ID will be of next thumbnail which will be flipped.
#Override
public void onThumbnailLoaded(YouTubeThumbnailView thumbnail, String videoId) {
nextThumbnailLoaded = true;
strThumbnailVideoId = videoId;
if (activityResumed) {
if (state.equals(State.LOADING_THUMBNAILS)) {
flipNext();
} else if (state.equals(State.VIDEO_FLIPPED_OUT)) {
// load player with the video of the next thumbnail being flipped in
state = State.VIDEO_LOADING;
player.cueVideo(videoId);
}
}
}
Now set the strThumbnailVideoId in onFlipped as a ImageWallView tag.
#Override
public void onFlipped(FlippingView view) {
imageWallView.showImage(flippingCol, flippingRow);
flippingView.setVisibility(View.INVISIBLE);
imageWallView.getChildAt(imageWallView.getElementIdx(flippingCol, flippingRow)).setTag(strThumbnailVideoId);
......
......