package com.example.android.home;
import android.app.Activity;
import android.os.Bundle;
import android.widget.*;
import android.view.*;
public class HomeActivity extends Activity {
/** Called when the activity is first created. */
private EditText input;
private EditText result;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
input = (EditText) findById(R.id.input1);
result = (EditText) ***findById***(R.id.result); //Error:Undefined for the type HomeActivity
input.addKeyListener(new View.OnKeyListener() { Error: Undefined for the type EditText
public boolean onKey(View v, int keycode, KeyEvent keyevent) {
if (keyevent.getAction() == KeyEvent.ACTION_UP) {
doCalculation();
}
return false;
}
});
}
private void doCalculation()
{
String strValue = input.getText().toString();
int resultt = Integer.parseInt(strValue) * 2;
result.setText("Result: "+ resultt);
}
}
As #Varun states, there is no findById() method. You are probably thinking of findViewById().
You would have found this on your own by examining any sample Android activity and seeing how it accesses the widgets. There are many sample activities in your SDK installation, plus online.
Related
I'm learning to use Android Studio and for my first App I'm doing a Tic Tac Toe. I have an activity where a player can write its name so it can be displayed later with his points. I want to implement the possibility to press ENTER to do it instead of having to press the Button "DONE" but I get the error "cannot resolve the symbol setOnKeyListener" (also with "event" and the two constants). What am I doing wrong?
package com.example.tictactoe;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.view.View.OnKeyListener;
public class login1 extends AppCompatActivity {
EditText playerOne = (EditText) findViewById(R.id.playerOneLogin);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login1);
Button button = (Button) findViewById(R.id.button_player_one);
final EditText playerOne = (EditText) findViewById(R.id.playerOneLogin);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity2();
}
playerOne.setOnKeyListener(new View.OnKeyListener) {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
startActivity2();
return true;
}
return false;
}
}
});
}
public void startActivity2() {
Intent intentPlayerOne = new Intent(this, login2.class);
intentPlayerOne.putExtra("playerOne", playerOne.getText().toString());
startActivity(intentPlayerOne);
}
}
you've missed some opening bracket for OnKeyListener constructor...
playerOne.setOnKeyListener(new View.OnKeyListener() { // missing ( in here
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
startActivity2();
return true;
}
return false;
}
// one additional unnecessary } was in here
});
I use an Edittext in android to fill a cell of xls.file by using aspose-cell for android API. But when i put some text in the edittext, the displayed value in the xls. file is always the same : 2131492965 !! and not the text of the edittext.
Can you help me ?
Here is my code :
MainActivity.java
package com.example.lionel.cells;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.aspose.cells.Cell;
import com.aspose.cells.Cells;
import com.aspose.cells.*;
import com.aspose.cells.Workbook;
import com.aspose.cells.Worksheet;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import java.io.File;
import static com.aspose.cells.b.b.zp.v;
import static com.example.lionel.cells.R.id.button1;
public class MainActivity extends AppCompatActivity {
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public EditText mEditText;
public String text;
// public String text = textview.getText().toString();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LibsLoadHelper.loadLibs(getApplicationContext());
mEditText = (EditText) findViewById(R.id.Edittext1);
// mEditText.setOnKeyListener(new EditText.OnKeyListener()
// {
// #Override
// public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
//
// if(KeyEvent.KEYCODE_ENTER == keyCode)
// {
// if(KeyEvent.ACTION_UP == keyEvent.getAction())
// {
// EditText editText = (EditText)view;
// mCellValue = editText.getText().toString();
// Toast.makeText(MainActivity.this, mCellValue, Toast.LENGTH_SHORT).show();
// }
// return true;
// }
// return false;
// }
// });
text = mEditText.getText().toString();
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new TestTask().execute();
}
});
}
}
TestTask.java :
package com.example.lionel.cells;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.TextView;
import android.widget.Toast;
import com.aspose.cells.Cell;
import com.aspose.cells.Cells;
import com.aspose.cells.Workbook;
import com.aspose.cells.Worksheet;
import java.io.File;
import java.io.IOException;
import static com.example.lionel.cells.R.id.text;
/**
* Created by Lionel on 25/09/2016.
*/
public class TestTask extends AsyncTask<Void, String, Boolean> {
// File sdDir = Environment.getExternalStorageDirectory();
File sdDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
String sdPath = sdDir.getAbsolutePath();
#Override
protected Boolean doInBackground(Void... params) {
Boolean result = false;
Workbook book = new Workbook();
Worksheet sheet = book.getWorksheets().get(0);
Cells cells = sheet.getCells();
Cell cell = cells.get("A1");
Cell cell1 = cells.get("A2");
Cell cell2 = cells.get("A3");
cell.putValue(text);
cell1.setValue(true);
cell2.setValue(123);
try {
book.save(sdPath + "/output.xlsx");
//
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
#Krukiou,
A similar inquiry of yours have already been replied in Aspose.Cells support forum. Please check the following piece of code as well as this thread for details.
Regarding the following snippet, it uses the mCellValue variable to load the contents of the EditText field on Enter key. You can use the same variable to insert the contents of the EditText field to the spreadsheet cell using the UI button mButton. Moreover, as by default, the EditText can span over multiple lines therefore the Enter key on the real device (or soft keyboard) will act as carriage return, therefore the code sets the EditText.SingleLine as true in order to change the behaviour of the soft Enter key.
private TextView mResultTextView;
private TextView mProgressTextView;
private Button mButton;
private EditText mEditText;
private String mCellValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LibsLoadHelper.loadLibs(getApplicationContext());
mResultTextView = (TextView)findViewById(R.id.result_textview);
mProgressTextView = (TextView)findViewById(R.id.progress_textview);
mButton = (Button)findViewById(R.id.button);
mEditText = (EditText)findViewById(R.id.edit_text);
mEditText.setSingleLine(true);
mEditText.setOnKeyListener(new EditText.OnKeyListener()
{
#Override
public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
if(KeyEvent.KEYCODE_ENTER == keyCode)
{
if(KeyEvent.ACTION_UP == keyEvent.getAction())
{
EditText editText = (EditText)view;
mCellValue = editText.getText().toString();
Toast.makeText(MainActivity.this, mCellValue, Toast.LENGTH_SHORT).show();
}
return true;
}
return false;
}
});
mButton.setOnClickListener(new Button.OnClickListener()
{
#Override
public void onClick(View v) {
new TestTask().execute();
}
});
Note: I work with Aspose as Developer Evangelist.
i am trying to listen for certain key events in android , i attached the event listener to a an Edit Text. i am looking for the space-bar press,pound and # key.for some reason this event gets only fired for the space bar and the number keys. The function doesn't even gets to be executed for any other key.... i would like to know why ? is their something that i am doing wrong ?
package com.stv.mynotes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.util.StringTokenizer;
public class TestActivity extends AppCompatActivity implements View.OnKeyListener
{
EditText edit_txt;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
edit_txt = (EditText) (findViewById(R.id.test_txt));
edit_txt.setOnKeyListener(this);
}
public boolean onKey(View v,int keyCode,KeyEvent event)
{
int tmpCode = event.getKeyCode();
if (event.getAction() == KeyEvent.ACTION_DOWN)
{
if (tmpCode == KeyEvent.KEYCODE_SPACE)
{
Log.i("Test", "Space pressed:"+tmpCode);
return true;
}
if (tmpCode == KeyEvent.KEYCODE_9)
{
Log.i("Test", "9 pressed:"+tmpCode);
return true;
}
else
{
Log.i("Test","Unknown Down:"+tmpCode);
return false;
}
}
if(event.getAction()==KeyEvent.ACTION_UP)
{
if (tmpCode == KeyEvent.KEYCODE_POUND)
{
Log.i("Test", "Pound pressed:"+tmpCode);
return true;
}
if (tmpCode == KeyEvent.KEYCODE_AT)
{
Log.i("Test", "# pressed:"+tmpCode);
return true;
}
else
{
Log.i("Test","Unknown UP:"+tmpCode);
return false;
}
}
else
return false;
}
}
I found this here http://developer.android.com/reference/android/text/method/KeyListener.html about onClickListener:
Key presses on soft input methods are not required to trigger the methods in this listener, and are in fact discouraged to do so.The default android keyboard will not trigger these for any key to any application targetting Jelly Bean or later, and will only deliver it for some key presses to applications targetting Ice Cream Sandwich or earlier.
Also:
Note that for most cases this interface has been superceded by general soft input methods as defined by InputMethod; it should only be used for cases where an application has its own on-screen keypad and also wants to process hard keyboard events to match it.
So, if you are in the situation described above, try to reconsider you code as recommended by documentation.
As an alternative, you could try to use this:
edit_txt.addTextChangedListener(new TextWatcher() {
int initialLength = 0;
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
initialLength = edit_txt.getText().length();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int newLength = edit_txt.getText().length();
if(newLength<initialLength) return;
if(edit_txt.getText().charAt(newLength-1)=='#'){
Log.i("test", "#");
}
}
#Override
public void afterTextChanged(Editable s) {}
});
I am trying to create an android application which acts as a Web Socket server. Here is my MainActivity.java.
package com.example.websocket;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import org.apache.http.conn.util.InetAddressUtils;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
EditText port, msg;
Button listen, send;
TextView status;
int p;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
port = (EditText)findViewById(R.id.editText1);
msg = (EditText)findViewById(R.id.editText2);
listen = (Button)findViewById(R.id.button1);
send = (Button)findViewById(R.id.button2);
status = (TextView)findViewById(R.id.textView1);
listen.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0) {
String temp = port.getText().toString();
p = Integer.parseInt(temp);
try
{
custom_web_socket wsocket = new custom_web_socket(p);
wsocket.start();
}
catch (UnknownHostException e) {
e.printStackTrace();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class custom_web_socket extends WebSocketServer
{
public custom_web_socket(int port_add) throws UnknownHostException {
super(new InetSocketAddress(port_add));
// pass
}
#Override
public void onClose(WebSocket arg0, int arg1, String arg2, boolean arg3) {
status.setText("Connection closed.");
}
#Override
public void onError(WebSocket arg0, Exception arg1) {
status.setText((CharSequence) arg1);
}
#Override
public void onMessage(WebSocket arg0, String arg1) {
// TODO Auto-generated method stub
}
#Override
public void onOpen(WebSocket arg0, ClientHandshake arg1) {
status.setText("Connected");
}
}
}
When I run the program, the application starts. However, wheneve I try to enter value into the EditText field, the application hangs and ends. I am referring this example for web sockets - https://github.com/TooTallNate/Java-WebSocket/blob/master/src/main/example/ChatServer.java
I have imported the necessary jar file. This is my first attempt at android programming and I am not sure what the problem could be.
You are using an event onClick.
So whenever you are trying to type something , it calls your method. and hangs up.
your action should happen when user finished typing the code.
You can use following code
port.setOnEditorActionListener(
new EditText.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent
event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH ||
actionId == EditorInfo.IME_ACTION_DONE ||
event.getAction() == KeyEvent.ACTION_DOWN &&
event.getKeyCode()==KeyEvent.KEYCODE_ENTER)
{
if (!event.isShiftPressed()) {
// the user is done typing.
return true; // consume.
}
}
return false; // pass on to other listeners.
}
});
Also , refer to http://developer.android.com/reference/android/widget/EditText.html
you will get the clear idea.
hm.. maybe a little stupid question, but i dont get it on my i own...
package com.example.wettkampftimerbt;
import android.content.Intent;
import android.inputmethodservice.Keyboard.Key;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class ServMPW extends Activity_ActivityGroup implements OnClickListener{
Button enter, cancel;
EditText eingabe, eingabe2, masterpw;
String pwx, eingabex, pass, adminacchint1x, adminacchint2x;
private final String PREFS_NAME = "prefs";
private final String PREFS_PW = "pw";
private final String PREFS_lang = "lang";
private final String TITLE5 = "title5";
private final String ADMINACCHINT1 = "adminacchint1";
private final String ADMINACCHINT2 = "adminacchint2";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.servmpw);
//((TextView)((FrameLayout)((LinearLayout)((ViewGroup) getWindow().getDecorView()).getChildAt(0)).getChildAt(0)).getChildAt(0)).setGravity(Gravity.CENTER);
String title5x=(getSharedPreferences(PREFS_lang, MODE_PRIVATE).getString(TITLE5, "Administrationszugang"));
this.setTitle(title5x);
adminacchint1x=(getSharedPreferences(PREFS_lang, MODE_PRIVATE).getString(ADMINACCHINT1, "Passwort"));
adminacchint2x=(getSharedPreferences(PREFS_lang, MODE_PRIVATE).getString(ADMINACCHINT2, "falsches Passwort"));
enter=(Button)findViewById(R.id.enter);
cancel=(Button)findViewById(R.id.cancel);
eingabe=(EditText)findViewById(R.id.eingabe);
masterpw=(EditText)findViewById(R.id.masterpw);
eingabe.setHint(adminacchint1x);
eingabe2=(EditText)findViewById(R.id.eingabe2);
enter.setOnClickListener(this);
cancel.setOnClickListener(this);
}
public void onClick (View v){
if (v==cancel){
finish();}
else if (v == enter){
entermeth();
}
else {
eingabe.setText("");
eingabe.setHint(adminacchint2x);}}
public void OnKey (View v, int keyCode, KeyEvent event)
{
if (keyCode==66)
entermeth();
}
public void entermeth(){
eingabe2.setText(getSharedPreferences(PREFS_NAME, MODE_PRIVATE).getString(PREFS_PW, "bbb"));
pwx = eingabe2.getText().toString();
Log.e("pw", PREFS_PW + "." + pwx);
eingabex = eingabe.getText().toString();
masterpw.setText("aaa");
String masterpwx = masterpw.getText().toString();
Log.e("pw:", masterpwx);
if (eingabex.equals(pwx)||(eingabex.equals(masterpwx))){
Intent admin = new Intent (ServMPW.this, Admin.class);
ServMPW.this.finish();
startActivity(admin);}
}
}
I want to perform the click on my own enterbutton, if the enter button on the softkeyboard is pressed. But it doesnt work... What did i miss?
On your EditText you can bind OnEditorActionListener. Something like this
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
//do here your stuff here
return true;
}
return false;
}
});
nothing is ever calling the OnKey method. That's what u missed.
Also, it's not a good programming practice to force clicks. You should instead create a method private doEnterActions(){ } and on both enter key and enter button u just call that method.
edit:
just like you setClickListener to your button (implemented by the activity) you have to make the activity implement, and set as listeners for the key events. That is done using enter.setOnKeyListener()