Random Words App - General Questions and Answers

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.

Related

[Q] OnKey error

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?

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

[Q] google map v1

Hi,
I am trying to load google map v1 on android application but only able to see grid. no map. Guide please what thing i am missing?
My main activity file is:
**************************************************************************
package com.example.mymapactivity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MyMapActivity extends Activity {
static final LatLng HAMBURG = new LatLng(53.558, 9.927);
static final LatLng KIEL = new LatLng(53.551, 9.993);
private GoogleMap map;
@suppressLint("NewApi")
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_map);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
Marker hamburg = map.addMarker(new MarkerOptions().position(HAMBURG)
.title("Hamburg"));
Marker kiel = map.addMarker(new MarkerOptions()
.position(KIEL)
.title("Kiel")
.snippet("Kiel is cool")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_launcher)));
// Move the camera instantly to hamburg with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
}
@override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my_map, menu);
return true;
}
}
Please guide
Thanks

[Q] WebView app opens up default browser.

Hello I am a Android newbie and I am currently learning how to code applications using Eclipse so I made one yesterday using webview on eclipse but everytime I open the app it takes me to the website but on my default browser. I want the website to open up in the app not on my browser. Anyone know how to fix this?
You need to read the WebView Reference on Android.
Apparently you open the website on a Intent, so the website is opened on the default browser.
Instead, you need to make you Activity act as a WebView on the 'onCreate()' :
Code:
WebView webview = new WebView(this);
setContentView(webview);
And then open the website :
Code:
// Simplest usage: note that an exception will NOT be thrown
// if there is an error loading this page (see below).
webview.loadUrl("my_url");
// OR, you can also load from an HTML string:
String summary = "<html><body>You scored <b>192</b> points.</body></html>";
webview.loadData(summary, "text/html", null);
// ... although note that there are restrictions on what this HTML can do.
// See the JavaDocs for loadData() and loadDataWithBaseURL() for more info.
Um this is my MainActivity.java
package com.graaltailor.JFA;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.webkit.WebView;
public class MainActivity extends Activity {
WebView mWebView;
/** Called when the activity is first created. */
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("examplewebsite");
}
}
You need to do something like this to overwrite urlredirect opened in the default browser :
Code:
package com.graaltailor.JFA;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.webkit.WebView;
public class MainActivity extends Activity {
WebView mWebView;
/** Called when the activity is first created. */
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("examplewebsite");
}
mWebView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url){
// do your handling codes here, which url is the requested url
// probably you need to open that url rather than redirect:
view.loadUrl(url);
return false; // then it is not handled by default action
}
});
}
I replaced the code with the one you replied with and I get a bunch of errors.
sorry I made a mistake in the code
Code:
package com.graaltailor.JFA;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.webkit.WebView;
public class MainActivity extends Activity {
WebView mWebView;
/** Called when the activity is first created. */
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("examplewebsite");
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
// do your handling codes here, which url is the requested url
// probably you need to open that url rather than redirect:
view.loadUrl(url);
return false; // then it is not handled by default action
}
});
}
}

[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