Use a function like a class method - android

This is my code:
public class MainActivity extends AppCompatActivity {
int mazzo[]=new int[40];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mescolamento(mazzo);
}
public void mescolamento(int[] array) { //THIS
int n = array.length;
Random random = new Random();
random.nextInt();
for (int i = 0; i < n; i++) {
int change = random.nextInt(n -i);
swap(array, i, change);
}
}
public void swap(int[] mazzo2, int i, int change) {
int appoggio = mazzo2[i];
mazzo2[i] = mazzo2[change];
mazzo2[change] = appoggio;
}
}
Is it possible to transfer this function into a class?
It works also like this but I need to make the mainActivity clearer.

Yes of course . Define your class :
public class ActivityHelper{
private int[] array
//declare constructor
public ActivityHelper(int[] array){
this.array = array;
}
public void mescolamento() {
int n = array.length;
Random random = new Random();
random.nextInt();
for (int i = 0; i < n; i++) {
int change = random.nextInt(n -i);
swap(array, i, change);
}
}
public void swap(int[] mazzo2, int i, int change) {
int appoggio = mazzo2[i];
mazzo2[i] = mazzo2[change];
mazzo2[change] = appoggio;
}
}
and than in your activity , in onCreate method , remove : mescolamento() and add :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityHelper activityHelper = new ActivityHelper(mazzo);
acvitivyHelper.mescolamento();
}
If you don't want instance of that class create a static method :
public class ActivityHelper{
public static void mescolamento(int[] array) {
int n = array.length;
Random random = new Random();
random.nextInt();
for (int i = 0; i < n; i++) {
int change = random.nextInt(n -i);
swap(array, i, change);
}
}
public static void swap(int[] mazzo2, int i, int change) {
int appoggio = mazzo2[i];
mazzo2[i] = mazzo2[change];
mazzo2[change] = appoggio;
}
}
And than in your onCreate method :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityHelper.mescolamento(mezzo);
}

You could make it a static method in a different class. The swap method could be private if you wanted. Just depends on if you will use it anywhere else or not.
public class ClassName {
public static void mescolamento(int[] array) { //THIS
int n = array.length;
Random random = new Random();
random.nextInt();
for (int i = 0; i < n; i++) {
int change = random.nextInt(n -i);
swap(array, i, change);
}
}
public static void swap(int[] mazzo2, int i, int change) {
int appoggio = mazzo2[i];
mazzo2[i] = mazzo2[change];
mazzo2[change] = appoggio;
}
}
And then call it with
ClassName.mescolamento(array)

Related

Not Getting desired output for android application

EditText numDisplay;
Button calculateNow;
int n=100;
int count=0;
List<Integer> primes = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
numDisplay= (EditText)findViewById(R.id.editText1);
n= Integer.parseInt(numDisplay.toString());
calculateNow = (Button)findViewById(R.id.button1);
calculateNow.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
for (int i = 2; i < n; i++) {
boolean res = checkprime(primes, i);
if (res) {
count++;
primes.add(i);
}
}
numDisplay.setText( String.valueOf(count));
// writer.write("total prime number till " + n + " is " + count);
}});}
private static boolean checkprime(List<Integer> primes, int n) {
int fence = (int) Math.sqrt(n);
for (int prime : primes) {
if (n % prime == 0) {
return false;
}
if (prime >= fence)
break;
}
return true;
}
The output of program must print total number of prime numbers from 1 to 100.
I have used edit text to display total number of prime numbers when button is clicked.
But when I click button I don't get desired output.Any Help appreciated .
Thanx
Update your as :-
public class AnimationActivity extends ActionBarActivity {
EditText numDisplay;
Button calculateNow;
private int n;
int count=0;
List<Integer> primes = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
numDisplay= (EditText)findViewById(R.id.editText1);
calculateNow = (Button)findViewById(R.id.button1);
calculateNow.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
n= Integer.parseInt(numDisplay.getText().toString());
for (int i = 2; i < n; i++) {
boolean res = checkprime(primes, i);
if (res) {
count++;
primes.add(i);
}
}
numDisplay.setText(String.valueOf(count));
}
});}
private static boolean checkprime(List<Integer> primes, int n) {
int fence = (int) Math.sqrt(n);
for (int prime : primes) {
if (n % prime == 0) {
return false;
}
if (prime >= fence)
break;
}
return true;
}}

type missmatch : cannot convert from string to int

public void clickresult(View v){
String temp = "";
int cards[] = {etnumber1.getText().toString(),etnumber2.getText().toString(),
etnumber3.getText().toString(),etnumber4.getText().toString()
,etnumber4.getText().toString()};
int noOfCard = cards.length;
for (int marker = 1; marker < noOfCard; marker++) {
for (int j = 0; j < marker; j++) {
if (cards[marker] < cards[j]) {
int tmp = cards[marker];
cards[marker] = cards[j];
cards[j] = tmp;
}
}
}
for (int i = 0; i < noOfCard; i++) {
temp += cards[i] + " ";
}
Toast.makeText(this, temp, Toast.LENGTH_LONG).show();
}
it still have one error -> type missmatch : cannot convert from string to int
how to fix that
int cards[] = {etnumber1.getText().toString(),etnumber2.getText().toString(),
etnumber3.getText().toString(),etnumber4.getText().toString()
,etnumber4.getText().toString()};
#Override
protected void onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.your_fragment_layout, container, false);
etnumber1 = (EditText)findViewById(R.id.etnumber1);
etnumber2 = (EditText)findViewById(R.id.etnumber2);
etnumber3 = (EditText)findViewById(R.id.etnumber3);
etnumber4 = (EditText)findViewById(R.id.etnumber4);
etnumber5 = (EditText)findViewById(R.id.etnumber5);
}
public void onClickResult(){
String cards[] = {etnumber1.getText().toString,
etnumber2.getText().toString(),
etnumber3.getText().toString(),
etnumber4.getText().toString(),
etnumber5.getText().toString()
};
int noOfCard = cards.length;
Arrays.sort(cards);
StringBuilder builder = new StringBuilder();
for (String s : cards)
builder.append(s).append(" ");
Toast.makeText(context, builder.toString(), Toast.LENGTH_SHORT).show();
}
This will sort your array and display it in a Toast in this format: "2 3 5 6 7" (according to the numbers you provided). If the EditTexts are going to have only numbers, consider using NumberPicker instead.
LENGTH_SHORT can also be LENGTH_LONG.
public class MainActivity extends Activity {
EditText number1,number2,number3,number4,number5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
number1 = (EditText)findViewById(R.id.etnumber1);
number2 = (EditText)findViewById(R.id.etnumber2);
number3 = (EditText)findViewById(R.id.etnumber3);
number4 = (EditText)findViewById(R.id.etnumber4);
number5 = (EditText)findViewById(R.id.etnumber5);
}
public void clickresult(){
int cards[] = {6,7,3,2,5};
int noOfCard = cards.length;
for (int marker = 1; marker < noOfCard; marker++) {
for (int j = 0; j < marker; j++) {
if (cards[marker] < cards[j]) {
int tmp = cards[marker];
cards[marker] = cards[j];
cards[j] = tmp;
}
}
}
for (int i = 0; i < noOfCard; i++) {
System.out.print(cards[i] + " ");
}
System.out.println();
}

[Android]Compare two images/drawables in android for a memory game?

I have two activities. One activity shows a set of random images from an array of images. Then after 10 seconds, the second activity shows a set of clickable random images. The objective is to make the user click the images common to both the activities. The app should show the number of correct clicks and wrong clicks on a textview. I tried to compare the drawables of the two activities but with no luck. Please suggest me a way to get out of this problem. Getting the resource ID of the clicked images would help. But I was not able to find anything that would help me get that.I am fairly new to Android.
MainActivity.java:
public class MainActivity extends Activity
{
int i=5;
static int[] imageViews ={
R.id.imageView1,R.id.imageView2,R.id.imageView3,
R.id.imageView4,R.id.imageView5,R.id.imageView6,
R.id.imageView7,R.id.imageView8,R.id.imageView9,
R.id.imageView10,R.id.imageView11,R.id.imageView12,
R.id.imageView13,R.id.imageView14,R.id.imageView15,
R.id.imageView16,R.id.imageView17,R.id.imageView18
};
static int[] images = {
R.drawable.animalsimg1,R.drawable.animalsimg2,R.drawable.animalsimg3, R.drawable.animalsimg4,R.drawable.animalsimg5,R.drawable.animalsimg6,
R.drawable.animalsimg7,R.drawable.animalsimg8,R.drawable.animalsimg9,
R.drawable.animalsimg10,R.drawable.animalsimg11,R.drawable.animalsimg12,
R.drawable.animalsimg13,R.drawable.animalsimg14,R.drawable.animalsimg15,
R.drawable.animalsimg16,R.drawable.animalsimg17,R.drawable.animalsimg18,
R.drawable.animalsimg19,R.drawable.animalsimg20
};
int[] a;
int[] b;
static int[] c=new int[5];
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
a=RandomizeArray(images);
b=RandomizeArray(imageViews);
for(int j=0;j<4;j++){
int imv = b[j];
int im = a[j];
ImageView iv = (ImageView)findViewById(imv);
iv.setImageResource(im);
c[j]=a[j];
}
new CountDownTimer(7000, 1000) {
TextView timertext=(TextView)findViewById(R.id.textView1);
public void onTick(long millisUntilFinished) {
timertext.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
timertext.setText("done!");
finish();
Intent intent=new Intent(MainActivity.this,SecondActivity.class);
startActivity(intent);
}
}.start();
}
public static int[] RandomizeArray(int[] array){
Random rgen = new Random(); // Random number generator
for (int i=0; i<array.length; i++) {
int randomPosition = rgen.nextInt(array.length);
int temp = array[i];
array[i] = array[randomPosition];
array[randomPosition] = temp;
}
return array;
}
}
SecondActivity.java:
public class SecondActivity extends Activity{
int[] a;
int[] b;
int p=0;
int im;
int imv;
int[] c=new int[4];
int j;
int correct=0;
int wrong=0;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
tv=(TextView)findViewById(R.id.textView1);
a=RandomizeArray(MainActivity.images);
b=RandomizeArray(MainActivity.imageViews);
for(j=0;j<4;j++){
imv = b[j];
im = a[j];
ImageView iv = (ImageView)findViewById(imv);
iv.setImageResource(im);
}
}
public void onClick(View v){
for(p=0;p<4;p++){
int s=c[p];
if(((ImageView) v).getDrawable().getConstantState().equals(getResources().getDrawable(MainActivity.images[s]).getConstantState())){
correct++;
}
else{
wrong++;
}
v.setBackgroundResource(R.drawable.vattom_2);
tv.setText("Correct="+Integer.toString(correct)+" Wrong="+Integer.toString(wrong));
}
}
public static int[] RandomizeArray(int[] array){
Random rgen = new Random(); // Random number generator
for (int i=0; i<array.length; i++) {
int randomPosition = rgen.nextInt(array.length);
int temp = array[i];
array[i] = array[randomPosition];
array[randomPosition] = temp;
}
return array;
}
}
You should consider using tags, I believe it would solve your problem as they're easily comparable

Creating a TextView for the first 46 Fibonacci numbers on Android

I have this so far, and the result is a blank screen. What might I do to achieve the desired effect of listing the first 46 Fibonacci numbers?
TextView fibNum;
static int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public static int fib(int n) {
int prev1=0, prev2=1;
for( i=0; i<n; i++) {
int savePrev1 = prev1;
prev1 = prev2;
prev2 = savePrev1 + prev2;
}
return prev1;
}
public void main(String[] args) {
for (int i=0; i<=46; i++)
fibNum = new TextView(this);
fibNum.setText(String.valueOf(fib(i)+", "));
}
}
First, just creating a TextView doesn't make it part of the view hierarchy being displayed. Second, Android will never call your main method. Third, I don't see how your code even compiles; the loop inside main only covers the assignment to fibNum, so at the call to setText, the variable i is not even in scope.
Putting all that aside, let's assume your activity_main.xml layout file already has a TextView in it with id #+id/text where you want to display the numbers. I suggest something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView text = (TextView) findViewById(R.id.text);
text.setText(getFib(46));
}
public static int fib(int n) {
int prev1 = 0, prev2 = 1;
for(int i = 0; i < n; i++) {
int savePrev1 = prev1;
prev1 = prev2;
prev2 = savePrev1 + prev2;
}
return prev1;
}
public static String getFib(int n) {
StringBuilder sb = new StringBuilder(fib(0));
for (int i = 1; i < n; ++i) {
sb.append(", ");
sb.append(fib(i));
}
return sb.toString();
}
This assumes that calculating 46 Fibonacci numbers doesn't take an inordinate amount of time. If it does, you'll have to move the calculation to a worker thread (probably easiest to do using an AsyncTask).

How can I separate this code for greater clarity?

I made a Memory Game for Android.
My problem is that all the code is in one class. So I need to separate the code with a new class to help make it more clear.
This is the code:
public class NivelA extends Activity implements OnClickListener{
private int [] fichasIds = {
R.drawable.img_1,
R.drawable.img_2,
R.drawable.img_3,
R.drawable.img_4,
R.drawable.img_5,
R.drawable.img_6,
R.drawable.imgOculto,
};
protected int[] fichas;
private ImageView[] imageviews;
private static final int cantFichas = 6;
private int fichasUp;
private int currentIndex = -1;
private int lastIndex = -1;
private int fichasIguales = 0;
private int vidas = 3;
private TextView vidas_txt;
Handler handler;
private int [] imgIds = {
R.id.img_1,
R.id.img_2,
R.id.img_3,
R.id.img_4,
R.id.img_5,
R.id.img_6,
R.id.img_7,
R.id.img_8,
R.id.img_9,
R.id.img_10,
R.id.img_11,
R.id.img_12,
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nivel1);
//Toast
Toast toast = Toast.makeText(NivelA.this, "Nivel: 1", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER|Gravity.CENTER, 0, 65);
toast.show();
handler = new Handler ();
fichasIguales = 0;
vidas_txt = (TextView) findViewById(R.id.vidas_iguales);
fichas = new int [12];
for (int i=0; i<12; i++)
{
fichas[i] = -1;
}
imageviews = new ImageView [imgIds.length];
for (int i=0; i<imgIds.length; i++)
{
imageviews[i] = (ImageView) findViewById(imgIds[i]);
}
Random random = new Random ();
for (int i=0; i<6; i++){
for (int z=0; z<2; z++)
{
int fichasRandom = random.nextInt(12);
while (fichas[fichasRandom]!= -1)
{
fichasRandom = random.nextInt(12);
}
fichas[fichasRandom]= i;
}
}
//Los listener
for (int i=0; i<12; i++)
{
((ImageView)findViewById(imgIds[i])).setOnClickListener(this);
}
for (int i=0; i<12; i++)
{
((ImageView)findViewById(imgIds[i])).setImageResource(R.drawable.imgOculto);
}
}
#Override
public void onClick(View v) {
int index = Integer.parseInt((String)v.getTag());
for (int i=0; i<12; i++)
{
if (v.getId() == imgIds [i])
{
index = i;
((ImageView)findViewById(imgIds[i])).setImageResource(fichasIds[fichas[i]]);
imageviews[i].setFocusable(false);
imageviews[i].setClickable(false);
break;
}
}
fichasUp++;
if (fichasUp == 2)
{
vidas--;
vidas_txt.setText(String.valueOf(vidas));
currentIndex = index;
for (ImageView view:imageviews)
{
view.setFocusable(false);
view.setClickable(false);
}
fichasUp = 0;
handler.postDelayed(fichasOcultas, 1000);
}
else{
lastIndex = index;
}
}
Runnable fichasOcultas = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if (fichas[currentIndex]== fichas[lastIndex])
{
((ImageView)findViewById(imgIds[lastIndex])).setVisibility(View.INVISIBLE);
((ImageView)findViewById(imgIds[currentIndex])).setVisibility(View.INVISIBLE);
fichasIguales ++;
//Toast [ Hay Coincidencia ]
Toast toast = Toast.makeText(NivelA.this, "Hay Coincidencia!", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER|Gravity.CENTER, 14, 0);
toast.show();
if (fichasIguales == cantFichas)
{
win ();
}
}else
{
((ImageView)findViewById(imgIds[currentIndex])).setImageResource(R.drawable.imgOculto);
((ImageView)findViewById(imgIds[lastIndex])).setImageResource(R.drawable.imgOculto);
}
for (ImageView view:imageviews)
{
view.setFocusable(true);
view.setClickable(true);
}
}
};
protected void win() {
Toast toast = Toast.makeText(NivelA.this, "Ganaste!!", Toast.LENGTH_SHORT);
toast.show();
}
}
I would suggest that you move all your game logic out of the NivelA class. That should go a long way toward simplifying your code. In general, each Activity subclass should be responsible for creating the screen, perhaps responding to events, and not much else.
Also, instead of making NivelA implement OnClickListener, you might want to use the android:onClick attribute that views can have. If you assign a view the attribute
android:onClick="aClickMethod"
then you just need to implement a public method:
public void aClickMethod(View view) { . . . }
(The name of the method is totally up to you.) Assigning the android:onClick method automatically makes the view clickable. You'll be surprised how much code will be eliminated with this trick.

Resources