[Q] OnKey error - General Questions and Answers

Check this class below,
______ My Code _______
public class Main extends Activity implements OnKeyListener {
DisplayWord currentWord;
TextView wordStatus;
EditText inputWord;
Button okBtn;
int pos = 1;
char currentChar;
char inputChar;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
currentWord = (DisplayWord) this.findViewById(R.id.trueWord);
currentWord.setText("Bonjure"); // word from database
wordStatus = (TextView) this.findViewById(R.id.wordStatus);
inputWord = (EditText) this.findViewById(R.id.wordInput);
inputWord.setOnKeyListener(this);
}
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (inputWord.getText().toString().length() <= currentWord.getText().toString().length()) {
pos = inputWord.getText().toString().length();
currentChar = currentWord.getText().toString().charAt(pos);
inputChar = inputWord.getText().toString().charAt(pos);
} return false;
}
}
_____ END _____
When running this code, upon entering data into the input box it causes an exception straight away and for the program exit unexpectedley.
I am trying to extract the input word from EditText field and the word stored in a TextView and to compare them char by char as those chars are entered into the input box, sort of a word game, where the character will be highlighted green if it is correct and red if it is not.
I have no idea why this behaviour happens, I can see in debugger an StringIndexOutOfBounds exception, and a ResourceNotFound when I have been tampering with different ways of attempting this, access position or the char array, it always seems to throw an exception.
Any advice or links appreciated,
AnthonyI am trying to post a copy and paste of just text, no links but validation error on starting a new thread is telling me that I cannot submit a message with a link in it? I want to show everyone a simple class because of some problem's i'm having.. any ideas?

Related

Random Words App

Hello all,
I'm trying to write a Random Words Generator App. I am just starting out and I have read a little and watched a few tutorials. What I have so far is the main.xml file that has my layout. It has a 2 TextViews (Left TextView & Right TextView), and 2 buttons (Left Spin & Right Spin)
Where I'm at... I click the Left Button, the screen flashes and then displays a random Word. But then that's it, I can not click it or any other button again. They do nothing until I hit the back button, which displays the main screen again as if I never clicked anything. Then, and only then, I can click a button only once until I go back.
Here is my code for the Left side. I have another class for the Right side that is the same.
I was hoping someone could tell me what I am doing wrong.
Thanks!!
Code:
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class LeftSideWord extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnls = (Button) findViewById(R.id.btLeftSpin);
btnls.setOnCreateContextMenuListener(this);
Random generator = new Random();
int num;
String[] lword;
lword= new String[5];
lword[0]= "Word1";
lword[1]= "Word2";
lword[2]= "Word3";
lword[3]= "Word4";
lword[4]= "Word5";
TextView tvLeft = (TextView) findViewById(R.id.tvLeftWord);
num=generator.nextInt(5);
tvLeft.setText(lword[num]);
}
}
Why is LeftSideWord and RightSideWord both an extra activity?
Put the code for both buttons in your main activity.
You seem to launch a new activity by button press with your random word instead of modifying the textviews in your existing one.
OK, I will see if I can combine the two. Thanks!
Edited: Making more Progress
OK, I'm getting closer and I also added a 3rd Button.
What I have so far is the main.xml file that has my layout. It has a 2 TextViews (Left TextView & Right TextView), and now 3 buttons (Left Spin, Right Spin & Spin Both)
Where I'm at... I click any button the first time, it does nothing on the First Click, 2nd click, it displays a random word depending on which button I press. So everything works as it should, Except for that First Click doing nothing.
I would like for it to work on the First Click.
Here the code below it has both word lists in one class.
Again, I was hoping someone could tell me what I am doing wrong.
Thanks!!
Code:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class WordList extends Activity{
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Code for Left Spin
Button btnls = (Button) findViewById(R.id.btLeftSpin);
btnls.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Random generator = new Random();
int num;
// Left Word
String[] lword;
lword= new String[5];
lword[0]= "Word1";
lword[1]= "Word2";
lword[2]= "Word3";
lword[3]= "Word4";
lword[4]= "Word5";
// Generate Random Left Word
TextView tvLeft = (TextView) findViewById(R.id.tvLeftWord);
num=generator.nextInt(5);
tvLeft.setText(lword[num]);
}
});
// Code for Right Spin
Button btnrs = (Button) findViewById(R.id.btRightSpin);
btnrs.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Random generator = new Random();
int num;
// Right Word
String[] rword;
rmword= new String[5];
rword[0]= "rWord1";
rword[1]= "rWord2";
rword[2]= "rWord3";
rword[3]= "rWord4";
rword[4]= "rWord5";
// Generate Random Right Word
TextView tvRight = (TextView) findViewById(R.id.tvRightWord);
num=generator.nextInt(5);
tvRight.setText(rword[num]);
}
});
// Code for Both Left and Right Words
Button btns = (Button) findViewById(R.id.btSpin);
btns.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Random generator = new Random();
int num;
// Left Word
String[] lword;
lword= new String[5];
lword[0]= "Word1";
lword[1]= "Word2";
lword[2]= "Word3";
lword[3]= "Word4";
lword[4]= "Word5";
// Right Word
String[] rword;
rmword= new String[5];
rword[0]= "rWord1";
rword[1]= "rWord2";
rword[2]= "rWord3";
rword[3]= "rWord4";
rword[4]= "rWord5";
// Generate Random Left Word
TextView tvLeft = (TextView) findViewById(R.id.tvLeftWord);
num=generator.nextInt(5);
tvLeft.setText(lword[num]);
// Generate Random Right Word
TextView tvRight = (TextView) findViewById(R.id.tvRightWord);
num=generator.nextInt(5);
tvRight.setText(rword[num]);
}
});
}
}
I don't think this is the problem but why don't you assign the textview objects globally instead of each time when the button is pressed.

[Q] Problem developing app for Android

Hi All,
I am a not experienced developer. All I want to do is make a small app to track information of football on TV. I want to do it through a small DB however I've been struggling a lot with an error I've been trying to discover in the last two weeks but I have not been able.
I have teh following code in the class I create the DB
public class DBAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_GDATE = "gdate";
public static final String KEY_GTIME = "gtime";
public static final String KEY_GGAME = "ggame";
public static final String KEY_GCOMPETITION = "gcompetition";
public static final String KEY_GCHANNEL = "gchannel";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "FonTV";
private static final String DATABASE_TABLE = "games";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE =
"create table games (_id integer primary key autoincrement, "
+ "gdate text not null, gtime text not null, ggame text not null" +
"gcompetition text not null, gchannel text not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a contact into the database---
public long insertContact(String gdate, String gtime, String ggame, String gcompetition, String gchannel )
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_GDATE, gdate);
initialValues.put(KEY_GTIME, gtime);
initialValues.put(KEY_GGAME, ggame);
initialValues.put(KEY_GCOMPETITION, gcompetition);
initialValues.put(KEY_GCHANNEL, gchannel);
return db.insert(DATABASE_TABLE, null, initialValues);
}
}
And the main class where I try to insert data has this:
public class ResultsDBActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DBAdapter db = new DBAdapter(this);
db.open();
long id = db.insertContact("12/may", "08:00", "Leeds vs York", "JUME Cup", "ITV, BBC");
id = db.insertContact("13/may", "09:00", "London vs Bath", "JUME Cup", "ITV, BBC2");
db.close();
}
}
However when I try to run it, the debugger shows and error that says:
E/Database(330): android.database.sqlite.SQLiteException: no such table: games: , while compiling: INSERT INTO games(gchannel, ggame, gtime, gdate, gcompetition) VALUES(?, ?, ?, ?, ?);
I’ve trying to change parameters and many things but I haven’t found where the problem is. Can someone help me please?

Long Press on Home

Hello, I have never done this for Android, though I do develop web apps. I'd like to give it a shot with the Android OS and my first project would be to modify behavior of long pressing a Home Button on our Note II's. I found some information on the web by using a function to hook into the KeyLongPress and Key ID.
What I would like to know, if where do I begin to start adding my custom functions? Do I create a separate file or put the function in an existing file?
How do I make this apply only during the lockscreen or home screen?
Using the example below, I imagine I need to create a folder called com.example.demo, but not sure where and what else would be needed.
Code:
package com.example.demo;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
public class TestVolumeActivity extends Activity {
boolean flag = false;
boolean flag2 = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_splash_screen, menu);
return true;
}
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
Log.d("Test", "Long press!");
flag = false;
flag2 = true;
return true;
}
return super.onKeyLongPress(keyCode, event);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
event.startTracking();
if (flag2 == true) {
flag = false;
} else {
flag = true;
flag2 = false;
}
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
event.startTracking();
if (flag) {
Log.d("Test", "Short");
}
flag = true;
flag2 = false;
return true;
}
return super.onKeyUp(keyCode, event);
}
}
Any help is appreciated.
It would be helpful to take a look at CM code and how the long press hardware key actions, as well as lock screen button actions are implemented.
Sent from my SGH-T999 using Tapatalk 2
Not sure if I understood you correctly, but you can't just put the code in a text file like a PHP script and expect it to work You need to compile it first using the Android SDK.
In any case, you can't hook keys globally the way you are suggesting. You'd need to modify the system's framework files (inside android.policy.jar) for it to work, which frankly sounds to be beyond your capabilities at the moment.
Are you talking about in your own app or for your ROM?
Sent from my SGH-T999
"So I put my phone into airplane mode and threw it... worst transformer ever. -.-" -My friend

Popup box Help

So i have created a pop up window with the source code below. I also have designed the popup really good. and it displays right. The only problem i have is the damn button to close it. lol I had it so it closed fine before. Then i started adding stuff in to make the app work the way i want it to.
So What i have done is this, I have the popup created i want to be able to have the Text box checked for a string if this string exists then I need to go to thread allApps which then launches my 2nd Activity which that works fine as well. But the problem is the damn pop uup is still up so i need to close this. Any way of doing this with using the code I have or do i need to redo something. Please Any help thanks
PHP:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
final Button btnOpenPopup = (Button)findViewById(R.id.apps_button);
btnOpenPopup.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
LayoutInflater layoutInflater
= (LayoutInflater)getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(
popupView,
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
popupWindow.showAtLocation(btnOpenPopup, Gravity.CENTER, 0, 0);
}});
}
public void allApps(View arg)
{
Intent intent = new Intent(arg.getContext(), AppList.class);
startActivity(intent);
}

[Completed] Android Studio Listview Needs To Be Visible

Hi guys I am new to developing i need help with some codes. Hope you guys can help.
I am using Sqlite database i need to create a list view that display the word from database so hope you guys can help me. here is my code above. ty
//Code
public class Ortho extends ActionBarActivity {
private final String TAG = "Ortho";
DatabaseHelper dbhelper;
TextView word;
TextView mean;
AutoCompleteTextView actv;
Cursor cursor;
Button search;
int flag = 0;
ListView ls;
ArrayList<String> dataword;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ortho);
ls = (ListView) findViewById(R.id.mainlist);
ls.setVisibility(View.VISIBLE);
//need code here
dbhelper = new DatabaseHelper(this);
try {
dbhelper.createDataBase();
} catch (IOException e) {
Log.e(TAG, "can't read/write file ");
Toast.makeText(this, "error loading data", Toast.LENGTH_SHORT).show();
}
dbhelper.openDataBase();
word = (TextView) findViewById(R.id.word);
mean = (TextView) findViewById(R.id.meaning);
String[] from = {"english_word"};
int[] to = {R.id.text};
actv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.singalline, null, from, to);
// This will provide the labels for the choices to be displayed in the AutoCompleteTextView
adapter.setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() {
@override
public CharSequence convertToString(Cursor cursor) {
return cursor.getString(1);
}
});
adapter.setFilterQueryProvider(new FilterQueryProvider() {
@override
public Cursor runQuery(CharSequence constraint) {
cursor = null;
int count = constraint.length();
if (count >= 1) {
String constrains = constraint.toString();
cursor = dbhelper.queryr(constrains);
}
return cursor;
}
});
briza-jann23 said:
Hi guys I am new to developing i need help with some codes. Hope you guys can help.
I am using Sqlite database i need to create a list view that display the word from database so hope you guys can help me. here is my code above. ty
//Code
public class Ortho extends ActionBarActivity {
private final String TAG = "Ortho";
DatabaseHelper dbhelper;
TextView word;
TextView mean;
AutoCompleteTextView actv;
Cursor cursor;
Button search;
int flag = 0;
ListView ls;
ArrayList<String> dataword;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ortho);
ls = (ListView) findViewById(R.id.mainlist);
ls.setVisibility(View.VISIBLE);
//need code here
dbhelper = new DatabaseHelper(this);
try {
dbhelper.createDataBase();
} catch (IOException e) {
Log.e(TAG, "can't read/write file ");
Toast.makeText(this, "error loading data", Toast.LENGTH_SHORT).show();
}
dbhelper.openDataBase();
word = (TextView) findViewById(R.id.word);
mean = (TextView) findViewById(R.id.meaning);
String[] from = {"english_word"};
int[] to = {R.id.text};
actv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.singalline, null, from, to);
// This will provide the labels for the choices to be displayed in the AutoCompleteTextView
adapter.setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() {
@override
public CharSequence convertToString(Cursor cursor) {
return cursor.getString(1);
}
});
adapter.setFilterQueryProvider(new FilterQueryProvider() {
@override
public Cursor runQuery(CharSequence constraint) {
cursor = null;
int count = constraint.length();
if (count >= 1) {
String constrains = constraint.toString();
cursor = dbhelper.queryr(constrains);
}
return cursor;
}
});
Click to expand...
Click to collapse
Hi, thank you for using XDA assist.
There is a general forum for android here http://forum.xda-developers.com/android/help where you can get better help and support if you try to ask over there.
Good luck.
You can also ask here http://forum.xda-developers.com/coding/java-android

Categories

Resources