Android: Adding functionality that activty changes when game is complete - android

I wish to add the following functionality to my game:
-When the game is complete (no more cards are visible on screen) then move to a new activity
I am aware how to move to another activty using intents but I am not sure how to implement the functionality in this case.
I.e. what variable/info can I use to ensure the game is complete when I move before moving to the next activity?
For reference, The game is based off this open source game Images of the game are shown here to give an idea.
Current code:
public class Manager extends Activity {
private static int ROW_COUNT = -1;
private static int COL_COUNT = -1;
private Context context;
private Drawable backImage;
private int [] [] cards;
private List<Drawable> images;
private Card firstCard;
private Card seconedCard;
private ButtonListener buttonListener;
private static Object lock = new Object();
int turns;
private TableLayout mainTable;
private UpdateCardsHandler handler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new UpdateCardsHandler();
loadImages();
setContentView(R.layout.main);
TextView url = ((TextView)findViewById(R.id.myWebSite));
Linkify.addLinks(url, Linkify.WEB_URLS);
backImage = getResources().getDrawable(R.drawable.icon);
/*
((Button)findViewById(R.id.ButtonNew)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
newGame();
}
});*/
buttonListener = new ButtonListener();
mainTable = (TableLayout)findViewById(R.id.TableLayout03);
context = mainTable.getContext();
Spinner s = (Spinner) findViewById(R.id.Spinner01);
ArrayAdapter adapter = ArrayAdapter.createFromResource(
this, R.array.type, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
s.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(
android.widget.AdapterView<?> arg0,
View arg1, int pos, long arg3){
((Spinner) findViewById(R.id.Spinner01)).setSelection(0);
int x,y;
switch (pos) {
case 1:
x=4;y=4;
break;
case 2:
x=4;y=5;
break;
case 3:
x=4;y=6;
break;
case 4:
x=5;y=6;
break;
case 5:
x=6;y=6;
break;
default:
return;
}
newGame(x,y);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
private void newGame(int c, int r) {
ROW_COUNT = r;
COL_COUNT = c;
cards = new int [COL_COUNT] [ROW_COUNT];
mainTable.removeView(findViewById(R.id.TableRow01));
mainTable.removeView(findViewById(R.id.TableRow02));
TableRow tr = ((TableRow)findViewById(R.id.TableRow03));
tr.removeAllViews();
mainTable = new TableLayout(context);
tr.addView(mainTable);
for (int y = 0; y < ROW_COUNT; y++) {
mainTable.addView(createRow(y));
}
firstCard=null;
loadCards();
turns=0;
((TextView)findViewById(R.id.tv1)).setText("Tries: "+turns);
}
private void loadImages() {
images = new ArrayList<Drawable>();
images.add(getResources().getDrawable(R.drawable.card1));
images.add(getResources().getDrawable(R.drawable.card2));
images.add(getResources().getDrawable(R.drawable.card3));
images.add(getResources().getDrawable(R.drawable.card4));
images.add(getResources().getDrawable(R.drawable.card5));
images.add(getResources().getDrawable(R.drawable.card6));
images.add(getResources().getDrawable(R.drawable.card7));
images.add(getResources().getDrawable(R.drawable.card8));
images.add(getResources().getDrawable(R.drawable.card9));
images.add(getResources().getDrawable(R.drawable.card10));
images.add(getResources().getDrawable(R.drawable.card11));
images.add(getResources().getDrawable(R.drawable.card12));
images.add(getResources().getDrawable(R.drawable.card13));
images.add(getResources().getDrawable(R.drawable.card14));
images.add(getResources().getDrawable(R.drawable.card15));
images.add(getResources().getDrawable(R.drawable.card16));
images.add(getResources().getDrawable(R.drawable.card17));
images.add(getResources().getDrawable(R.drawable.card18));
images.add(getResources().getDrawable(R.drawable.card19));
images.add(getResources().getDrawable(R.drawable.card20));
images.add(getResources().getDrawable(R.drawable.card21));
}
private void loadCards(){
try{
int size = ROW_COUNT*COL_COUNT;
Log.i("loadCards()","size=" + size);
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0;i<size;i++){
list.add(new Integer(i));
}
Random r = new Random();
for(int i=size-1;i>=0;i--){
int t=0;
if(i>0){
t = r.nextInt(i);
}
t=list.remove(t).intValue();
cards[i%COL_COUNT][i/COL_COUNT]=t%(size/2);
Log.i("loadCards()", "card["+(i%COL_COUNT)+
"]["+(i/COL_COUNT)+"]=" + cards[i%COL_COUNT][i/COL_COUNT]);
}
}
catch (Exception e) {
Log.e("loadCards()", e+"");
}
}
private TableRow createRow(int y){
TableRow row = new TableRow(context);
row.setHorizontalGravity(Gravity.CENTER);
for (int x = 0; x < COL_COUNT; x++) {
row.addView(createImageButton(x,y));
}
return row;
}
private View createImageButton(int x, int y){
Button button = new Button(context);
button.setBackgroundDrawable(backImage);
button.setId(100*x+y);
button.setOnClickListener(buttonListener);
return button;
}
class ButtonListener implements OnClickListener {
#Override
public void onClick(View v) {
synchronized (lock) {
if(firstCard!=null && seconedCard != null){
return;
}
int id = v.getId();
int x = id/100;
int y = id%100;
turnCard((Button)v,x,y);
}
}
private void turnCard(Button button,int x, int y) {
button.setBackgroundDrawable(images.get(cards[x][y]));
if(firstCard==null){
firstCard = new Card(button,x,y);
}
else{
if(firstCard.x == x && firstCard.y == y){
return; //the user pressed the same card
}
seconedCard = new Card(button,x,y);
turns++;
((TextView)findViewById(R.id.tv1)).setText("Tries: "+turns);
TimerTask tt = new TimerTask() {
#Override
public void run() {
try{
synchronized (lock) {
handler.sendEmptyMessage(0);
}
}
catch (Exception e) {
Log.e("E1", e.getMessage());
}
}
};
Timer t = new Timer(false);
t.schedule(tt, 1300);
}
}
}
class UpdateCardsHandler extends Handler{
#Override
public void handleMessage(Message msg) {
synchronized (lock) {
checkCards();
}
}
public void checkCards(){
if(cards[seconedCard.x][seconedCard.y] == cards[firstCard.x][firstCard.y]){
firstCard.button.setVisibility(View.INVISIBLE);
seconedCard.button.setVisibility(View.INVISIBLE);
}
else {
seconedCard.button.setBackgroundDrawable(backImage);
firstCard.button.setBackgroundDrawable(backImage);
}
firstCard=null;
seconedCard=null;
}
}
}

The easiest way to do this would be to check win conditions with an if statement. This should be done in the method when a turn is actually taken which I assume happens in the turnCard() method.
if (winConditionMet) {
displayWinningScreen();
} else if (lossConditionMet) {
displayLosingScreen();
}
If conditions have been met, then call a method which handles wrapping up that screen, and then launching a new activity. For instance you could add a button to the screen with whatever text you wanted, that when pushed, would take the user to the next screen, be it your score screen, replay screen, main menu, or what have you.
Edit: Okay, since this is a game of memory, you could iterate through the cards at the end of every turn taken and check if any card still has its image set to backImage. If there are none left that are set to backImage, you can then end the game with your code inside of the if statement.
Or, instead of using an ArrayList, you could use some form of Map to keep track of if each card has been permanently turned up or not with the boolean value.

Related

Why can't function "if (counter >10)" work?

I'm trying to get an AlertDialog to appear if my counter is above 10.
I have tried using the TextView variable peopleCount in the if statement but it does not work too. I know using TextView will not work but I need to know if there is a workaround.
private TextView peopleCount;
private ImageView plusOne;
private ImageView minusOne;
private ImageView reset;
private int counter;
private View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.ivPlusOne :
plusCounter();
break;
case R.id.ivMinusOne :
minusCounter();
break;
case R.id.ivReset :
initCounter();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_people);
peopleCount = (TextView)findViewById(R.id.tvPeopleCount);
plusOne = (ImageView)findViewById(R.id.ivPlusOne);
plusOne.setOnClickListener(clickListener);
minusOne = (ImageView)findViewById(R.id.ivMinusOne);
minusOne.setOnClickListener(clickListener);
reset = (ImageView)findViewById(R.id.ivReset);
reset.setOnClickListener(clickListener);
initCounter();
if( counter > 10) {
AlertDialog.Builder peopleAlert = new AlertDialog.Builder(PeopleActivity.this);
peopleAlert.setCancelable(false);
peopleAlert.setTitle("People Count High");
peopleAlert.setMessage("Please check and replenish inventory");
peopleAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogPeople, int which) {
dialogPeople.cancel();
}
});
peopleAlert.show();
}
private void initCounter(){
counter = 0;
peopleCount.setText(counter + "");
}
private void plusCounter(){
counter++;
peopleCount.setText(counter + "");
}
private void minusCounter(){
counter--;
peopleCount.setText(counter + "");
}
I expected the AlertDialog to appear when counter reached 11 but nothing happens.
OnCreate only runs once, You need to move the if statement to a function and call it from your plusCounter() and minusCounter() functions.

How a button click can call another activity?

So I am trying to create an android app to show some simple battery information. And now I want to take that info and plot a graph inside the app. I have the following codes:
public class MainActivity extends ActionBarActivity {
private TextView level,voltage, status1,temp,health1,tech,sour,amp;
Thread myThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
level=(TextView)findViewById(R.id.level);
voltage=(TextView)findViewById(R.id.volt);
status1=(TextView)findViewById(R.id.stat);
temp=(TextView)findViewById(R.id.temp);
health1=(TextView)findViewById(R.id.healt);
tech=(TextView)findViewById(R.id.tech);
sour=(TextView)findViewById(R.id.source);
Button b = (Button) findViewById(R.id.ex);
Button g = (Button) findViewById(R.id.graphButton);
amp=(TextView)findViewById(R.id.current);
b.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
g.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
//how can i jump to DynamicGraphActivity
}
});
this.registerReceiver(this.myBatteryReceiver,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
private BroadcastReceiver myBatteryReceiver
= new BroadcastReceiver(){
#SuppressLint("InlinedApi")
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
if (arg1.getAction().equals(Intent.ACTION_BATTERY_CHANGED)){
int lv = arg1.getIntExtra("level", 0);
level.setText("Level: "
+ String.valueOf(lv) + "%");
voltage.setText("Voltage: "
+ String.valueOf((float)arg1.getIntExtra("voltage", 0)/1000) + "V");
temp.setText("Temperature: "
+ String.valueOf((float)arg1.getIntExtra("temperature", 0)/10) + "c");
tech.setText("Technology: " + arg1.getStringExtra("technology"));
int status = arg1.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN);
String strStatus;
if (status == BatteryManager.BATTERY_STATUS_CHARGING){
strStatus = "Charging";
} else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING){
strStatus = "Dis-charging";
} else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING){
strStatus = "Not charging";
} else if (status == BatteryManager.BATTERY_STATUS_FULL){
strStatus = "Full";
} else {
strStatus = "Unknown";
}
status1.setText("Status: " + strStatus);
//int source=arg1.getIntExtra("source", BatteryManager.BATTERY_STATUS_UNKNOWN);
if(Build.VERSION.SDK_INT >= 21){
BatteryManager battery = (BatteryManager)getSystemService(Context.BATTERY_SERVICE);
int current=battery.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW);
int currentAvg=battery.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_AVERAGE);
int energy=battery.getIntProperty(BatteryManager.BATTERY_PROPERTY_ENERGY_COUNTER);
int capacity=battery.getIntProperty(BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER);
int bCapacity=battery.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
String string1 = "Current: "+ current*1000+" uA"+"\n";
string1+="Average Current: "+currentAvg+" uA"+"\n";
string1+="Remaining energy: "+energy+" nWh"+"\n";
string1+="Capacity: "+capacity+" uAh"+"\n\n";
amp.setText(string1);
}
int health = arg1.getIntExtra("health", BatteryManager.BATTERY_HEALTH_UNKNOWN);
String strHealth;
if (health == BatteryManager.BATTERY_HEALTH_GOOD){
strHealth = "Good";
} else if (health == BatteryManager.BATTERY_HEALTH_OVERHEAT){
strHealth = "Over Heat";
} else if (health == BatteryManager.BATTERY_HEALTH_DEAD){
strHealth = "Dead";
} else if (health == BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE){
strHealth = "Over Voltage";
} else if (health == BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE){
strHealth = "Unspecified Failure";
} else{
strHealth = "Unknown";
}
health1.setText("Health: " + strHealth);
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
2nd Activity or DynamicGraphActivity:
public class DynamicGraphActivity extends Activity {
private static GraphicalView view;
private LineGraph line = new LineGraph();
private static Thread thread;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
thread = new Thread() {
public void run()
{
for (int i = 0; i < 15; i++)
{
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Point p = MockData.getDataFromReceiver(i); // We got new data!
line.addNewPoints(p); // Add it to our graph
view.repaint();
}
}
};
thread.start();
}
#Override
protected void onStart() {
super.onStart();
view = line.getView(this);
setContentView(view);
}
}
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import android.content.Context;
import android.graphics.Color;
public class LineGraph {
private GraphicalView view;
private TimeSeries dataset = new TimeSeries("Rain Fall");
private XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset();
private XYSeriesRenderer renderer = new XYSeriesRenderer(); // This will be used to customize line 1
private XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer(); // Holds a collection of XYSeriesRenderer and customizes the graph
public LineGraph()
{
// Add single dataset to multiple dataset
mDataset.addSeries(dataset);
// Customization time for line 1!
renderer.setColor(Color.WHITE);
renderer.setPointStyle(PointStyle.SQUARE);
renderer.setFillPoints(true);
// Enable Zoom
mRenderer.setZoomButtonsVisible(true);
mRenderer.setXTitle("Day #");
mRenderer.setYTitle("CM in Rainfall");
// Add single renderer to multiple renderer
mRenderer.addSeriesRenderer(renderer);
}
public GraphicalView getView(Context context)
{
view = ChartFactory.getLineChartView(context, mDataset, mRenderer);
return view;
}
public void addNewPoints(Point p)
{
dataset.add(p.getX(), p.getY());
}
}
import java.util.Random;
public class MockData {
// x is the day number, 0, 1, 2, 3
public static Point getDataFromReceiver(int x)
{
return new Point(x, generateRandomData());
}
private static int generateRandomData()
{
Random random = new Random();
return random.nextInt(40);
}
}
public class Point {
private int x;
private int y;
public Point( int x, int y)
{
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
Now inside the button g, I want to call DynamicGraphActivity class so that it calls the class and plots a graph using some random values. but its not working. When i click on the button, it doesnt do anything. How can I fix this?
And my another question is, how can I plot the battery info such as voltage, charge or discharge over time using these codes/
Any help would be greatly appreciated.
Thank you
Well there is a difference between any class or an activity.
Activity have a visual layout maps to it.Check this link for more info.
Inside your g button click listener add this code.
g.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, DynamicGraphActivity.class);
startActivity(intent);
}
});
Also you need to add the other activity in the AndroidManifest.xml as well under application tag.(You already have activity tag inside application tag if you create a new app.But you don't need any intent filters for newer activity)
<activity
android:name=".DynamicGraphActivity"
/>
I noticed one more thing you are using same layout(main.xml) for both activities.
Create another layout in layouts folder and map it to the DynamicGraphActivity.
Lets say you create second.xml.
So your DynamicGraphActivity oncreate() have:
setContentView(R.layout.second);
Intent 2ndActivity = new Intent(this, blabla.class);
startActivity(2ndActivity);
For the button and for the extra value you can use Bundle,Parcel or just use putExtra.
And for the battery info, Read from google developer
In your button click put this code
Intent intent = new Intent(MainActivity.this, DynamicGraphActivity.class);
startActivity(intent);
and define this activity in your AndroidManifest.xml
<activity
android:name=".DynamicGraphActivity"
android:theme="#android:style/Theme.Translucent.NoTitleBar" />
and for Battery information you can refer this links...
http://developer.android.com/reference/android/os/BatteryManager.html
http://mobiledevtuts.com/android/android-sdk-get-device-battery-information/
Get battery level and state in Android

CountDownTimer switch background of RelativeLayouts (1&2)

I trying to run a timer to switch Backgrounds of two relative layouts in loop if user set or unset it while app is running.
Not enough I tried to work with drawable_image.setAlpha(x) to let the Background vanish slowly while the relative layout 2 behind has an other image (afterwords switch position).
My method private void switchBackground(){} do it right well. BUT it is too much work for the device and I lose a lot of frames (15-39) so that the "slow vanish" by .setAlph(x) sometimes totally fail and not working (the pics switch just by time, like the onTick() method do not exists anymore).
I think one reason for this is the countDownTimer itself and a second that the method is (should) running in the main Activity Class. May be the third reason is the problem that I choose "setBackground" of relative Layouts instead of image showing stuff?!
I tried adding a new Class to do the "switchBackground .."- method outside, but this failed cause of "nullpointerexception" and "non-static / static" problems.
Which classes and methods would be better, so as not to lose too much frames / memory.
//"/---/" short up stuff which isn't important, but still much do there
public class MainActivity extends AppCompatActivity {
//class value
//private static final String TAG = "App";
private RelativeLayout layout_behind;
private RelativeLayout layout_front;
private CountDownTimer myCountdown;
private final int[][] matrix = new int[9][9];
private EditText sumNum;
private MediaPlayer music;
private SoundPool multiTon;
private int whoopId;
private int failId;
private int winId;
private boolean soundOn =WelcomeScreen.soundCheck;
//class MathThing, Welcome_Screen exists too
private final int[][] detected = MathThing.detected;
private final ArrayList<int[][]> returnArr = new ArrayList<>();
private int switch_draw=0;
private boolean switchDraw;
private Drawable image_2;
private Drawable image_1;
private Drawable image_3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Music
multiTon = new SoundPool(1,AudioManager.STREAM_MUSIC,0);
whoopId = multiTon.load(this, R.raw.whoop,1);
failId = multiTon.load(this, R.raw.fail, 1);
winId = multiTon.load(this, R.raw.win,1);
music = MediaPlayer.create(MainActivity.this, R.raw.backgroundmusic);
if(WelcomeScreen.musicCheck) {
music.setVolume(1, 1);
music.setLooping(true);
music.start();
}
//create/initialize some stuff and initialize layouts and images
hideAndCreate();
//switch Background
switchBackground(); switchDraw=true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// . . . settings in Toolbar
int id = item.getItemId();
switch(id){
case R.id.bla: //just cut some here to do it shorter
break;// /.../
}
return super.onOptionsItemSelected(item);
}
private void hideAndCreate(){
// /----/ create a lot of edittexts / textviews/ buttons
//initialize layouts / images
}
protected void onPause(){
super.onPause();
if(switchDraw){
myCountdown.cancel();}
music.release();
finish();
}
//method with CountDownTimer
private void switchBackground(){
//Layout Background
switch_draw=0;
layout_behind.setBackground(image_2);
int duration=15000;
int tick=250;
myCountdown = new CountDownTimer(duration, tick){
int a = 255;
public void onTick(long millisUntilFinished) {
if(switch_draw==0){
image_1.setAlpha(a);
layout_front.setBackground(image_1);
if(a>=4){a=a-4;}
}else if(switch_draw==1){
image_2.setAlpha(a);
layout_front.setBackground(image_2);
if(a>=4){a=a-4;}
}else{
image_3.setAlpha(a);
layout_front.setBackground(image_3);
if(a>=4){a=a-4;}
}
}
public void onFinish() {
if(switch_draw==0){
image_2.setAlpha(255);
layout_front.setBackground(image_2);
image_3.setAlpha(255);
layout_behind.setBackground(image_3);
switch_draw=1;
}else if(switch_draw==1){
image_3.setAlpha(255);
layout_front.setBackground(image_3);
image_1.setAlpha(255);
layout_behind.setBackground(image_1);
switch_draw=2;
}else{
image_1.setAlpha(255);
layout_front.setBackground(image_1);
image_2.setAlpha(255);
layout_behind.setBackground(image_2);
switch_draw=0;
}
a=255;
start();//loop stuff
}
}.start();
}
public void StartOnClick(View v){
//do something when the button is clicked
if(v.getId()==R.id.button1){
/---/
}else if(v.getId()==R.id.button2){
/---/
}else if(v.getId()==R.id.buttonw1){
/---/
}else if(v.getId()==R.id.buttonw2){
/---/
}else if(v.getId()==R.id.buttonw3){
/---/
}
}
private void setReset(){
/---/ //clear all
}
private void againRestart(){
/---/ //reset entries only
}
// main Method
private void numInput(){
int[][]found;
int n = 81;
int mini=1;
while(mini==1 && n>0){
TextView text;
Button but1;
int[][]nul=new int[2][81];
int[][]value=new int[3][81];
int i=-1;
int j=-1;
int a=0;
int b=0;
for(int idN=0; idN<81; idN++) {
int iDn=idN +1;
String editTextId = "editText" + iDn;
int resID = getResources().getIdentifier(editTextId, "id",
getPackageName());
sumNum=((EditText)findViewById(resID) );
if(idN%9 == 0){
i=i+1;
j=0;
}else{
j=j+1;
}if(!TextUtils.isDigitsOnly(sumNum.getText()) ||
sumNum.getText ().toString().equals("0") ){
sumNum.setText("");
}
if(sumNum.getText().toString().trim().length()==0){
matrix[i][j]= 0;
nul[0][a]=i;
nul[1][a]=j;
a=a+1;
}else {
matrix[i][j] = Integer.parseInt(sumNum.getText().toString());
value[0][b]=i;
value[1][b]=j;
value[2][b]=matrix[i][j];
b=b+1;
}
}
//copy array
int[][]nuL=new int[2][a];
int[][]val=new int[3][b];
for(int u=0;u<b;u++){
val[0][u]=value[0][u];
val[1][u]=value[1][u];
val[2][u]=value[2][u];
}
for(int nu=0;nu<a;nu++){
nuL[0][nu]=nul[0][nu];
nuL[1][nu]=nul[1][nu];
}
n = nuL[0].length;
// matrix check
if(MathThing.matrixIsGood(val) && n>0){
//method matrixCheck
found = MathThing.matrixCheck(matrix, nuL);
//cut method
found = MathThing.zeroCut(found, n);
// method
int[] min = MathThing.minSearch(found);
mini = min[0];
if(min[0]==1 && n>0) {
/---/
}else if(min[0]==2 && n>0 ){
/---/
}else if(min[0]>2 && n>0 || n==81){
/---/
}else if(min[0]==0 && n>0) {
/---/
}}else if(n!=0){
/---/
}
if(n==0){
/---/
}
}
}

Adding ProgressBar to DetailsOverviewRow on Android TV

I'm trying to create a slightly modified version of the android.support.v17.leanback.widget.DetailsOverviewRow for an Android TV app. The layout I'm trying to accomplish is roughly the same as Google's default version, but with the addition of a progress bar above the actions panel. What I have now looks like this:
Current Version
What I want to create is something roughly like this:
Goal Version
I would like to add this in dynamically without having to create an entirely new layout from scratch if possible. Here's the code I'm using currently, slightly modified from the default Android TV app in Android Studio:
public class VideoDetailsFragment extends DetailsFragment {
private static final String TAG = "VideoDetailsFragment";
private static final int ACTION_UPDATE = 1;
private static final int ACTION_CHANGELOG = 2;
private static final int ACTION_INSTALLED = 3;
private static final int DETAIL_THUMB_WIDTH = 274;
private static final int DETAIL_THUMB_HEIGHT = 274;
private static final int NUM_COLS = 10;
private static final String UPDATE = "Update";
private Update mSelectedUpdate;
private Drawable mDefaultBackground;
private Target mBackgroundTarget;
private DisplayMetrics mMetrics;
private DetailsOverviewRowPresenter mDorPresenter;
private DetailRowBuilderTask mDetailRowBuilderTask;
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate DetailsFragment");
super.onCreate(savedInstanceState);
mDorPresenter =
new DetailsOverviewRowPresenter(new DetailsDescriptionPresenter());
BackgroundManager backgroundManager = BackgroundManager.getInstance(getActivity());
backgroundManager.attach(getActivity().getWindow());
mBackgroundTarget = new PicassoBackgroundManagerTarget(backgroundManager);
mDefaultBackground = getResources().getDrawable(R.drawable.default_background);
mMetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(mMetrics);
List<Update> list = UpdateList.setupMovies();
mSelectedUpdate = list.get(0);//(Update) getActivity().getIntent().getSerializableExtra(MOVIE);
mDetailRowBuilderTask = (DetailRowBuilderTask) new DetailRowBuilderTask().execute(list);
mDorPresenter.setSharedElementEnterTransition(getActivity(),
DetailsActivity.SHARED_ELEMENT_NAME);
setOnItemViewClickedListener(new ItemViewClickedListener());
}
#Override
public void onStop() {
mDetailRowBuilderTask.cancel(true);
super.onStop();
}
private class DetailRowBuilderTask extends AsyncTask<List<Update>, Integer, List<DetailsOverviewRow>> {
#Override
protected List<DetailsOverviewRow> doInBackground(List<Update>... movies) {
List<DetailsOverviewRow> rows = new ArrayList<DetailsOverviewRow>();
int exampleUpdate = 0;
for (Update m: movies[0]) {
DetailsOverviewRow row = new DetailsOverviewRow(m);
try {
//String test = mSelectedUpdate.getCardImageUrl();
Bitmap poster = Picasso.with(getActivity())
.load(m.getCardImageUrl())
.resize(Utils.convertDpToPixel(getActivity().getApplicationContext(), DETAIL_THUMB_WIDTH),
Utils.convertDpToPixel(getActivity().getApplicationContext(), DETAIL_THUMB_HEIGHT))
.centerCrop()
.get();
row.setImageBitmap(getActivity(), poster);
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, e.toString(), e);
}
SparseArrayObjectAdapter adapter = new SparseArrayObjectAdapter();
if (exampleUpdate++ == 0) {
Action a1 = new Action(ACTION_UPDATE, getResources().getString(R.string.download));
Action a2 = new Action(ACTION_CHANGELOG, getResources().getString(R.string.release_notes));
adapter.set(ACTION_UPDATE, a1);
adapter.set(ACTION_CHANGELOG, a2);
row.setActionsAdapter(adapter);
}else{
Action a1 = new Action(ACTION_INSTALLED, getResources().getString(
R.string.installed));
Action a2 = new Action(ACTION_CHANGELOG, getResources().getString(R.string.release_notes));
//ProgressBar p1 = new ProgressBar(getActivity(),null, android.R.attr.progressBarStyleHorizontal);
adapter.set(1, a1);
adapter.set(2, a2);
//adapter.set(3, p1);
row.setActionsAdapter(adapter);
}
rows.add(row);
}
return rows;
}
#Override
protected void onPostExecute(List<DetailsOverviewRow> detailRows) {
ClassPresenterSelector ps = new ClassPresenterSelector();
// set detail background and style
mDorPresenter.setBackgroundColor(getResources().getColor(R.color.black_opaque));
Log.i("TEST", "Setting BG Color of Detail View");
mDorPresenter.setStyleLarge(true);
mDorPresenter.setOnActionClickedListener(new OnActionClickedListener() {
#Override
public void onActionClicked(Action action) {
if (action.getId() == ACTION_UPDATE) {
/*Intent intent = new Intent(getActivity(), PlaybackOverlayActivity.class);
intent.putExtra(getResources().getString(R.string.movie), mSelectedUpdate);
intent.putExtra(getResources().getString(R.string.should_start), true);
startActivity(intent);*/
Toast.makeText(getActivity(), "Download Update", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), action.toString(), Toast.LENGTH_SHORT).show();
}
}
});
ps.addClassPresenter(DetailsOverviewRow.class, mDorPresenter);
ps.addClassPresenter(ListRow.class,
new ListRowPresenter());
ArrayObjectAdapter adapter = new ArrayObjectAdapter(ps);
for(DetailsOverviewRow detailRow : detailRows){
adapter.add(detailRow);
}
String subcategories[] = {
getString(R.string.related_movies)
};
//HeaderItem header = new HeaderItem(0, subcategories[0]);
//adapter.add(new ListRow(header, listRowAdapter));
setAdapter(adapter);
}
}
private final class ItemViewClickedListener implements OnItemViewClickedListener {
#Override
public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item,
RowPresenter.ViewHolder rowViewHolder, Row row) {
if (item instanceof Update) {
Update update = (Update) item;
Log.d(TAG, "Item: " + item.toString());
Intent intent = new Intent(getActivity(), DetailsActivity.class);
intent.putExtra(DetailsActivity.MOVIE, update);
Bundle bundle = ActivityOptionsCompat.makeSceneTransitionAnimation(
getActivity(),
((ImageCardView) itemViewHolder.view).getMainImageView(),
DetailsActivity.SHARED_ELEMENT_NAME).toBundle();
getActivity().startActivity(intent, bundle);
}
}
}
}
Is there a simple way to add the ProgressBar or do I need to create a completely new xml layout to do this?
I figured out a way to do it. I ended up creating a modified version of lb_details_overview.xml, which is used by the support.v17.leanback library when creating a DetailOverviewRow. I basically just added a RelativeLayout with a ProgressBar. I also had to make a modified version of DetailsOverviewRowPresenter.java in the leanback library in order to inflate the new xml layout instead of the existing one. It might not be the best or the easiest way to do this, but it works.

Android GridView first button not working

I am having weird problems with Android GridView. I create a 3x4 grid and insert buttons into that grid. I want the background of the button to change when the user clicks that button. And this is working just fine for all buttons except the first one (the one with index 0 - top left). OnClick event listener doesn't fire at all for that button no matter what I do.
Here is the code where I create the view:
public View getView(int position, View convertView, ViewGroup parent) {
Button imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
Log.w("NOVO", "narejena nova celica");
imageView = new Button(mContext);
imageView.setPadding(8, 8, 8, 8);
} else {
Log.w("STARO", "stara celica");
imageView = (Button) convertView;
}
imageView.setEnabled(true);
int visina = parent.getHeight();
int sirina = parent.getWidth();
float dip = mContext.getResources().getDisplayMetrics().density;
float margin = 10*dip;
int view_height = (int)(visina - 3*margin)/4;
int view_width = (int)(sirina - 2*margin)/3;
int view_dim = 0;
if (view_height <= view_width)
view_dim = view_height;
else
view_dim = view_width;
imageView.setLayoutParams(new GridView.LayoutParams(view_dim, view_dim));
imageView.setId(position);
imageView.setOnClickListener(celice.get(position));
/*imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Toast toast = Toast.makeText(mContext, v.getId() + "bla", Toast.LENGTH_SHORT);
//toast.show();
celice.get(v.getId()).celicaVisible(4000);
}});*/
celice.get(position).id = position;
celice.get(position).setButton(imageView);
return imageView;
}
If I replace
imageView = (Button) convertView;
with
imageView = new Button(mContext);
then the onClick() gets fired but the background still doesn't change. All the other buttons are working as expected.
And here is the custom class "Celica" that takes care of the actual work - changing the background...
public class Celica implements OnClickListener {
public boolean odkrit;
public boolean najden;
public int id;
public Drawable slikca1, slikca2;
public Celica par;
private Timer tim;
public Button but;
public Context con;
static int buttonsVisible = 0;
Celica(Drawable s1, Drawable s2) {
this.slikca1 = s1;
this.slikca2 = s2;
}
void celicaVisible(int millis) {
if (odkrit)
return;
Log.w("TEST", "prizganih " + buttonsVisible);
if (buttonsVisible >= 2)
return;
odkrit = true;
buttonsVisible++;
tim = new Timer();
tim.schedule(new timerDone(), millis);
((Activity)con).runOnUiThread(new Runnable() {
#Override
public void run() {
but.setBackground(slikca2);
}
});
}
void setButton(Button b) {
but = b;
((Activity)con).runOnUiThread(new Runnable() {
#Override
public void run() {
but.setBackground(slikca1);
}
});
}
class timerDone extends TimerTask {
#Override
public void run() {
if (!najden) {
odkrit = false;
((Activity)con).runOnUiThread(new Runnable() {
#Override
public void run() {
but.setBackground(slikca1);
}
});
}
buttonsVisible--;
tim.cancel();
}
}
#Override
public void onClick(View v) {
celicaVisible(4000);
}
}
In Android, ID of any View must be non zero and non negative number. means View ID should be > 0. and there is problem, when you are setting ID to the Button like
imageView.setId(position)
here ID of a button will be zero when position is zero(means first item). may be due to this, First Button's OnClickListener is not getting fired...try setting a ID that is greater than zero to Button and try once...
you can write like
imageView.setId(position+1) to ensure ID > 0
I actually figured it out. Everything works if I use the view that gets provided by the onClick() method instead of saving the actual button at the creation of the Celica object.
So basically adding:
but = (Button) v;
to the onClick() method solved the problem.

Categories

Resources