So I am a complete newb, and am currently taking an intro to Mobile Programming course in which we use Android (I have some experience with Java). I am trying to do a simple assignment which displays a text field and an image, and upon entering the correct "password" and pressing enter, the image changes.
Should be so simple! But I am having a really hard time with this and can't figure out what I am doing wrong, even after doing a good bit of searching (I assume it is something super obvious and I'm missing it).
Here is my code:
package CS285.Assignment1;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.ImageView;
public class DisplayImage extends Activity
implements OnKeyListener{
private EditText enteredText;
private String pass = "monkey";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
enteredText = (EditText)findViewById(R.id.passField);
enteredText.setOnKeyListener(this);
}
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)){
// Perform action on key press
switchImage();
return true;
}
return false;
}
public void switchImage(){
if(enteredText.getText().toString() == pass){
ImageView imgView = (ImageView)findViewById(R.id.Image);
imgView.setImageResource(R.drawable.marmoset);
}
}
}
and my main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:id="#+id/textPrompt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ff993300"
android:text="Please enter password to see my real picture:"
>
</TextView>
<EditText android:id="#+id/passField"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
</EditText>
<ImageView
android:id="#+id/Image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:src="#drawable/airplane"
/>
</LinearLayout>
I thought at first that I was not properly extracting the String from "enteredText" so the comparison to the "password" wasn't happening correctly, but I have since tried just printing the enteredText and it works fine.
Totally frustrated--Any help would be greatly appreciated!
Daniel
if(enteredText.getText().toString() == pass) should be if(enteredText.getText().toString().equals(pass)).
As a stylistic matter, you should not do the checking within the switch image function - you should check that the password matches and then call the switch image function.
Related
I'm trying to make a simple number guessing game in android. A random number is generated when the app in launched and the user has to guess the number. The result is displayed in the form of a long toast. But when I run the app and try and enter a number the emulator says: "unfortunately High Low Game has stopped working". I have tried resetting the app and also clearing data from my emulators settings menu but it didn't make a difference. I sense something is wrong with my java code but haven't been able to figure out what is the problem so far.
Here is the java code:
package com.example.pooria.hilowgame;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.Random;
import android.widget.EditText;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
int randomNum;
public void buttonClicked(View view){
EditText numField=(EditText) findViewById(R.id.numField);
int numFieldVal= Integer.parseInt(numField.toString());
String toastMessage= "";
if(numFieldVal>randomNum){
toastMessage= "Higher";
}else if(numFieldVal==randomNum){
toastMessage= "You made the right guess!!!";
}else{
toastMessage= "Lower";
}
Toast.makeText(getApplicationContext(),toastMessage,Toast.LENGTH_LONG).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random randomGenerator= new Random();
int randomNum= randomGenerator.nextInt(101);
}
}
and the xml code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.pooria.hilowgame.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Guess the random number"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp"
android:gravity="center_horizontal" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Guess!!!"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:onClick="buttonClicked" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/numField"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="34dp" />
</RelativeLayout>
Thanks
package com.example.pooria.hilowgame;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.Random;
import android.widget.EditText;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
int randomNum; <--------
public void buttonClicked(View view){
EditText numField=(EditText) findViewById(R.id.numField);
int numFieldVal= Integer.parseInt(numField.getText().toString()); <-------
String toastMessage= "";
if(numFieldVal>randomNum){
toastMessage= "Higher";
}else if(numFieldVal==randomNum){
toastMessage= "You made the right guess!!!";
}else{
toastMessage= "Lower";
}
Toast.makeText(getApplicationContext(),toastMessage,Toast.LENGTH_LONG).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random randomGenerator= new Random();
randomNum = randomGenerator.nextInt(101); <--------
}
}
See the marked lines. Code is changed to the correct, but I added text to explain what is wrong.
Change
int numFieldVal= Integer.parseInt(numField.toString());
to
int numFieldVal= Integer.parseInt(numField.getText().toString());
The unchanged line is the cause of the crash.
And for a game related problem:
This line:
int randomNum = randomGenerator.nextInt(101);
is wrong. You create a new local variable, meaning the global randomNum is 0 - always. The solution is simple - remove the int, so it references the main randomNum variable.
And by doing that, you have solved unwanted results and solved the crash.
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<!-- <TextView
android:id="#+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="18dp"
android:layout_marginTop="24dp"
android:text="#string/name" /> -->
<EditText
android:id="#+id/etname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:ems="10" android:inputType="text"/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/etname"
android:layout_centerHorizontal="true"
android:layout_marginTop="79dp"
android:text="Login" />
</RelativeLayout>
I have a button, I want when I "hover" over the button it shows a hello message with a toast.
I have a button in the layout. I tried to fetch it by findViewById in the FirstActivity. Then I tried using button.setOnHoverListener but it isn't working.
package com.example.datapass;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class FirstActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.form);
final EditText name ;
Button loginButton ;
//final Context context = this;
/** Called when the activity is first created. */
//name= (EditText) findViewById(R.id.etname) ;
final TextView tv = (TextView) (findViewById(R.id.textView1) );
loginButton = (Button) findViewById(R.id.button1);
loginButton.setOnHoverListener(new View.OnHoverListener() {
#Override
public boolean onHover(View v, MotionEvent event) {
// TODO Auto-generated method stub
Log.d("hover", "Bring yor cursor over the button");
if(event.getAction()==MotionEvent.ACTION_HOVER_ENTER)
{
//tv.setText("hi");
Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_SHORT).show();
}
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Can anyone explain what's wrong?
It would be worth changing your onHover method to be like below and break once it carries out an individual action:
#Override
public boolean onHover(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_HOVER_ENTER:
Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_SHORT).show();
break;
}
return false;
}
I would also advise changing this line as this is not standard format/syntax:
final TextView tv = (TextView) (findViewById(R.id.textView1) );
To be this instead:
final TextView tv = (TextView) findViewById(R.id.textView1);
However I think your actual issue is more relating to the support on mobile devices of hovering as none of your code actually seems like it would break this code section. The majority of devices can only recognise hovers whilst using a stylus and not actually just with a finger. Only some of the higher end devices can actually recognise a hover action with just a finger. This might be something to note and may be advisable to use a swipe or a click instead of a hover to display the Toast.
Another newbie question here. I'm trying to create a form which takes several text input fields from the user, however my view keeps crashing/failing to load with the following error reported in the log:
Window already focused, ignoring focus gain of:com.android.internal.view.IInputMethodClient$Stub$Proxy#628a9148
This is what my xml looks like (this crashes)
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">"
<LinearLayout
android:orientation="vertical"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_gravity="top">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Please enter contact details\n\nName:"/>
<EditText
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:maxLength="30"
android:maxLines="1"
android:hint="#string/compose_name"></EditText>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="\nSurname:"/>
<EditText
android:id="#+id/surname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:layout_below="#id/name"
android:maxLength="30"
android:maxLines="1"
android:hint="#string/compose_surname"></EditText>-->
<Button
android:id="#+id/new_contact_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/submit" />
</LinearLayout>
</ScrollView>
However if I remove just the line:
android:id="#+id/surname"
It works (well at least it loads the view, of course I can't access the content in the EditText field without creating an id for it).
The view also fails if I add #+id tags to both the TextView fields (but works if I add only one).
What's going on here? I thought you should be able to label multiple view fields in your UI (all the examples in my book let me do this)?
I'm using NetBeans to develop on.
EDIT: Adding Javacode:
package org.me.savingsdepositrecord;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
public class NewContact extends Activity
implements OnClickListener, View.OnKeyListener {
//private EditText nameField;
//private String name;
private Button submitButton;
EditText nameField = null;
EditText surnameField = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_contact);
nameField = (EditText) findViewById(R.id.name);
nameField.setOnKeyListener(this);
surnameField = (EditText) findViewById(R.id.surname);
submitButton = (Button) findViewById(R.id.new_contact_button);
// Set up click listeners for all the buttons
submitButton.setOnClickListener(this);
}
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
String name = nameField.getText().toString();
String surname = surnameField.getText().toString();
// TODO: Save Nickname setting (strNicknameToSave)
return true;
}
return false;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.new_contact_button:
Intent i = new Intent(this, MainActivity.class);
finish();
startActivity(i);
break;
// More buttons go here (if any) ...
}
}
}
Yes, you can label multiple fields. It might be a good to take out the android:layout_below attribute since that isn't supported in LinearLayout.
Otherwise, your Java code might be the culprit. Can you post it as well?
Edit: I also tested your code and found no errors, although I had to remove the '-->' and the #string references.
I'm having a problem where it seems I can't get key events to fire at all in the emulator (it was working before, but, somehow.. something broke).
Here is some sample code that should fill the second text box with the text of the first when a key is pressed in the first (or if the button is clicked). But it doesn't do that.
Am I doing something wrong?
Activity class:
package abc.def;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
public class Fill extends Activity {
/** Called when the activity is first created. */
EditText e1;
EditText e2;
Button b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
e1 = (EditText) findViewById(R.id.EditText01);
e2 = (EditText) findViewById(R.id.EditText02);
b = (Button) findViewById(R.id.Button01);
e1.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
e2.setText(e1.getText());
return false;
}
});
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
e2.setText(e1.getText());
}
});
}
}
Layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
<EditText android:text="" android:id="#+id/EditText01" android:layout_width="wrap_content" android:layout_height="wrap_content"></EditText>
<EditText android:text="" android:id="#+id/EditText02" android:layout_width="wrap_content" android:layout_height="wrap_content"></EditText>
<Button android:text="Click" android:id="#+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
You should use e1.getText().toString() to get result.
LogCat will be useful to find out the values that are passed around. You can add the following LogCat for finding out similar issues
Log.d("SOMENAME",e1.getText().toString);
I got this to work by implementing TextWatcher and using addTextChangedListener() instead. No clue why this works when the onKeyListener does not - I suspect the keyboard events aren't even reaching my widget for some reason..
Am following the tutorial here on creating a simple todo list app:
http://www.mydroid.apnafundaz.com/2010/07/todolist-application-in-android-step-by-step-guide-with-screen-shots/
Have completed and have no errors, however my app doesn't appear like in that example, rather it looks like this - basically the EditText appears, but there's no ListView with previous tasks...
As there's no errors, it's rather hard to work out where I'm going wrong, but as my partner's also doing the same tutorial and has come up with exactly the same result, I am thinking there could be an issue with the tut - any advice much appreciated!
Just in case, here's my java file:
package com.example.helloworld;
import java.util.ArrayList;
import android.R.string;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
public class HelloWorld extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate your view
setContentView(R.layout.main);
// Get references to UI widgets
ListView myListView = (ListView)findViewById(R.id.myListView);
final EditText myEditText = (EditText)findViewById(R.id.myEditText);
// Create the array list of todo items
final ArrayList<String> todoItems = new ArrayList<String>();
// Create the array adaptor to bind the array to the listview
final ArrayAdapter<String> aa;
aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
todoItems);
// Bind the array adapter to the listview
myListView.setAdapter(aa);
myEditText.setOnKeyListener(new OnKeyListener(){
public boolean onKey(View v, int keyCode, KeyEvent event){
if(event.getAction() == KeyEvent.ACTION_DOWN)
if(keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
{
todoItems.add(0,myEditText.getText().toString());
aa.notifyDataSetChanged();
myEditText.setText("");
return true;
}
return false;
}
}
);
}
}
And here's my main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText
android:id="#+id/myEditText"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="New to Do Item"
/>
<ListView
android:id="#+id/myListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
Do one small change, in your EditText you are setting android:layout_height="fill_parent". So you cannot see List view. Just change it to wrap_content
<EditText
android:id="#+id/myEditText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="New to Do Item"
/>
KEYCODE_DPAD_CENTER is an odd choice of keycode... are you actually pressing this to add the edittext contents to the list? It's an odd choice cos some phones don't have directional pads. Try changing it for KEYCODE_ENTER.
On the first start, your list should be empty, because you have no previous todos defined. Have you tried to add a todo with the edittext? After that you should see it in the listview.