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.
Related
I am developing something like X11 server for Android and I need some help.
I found out that applications like bVNC and Microsoft Remote Desktop client can intercept Super, Alt-Tab, Alt-F4 and almost all keyboard events.
I tried to guess what exactly is done to achieve this but failed.
I found out that after running bVNC on my phone I can run my own com.iiordanov.bVNC.RemoteCanvasActivity with simple View.OnKeyListener and focused View receives all the events I need without system response (i.e. no recents menu on Alt-Tab). But when I change package name or class name I loose this ability.
Is there anyone who can help with this please?
package com.iiordanov.bVNC;
import android.os.Build;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.widget.TextView;
public class RemoteCanvasActivity extends AppCompatActivity implements OnKeyListener {
private final static String TAG = "RemoteCanvas";
TextView log;
#Override
public void onCreate(Bundle b) {
super.onCreate(b);
log = new TextView(this);
setContentView(log);
log.setSingleLine(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
log.setDefaultFocusHighlightEnabled(false);
}
log.setOnKeyListener(this);
log.setFocusableInTouchMode(true);
log.setDrawingCacheEnabled(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
log.setFocusedByDefault(true);
}
log.requestFocus();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
#Override
public boolean onKey(View v, int keyCode, KeyEvent evt) {
if (log != null) {
log.append("Got keycode " + keyCode + " " + evt.getAction() + "\n");
final int scrollAmount = log.getLayout().getLineTop(log.getLineCount()) - log.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if (scrollAmount > 0)
log.scrollTo(0, scrollAmount);
else
log.scrollTo(0, 0);
}
return true;
}
}
117 is KeyEvent.KEYCODE_META_LEFT.
25 is KeyEvent.KEYCODE_VOLUME_DOWN.
Thank you very much.
I followed a tutorial online to create an AR app that could show my 3D models in AR.
I put my .obj and .gltf 3d model files in my assets folder,
when the I tap on a plane, the method placeObject() should run and put my model (selectObject) on the place.
but when I test it on my phone,after the plane was detected and I tapped the screen, nothing happened, I checked my logcat and it shows the error when I tapped:
2021-11-04 01:55:46.629 11172-12363/com.example.arcoretest E/ModelRenderable: Unable to load Renderable registryId='testscene.obj'
java.util.concurrent.CompletionException: java.lang.AssertionError: No RCB file at uri: testscene.obj
at java.util.concurrent.CompletableFuture.encodeThrowable(CompletableFuture.java:278)
at java.util.concurrent.CompletableFuture.completeThrowable(CompletableFuture.java:284)
at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1629)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:920)
Caused by: java.lang.AssertionError: No RCB file at uri: testscene.obj
at com.google.ar.sceneform.rendering.LoadRenderableFromSfbTask.byteBufferToSfb(LoadRenderableFromSfbTask.java:191)
at com.google.ar.sceneform.rendering.LoadRenderableFromSfbTask.lambda$downloadAndProcessRenderable$0$com-google-ar-sceneform-rendering-LoadRenderableFromSfbTask(LoadRenderableFromSfbTask.java:121)
I'm not sure where the problem is, is it my uri is wrong or I should use other 3d model format?
(I tried .obj/.fbx/.gltf but none of them worked)
(I can't use .sfb or .sfa ,I can no longer use sceneform plugin to convert files into sfa/sfb because it was deprecated)
here is my grade dependencies:
{
implementation 'com.google.ar.sceneform.ux:sceneform-ux:1.15.0'
implementation 'com.google.ar:core:1.15.0'
implementation 'com.google.ar.sceneform:assets:1.15.0'
...
}
My mainActivity.java:
package com.example.arcoretest;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import com.google.ar.core.Anchor;
import com.google.ar.core.HitResult;
import com.google.ar.core.Plane;
import com.google.ar.sceneform.AnchorNode;
import com.google.ar.sceneform.rendering.ModelRenderable;
import com.google.ar.sceneform.rendering.Renderable;
import com.google.ar.sceneform.ux.ArFragment;
import com.google.ar.sceneform.ux.TransformableNode;
public class MainActivity extends AppCompatActivity {
private ArFragment fragment;
private Uri selectObject;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectObject = Uri.parse("testscene.obj");
fragment = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.sceneFormFragment);
//when tapped on a plane, code below will run
fragment.setOnTapArPlaneListener(
(HitResult hitResult, Plane plane, MotionEvent motionEvent)->{
Anchor anchor = hitResult.createAnchor();
placeObject(fragment,anchor,selectObject);
}
);
}
//this method put 3d model in scene
private void placeObject(ArFragment fragment, Anchor anchor,Uri model){
ModelRenderable.builder()
.setSource(fragment.getContext(),model)
.build()
.thenAccept( renderable -> addNodeToScene(fragment,anchor,renderable))
.exceptionally((throwable -> {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(throwable.getMessage())
.setTitle("Error!");
AlertDialog dialog = builder.create();
dialog.show();
return null;
}));
}
private void addNodeToScene(ArFragment fragment, Anchor anchor, Renderable renderable){
AnchorNode anchorNode = new AnchorNode(anchor);
TransformableNode node = new TransformableNode(fragment.getTransformationSystem());
node.setRenderable(renderable);
node.setParent(anchorNode);
fragment.getArSceneView().getScene().addChild(anchorNode);
node.select();
}
}
and I put my 3d model files in assets folder like this:
I would recommend to update to the latest version of SceneForm. This is a community maintained version, with the latest dependencies of ArCore, Filament and Android. For your usecase the 3d-model-viewer sample might be interesting.
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
I'm working on an app that involved comparing to numbers inputted by the user via text box, but wen I put in any if statements the program crashes whenever they are called. Otherwise the program runs just fine without any crashes or errors.
package improvecredit.app.basic;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.text.Editable;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class ImprovrCreditBasicActivity extends Activity {
/** Called when the activity is first created. */
public int minCredScore = 300;
public int maxCredScore = 850;
public int inputScore;
public int idealScore;
public Editable inputString;
public Editable idealString;
public EditText user;
public EditText desired;
public TextView output;
public Button submit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
user = (EditText) findViewById(R.id.user_text);
desired = (EditText) findViewById(R.id.desired_text);
output = (TextView) findViewById(R.id.output_text);
submit = (Button) findViewById(R.id.submit_button);
//submit.setOnClickListener(new View.OnClickListener());
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//inputString = user.getText();
//idealString = desired.getText();
inputScore = Integer.getInteger(user.getText().toString());
idealScore = Integer.getInteger(desired.getText().toString());
if (inputScore >= 0 && idealScore >= 0){
if (inputScore < minCredScore || idealScore < minCredScore){
output.setText("Invalid Entries");
}
if (inputScore > maxCredScore || idealScore > maxCredScore){
output.setText("Invalid Entries");
}
if (inputScore > idealScore){
output.setText("Nice Credit Score!");
}
if (inputScore < idealScore){
output.setText("For more information on how to improve your credit score, please visit" + "/n" + "http://www.creditscoresandcredit.com/");
}
}
else{
output.setText("Please enter valid credit scores");
}
}
});
}
If someone can point out what may have been done wrong in the code I would really appreciate it.
On first glance, don't use Integer.getInteger(), use Integer.parseInt().
If that doesn't fix it, please include the crash log from the console so we can see exactly what exception is being raised.
I'm betting that there is a null value introduced. If you check for null before using the variables idealScore and inputScore in the If statement, it will avoid this error. Until you paste the error trace, we can only guess for you.
I am working on an android beginner's tutorial that is a tip calculator. It runs properly, but I was wondering how to replace the else-if statement with a switch statement. Not that it is that important for the purposes of this program, but I'm just trying to wrap my mind around the syntax.
package com.android.tipcalc;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Button;
import android.widget.RadioButton;
import android.view.View;
public class tipcalc extends Activity
{
private EditText txtbillamount;
private EditText txtpeople;
private RadioGroup radiopercentage;
private RadioButton radio15;
private RadioButton radio18;
private RadioButton radio20;
private TextView txtperperson;
private TextView txttipamount;
private TextView txttotal;
private Button btncalculate;
private Button btnreset;
private double billamount = 0;
private double percentage = 0;
private double numofpeople = 0;
private double tipamount = 0;
private double totaltopay = 0;
private double perperson = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
private void initControls()
{
txtbillamount = (EditText)findViewById(R.id.txtbillamount);
txtpeople = (EditText)findViewById(R.id.txtpeople);
radiopercentage = (RadioGroup)findViewById(R.id.radiopercentage);
radio15 = (RadioButton)findViewById(R.id.radio15);
radio18 = (RadioButton)findViewById(R.id.radio18);
radio20 = (RadioButton)findViewById(R.id.radio20);
txttipamount=(TextView)findViewById(R.id.txttipamount);
txttotal=(TextView)findViewById(R.id.txttotal);
txtperperson=(TextView)findViewById(R.id.txtperperson);
btncalculate = (Button)findViewById(R.id.btncalculate);
btnreset = (Button)findViewById(R.id.btnreset);
btncalculate.setOnClickListener(new Button.OnClickListener() {
public void onClick (View v){ calculate(); }});
btnreset.setOnClickListener(new Button.OnClickListener() {
public void onClick (View v){ reset(); }});
}
private void calculate()
{
billamount=Double.parseDouble(txtbillamount.getText().toString());
numofpeople=Double.parseDouble(txtpeople.getText().toString());
if (radio15.isChecked()) {
percentage = 15.00;
} else if (radio18.isChecked()) {
percentage = 18.00;
} else if (radio20.isChecked()) {
percentage = 20.00;
}
tipamount=(billamount*percentage)/100;
totaltopay=billamount+tipamount;
perperson=totaltopay/numofpeople;
txttipamount.setText(Double.toString(tipamount));
txttotal.setText(Double.toString(totaltopay));
txtperperson.setText(Double.toString(perperson));
}
private void reset()
{
txtbillamount.setText("");
txtpeople.setText("");
radiopercentage.clearCheck();
radiopercentage.check(R.id.radio15);
txttipamount.setText("...");
txttotal.setText("...");
txtperperson.setText("...");
}
}
What the people above me said is correct, but for the sake of using a switch statement for the hell of it, you could set an OnCheckedChangedListener on your RadioGroup, then use a class like this:
private class MyCheckedChangedListener implements OnCheckedChangeListener {
#Override
public void onCheckedChanged( RadioGroup group, int checkedId ) {
switch (checkedId) {
case R.id.radio15:
percentage = 15f;
break;
case R.id.radio18:
percentage = 18f;
break;
case R.id.radio20:
percentage = 20f;
break;
}
}
}
A switch is used on one variable - i.e. you have x, which can equal 3,5 or 7. Then you switch x and give several cases - what to do on each possible value (you can also have a default case, when none of the given values match). In your case, you're checking several different variables, so if ... else if ... else is the correct method. You can, of course, make the radio boxes set a shared variable, which you can then switch.
If you're talking about the if-else statements in calculate(), you can't replace it directly with a switch statement. The case values in a switch statement need to be compile-time constants (either integers or enum values). Besides, the if-else here perfectly expresses the logic of what you are trying to do.
You could compute a "switch test value" based on the states of radio15, radio18, and radio20 (say, an integer from 0 to 8, based on the eight possible combinations of values) and switch on that, but I would strongly recommend against such an approach. Not only would it needlessly complicate and obscure the logic of what's going on, you would be cursing yourself if you needed to maintain the code six months from now after you had forgotten the clever trick.