multiple showcaseviews android - java

How can I add multiple showcaseviews to my layout...
I've tried this:
import com.github.amlcurran.showcaseview.sample.R;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class MultipleShowcaseSampleActivity extends Activity {
private static final float SHOWCASE_KITTEN_SCALE = 1.2f;
private static final float SHOWCASE_LIKE_SCALE = 0.5f;
//ShowcaseViews mViews;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample_legacy);
findViewById(R.id.buttonLike).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), R.string.like_message, Toast.LENGTH_SHORT).show();
}
});
//mOptions.block = false;
// mViews = new ShowcaseViews(this,
// new ShowcaseViews.OnShowcaseAcknowledged() {
// #Override
// public void onShowCaseAcknowledged(ShowcaseView showcaseView) {
// Toast.makeText(MultipleShowcaseSampleActivity.this, R.string.dismissed_message, Toast.LENGTH_SHORT).show();
// }
// });
// mViews.addView( new ShowcaseViews.ItemViewProperties(R.id.image,
// R.string.showcase_image_title,
// R.string.showcase_image_message,
// SHOWCASE_KITTEN_SCALE));
// mViews.addView( new ShowcaseViews.ItemViewProperties(R.id.buttonLike,
// R.string.showcase_like_title,
// R.string.showcase_like_message,
// SHOWCASE_LIKE_SCALE));
// mViews.show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
enableUp();
}
}
You can see the comment part, When I uncomment Showcaseview cant found those methods so maybe ShowcaseViews missing, anyway I tried to copy and create that class, but still need methods from showcaseview that cant be found.
Help Me.
Update: Ok according the answer below, I have a problem:
mViews = new ShowcaseView(this,
new ShowcaseView.setOnShowcaseEventListener() {
#Override
public void onShowCaseAcknowledged(ShowcaseView showcaseView) {
Toast.makeText(MultipleShowcaseSampleActivity.this, R.string.dismissed_message, Toast.LENGTH_SHORT).show();
}
});
mViews.addView( new ShowcaseView.ItemViewProperties(R.id.image,
R.string.showcase_image_title,
R.string.showcase_image_message,
SHOWCASE_KITTEN_SCALE));
mViews.addView( new ShowcaseView.ItemViewProperties(R.id.buttonLike,
R.string.showcase_like_title,
R.string.showcase_like_message,
SHOWCASE_LIKE_SCALE));
mViews.show();
On new ShowcaseView.setOnShowcaseEventListener() Cannot be resolve to a type
then new ShowcaseView.ItemViewProperties Cannot be resolve to a type too.

The library doesn't have any class called ShowCaseViews. It only has a class ShowCaseView.
If you are following this github example you have to have the class given in the link
EDIT Okay let me try and explain classes
There are 2 classes
ShowcaseView (in the library)
ShowcaseViews (in the example on Github)
You cannot say ShowcaseView.ItemProperties because ShowcaseView doesn't have them. They belong to ShowcaseViews. Hence they cannot be resolved or found.
OnShowcaseEventListener is a whole different class, contained in neither one of these but just exists separately and hence also when you say ShowcaseView.OnShowcaseEventListener it can't be resolved.
Change ShowcaseView.OnShowcaseEventListener to just OnShowcaseEventListener and ShowcaseView.ItemPropertiesto ShowcaseViews.ItemProperties

Related

Firebase Realtime Database - Data from Code doesn't "reach" the database

I'm working with Firebase's realtime database in order to make a recipe application in android studio. The code runs fine and nothing crashes, but every time it's supposed to send information to the database, it does not. I attempted to create a shell for it to put data into, and instead, I saw it erase it once it got past the part where it was supposed to send the data. I've done all the required imports, implementations and dependencies according to their documentation, as well as wrote the code according to it too, but it doesn't seem to work.
Firebase Realtime Database before I send data, plus rules screenshot:
Firebase RD before
Firebase RD rules
After it runs the logic to send the data, I see it go red and disappear, like it was deleted, and nothing is left behind.
Here is my HomeScreen.java code:
package com.capteamfour.recipeappdatabase;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
public class HomeScreen extends AppCompatActivity {
final FirebaseDatabase mDatabase = FirebaseDatabase.getInstance();
DatabaseReference mDatabaseUsers = mDatabase.getReference("USERS");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
newUser(FirebaseAuth.getInstance().getCurrentUser().getDisplayName(),
FirebaseAuth.getInstance().getCurrentUser().getEmail());
String username = FirebaseAuth.getInstance().getCurrentUser().getDisplayName();
String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
TextView userWelcome = (TextView) findViewById(R.id.userWelcome);
FloatingActionButton addRecipe = (FloatingActionButton) findViewById(R.id.addRecipeButton);
ImageButton userProfile = (ImageButton) findViewById(R.id.userProfileButton);
// Welcomes the current user
userWelcome.setText("Welcome, " + username + "!");
// Creates a listener for the "add recipe" button; takes user to recipe form activity
addRecipe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent toRecipeForm = new Intent(HomeScreen.this, recipeForm.class);
startActivity(toRecipeForm);
}
});
// Creates a listener for the "user Profile Button" button; takes user to profile activity
userProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ToProfile = new Intent(HomeScreen.this, Profile.class);
startActivity(ToProfile);
}
});
}
public void newUser(String name, String email)
{
userProfile user = new userProfile(name, email);
System.out.println("This is what I need to send: " + mDatabaseUsers.setValue(user));
mDatabaseUsers.setValue(user);
}
}
I declare a database instance and create a reference to the USERS path as global variables, and then made a function newUser(String name, String email) that creates an instance of a userProfile() class for me and is supposed to then send it to the database using the next line (the Sys.out was me trying to see what it was attempting to send if anything at all).
userProfile class code:
package com.capteamfour.recipeappdatabase;
import com.google.firebase.database.IgnoreExtraProperties;
import java.util.ArrayList;
import java.util.List;
#IgnoreExtraProperties
public class userProfile {
private String username;
private String email;
private List<Recipe> subRecipes = new ArrayList<>();
// Not yet implemented
private List<Recipe> favRecipes = new ArrayList<>();
private List<Recipe> savedRecipes = new ArrayList<>();
// A user profile will include their name, the recipes they've submitted, as well as recipes they've
// favorited or saved to their profile. Saved recipes are private to the user.
public userProfile() {
// Default constructor for DataSnapshot.getValue(userProfile.class) calls
}
public userProfile(String usernameIn, String emailIn)
{
this.username = username;
this.email = email;
}
public String getUsername () {
return this.username;
}
public String getEmail() {
return this.email;
}
/*
Each of these add functions will check the length of the given array and either
add to the end of it if there's already results, or just adds it on the empty array.
Example: array empty, then array[0] = recipe
array has values, then array[length + 1] = recipe
*/
public void addSubRecipe (Recipe recipe) {
int size = this.subRecipes.size();
if (size == 0) {
subRecipes.add(recipe);
}
else {
subRecipes.add(size+1, recipe);
}
}
public List<Recipe> getSubRecipes() {
return subRecipes.subList(0, (subRecipes.size()));
}
/*
These are commented out to prevent additional bugs and confusion while they're not implemented
public void addSavedRecipe (Recipe recipe) {
int size = this.savedRecipes.size();
if (size == 0) {
savedRecipes.add(recipe);
}
else {
savedRecipes.add(size + 1, recipe);
}
}
public List<Recipe> getSavedRecipes() {
return this.savedRecipes.subList(0, (subRecipes.size() + 1));
}
/*public void addFavRecipe (Recipe recipe) {
int size = this.favRecipes.size();
if (size == 0) {
favRecipes.add(recipe);
}
else {
favRecipes.add(size + 1, recipe);
}
}
public List<Recipe> getFavRecipes() {
return this.favRecipes.subList(0, (subRecipes.size() + 1));
}*/
}
In this class, I made sure to have an empty constructor with additional constructors and the usual get/set functions so that the database could work with it.
I appreciate any and all pointers that anyone could provide on how to fix this issue. This is for my college capstone course, and it's holding us up quite drastically for what appears to be no good reason. Thanks everyone.

How to extend Activity in a Java class already extended [duplicate]

This question already has answers here:
Extending from two classes
(13 answers)
Closed 7 years ago.
I'm developing an AR Android App using Metaio. I need to show some data when a real object has been tracked. To do this I register a callback, this is the best way that I have found.
Unfortunately to use correctly getFragmentManager(), I need to import Activity properties but i can't extend the class (already extended).
I think that getContext is the right way, but I do not know how to implement it.
This is the callback register in main activity:
metaioSDK.registerCallback(new ProvaTracking());
This is the Tracking class:
package com.metaio.Example;
import android.annotation.TargetApi;
import android.os.Build;
import android.util.Log;
import com.metaio.sdk.jni.IMetaioSDKCallback;
import com.metaio.sdk.jni.TrackingValues;
import com.metaio.sdk.jni.TrackingValuesVector;
public class ProvaTracking extends IMetaioSDKCallback {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onTrackingEvent(TrackingValuesVector trackingValuesVector) {
super.onTrackingEvent(trackingValuesVector);
for (int i=0; i<trackingValuesVector.size(); i++)
{
final TrackingValues v = trackingValuesVector.get(i);
if (v.isTrackingState())
{
TestFragment trendsFragment = new TestFragment();
getFragmentManager().beginTransaction().add(android.R.id.content, trendsFragment).commit();
Log.d("Alessandro", "Works!!");
}
}
}
}
Add a constructor that takes in Context (Note that you want the Activity context, not the application context)
so you would change your class to be:
public class ProvaTracking extends IMetaioSDKCallback {
private Contect mCtx;
public ProvaTracking(Context context) {
mCtx = context;
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onTrackingEvent(TrackingValuesVector trackingValuesVector) {
super.onTrackingEvent(trackingValuesVector);
for (int i=0; i<trackingValuesVector.size(); i++)
{
final TrackingValues v = trackingValuesVector.get(i);
if (v.isTrackingState())
{
TestFragment trendsFragment = new TestFragment();
if (mCtx instanceof Activity)
((Activity) mCtx).getFragmentManager().beginTransaction().add(android.R.id.content, trendsFragment).commit();
Log.d("Alessandro", "Works!!");
}
}
}
}
then call it with metaioSDK.registerCallback(new ProvaTracking(getContext()));

Calling values from an array in the string.xml file in an Android app

I have built a fortune cook app that previously currently has values hardcoded into an array
FortuneActivity.java
package juangallardo.emofortunecookie;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class FortuneActivity extends Activity {
private FortuneBox mFortuneBox = new FortuneBox();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fortune);
// Declare our View variables and assign them the Views from the layout file
final TextView fortuneLabel = (TextView) findViewById(R.id.fortuneTextView);
Button showFortuneButton = (Button) findViewById(R.id.showFortuneButton);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
String fortune = mFortuneBox.getFortune();
// Update the label with dynamic fortune
fortuneLabel.setText(fortune);
}
};
showFortuneButton.setOnClickListener(listener);
}
}
FortuneBox.java
package juangallardo.emofortunecookie;
import java.util.Random;
public class FortuneBox {
public String[] mFortunes = {
"What is the point?",
"Sometimes it is best to just sleep in.",
#98 other fortunes...
};
// Methods (abilities)
public String getFortune() {
String fortune = "";
// Randomly select a fortune
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(mFortunes.length);
fortune = mFortunes[randomNumber];
return fortune;
}
}
The problem is that now I want to add a Spanish version. So I realize that i should add that array into the strings.xml.
I looked up string resources on the Android developer page. and it gave me the idea to add this to my code
strings.xml
<string-array name="emo_fortunes">
<item>What is the point?</item>
<item>Sometimes it is best to just sleep in.</item>
</string-array>
But now I am stuck on where to add this part that has the part about Resources, etc.
I followed along to a tutorial from Treehouse about strings but my app kept crashing.
Basically the change that I made was to make the original array into
FortuneBox.java
# above unchanged from previous code
public String[] mFortunes;
# below unchanged from previous code
FortuneActivity.java
# same imports as before
public class FortuneActivity extends Activity {
private FortuneBox mFortuneBox = new FortuneBox();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fortune);
Resources resources = getResources();
final String[] mFortuneBox = resources.getStringArray(R.array.emo_fortunes);
// Declare our View variables and assign them the Views from the layout file
final TextView fortuneLabel = (TextView) findViewById(R.id.fortuneTextView);
Button showFortuneButton = (Button) findViewById(R.id.showFortuneButton);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
String fortune = mFortuneBox.getFortune();
// Update the label with dynamic fortune
fortuneLabel.setText(fortune);
}
};
showFortuneButton.setOnClickListener(listener);
}
}
These were my errors, but not sure where to go from here as I am new to Android and I have not touched Java since college.
log
FortuneActivity.java
FortuneBox.java
Mikki has the right answer, but it is a little confusing. In your code above, you are using the same name for two different variables: mFortuneBox. This is the root of your trouble:
private FortuneBox mFortuneBox = new FortuneBox();
...
final String[] mFortuneBox = resources.getStringArray(R.array.emo_fortunes);
Change the second one to a different name, like this, and the errors go away:
final String[] fortunes = resources.getStringArray(R.array.emo_fortunes);
However, you still aren't using these fortunes from the array anywhere. You can actually delete fortunes from your Activity and move it to your FortuneBox class instead. This is slightly tricky, though, as you need to know what the context is to get a string array resource in your other class. The context is the Activity, so you need to pass this along as a parameter when you create your FortuneBox object.
I'd recommend a slight restructuring. Below are the two files that should work for you:
FortuneActivity.java
public class FortuneActivity extends Activity {
private FortuneBox mFortuneBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fortune);
mFortuneBox = new FortuneBox(this);
// Declare our View variables and assign them the Views from the layout file
final TextView fortuneLabel = (TextView) findViewById(R.id.fortuneTextView);
Button showFortuneButton = (Button) findViewById(R.id.showFortuneButton);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
String fortune = mFortuneBox.getFortune();
// Update the label with dynamic fortune
fortuneLabel.setText(fortune);
}
};
showFortuneButton.setOnClickListener(listener);
}
}
FortuneBox.java
public class FortuneBox {
public String[] mFortunes;
public FortuneBox(Context context) {
Resources resources = context.getResources();
mFortunes = resources.getStringArray(R.array.emo_fortunes);
}
// Methods (abilities)
public String getFortune() {
String fortune = "";
// Randomly select a fortune
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(mFortunes.length);
fortune = mFortunes[randomNumber];
return fortune;
}
}
Your problem is simple. You can not access a non-final from an inner class (in this case your OnClickListener).
final String[] mFortuneBox = resources.getStringArray(R.array.emo_fortunes);
Try just changing the line to look like this one above.
Hope it helps.
The mFortuneBox variable in the previous way you have used is an object of FortuneBox class and hence this call mFortuneBox.getFortune() works.
In the later changed code, you have made mFortuneBox variable a reference to an Array of strings. But still tried calling mFortuneBox.getFortune(). 'getFortune()' is a method of FortuneBox class right, so you can call it with an object of Forune Box class itself.
Try doing this:
final String[] fortuneArray = resources.getStringArray(R.array.emo_fortunes);
and
private FortuneBox mFortuneBox = new FortuneBox();
Now call mFortuneBox.getFortune(fortunearray) sending it this array to the getfortune method.
Now let the getFortune() method randomly pick one from this array passed and return the random string picked

ArcGIS Runtime SDK for Android zooming to a feature from a spinner dropdown list

I am relatively new to Java and working with the ArcGIS Runtime SDK for Android. I am making an app where the user selects the parcel id from spinner list. If the user clicks on a 'ZOOM' button the map should zoom to the parcel that was selected. Here is my code:
package gist8010.main;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import com.esri.android.map.MapView;
import com.esri.android.map.ags.ArcGISDynamicMapServiceLayer;
import com.esri.android.map.ags.ArcGISTiledMapServiceLayer;
import com.esri.core.geometry.Envelope;
import com.esri.core.geometry.Point;
import com.esri.core.map.Feature;
import com.esri.core.map.FeatureResult;
import com.esri.core.tasks.query.QueryParameters;
import com.esri.core.tasks.query.QueryTask;
public class Spinner_WalkActivity extends Activity {
MapView mMapView;
Button mBtnZoom;
ArcGISDynamicMapServiceLayer mDynamicLayer;
Spinner mSpnParcels;
String mMapServiceURL = "http://indy14.athena.bcit.ca:8080/"
+ "esri_rest/services/gist_8010_test_ms/MapServer";
int mLotLayerID = 0;
String mLotLayerURL = mMapServiceURL + "/" + mLotLayerID;
String mLotNumColName = "PARCELS_ID";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/** Allow querying on main thread */
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
/** Create spinner and button */
setMapView();
this.mBtnZoom = (Button) findViewById(R.id.btnZoom);
mBtnZoom.setOnClickListener(new OnClickListener() {
/** Upon click of zoom button, invoke th zoomtoFeature Method */
public void onClick(View v) {
zoomToFeature(v);
}
});
this.mSpnParcels = (Spinner) findViewById(R.id.spnParcels);
/** Add Layer to map */
mDynamicLayer = new ArcGISDynamicMapServiceLayer(mMapServiceURL);
mMapView.addLayer(mDynamicLayer);
QueryParameters qryLotNums = new QueryParameters();
qryLotNums.setReturnGeometry(false);
qryLotNums.setOutFields(new String[] { mLotNumColName });
qryLotNums.setWhere(mLotNumColName + ">0");
com.esri.core.tasks.query.QueryTask qtask = new com.esri.core.tasks.query.QueryTask(
mLotLayerURL);
try {
FeatureResult fSet = qtask.execute(qryLotNums);
ArrayList<String> listOfLotsNums = new ArrayList<String>();
Feature tmpFeat;
for (Object featAsObj : fSet) {
tmpFeat = (Feature) featAsObj;
listOfLotsNums.add(tmpFeat.getAttributeValue(mLotNumColName)
.toString());
}
ArrayAdapter<String> adtTmp = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item,
listOfLotsNums);
mSpnParcels.setAdapter(adtTmp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}// of catch
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
mMapView.pause();
}
#Override
protected void onResume() {
super.onResume();
mMapView.unpause();
}
// =============================================================================
// Zooms the map the the MBR of the feature selected in the spinner
// import android.view.View;
// =============================================================================
public void zoomToFeature(View v) {
QueryParameters zoomQuery = new QueryParameters();
zoomQuery.setReturnGeometry(true);
zoomQuery.setOutFields(new String[] { mLotNumColName });
zoomQuery.setWhere(mLotNumColName + "=" + mSpnParcels.getSelectedItem());
QueryTask qtask = new QueryTask(mLotLayerURL);
try {
FeatureResult fset = qtask.execute(zoomQuery);
Feature tmpFeat = (Feature) fset.iterator().next();
Envelope envelope = new Envelope();
envelope.queryEnvelope((Envelope) tmpFeat.getGeometry());
getMapView().setExtent(envelope);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// =============================================================================
// getter for the main map
// =============================================================================
private MapView getMapView() {
// =============================================================================
// if MapView is underlined in red, change the name to match your
// MapView
// =============================================================================
return mMapView;
}
// =============================================================================
// setter for the main map
// =============================================================================
private void setMapView() {
// ========================================================================
// if mapView is underlined in red then sync class-level var names
// if R.id.map is underlined in red ensure that you added the xml
// fragment
// such as "MapView Generic" to a layout
// ========================================================================
mMapView = (MapView) findViewById(R.id.map);
}
}
After attempting to debug, I think my issue is with the Envelope class. The queryEnvelope method accepts a Envelope argument. As you can see, I cast the geometry of the Feature tmpFeat from a geometry type into a Envelope type.
When I run the application on my phone I get an System.Err in my log Cat saying:
java.lang.ClassCastException: com.esri.core.geometry.Polygon cannnot be cast to com.esri.core.geometry.Envelope
Am I doing the casting incorrectly? I cannot think of another way of linking my Envelope instance with the geometry of the feature class i want to zoom to.
Envelop is a child class of com.esri.core.geometry.Geometry, not vice versa. I guess this is why you fail when do the cast.
https://developers.arcgis.com/android/api-reference/reference/com/esri/core/geometry/Envelope.html
As it to your question, I guess envelop is not necessary to zoom to a feature. MapView.zoomToResolution(Point centerPt, double res) or zoomTo(Point centerPt, float factor) may be a better choice. You may find these sample codes helpful:
https://developers.arcgis.com/android/sample-code/geocoding/

I can't seem to find android.R.id.radio0?(among others)

i'm dooing this tutorial and at one point he uses the R.id.xxxx where x is the name/id of a control I'm using, if I understood it correctly.
Now I have two of those R thing's -.-' and one is android.R and the other is dk.ilizane.android.temperatur.R which doesn't contain any id at all so I kinda figured I will be using android.R.id but i'm looking for editText1, radio0, radio1 and it doesn't contain any of those.
Is there anyone kind enough to try explain this to me? I'm trying to learn this so I would appreciate if the answer wasn't just the correct code but an answer which I can
My code:
package dk.ilizane.android.temperatur;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class Omregn extends Activity
{
private EditText text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (EditText) findViewById(android.R.id.editText1);
}
public void myClickHandler(View view) {
switch (view.getId())
{
case android.R.id.button1:
RadioButton celsiusButton = (RadioButton) findViewById(dk.ilizane.android.temperatur.R);
RadioButton fahrenheitButton = (RadioButton) findViewById(android.R.id.radio1);
if (text.getText().length() == 0)
{
Toast.makeText(this, "Please enter a valid number", Toast.LENGTH_LONG).show();
return;
}
float inputValue = Float.parseFloat(text.getText().toString());
if(celsiusButton.isChecked()){
text.setText(String.valueOf(convertFahrenheitToCelsius(inputValue)));
}else {
text.setText(String.valueOf(convertCelsiusToFahrenheit(inputValue)));
}
if(fahrenheitButton.isChecked()){
fahrenheitButton.setChecked(false);
celsiusButton.setChecked(true);
}
else
{
fahrenheitButton.setChecked(true);
celsiusButton.setChecked(false);
}
break;
}
}
private float convertFahrenheitToCelsius(float fahrenheit){
return ((fahrenheit - 32) * 5 / 9);
}
private float convertCelsiusToFahrenheit(float celsius){
return ((celsius *9) / 5) + 32;
}
}
It should be in dk.ilizane.android.temperatur.R.id.radio1. If you look at the tutorial in the main.xml file the ids of the RadioButtons are radio0 and radio1. Your projects custom resources will be compiled into a class named R in your package. In Eclipse there should be a gen src directory that contains the java file.
Do you have a main.xml under /res/layout/? The R file you mentioned is generated as a way to reference your project resources. Check that you have the same resources defined as the ones in the tutorial. The R file will then exist as dk.ilizane.android.temperatur.R in the /gen directory.
I had this problem before, for some reason I had an import android.R; which causes conflict between import android.R; & com.packagename.R. If you delete the import android.R;, there will be no conflict & your code will compile.
But, if you really need the import android.R; then you have to specify which R you want.
For example, if you want to reference a View in you project you have to refer to the full path of the View like this com.packagename.R.id.viewName.

Categories

Resources