I'm making an application, in this application I need the width and height of the display device. Initially I made a calculation of the width and height in one class and then instantly displayed. But to make it look more organized, I separate them in a separate class. This code in the class:
public class DisplayMeasurement extends Activity{
public int widthScreen = 0;
public int heightScreen = 0;
#SuppressWarnings("deprecation")
public void DisplayHeightWidthMeasurement(){
int Measuredwidth = 0;
int Measuredheight = 0;
Point size = new Point();
WindowManager w = getWindowManager();
if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB_MR2){
w.getDefaultDisplay().getSize(size);
Measuredwidth = size.x;
Measuredheight = size.y;
}else{
Display d = w.getDefaultDisplay();
Measuredwidth = d.getWidth();
Measuredheight = d.getHeight();
}
//int sepertiga = Measuredwidth/3;
//akhir ngukur layar
set(Measuredwidth,Measuredheight);
}
public void set(int Measuredwidth, int Measureheight){
this.widthScreen = Measuredwidth;
this.heightScreen = Measureheight;
}
public int getWidthScreen(){
return widthScreen;
}
public int getHeightScreen(){
return heightScreen;
}
}
then this is a piece of code on mainActivity:
DisplayMeasurement screenValue = new DisplayMeasurement();
int WidthScreen = screenValue.getWidthScreen();
int HeightScreen = screenValue.getHeightScreen();
TextView text1 = (TextView) findViewById(R.id.text1);
TextView text2 = (TextView) findViewById(R.id.text2);
text1.setText("lebar" + WidthScreen);
text2.setText("tinggi" + HeightScreen);
But that I get is the value 0. Is there anyone who has experienced the same thing, or are there who know about this problem.
Sorry, I'm kind of new to Android but I'll give it a go.
I'm not sure why you're trying to organise code by creating a new Activity which seems to over-complicate things.
public class DisplayMeasurement {
public int widthScreen = 0;
public int heightScreen = 0;
public void DisplayMeasurement(Context context){
Point size = new Point();
WindowManager w = (WindowManager) mContext.getSystemService(mContext.WINDOW_SERVICE);
if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB_MR2){
w.getDefaultDisplay().getSize(size);
widthScreen = size.x;
heightScreen = size.y;
} else {
Display d = w.getDefaultDisplay();
widthScreen = d.getWidth();
heightScreen = d.getHeight();
}
}
public int getWidthScreen(){
return widthScreen;
}
public int getHeightScreen(){
return heightScreen;
}
}
And then in your main activity;
DisplayMeasurement screenValue = new DisplayMeasurement(this);
int WidthScreen = screenValue.getWidthScreen();
int HeightScreen = screenValue.getHeightScreen();
TextView text1 = (TextView) findViewById(R.id.text1);
TextView text2 = (TextView) findViewById(R.id.text2);
text1.setText("lebar" + WidthScreen);
text2.setText("tinggi" + HeightScreen);
Not sure if it will work though, haven't tested it.
Also, I'm not sure why (have been only coding for 6 months) - but how is DisplayHeightWidthMeasurement() meant to be ever called, when you never call for it. All you do is:
DisplayMeasurement screenValue = new DisplayMeasurement();
and so your method: DisplayHeightWidthMeasurement, which actually has the logic to get the width and height is never called. You would need to call that first, otherwise it would just return 0, which is what you initialised.
You never call the function DisplayHeightWidthMeasurement() so the method in it set() is not called yet, so the values of height and width are zero just as you set, just as #TheIT said it is not a good way to instantiate an Activity, you can just define a Class that get the width and height of the diplay rather than use an Activity.
Related
example
What I've tried.
Please help me.. I really don't know.
I think it's related to canvas class.
CustomLineChartRenderer
It seems to me that color is not filled according to x value, but color is filled at once.
It's hard because I'm not used to canvas. Please help me.
Here are three methods for drawing lines and filling in colors.
#Override
protected void drawLinearFill(Canvas c, ILineDataSet dataSet, Transformer trans, XBounds bounds) {
final Path filled = mGenerateFilledPathBuffer;
final int startingIndex = bounds.min;
final int endingIndex = bounds.range + bounds.min;
final int indexInterval = 128;
int currentStartIndex = 0;
int currentEndIndex = indexInterval;
int iterations = 0;
// Doing this iteratively in order to avoid OutOfMemory errors that can happen on large bounds sets.
do {
currentStartIndex = startingIndex + (iterations * indexInterval);
currentEndIndex = currentStartIndex + indexInterval;
currentEndIndex = currentEndIndex > endingIndex ? endingIndex : currentEndIndex;
if (currentStartIndex <= currentEndIndex) {
generateFilledPath(dataSet, currentStartIndex, currentEndIndex, filled);
trans.pathValueToPixel(filled);
final Drawable drawable = dataSet.getFillDrawable();
if (drawable != null) {
drawFilledPath(c, filled, drawable);
} else {
//////Here part of applying color
drawFilledPath(c, filled, dataSet.getFillColor(), dataSet.getFillAlpha());
}
}
iterations++;
} while (currentStartIndex <= currentEndIndex);
}
#Override
protected void drawFilledPath(Canvas c, Path filledPath, int fillColor, int fillAlpha) {
int color = (fillAlpha << 24) | (fillColor & 0xffffff);
if (clipPathSupported()) {
Log.e("clipPathSupported","1");
int save = c.save();
c.clipPath(filledPath);
c.drawColor(color);
c.restoreToCount(save);
} else {
Log.e("clipPathSupported","2");
// save
Paint.Style previous = mRenderPaint.getStyle();
int previousColor = mRenderPaint.getColor();
// set
mRenderPaint.setStyle(Paint.Style.FILL);
mRenderPaint.setColor(color);
c.drawPath(filledPath, mRenderPaint);
// restore
mRenderPaint.setColor(previousColor);
mRenderPaint.setStyle(previous);
}
}
private void generateFilledPath(final ILineDataSet dataSet, final int startIndex, final int endIndex, final Path outputPath) {
final float fillMin = dataSet.getFillFormatter().getFillLinePosition(dataSet, mChart);
final float phaseY = mAnimator.getPhaseY();
final boolean isDrawSteppedEnabled = dataSet.getMode() == LineDataSet.Mode.STEPPED;
final Path filled = outputPath;
filled.reset();
final Entry entry = dataSet.getEntryForIndex(startIndex);
filled.moveTo(entry.getX(), fillMin);
filled.lineTo(entry.getX(), entry.getY() * phaseY);
// create a new path
Entry currentEntry = null;
Entry previousEntry = entry;
for (int x = startIndex + 1; x <= endIndex; x++) {
currentEntry = dataSet.getEntryForIndex(x);
if (isDrawSteppedEnabled) {
filled.lineTo(currentEntry.getX(), previousEntry.getY() * phaseY);
}
filled.lineTo(currentEntry.getX(), currentEntry.getY() * phaseY);
previousEntry = currentEntry;
}
// close up
if (currentEntry != null) {
filled.lineTo(currentEntry.getX(), fillMin);
}
filled.close();
}
You can use shader, same :
mRenderPaint.shader = LinearGradient(fromX, fromY, toX, toY, color1,
color2,
Shader.TileMode.CLAMP)
new to programming i know i'm doing something that's probably really obviously wrong to do with passing or using the wrong variables but i just can't work out what.
Here is my code:
public class CameraViewActivity extends Activity implements
SurfaceHolder.Callback, OnLocationChangedListener, OnAzimuthChangedListener {
private double mAzimuthReal = 0;
private double mAzimuthTheoretical = 0;
private static double AZIMUTH_ACCURACY = 5;
private double mMyLatitude = 0;
private double mMyLongitude = 0;
private List<Double> calculateAzimuthAccuracy(double azimuth) {
double minAngle = azimuth - AZIMUTH_ACCURACY;
double maxAngle = azimuth + AZIMUTH_ACCURACY;
List<Double> minMax = new ArrayList<Double>();
#Override
public void onAzimuthChanged(float azimuthChangedFrom, float azimuthChangedTo) {
mAzimuthReal = azimuthChangedTo;
mAzimuthTheoretical = calculateTheoreticalAzimuth();
pointerIcon = (ImageView) findViewById(R.id.icon);
double minAngle = calculateAzimuthAccuracy(mAzimuthTheoretical).get(0);
double maxAngle = calculateAzimuthAccuracy(mAzimuthTheoretical).get(1);
if (isBetween(minAngle, maxAngle, mAzimuthReaal) {
pointerIcon.setVisibility(View.VISIBLE);
}
else {
pointerIcon.setVisibility(View.INVISIBLE);
}
updateDescription();
}
Thanks for reading
Use
isRange(mMyLatitude, mMyLongitude, mPoi.getPoiLatitude(), mPoi.getPoiLongitude)
instead of
isRange(MyLatitude, MyLongitude, MpoiLatitude, MpoiLongitude)
FYI, its better to use small letter for naming variable.
In this function you need to pass as paramters either two locations and use their coordinates in the function inRange or you pass four coordinates and use them.
public void onAzimuthChanged(float azimuthChangedFrom, float azimuthChangedTo) {
mAzimuthReal = azimuthChangedTo;
mAzimuthTheoretical = calculateTheoreticalAzimuth();
pointerIcon = (ImageView) findViewById(R.id.icon);
double minAngle = calculateAzimuthAccuracy(mAzimuthTheoretical).get(0);
double maxAngle = calculateAzimuthAccuracy(mAzimuthTheoretical).get(1);
if (isBetween(minAngle, maxAngle, mAzimuthReal) && isRange(MyLatitude, MyLongitude, MpoiLatitude, MpoiLongitude)) {
pointerIcon.setVisibility(View.VISIBLE);
}
else {
pointerIcon.setVisibility(View.INVISIBLE);
}
updateDescription();
}
This has no meaning
isRange(MyLatitude, MyLongitude, MpoiLatitude, MpoiLongitude);
One more thing, adapt a professional naming criteria. Giving your attributes names that start with capital letters is quite MEH.
I am developing an android application for a friend of mine that is a football trainer.
He asked me to create an application that is more of a table to count the stats of the players. The image below should clear things up:
Table of the application
As you can see, every time I press the upper left button I want to add a new player two a new row with a decrement button a counter and an increment button below each stat column.
I can currently do that but each player has 10 different column counters. So considering that I want to add 25 players for the maximum I should copy my code (250 times) with an incremented value in order to gain the same functionality for each player.
I've thought about using an array or a hashmap I'm just not sure what's the best practise to do it. Any suggestions are more than welcome.
Pre-declared variables for one player:
private int counter1 = 0;
private int counter2 = 0;
private int counter3 = 0;
private int counter4 = 0;
private int counter5 = 0;
private int counter6 = 0;
private int counter7 = 0;
private int counter8 = 0;
private int counter9 = 0;
private int counter10 = 0;
private TextView textCounter1;
private TextView textCounter2;
private TextView textCounter3;
private TextView textCounter4;
private TextView textCounter5;
private TextView textCounter6;
private TextView textCounter7;
private TextView textCounter8;
private TextView textCounter9;
private TextView textCounter10;
Routine that needs to be copied 250 times:
if (playersAdded == 1) {
//Set 1
ImageButton decrementButton1 = new ImageButton(getApplicationContext());
decrementButton1.setImageDrawable(decrementDrawableScaled);
decrementButton1.setLayoutParams(layoutParams);
textCounter1 = new TextView(getApplicationContext());
textCounter1.setText(String.valueOf(counter1));
textCounter1.setLayoutParams(layoutParams);
ImageButton incrementButton1 = new ImageButton(getApplicationContext());
incrementButton1.setImageDrawable(incrementDrawableScaled);
incrementButton1.setLayoutParams(layoutParams);
decrementButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (counter1 > 0) {
counter1 -= 1;
textCounter1.setText(String.valueOf(counter1));
}
}
});
incrementButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter1 += 1;
textCounter1.setText(String.valueOf(counter1));
}
);
//End of Set 1
}
Make class Player. (Learn Object-oriented programming)
Make row for one player. (Learn how to create listView, this tutorial should help you, or just google android listView)
Make listView with players row.
I want to print the three values of each axes(scaledX , scaledY, scaledZ) of accelerometer in three TextView.
Can somebody help me?
thanks.
CODE:
MainActivity.java.
public class MainActivity extends Activity implements BluetoothAdapter.LeScanCallback {
private TextView mAccelerometerx, mAccelerometery, mAccelerometerz;
mAccelerometerx =(TextView) findViewById(R.id.ejex);
mAccelerometery =(TextView) findViewById(R.id.ejey);
mAccelerometerz =(TextView) findViewById(R.id.ejez);
private void updateAccelerometerValue(BluetoothGattCharacteristic characteristic ){
double accelerometerx = SensorTagData.extractAccelerometer(characteristic, mAccelerometerx);
double accelerometery = SensorTagData.extractAccelerometer(characteristic, mAccelerometery);
double accelerometerz = SensorTagData.extractAccelerometer(characteristic, mAccelerometerz);
mAccelerometerx.setText(String.format("%.4f", accelerometerx));
mAccelerometery.setText(String.format("%.4f", accelerometery));
mAccelerometerz.setText(String.format("%.4f", accelerometerz));
}
}
SensorData.java
public class SensorData {
public static double [] extractAccelerometer(BluetoothGattCharacteristic c) {
Integer x = c.getIntValue(FORMAT_SINT8, 0);
Integer y = c.getIntValue(FORMAT_SINT8, 1);
Integer z = c.getIntValue(FORMAT_SINT8, 2) * -1;
double scaledX = x / 64.0;
double scaledY = y / 64.0;
double scaledZ = z / 64.0;
return new double[] {scaledX, scaledY, scaledZ};
}
}
private void updateAccelerometerValue(BluetoothGattCharacteristic characteristic ){
double accelerometerx = SensorTagData.extractAccelerometer(characteristic, mAccelerometerx);
double accelerometery = SensorTagData.extractAccelerometer(characteristic, mAccelerometery);
double accelerometerz = SensorTagData.extractAccelerometer(characteristic, mAccelerometerz);
mAccelerometerx.setText(String.format("%.4f", accelerometerx)); //ERROR HERE
mAccelerometery.setText(String.format("%.4f", accelerometery)); //ERROR HERE
mAccelerometerz.setText(String.format("%.4f", accelerometerz)); //ERROR HERE
}
ERROR Type
The method extractAccelerometer(BluetoothGattCharacteristic) in the type SensorTagData is not applicable for the arguments (BluetoothGattCharacteristic, TextView)
I know I am giving more than two parameters, but if I delete "accelerometerx", "accelerometery" , "accelerometerz" the error disappears but I suppose will not see anything.
Okay so put simply i am trying to save and then load data to and from a NumberPicker. The NumberPicker values are set initially with a string array as specific values are required to be chosen from in the NumberPicker setDisplayedValues() method is used.
I dont have any trouble saving its just when it comes to loading. because im guessing i need to give the index of the position in which that value is found in the array. This is what i have been trying but to no avail
minSpinNP.setValue(Integer.parseInt(spinValues[minSpinPos]));
maxSpinNP.setValue(Integer.parseInt(spinValues[maxSpinPos]));
Ibelieve numberPicker must take an int or an array of strings.
I am also getting this error when loading the prefs()
12-12 19:57:34.724: E/AndroidRuntime(7612): Caused by: java.lang.ClassCastException:
java.lang.String cannot be cast to java.lang.Integer
12-12 19:57:34.724: E/AndroidRuntime(7612):
at android.app.SharedPreferencesImpl.getInt(SharedPreferencesImpl.java:240)
12-12 19:57:34.724: E/AndroidRuntime(7612):
at sweetbix.android.shredbox.JumpSettings.loadPrefs(JumpSettings.java:228)
any help would be appreciated :)
global variables
SeekBar switchSlider;
RadioGroup directionRadioGroup;
RadioButton fsRadioBtn;
RadioButton bsRadioBtn;
RadioButton fsBsRadioBtn;
RadioButton dirOffRadioBtn;
SeekBar corkSlider;
SeekBar spinSlider;
SeekBar grabSlider;
NumberPicker minSpinNP;
NumberPicker maxSpinNP;
Button saveBtn;
boolean safe;
int maxSpinPos;
int minSpinPos;
private int switchProbability;
private int corkProbability;
private int spinProbability;
private int grabProbability;
private int spin = 0;
private int minSpin;
private int maxSpin;
private String[] spinValues = new String[8];
strings added to spinValues
for (int i = 0; i < spinValues.length; i++) {
String rotation = Integer.toString(spin += 180);
spinValues[i] = rotation;
}
the save method used,
private void savePrefs(String key, int value){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Editor editor = prefs.edit();
editor.putInt(key, value);
editor.commit();
}
onchangelistener for the numberpicker, somecode commented but shows what i have tried.
maxSpinNP.setOnValueChangedListener(new OnValueChangeListener(){
#Override
public void onValueChange(NumberPicker picker, int oldVal,
int newVal) {
// TODO Auto-generated method stub
//maxSpin = Integer.parseInt(spinValues[maxSpinNP.getValue()]);
//maxSpin = spinValues[maxSpinNP.getValue()];
maxSpinPos = Arrays.asList(spinValues).indexOf(maxSpin);
Toast.makeText(JumpSettings.this,"maxspinpos:"+ maxSpinPos,
Toast.LENGTH_SHORT).show();
}
});
calling the save method
savePrefs("MIN_SPIN_JUMPS", minSpinPos);
savePrefs("MAX_SPIN_JUMPS", maxSpinPos);
finally calling the loadprefs method, more code commented
private void loadPrefs(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
switchProbability = prefs.getInt("SWITCH_JUMPS", 35);
switchSlider.setProgress(switchProbability);
corkProbability = prefs.getInt("CORK_JUMPS", 20);
corkSlider.setProgress(corkProbability);
spinProbability = prefs.getInt("SPIN_JUMPS", 80);
spinSlider.setProgress(spinProbability);
grabProbability = prefs.getInt("GRAB_JUMPS", 80);
grabSlider.setProgress(grabProbability);
minSpinPos = prefs.getInt("MIN_SPIN_JUMPS", 0);
maxSpinPos = prefs.getInt("MAX_SPIN_JUMPS", 7);
//minSpin = prefs.getString("MIN_SPIN_JUMPS", "180");
//minSpinNP.setValue(Integer.parseInt(spinValues[minSpinPos]));
//maxSpin = prefs.getString("MAX_SPIN_JUMPS", 1080);
//maxSpinNP.setValue(Integer.parseInt(spinValues[maxSpinPos]));
Log.e("min", "" + minSpinPos);
Log.e("max", "" + maxSpinPos);
//Log.e("prob", switchProbability + "");
}
this is line 228
minSpinPos = prefs.getInt("MIN_SPIN_JUMPS", 0);
solved it. i used this in the load preferences method
for( int i=0; i<spinValues.length ; i++ )
if( spinValues[i].equals(maxSpinPos) )
maxSpinNP.setValue(i);
numberpicker takes an int value and i thought i was getting an int value when i was trying to get the array index but i was actually getting the index and setting the variable to the value of that index
yay :)