Setter/Getter method not working - java

Hi I am having a problem accessing variables/methods in my view class from my main activity. I just need to return the turns int from GameView.java and be able to access it in MainActivity and then insert it into my database. I try to use GameView mGameView = new GameView(getApplicationContext()); but this doesn't work and I can't access any methods from GameView with this.
My GameView class:
public class GameView extends View {
int mcolumns = 5;
int mrows = 5;
private NetwalkGrid mGame = new NetwalkGrid(mcolumns, mrows);
private GestureDetector mGestureDetector;
Random rand = new Random();
int sizeSqX;
int sizeSqY;
int sizeSq;
int turns = 0;
Paint bgPaint;
public GameView(Context context) {
super(context);
init();
}
private void init() {
bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
bgPaint.setStyle(Paint.Style.FILL);
bgPaint.setColor(0xff0000ff);
mGame.gridCopy();
for (int col = 0; col < mGame.getColumns(); col++) {
for (int row = 0; row < mGame.getRows(); row++) {
int num = rand.nextInt(3) + 1;
for (int turns = 1; turns < num; turns++) {
mGame.rotateRight(col, row);
}
}
}
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
sizeSqX = getWidth() / mcolumns;
sizeSqY = getHeight() / mrows;
if (sizeSqX < sizeSqY) {
sizeSq = sizeSqX;
}
else {
sizeSq = sizeSqY;
}
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder);
int cellContent;
int square = 140;
for (int col = 0; col < mGame.getColumns(); col++) {
for (int row = 0; row < mGame.getRows(); row++) {
cellContent = mGame.getGridElem(col,row);
if (cellContent == 1) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.up_down); // Image for down position
if (cellContent == 65 && mGame.checkWin()) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.up_down_connected);
}
}
else if (cellContent == 2) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.left_right); // Right position
if (mGame.checkWin()) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.left_right_connected);
}
}
else if (cellContent == 3) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.right_down); // Down right position WORKS
if (mGame.checkWin()) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.right_down_connected);
}
}
else {
b = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder2); //
}
canvas.drawBitmap(b, null,new Rect(col * sizeSq, row * sizeSq,col*sizeSq+sizeSq, row*sizeSq+sizeSq), null);
TextPaint tp = new TextPaint();
tp.setColor(Color.GREEN);
tp.setTextSize(70);
tp.setTypeface(Typeface.create("Courier", Typeface.BOLD));
canvas.drawText("Moves: " + String.valueOf(turns), 10, 1180, tp);
}
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
int column = getColTouched(event.getX());
int row = getRowTouched(event.getY());
try {
mGame.rotateRight(column, row);
System.out.println(mcolumns);
mGame.checkWin();
if (mGame.checkWin()) {
System.out.println("check win works");
invalidate();
}
invalidate();
}
catch (ArrayIndexOutOfBoundsException err) {
System.out.println("User has pressed outside game grid - exception caught");
}
turns++;
return super.onTouchEvent(event);
}
public int getColTouched(float x) {
return (int) (x / sizeSq);
}
public int getRowTouched(float y) {
return (int) (y / sizeSq);
}
public int getTurns() {
return turns;
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
private int mcolumns;
private int mrows;
DatabaseHelper myDb;
String test = "test data";
int turns;
static Context appcon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appcon = this;
myDb = new DatabaseHelper(this);
}
public void runGame(View view){
Intent intent = new Intent(this, GameViewActivity.class);
startActivity(intent);
}
public void runInstructions(View view) {
Intent intent = new Intent(this, InstructionsActivity.class);
startActivity(intent);
}
public void setTurns() {
GameView mGameView = new GameView(getApplicationContext());
this.turns = mGameView.turns;
System.out.println("Turns: " + Integer.toString(turns));
}
public void AddData() {
boolean isInserted = myDb.insertData(Integer.toString(turns));
if(isInserted == true) {
System.out.println("Data inserted");
}
else {
System.out.println("Data NOT inserted");
}
}
}

In MainAcivity, inside setTurns()
Replace this
this.turns = mGameView.turns; //you can't access this variable directly
with
this.turns = mGameView.getTurns(); // Calling the public method getTurns()
please see this answer for explanation about Access modifiers in Java

There are two ways to fix this.
1. Preferred way:
Add a new Method in GameView class
public int getTurns() {
return turns;
}
And use this method where you want to access turns like:
this.turns = mGameView.getTurns();
2. Bad way:
Make turns variable public.

Related

Cannot resolve constructor 'BaseBar(java.time.ZonedDateTime, java.lang.Double)'?

So I'm an amateur Android developer and have an issue.
My app uses this library (https://github.com/ta4j/ta4j) but after updating it to the latest stable release I'm having these errors!
Here's the error:
Cannot resolve constructor 'BaseBar(java.time.ZonedDateTime, java.lang.Double, java.lang.Double, java.lang.Double, java.lang.Double, java.lang.Double)'
Here's the java code of my class:
public class RVCardAdapter extends RecyclerView.Adapter<RVCardAdapter.CryptoViewHolder> {
//globals
private List<SingleCryptoData> mCryptos;
private int mExpandedPosition;
//private int previousExpandedPosition = -1;
//default constructor
public RVCardAdapter() {
super();
mCryptos = new ArrayList<>();
}
//this refreshes the list
public void clear() {
mCryptos.clear();
notifyDataSetChanged();
}
//this adds the POJO passed into the crypto list
public void addData(SingleCryptoData crypto) {
mCryptos.add(crypto);
notifyDataSetChanged();
}
#Override
public void onAttachedToRecyclerView(#NonNull RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#NonNull
#Override
public CryptoViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cryptocurrency_card, viewGroup, false);
return new CryptoViewHolder(v);
}
//onBindViewHolder binds the data to the layout elements for each crypto
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull CryptoViewHolder cryptoViewHolder, int i) {
//loading animation
FiftyShadesOf fiftyShades = new FiftyShadesOf(cryptoViewHolder.mCardViewDetails.getContext());
fiftyShades.on(cryptoViewHolder.mSignal, cryptoViewHolder.mCardViewDetails, cryptoViewHolder.mSignalStrength);
fiftyShades.fadein(true);
fiftyShades.start();
//set up output formatting
Currency usd = Currency.getInstance("USD");
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(Locale.US);
currencyFormat.setCurrency(usd);
NumberFormat twoDecimalFormat = DecimalFormat.getInstance(Locale.US);
twoDecimalFormat.setRoundingMode(RoundingMode.FLOOR);
twoDecimalFormat.setMinimumFractionDigits(0);
twoDecimalFormat.setMaximumFractionDigits(2);
//TODO get display POJO data
cryptoViewHolder.mCryptoName.setText(mCryptos.get(i).getName());
cryptoViewHolder.mCryptoValue.setText(currencyFormat.format(mCryptos.get(i).getRaw().getPrice()));
cryptoViewHolder.mCryptoSymbol.setText(mCryptos.get(i).getRaw().getFromSymbol());
cryptoViewHolder.mCryptoDetailsVolume.setText(twoDecimalFormat.format(mCryptos.get(i).getRaw().getVolume24Hour()) + " " + mCryptos.get(i).getRaw().getFromSymbol());
cryptoViewHolder.mCryptoDetailsLow.setText(currencyFormat.format(mCryptos.get(i).getRaw().getLow24Hour()));
cryptoViewHolder.mCryptoDetailsHigh.setText(currencyFormat.format(mCryptos.get(i).getRaw().getHigh24Hour()));
cryptoViewHolder.mCryptoDetailsOpen.setText(currencyFormat.format(mCryptos.get(i).getRaw().getOpen24Hour()));
cryptoViewHolder.mCryptoDetailsPercentChange.setText(twoDecimalFormat.format(mCryptos.get(i).getRaw().getChangePercent24Hour()) + " %");
//color percent change depending on value
if (mCryptos.get(i).getRaw().getChangePercent24Hour() >= 0) {
cryptoViewHolder.mCryptoDetailsPercentChange.setTextColor(Color.parseColor("#52BE80"));
} else {
cryptoViewHolder.mCryptoDetailsPercentChange.setTextColor(Color.RED);
}
//handles expanding animation
//TODO stop first card from expanding
final boolean isExpanded = cryptoViewHolder.getAdapterPosition() == mExpandedPosition;
cryptoViewHolder.mCardViewDetails.setVisibility((isExpanded) ? View.VISIBLE : View.GONE);
cryptoViewHolder.itemView.setActivated(isExpanded);
// if (isExpanded)
// previousExpandedPosition = cryptoViewHolder.getAdapterPosition();
cryptoViewHolder.itemView.setOnClickListener(v -> {
mExpandedPosition = (isExpanded) ? -1 : cryptoViewHolder.getAdapterPosition();
//notifyItemChanged(previousExpandedPosition); //this used to close the
notifyItemChanged(cryptoViewHolder.getAdapterPosition());
});
//HISTODATA API
CryptoCompareAPI service = ServiceFactory.createRetrofitRx(CryptoCompareAPI.class, CryptoCompareAPI.BASE_URL);
if (android.os.Build.VERSION.SDK_INT >= 26){
//DAYS OF HISTORY TO GET FOR EACH CRYPTO
int historyDays = 14;
service.getHistoricalData(mCryptos.get(i).getRaw().getFromSymbol(), "USD", historyDays, "CryptoAnalysis")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<HistoData>() {
#Override
public void onSubscribe(Disposable d) {
}
//in histodata, the last element is the newest, and is yesterday. it will be at position [days]
#Override
public void onNext(HistoData histoData) {
TimeSeries series = new BaseTimeSeries("Strategy");
//TODO make usable on API 21+
ZonedDateTime endTime = ZonedDateTime.now().minusDays(historyDays);
//loop for each day of results in histodata
for (int i = 0; i < histoData.getData().size(); i++) {
//create a new base bar
Bar bar = new BaseBar(
endTime.plusDays(i),
histoData.getData().get(i).getOpen(),
histoData.getData().get(i).getHigh(),
histoData.getData().get(i).getLow(),
histoData.getData().get(i).getClose(),
histoData.getData().get(i).getVolumeTo()
);
series.addBar(bar);
}
//RUN ANALYSIS
Signal signal = TechnicalAnalysis.getSignal(series);
//INFLATE LAYOUT STUFF
cryptoViewHolder.mSignal.setText(signal.getSignalResult());
cryptoViewHolder.mRsiValue.setVisibility(View.VISIBLE);
cryptoViewHolder.mRsiValue.setText(String.valueOf((int) signal.getRsiStrength()));
cryptoViewHolder.mMomentumValue.setVisibility(View.VISIBLE);
cryptoViewHolder.mMomentumValue.setText(String.valueOf((int) signal.getMomentumStrength()));
cryptoViewHolder.mEmaValue.setVisibility(View.VISIBLE);
cryptoViewHolder.mEmaValue.setText(String.valueOf((int) signal.getEmaStrength()));
//cryptoViewHolder.mSignalStrength.setText("(" + String.valueOf(signal.getSignalStrength()) + ")");
}
#Override
public void onError(Throwable e) {
if (e.getMessage() != null)
Log.e("Histo API Error", e.getMessage());
}
#Override
public void onComplete() {
fiftyShades.stop();
}
});
} else {
int historyDays = 14;
service.getHistoricalData(mCryptos.get(i).getRaw().getFromSymbol(), "USD", historyDays, "CryptoAnalysis")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<HistoData>() {
#Override
public void onSubscribe(Disposable d) {
}
//in histodata, the last element is the newest, and is yesterday. it will be at position [days]
#Override
public void onNext(HistoData histoData) {
TimeSeries series = new BaseTimeSeries("Strategy");
//RUN ANALYSIS
Signal signal = TechnicalAnalysis.getSignal(series);
//INFLATE LAYOUT STUFF
cryptoViewHolder.mSignal.setText(signal.getSignalResult());
}
#Override
public void onError(Throwable e) {
if (e.getMessage() != null)
Log.e("Histo API Error", e.getMessage());
}
#Override
public void onComplete() {
fiftyShades.stop();
}
});
}
}
#Override
public int getItemCount() {
return mCryptos.size();
}
static class CryptoViewHolder extends RecyclerView.ViewHolder {
CardView mCardView;
TextView mCryptoDetailsOpen;
TextView mCryptoDetailsHigh;
TextView mCryptoDetailsLow;
TextView mCryptoDetailsVolume;
TextView mCryptoDetailsPercentChange;
TextView mCryptoName;
TextView mCryptoValue;
TextView mCryptoSymbol;
ConstraintLayout mCardViewDetails;
TextView mSignal;
TextView mRsiValueLabel;
TextView mRsiValue;
TextView mEmaValueLabel;
TextView mEmaValue;
TextView mMomentumValueLabel;
TextView mMomentumValue;
TextView mSignalStrength;
TextView mLowerApi;
CryptoViewHolder(View itemView) {
super(itemView);
mCryptoDetailsHigh = itemView.findViewById(R.id.crypto_details_high);
mCryptoDetailsOpen = itemView.findViewById(R.id.crypto_details_open);
mCryptoDetailsLow = itemView.findViewById(R.id.crypto_details_low);
mCryptoDetailsVolume = itemView.findViewById(R.id.crypto_details_volume);
mCryptoDetailsPercentChange = itemView.findViewById(R.id.crypto_details_percent_change);
mCardViewDetails = itemView.findViewById(R.id.card_view_details);
mCardView = itemView.findViewById(R.id.card_view);
mCryptoName = itemView.findViewById(R.id.crypto_name);
mCryptoValue = itemView.findViewById(R.id.crypto_value);
mCryptoSymbol = itemView.findViewById(R.id.crypto_symbol);
mSignal = itemView.findViewById(R.id.signal);
if (android.os.Build.VERSION.SDK_INT >= 26) {
mRsiValue = itemView.findViewById(R.id.rsi_indicator_value);
mRsiValue.setVisibility(View.VISIBLE);
mEmaValue = itemView.findViewById(R.id.ema_indicator_value);
mEmaValue.setVisibility(View.VISIBLE);
mMomentumValue = itemView.findViewById(R.id.momentum_indicator_value);
mMomentumValue.setVisibility(View.VISIBLE);
mRsiValueLabel = itemView.findViewById(R.id.rsi_value_label);
mRsiValueLabel.setVisibility(View.VISIBLE);
mEmaValueLabel = itemView.findViewById(R.id.ema_value_label);
mEmaValueLabel.setVisibility(View.VISIBLE);
mMomentumValueLabel = itemView.findViewById(R.id.momentum_value_label);
mMomentumValueLabel.setVisibility(View.VISIBLE);
mLowerApi = itemView.findViewById(R.id.lowApi);
mLowerApi.setVisibility(View.GONE);
}
//mSignalStrength = itemView.findViewById(R.id.signal_strength);
}
}
}
The lines where the error is shown:
for (int i = 0; i < histoData.getData().size(); i++) {
//create a new base bar
Bar bar = new BaseBar(
endTime.plusDays(i),
histoData.getData().get(i).getOpen(),
histoData.getData().get(i).getHigh(),
histoData.getData().get(i).getLow(),
histoData.getData().get(i).getClose(),
histoData.getData().get(i).getVolumeTo()
);
series.addBar(bar);
}
Class 2:
public class TechnicalAnalysis {
//variables and their values, these dictate how likely the signal is to move one way or another.
//Eventually, these will be tweaked and changed to be more accurate.
private static double rsiOversold = 25;
private static double rsiOverbought = 75;
private static double rsiWeight = 0.35;
private static double momentumWeight = 0.3;
private static double emaWeight = 0.35;
public static Signal getSignal(TimeSeries series) {
int numBars = series.getBarCount(); //this is the number of days in the series
//create indicators from series
//in all of these, the LAST member is the latest
ClosePriceIndicator closePrices = new ClosePriceIndicator(series);
RSIIndicator rsi = new RSIIndicator(closePrices, numBars);
EMAIndicator shortEma = new EMAIndicator(closePrices, numBars / 4);
EMAIndicator longEma = new EMAIndicator(closePrices, numBars);
//init strength vars
int rsiStrength = 0;
int momentumStrength = 0;
int emaStrength = 0;
//RSI 35%
for (int i = 0; i < numBars; i++) {
if (rsi.getValue(i).isGreaterThanOrEqual(rsiOverbought)) {
rsiStrength += i;
} else if (rsi.getValue(i).isLessThanOrEqual(rsiOversold)) {
rsiStrength -= i;
}
}
//EMA 45%
for (int i = 0; i < numBars; i++) {
if (shortEma.getValue(i).isGreaterThan(longEma.getValue(i).multipliedBy(1.04))) {
emaStrength += i;
} else {
emaStrength -= i;
}
}
//MOMENTUM 20%
for (int i = 0; i < numBars; i++) {
if (series.getBar(i).getClosePrice().isGreaterThan(series.getBar(i).getOpenPrice())) {
momentumStrength += i;
} else {
momentumStrength -= i;
}
}
//finally, return the completed
double rsiValue = rsiStrength * rsiWeight;
double emaValue = emaStrength * emaWeight;
double momentumValue = momentumStrength * momentumWeight;
return new Signal(rsiValue, emaValue, momentumValue);
}
}
Class 2 error:
isGreaterThanOrEqual
(org.ta4j.core.num.Num)
in Num cannot be applied to (double)
Class 2 error line:
for (int i = 0; i < numBars; i++) {
if (rsi.getValue(i).isGreaterThanOrEqual(rsiOverbought)) {
rsiStrength += i;
} else if (rsi.getValue(i).isLessThanOrEqual(rsiOversold)) {
rsiStrength -= i;
}
}
Can someone help, please?

Trouble getting order of Image Bitmap layers in Android correct

I have a piece of code that compares to images and places a marker on the difference. So far it works well, except the latest marker layer that is added always shows underneath all the older markers. I have the latest one as a yellow color and the older ones as red. When the difference is close to one of the red markers, the yellow marker shows behind those ones.
Is there anyone that can help me get the yellow (Latest marker) to appear on top?
This is my code so far:
public class CheckmarkActivity extends AppCompatActivity implements ZoomLayout.OnZoomableLayoutClickEventListener {
TextView tv;
RelativeLayout relativeLayout_work;
ImageView imageViewtest;
Bitmap prevBmp = null;
Timer t;
TimerTask task;
int time = 100;
float image_Width;
float image_Height;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checkmark);
if (getResources().getBoolean(R.bool.is_tablet)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
tv = findViewById(R.id.tv);
relativeLayout_work = findViewById(R.id.relativeLayout_work);
imageViewtest = findViewById(R.id.imageViewtest);
prevBmp = ViewcontrollerActivity.workSession.getLastScreenShot();
if (prevBmp == null || ViewcontrollerActivity.workSession.workScreenShot == null) {
setResult(Activity.RESULT_CANCELED);
finish();
}
startTimer();
}
// image compare
class TestAsync extends AsyncTask<Object, Integer, String>
{
String TAG = getClass().getSimpleName();
PointF p;
Bitmap test_3;
protected void onPreExecute (){
super.onPreExecute();
Log.d(TAG + " PreExceute","On pre Exceute......");
}
protected String doInBackground(Object...arg0) {
test_3 = ImageHelper.findDifference(CheckmarkActivity.this, prevBmp, ViewcontrollerActivity.workSession.workScreenShot);
p = ImageHelper.findShot(test_3);
time = 1;
return "You are at PostExecute";
}
protected void onProgressUpdate(Integer...a){
super.onProgressUpdate(a);
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
addImageToImageview();
PointF np = Session.convertPointBitmap2View(p, relativeLayout_work, ViewcontrollerActivity.workSession.workScreenShot);
tv.setX(np.x - tv.getWidth() / 2);
tv.setY(np.y - tv.getHeight() / 2);
tv.setVisibility(View.VISIBLE);
// imageViewtest.setImageBitmap(test_3);
}
}
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i("OpenCV", "OpenCV loaded successfully");
new TestAsync().execute();
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
#Override
protected void onResume() {
super.onResume();
if (!OpenCVLoader.initDebug()) {
Log.d("OpenCV", "Internal OpenCV library not found. Using OpenCV Manager for initialization");
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, this, mLoaderCallback);
} else {
Log.d("OpenCV", "OpenCV library found inside package. Using it!");
mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
}
}
public static int[] getBitmapOffset(ImageView img, Boolean includeLayout) {
int[] offset = new int[2];
float[] values = new float[9];
Matrix m = img.getImageMatrix();
m.getValues(values);
offset[0] = (int) values[5];
offset[1] = (int) values[2];
if (includeLayout) {
ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) img.getLayoutParams();
int paddingTop = (int) (img.getPaddingTop() );
int paddingLeft = (int) (img.getPaddingLeft() );
offset[0] += paddingTop + lp.topMargin;
offset[1] += paddingLeft + lp.leftMargin;
}
return offset;
}
public static int[] getBitmapPositionInsideImageView(ImageView imageView) {
int[] ret = new int[4];
if (imageView == null || imageView.getDrawable() == null)
return ret;
// Get image dimensions
// Get image matrix values and place them in an array
float[] f = new float[9];
imageView.getImageMatrix().getValues(f);
// Extract the scale values using the constants (if aspect ratio maintained, scaleX == scaleY)
final float scaleX = f[Matrix.MSCALE_X];
final float scaleY = f[Matrix.MSCALE_Y];
// Get the drawable (could also get the bitmap behind the drawable and getWidth/getHeight)
final Drawable d = imageView.getDrawable();
final int origW = d.getIntrinsicWidth();
final int origH = d.getIntrinsicHeight();
// Calculate the actual dimensions
final int actW = Math.round(origW * scaleX);
final int actH = Math.round(origH * scaleY);
ret[2] = actW;
ret[3] = actH;
// Get image position
// We assume that the image is centered into ImageView
int imgViewW = imageView.getWidth();
int imgViewH = imageView.getHeight();
int top = (int) (imgViewH - actH)/2;
int left = (int) (imgViewW - actW)/2;
ret[0] = left;
ret[1] = top;
return ret;
}
private void addImageToImageview(){
if (ViewcontrollerActivity.workSession.workScreenShot != null) {
imageViewtest.setImageBitmap(ViewcontrollerActivity.workSession.workScreenShot);
Log.d("width", String.valueOf(imageViewtest.getWidth()));
}
Resources r = getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
for (int i = 0; i < ViewcontrollerActivity.workSession.getShotCount(); i++) {
PointF p = ViewcontrollerActivity.workSession.getPoint(i);
TextView t = new TextView(this);
t.setText("" + (i + 1));
RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams((int)px, (int)px);
relativeLayout_work.addView(t);
t.setLayoutParams(param);
t.setGravity(Gravity.CENTER);
t.setBackgroundResource(R.drawable.circle);
p = Session.convertPointBitmap2View(p, relativeLayout_work, ViewcontrollerActivity.workSession.workScreenShot);
t.setX(p.x);
t.setY(p.y);
t.setTag(10000 + i);
}
}
public void onConfirm(View v){
View vv = findViewById(R.id.relativeLayout_work);
PointF bp = Session.convertPointView2Bitmap(new PointF(tv.getX(), tv.getY()), relativeLayout_work, ViewcontrollerActivity.workSession.workScreenShot);
ViewcontrollerActivity.workSession.addNewShot(ViewcontrollerActivity.workSession.workScreenShot, bp);
setResult(Activity.RESULT_OK);
finish();
}
public void onCancel(View v){
setResult(Activity.RESULT_CANCELED);
finish();
}
#Override
public void onBackPressed() {
setResult(Activity.RESULT_CANCELED);
finish();
}
#Override
public void OnContentClickEvent(int action, float xR, float yR) {
int[] offset = new int[2];
int[] rect = new int[4];
offset = this.getBitmapOffset(imageViewtest, false);
int original_width = imageViewtest.getDrawable().getIntrinsicWidth();
int original_height = imageViewtest.getDrawable().getIntrinsicHeight();
rect = getBitmapPositionInsideImageView(imageViewtest);
Log.i("OffsetY", String.valueOf(offset[0]));
Log.i("OffsetX", String.valueOf(offset[1]));
Log.i( "0", String.valueOf(rect[0]));
Log.i( "1", String.valueOf(rect[1]));
Log.i( "2", String.valueOf(rect[2]));
Log.i( "3", String.valueOf(rect[3]));
if (xR > rect[0] && xR < rect[0] + rect[2] && yR > rect[1] && yR < rect[1] + rect[3]) {
tv.setX(xR - tv.getWidth() / 2);
tv.setY(yR - tv.getHeight() / 2);
}
// tv.setX(xR - tv.getWidth() / 2);
// tv.setY(yR - tv.getHeight() / 2);
}
public void onMoveButtonPressed(View v) {
ImageButton b = (ImageButton)v;
int mId = b.getId();
switch (mId) {
case R.id.imageButtonL:
tv.setX(tv.getX() - 1);
break;
case R.id.imageButtonR:
tv.setX(tv.getX() + 1);
break;
case R.id.imageButtonD:
tv.setY(tv.getY() + 1);
break;
case R.id.imageButtonU:
tv.setY(tv.getY() - 1);
break;
}
}
//timer change image
public void startTimer(){
t = new Timer();
task = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (time == 1){
imageViewtest.setImageBitmap(ViewcontrollerActivity.workSession.workScreenShot);
// tv.setVisibility(View.VISIBLE);
tv.setText("" + (ViewcontrollerActivity.workSession.getShotCount() + 1));
t.cancel();
return;
}
if (time % 2 == 0) {
imageViewtest.setImageBitmap(prevBmp);
}
else if(time % 2 == 1){
imageViewtest.setImageBitmap(ViewcontrollerActivity.workSession.workScreenShot);
}
time --;
}
});
}
};
t.scheduleAtFixedRate(task, 0, 500);
}
}
You can give the z-order of the child view with addView() function.
void addView (View child, int index)
ex)
private void addImageToImageview(){
if (ViewcontrollerActivity.workSession.workScreenShot != null) {
imageViewtest.setImageBitmap(ViewcontrollerActivity.workSession.workScreenShot);
Log.d("width", String.valueOf(imageViewtest.getWidth()));
}
Resources r = getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
int currChildrenCount = relativeLayout_work.getChildCount();
for (int i = 0; i < ViewcontrollerActivity.workSession.getShotCount(); i++) {
PointF p = ViewcontrollerActivity.workSession.getPoint(i);
TextView t = new TextView(this);
t.setText("" + (i + 1));
RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams((int)px, (int)px);
relativeLayout_work.addView(t, currChildrenCount+i); // You can control the order like this
t.setLayoutParams(param);
t.setGravity(Gravity.CENTER);
t.setBackgroundResource(R.drawable.circle);
p = Session.convertPointBitmap2View(p, relativeLayout_work, ViewcontrollerActivity.workSession.workScreenShot);
t.setX(p.x);
t.setY(p.y);
t.setTag(10000 + i);
}
}

Inserting and fetching data into SQLite [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 6 years ago.
I am having difficulty inserting data into my SQLite database. When I call my addData() method my app crashes. I call my addData method (which is in MainActivity) from my GameView class inside my onTouchEvent method. I need to insert my turns integer into the COLUMN_SCORES column in my database. Appreciate any help!
DatabaseHelper.java:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "scores.db";
public static final String TABLE_NAME = "scores_table";
public static final String COLUMN_ID = "ID";
public static final String COLUMN_SCORE = "SCORE";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT, SCORE INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String score) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_SCORE, score);
long result = db.insert(TABLE_NAME, null, contentValues);
if(result == -1) {
return false;
}
else {
return true;
}
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
return res;
}
public boolean updateData(String id, String score) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_ID, id);
contentValues.put(COLUMN_SCORE, score);
db.update(TABLE_NAME, contentValues, "ID = ?", new String[] { id });
return true;
}
public Integer deleteData(String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "ID = ?", new String[] { id });
}
}
GameView.java:
public class GameView extends View {
int mcolumns = 5;
int mrows = 5;
private NetwalkGrid mGame = new NetwalkGrid(mcolumns, mrows);
private GestureDetector mGestureDetector;
Random rand = new Random();
int sizeSqX;
int sizeSqY;
int sizeSq;
public static int turns;
Paint bgPaint;
public GameView(Context context) {
super(context);
init();
}
private void init() {
bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
bgPaint.setStyle(Paint.Style.FILL);
bgPaint.setColor(0xff0000ff);
mGame.gridCopy();
for (int col = 0; col < mGame.getColumns(); col++) {
for (int row = 0; row < mGame.getRows(); row++) {
int num = rand.nextInt(3) + 1;
for (int turns = 1; turns < num; turns++) {
mGame.rotateRight(col, row);
}
}
}
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
sizeSqX = getWidth() / mcolumns;
sizeSqY = getHeight() / mrows;
if (sizeSqX < sizeSqY) {
sizeSq = sizeSqX;
}
else {
sizeSq = sizeSqY;
}
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder);
//Bitmap s = BitmapFactory.decodeResource(getResources(), R.drawable.straight);
//Bitmap dl = BitmapFactory.decodeResource(getResources(), R.drawable.downleft);
int cellContent;
//square = get width / col
int square = 140;
for (int col = 0; col < mGame.getColumns(); col++) {
for (int row = 0; row < mGame.getRows(); row++) {
cellContent = mGame.getGridElem(col,row);
if (cellContent == 1) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.up_down); // Image for down position
if (cellContent == 65 && mGame.checkWin()) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.up_down_connected);
}
}
else if (cellContent == 2) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.left_right); // Right position
if (mGame.checkWin()) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.left_right_connected);
}
}
else if (cellContent == 3) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.right_down); // Down right position WORKS
if (mGame.checkWin()) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.right_down_connected);
}
else {
b = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder2); //
}
canvas.drawBitmap(b, null,new Rect(col * sizeSq, row * sizeSq,col*sizeSq+sizeSq, row*sizeSq+sizeSq), null);
//Paint paint = new Paint();
//paint.setColor(Color.WHITE);
// paint.setStyle(Paint.Style.FILL);
TextPaint tp = new TextPaint();
tp.setColor(Color.GREEN);
tp.setTextSize(70);
tp.setTypeface(Typeface.create("Courier", Typeface.BOLD));
canvas.drawText("Moves: " + String.valueOf(turns), 10, 1180, tp);
canvas.drawText("High score: ", 10, 1280, tp);
}
}
}
//SoundPoolPlayer sound = new SoundPoolPlayer(getContext());
#Override
public boolean onTouchEvent(MotionEvent event) {
//boolean eventConsumed = mGestureDetector.onTouchEvent(event);
//GameView mGameView = new GameView(getApplicationContext());
//if (eventConsumed) {
int x = (int) event.getX();
int y = (int) event.getY();
int column = getColTouched(event.getX());
int row = getRowTouched(event.getY());
try {
mGame.rotateRight(column, row);
System.out.println(mcolumns);
turns++;
MainActivity main = new MainActivity();
//main.setTurns();
main.addData();
//main.getData();
mGame.checkWin();
if (mGame.checkWin()) {
System.out.println("check win works");
invalidate();
//main.setTurns();
//main.AddData();
}
invalidate();
}
catch (ArrayIndexOutOfBoundsException err) {
System.out.println("User has pressed outside game grid - exception caught");
}
//sound.playShortResource(R.raw.click);
// sound.release();
return super.onTouchEvent(event);
}
public int getColTouched(float x) {
return (int) (x / sizeSq);
}
public int getRowTouched(float y) {
return (int) (y / sizeSq);
}
public int getCols() {
return mcolumns;
}
public void setColRow(int columns, int rows) {
this.mcolumns = columns;
this.mrows = rows;
}
public int getTurns() {
return turns;
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private GestureDetector mGestureDetector;
private ImageView imageView;
private RadioGroup radioGroup;
private int mcolumns;
private int mrows;
DatabaseHelper myDb;
String test = "test data";
int turns;
static Context appcon;
String highScore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appcon = this;
myDb = new DatabaseHelper(this);
}
public void runGame(View view){
Intent intent = new Intent(this, GameViewActivity.class);
startActivity(intent);
}
public void runInstructions(View view) {
Intent intent = new Intent(this, InstructionsActivity.class);
startActivity(intent);
}
public void setTurns() {
//GameView mGameView = new GameView(getApplicationContext());
this.turns = GameView.turns;
System.out.println("Turns: " + Integer.toString(turns));
}
public void addData() {
boolean isInserted = myDb.insertData(test);
if(isInserted == true) {
System.out.println("Data inserted");
}
else {
System.out.println("Data NOT inserted");
}
}
public void getData() {
Cursor res = myDb.getAllData();
StringBuffer buffer = new StringBuffer();
while(res.moveToNext()) {
buffer.append(res.getString(1));
}
System.out.println(buffer.toString());
}
}
In your onTouchEvent in the GameView class instead of creating a new instance of MainActivity, which I suspect is casuing the failiure, you could call the insertData method of the DatabaseHelper class directly. e.g. instead of using :-
MainActivity main = new MainActivity();
//main.setTurns();
main.addData();
//main.getData();
Try
DatabaseHelper mydb = new DatabaseHelper(this);
mydb.insertData("test");

Android: Starting intent from onClick on canvas

I recently started using a canvas over a layout because I could have animations in the background. However, I want to start a new activity after the user clicks a buttons. Here is the code so far...
public class GFX extends Activity implements View.OnTouchListener {
MyBringBack ourSurfaceView;
Paint title, play, options;
float x, y, sX, sY, fX, fY, dX, dY, aniX, aniY, scaledX, scaledY, changingRedX, changingYellowX, changingPurpleX, changingGreenX, whereIsRedXY, whereIsYellowXY, whereIsGreenXY, whereIsPurpleXY;
int whereIsRedY, redXThing, whereIsYellowY, whereIsGreenY, whereIsPurpleY, yellowXThing, greenXThing, purpleXThing, firstRun;
Bitmap green, yellow, red, purple, plus, redFixed, yellowFixed, greenFixed, purpleFixed, titleTest, playTest, playFixed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ourSurfaceView = new MyBringBack(this);
ourSurfaceView.setOnTouchListener(this);
x = 0;
y = 0;
sX = 0;
sY = 0;
fX = 0;
fY = 0;
Context ctx;
firstRun = 0;
dX = dY = aniX = aniY = scaledX = scaledY = redXThing = 0;
ctx = this;
green = BitmapFactory.decodeResource(getResources(), R.drawable.greenhairedpotatoblack);
yellow = BitmapFactory.decodeResource(getResources(), R.drawable.yellowhairedpotatoblack);
red = BitmapFactory.decodeResource(getResources(), R.drawable.redhairedpotatoblack);
purple = BitmapFactory.decodeResource(getResources(), R.drawable.purplehairedpotatoblack);
plus = BitmapFactory.decodeResource(getResources(), R.drawable.plus);
titleTest = BitmapFactory.decodeResource(getResources(), R.drawable.title);
playTest = BitmapFactory.decodeResource(getResources(), R.drawable.play);
setContentView(ourSurfaceView);
}
#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_gfx, menu);
return true;
}
#Override
protected void onPause() {
super.onPause();
ourSurfaceView.pause();
}
#Override
protected void onResume() {
super.onResume();
ourSurfaceView.resume();
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
try {
Thread.sleep(1000/60);
} catch (InterruptedException e) {
e.printStackTrace();
}
x = event.getX();
y = event.getY();
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
//if(y > play.getTextBounds("Play", );)
break;
}
return true;
}
public class MyBringBack extends SurfaceView implements Runnable {
SurfaceHolder ourHolder;
Thread ourThread = null;
boolean isRunning = false;
public MyBringBack(Context context) {
super(context);
ourHolder = getHolder();
}
public void pause(){
isRunning = false;
while(true){
try {
ourThread.join();
} catch (InterruptedException e){
e.printStackTrace();
}
break;
}
ourThread = null;
}
public void resume(){
isRunning = true;
ourThread = new Thread(this);
ourThread.start();
}
#Override
public void run() {
while(isRunning){
if(!ourHolder.getSurface().isValid())
continue;
Canvas canvas = ourHolder.lockCanvas();
canvas.drawColor(Color.BLACK);
if(firstRun == 0){
changingRedX = 0 - red.getWidth();
yellowXThing = 1;
changingYellowX = canvas.getWidth();
greenXThing = 1;
firstRun = 1;
title = new Paint();
title.setColor(Color.parseColor("#0889ec"));
title.setTextSize(180);
title.setTextAlign(Paint.Align.CENTER);
title.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
play = new Paint();
play.setTextSize(140);
play.setColor(Color.WHITE);
play.setTextAlign(Paint.Align.CENTER);
options = new Paint();
options.setTextSize(140);
options.setColor(Color.WHITE);
options.setTextAlign(Paint.Align.CENTER);
playFixed = getResizedBitmap(playTest, canvas.getWidth()/5, canvas.getHeight()/3);
redFixed = getResizedBitmap(red, canvas.getWidth()/6, (int)canvas.getWidth()/6 * (red.getHeight()/red.getWidth()));
yellowFixed = getResizedBitmap(yellow, canvas.getWidth()/6, (int)canvas.getWidth()/6 * (yellow.getHeight()/yellow.getWidth()));
greenFixed = getResizedBitmap(green, canvas.getWidth()/6, (int)canvas.getWidth()/6 * (green.getHeight()/green.getWidth()));
purpleFixed = getResizedBitmap(purple, canvas.getWidth()/6, (int)canvas.getWidth()/6 * (purple.getHeight()/purple.getWidth()));
}
if((x>(canvas.getWidth()/2)-(playFixed.getWidth()/2)&&(x<(canvas.getWidth()/2)-(playFixed.getWidth()/2) + playFixed.getWidth()))
&& ((y > 4*(canvas.getHeight()/9))&& (y<4*(canvas.getHeight()/9)+playFixed.getHeight()))){
**** HERE IS WHERE I WANT TO START THE NEW INTENT ****
}
if(whereIsRedY == 0){
whereIsRedXY = (int) (Math.random() * canvas.getHeight()) - 20;
whereIsRedY = 1;
}
if(whereIsYellowY == 0){
whereIsYellowXY = (int) (Math.random() * canvas.getHeight()) - 20;
whereIsYellowY = 1;
}
if(whereIsGreenY == 0){
whereIsGreenXY = (int) (Math.random() * canvas.getWidth()) - 20;
whereIsGreenY = 1;
}
if(whereIsPurpleY == 0){
whereIsPurpleXY = (int) (Math.random() * canvas.getWidth()) - 20;
whereIsPurpleY = 1;
}
if((changingRedX > canvas.getWidth() + redFixed.getWidth()) && redXThing == 0){
changingRedX = canvas.getWidth() + 3*(redFixed.getWidth());
whereIsRedY = 0;
redXThing = 1;
}
if((changingRedX < 0 - redFixed.getWidth()) && redXThing == 1){
changingRedX = 0 - 4*(redFixed.getWidth());
whereIsRedY = 0;
redXThing = 0;
}
if(redXThing == 0) {
changingRedX += 10;
}
if(redXThing == 1) {
changingRedX -= 10;
}
if((changingYellowX > canvas.getWidth() + yellowFixed.getWidth()) && yellowXThing == 0){
changingYellowX = canvas.getWidth() + 3*(yellowFixed.getWidth());
whereIsYellowY = 0;
yellowXThing = 1;
}
if((changingYellowX < 0 - yellowFixed.getWidth()) && yellowXThing == 1){
changingYellowX = 0 - 4*(yellowFixed.getWidth());
whereIsYellowY = 0;
yellowXThing = 0;
}
if(yellowXThing == 0) {
changingYellowX += 13;
}
if(yellowXThing == 1) {
changingYellowX -= 13;
}
if((changingGreenX > canvas.getHeight() + greenFixed.getHeight()) && greenXThing == 0){
changingGreenX = canvas.getHeight() + 3*(greenFixed.getHeight());
whereIsGreenY = 0;
greenXThing = 1;
}
if((changingGreenX < 0 - greenFixed.getHeight()) && greenXThing == 1){
changingGreenX = 0 - 4*(greenFixed.getHeight());
whereIsGreenY = 0;
greenXThing = 0;
}
if(greenXThing == 0) {
changingGreenX += 8;
}
if(greenXThing == 1) {
changingGreenX -= 8;
}
if((changingPurpleX > canvas.getHeight() + purpleFixed.getHeight()) && purpleXThing == 0){
changingPurpleX = canvas.getHeight() + 3*(purpleFixed.getHeight());
whereIsPurpleY = 0;
purpleXThing = 1;
}
if((changingPurpleX < 0 - purpleFixed.getHeight()) && purpleXThing == 1){
changingPurpleX = 0 - 4*(purpleFixed.getHeight());
whereIsPurpleY = 0;
purpleXThing = 0;
}
if(purpleXThing == 0) {
changingPurpleX += 15;
}
if(purpleXThing == 1) {
changingPurpleX -= 15;
}
canvas.drawBitmap(redFixed, changingRedX, whereIsRedXY, null);
canvas.drawBitmap(yellowFixed, changingYellowX, whereIsYellowXY, null);
canvas.drawBitmap(purpleFixed, whereIsPurpleXY, changingPurpleX, null);
canvas.drawBitmap(greenFixed, whereIsGreenXY, changingGreenX, null);
canvas.drawText("Mustache Me", (canvas.getWidth() ) / 2, (canvas.getHeight()/3), title);
//canvas.drawText("Play", canvas.getWidth()/2, canvas.getHeight()/2 + 40, play);
canvas.drawBitmap(playFixed, (canvas.getWidth()/2)-(playFixed.getWidth()/2), 4*(canvas.getHeight()/9), null);
canvas.drawText("Options", canvas.getWidth()/2, 2*(canvas.getHeight()/3), options);
ourHolder.unlockCanvasAndPost(canvas);
}
}
}
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth)
{
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
}
I labeled in my code where I want to intent to start, yet I keep getting the error: "Cannot resolve constructor Intetn(.....)"
The code I tried was this:
Intent i = new Intent(this, WhichGameActivity.class);
Thanks for any help :)
Cheers.
Use this:
new Intent(GFX.this,WhichGameActivity.class);
You can't just use this because you're inside a inner class, thus this belongs to the inner class context.
Pay attention to what Docs say about Intent constructor:
public Intent (Context packageContext, Class cls)
Create an intent for a specific component. ...
Parameters
packageContext A Context of the application package implementing this
class. cls The component class that is to be used for the
intent.
Your class MyBringBack is not a Context,so you can not use this code:
Intent i = new Intent(this, WhichGameActivity.class);
You have to store context that is received in constructor of MyBringBack as a field for example "myContext" and then use it in new Intent() like this:
Intent i = new Intent(myContext, WhichGameActivity.class);

change imageview using int

I've been stuck on this for a whole day, please help me. So I have 2 arrays filled with five dice rolls from two players and I want to set them to the according dice image that I put in my drawable. This is the original code that I have, displaying the arrays in TextView.
int player1[] = new int[5];
int player2[] = new int[5];
TextView p1Dice, p2Dice;
private void displayDice() {
StringBuffer sbfNumbers = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers.append(player1[i] + " ");
}
StringBuffer sbfNumbers2 = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers2.append(player2[i] + " ");
}
p1Dice.setText(sbfNumbers.toString());
p2Dice.setText(sbfNumbers2.toString());
I can't figure out how to get it to display the ImageView instead.
private final static int[] diceImages = new int[] { R.drawable.d1,
R.drawable.d2, R.drawable.d3, R.drawable.d4, R.drawable.d5, R.drawable.d6 };
ImageView p1Dice1, p1Dice2, p1Dice3, p1Dice4, p1Dice5;
for (int i = 0; i < 5; i++) {
p1Dice[i].setImageResource(diceImage[player1[i]]);
}
What I am missing?
Here's my full code, sorry its a mess. I just started to learn programming on my own and this is my first program. Any advice on making it better is appreciated too.
package com.kelvinblade.liardice;
import java.util.Random;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
int player1[] = new int[5];
int player2[] = new int[5];
TextView p1Dice, p2Dice, result, whosTurn, tvLog, score;
ImageView p1Dice1, p1Dice2, p1Dice3, p1Dice4, p1Dice5;
Button openDice, callDice;
EditText NumDice, DiceNum;
int NumOfDice, DiceNumber, turn;
int currentDiceQuantity, currentDiceFace;
boolean isOneWildCard = true;
int callLog[] = new int[70];
int playerOneEnergy, playerTwoEnergy;
boolean playerOneStart = true;
private final int[] diceImages = new int[] { R.drawable.d1, R.drawable.d2, R.drawable.d3, R.drawable.d4, R.drawable.d5, R.drawable.d6 };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializePlaceHolders();
startGame();
}
// Initialize the Place Holders
private void initializePlaceHolders() {
p1Dice = (TextView) findViewById(R.id.tvP1Dice);
p2Dice = (TextView) findViewById(R.id.tvP2Dice);
openDice = (Button) findViewById(R.id.bOpenDice);
callDice = (Button) findViewById(R.id.bCallDice);
whosTurn = (TextView) findViewById(R.id.tvWhosTurn);
tvLog = (TextView) findViewById(R.id.tvLog);
score = (TextView) findViewById(R.id.tvScore);
result = (TextView) findViewById(R.id.tvResult);
NumDice = (EditText) findViewById(R.id.etNumDice);
DiceNum = (EditText) findViewById(R.id.etDiceNum);
p1Dice1 = (ImageView) findViewById(R.id.ivDice1);
p1Dice2 = (ImageView) findViewById(R.id.ivDice2);
p1Dice3 = (ImageView) findViewById(R.id.ivDice3);
p1Dice4 = (ImageView) findViewById(R.id.ivDice4);
p1Dice5 = (ImageView) findViewById(R.id.ivDice5);
openDice.setOnClickListener(this);
callDice.setOnClickListener(this);
}
// Game starts here
public void startGame() {
playerOneEnergy = 4;
playerTwoEnergy = 4;
playGame();
}
// Starts level
public void playGame() {
if ((playerOneEnergy != 0) && (playerTwoEnergy != 0)) {
initialize();
player1 = rollDice();
player2 = rollDice();
displayDice();
displayTurn();
} else if (playerTwoEnergy == 0) {
result.setText("Loading Next Stage!");
startGame();
} else
result.setText("Game Over!");
}
// Initialize the Variables
private void initialize() {
turn = 0;
currentDiceQuantity = 0;
currentDiceFace = 0;
result.setText("New Game.");
tvLog.setText("Game Log:");
}
// Rolls the Dice
private int[] rollDice() {
int[] diceArray = new int[5];
Random randomDice = new Random();
for (int i = 0; i < 5; i++) {
diceArray[i] = randomDice.nextInt(6) + 1;
}
return diceArray;
}
// Displays the Dice for Player 1 & 2
private void displayDice() {
StringBuffer sbfNumbers = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers.append(player1[i] + " ");
}
StringBuffer sbfNumbers2 = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers2.append(player2[i] + " ");
}
p1Dice.setText(sbfNumbers.toString());
p2Dice.setText(sbfNumbers2.toString());
// try to display the dice array as image <here's the problem>
for (int i = 0; i < 5; i++) {
p1Dice[i].setImageResource(diceImage[player1[i]]);
}
}
// Button actions
public void onClick(View v) {
switch (v.getId()) {
case R.id.bCallDice:
try {
getCall();
} catch (Exception e) {
Dialog d = new Dialog(this);
d.setTitle("Invalid call. Please try again.");
d.show();
}
if ((validInput()) && (validCall()))
runCall();
else
result.setText("Invalid call");
break;
case R.id.bOpenDice:
checkDice();
break;
}
}
private void runCall() {
currentDiceQuantity = NumOfDice;
currentDiceFace = DiceNumber;
result.setText("Valid call");
writeLog();
displayLog();
turn++;
displayTurn();
}
private void startAImove() {
Random randomAction = new Random();
int randomCall = randomAction.nextInt(1);
if ((randomCall == 0) && (!isFirstMove()))
checkDice();
else {
while (!validCall()) {
NumOfDice = randomAction.nextInt(5) + 1;
DiceNumber = randomAction.nextInt(5) + 1;
}
runCall();
}
}
// Gets the Call from Player 1
private void getCall() {
String s = NumDice.getText().toString();
NumOfDice = Integer.parseInt(s);
String s1 = DiceNum.getText().toString();
DiceNumber = Integer.parseInt(s1);
if (DiceNumber == 1) {
isOneWildCard = false;
}
}
// Checks to see if the call is a valid input
private boolean validInput() {
int MaxNumOfDice = 5;
int MaxDiceQuantity = 6;
if ((NumOfDice <= MaxNumOfDice * 2) && (DiceNumber <= MaxDiceQuantity)) {
return true;
} else
return false;
}
// Checks to see if Valid Call
private boolean validCall() {
if (NumOfDice > currentDiceQuantity) {
return true;
} else if (((NumOfDice == currentDiceQuantity) && (currentDiceFace != 1))
&& ((DiceNumber == 1) || (DiceNumber > currentDiceFace))) {
return true;
} else {
return false;
}
}
// Writes to Log
private void writeLog() {
callLog[turn * 2] = currentDiceQuantity;
callLog[turn * 2 + 1] = currentDiceFace;
}
// Display Log
private void displayLog() {
StringBuffer sbfNumbers = new StringBuffer();
sbfNumbers.append("Game Log:\n");
for (int i = 0; i < turn + 1; i++) {
sbfNumbers.append((i + 1) + ": Player" + (i % 2 + 1) + " "
+ callLog[i * 2] + "x" + callLog[i * 2 + 1] + "\n");
}
tvLog.setText(sbfNumbers.toString());
}
// Display who's turn
public void displayTurn() {
if (whichPlayersTurn() == 1)
whosTurn.setText("Player 1's Turn...");
else {
whosTurn.setText("Player 2's Turn...");
// startAImove();
}
}
// Checks who's turn
private int whichPlayersTurn() {
boolean isTurnEven = false;
if (turn % 2 == 0)
isTurnEven = true;
if (((playerOneStart) && (isTurnEven))
|| ((!playerOneStart) && (!isTurnEven))) {
return 1;
} else
return 2;
}
// Checks if it's the first move
private boolean isFirstMove() {
if (currentDiceQuantity == 0)
return true;
else
return false;
}
// Checks the Player 1 & 2 for the Dice
private void checkDice() {
if (!isFirstMove()) {
int DiceCount = 0;
for (int i = 0; i < 5; i++) {
if (player1[i] == DiceNumber)
DiceCount++;
if (player2[i] == DiceNumber)
DiceCount++;
if ((player1[i] == 1) && (isOneWildCard))
DiceCount++;
if ((player2[i] == 1) && (isOneWildCard))
DiceCount++;
}
if (((DiceCount >= NumOfDice) && (whichPlayersTurn() != 1))
|| ((DiceCount < NumOfDice) && (whichPlayersTurn() == 1))) {
result.setText("Player 1 Wins!");
playerTwoEnergy--;
playerOneStart = false;
} else {
result.setText("Player 1 Loses!");
playerOneEnergy--;
playerOneStart = true;
}
displayWinLost();
playGame();
} else
result.setText("Can not open on first move!");
}
// Display Win / Lose
private void displayWinLost() {
StringBuffer sbfNumbers = new StringBuffer();
sbfNumbers.append("Player One Energy : " + playerOneEnergy
+ "\nPlayer Two Energy: " + playerTwoEnergy);
score.setText(sbfNumbers.toString());
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
}
Thank you so much in advanced. Any help is highly appreciated. Thanks again!!
In your code imageViews are not in an array, so you cannot do p1Dice[i] .
So please change to
private ImageView[] p1Dice = new ImageView[5];
or
p1Dice1.setImageResource(diceImage[player1[0]]);
p1Dice2.setImageResource(diceImage[player1[1]]);
p1Dice3.setImageResource(diceImage[player1[2]]);
The ImageViews are not in an array, so you cannot do p1Dice[i].something()
Change the declaration to ImageViews to this
private ImageView[] p1Dice = new ImageView[5];

Categories

Resources