this is my first time on this forum, so forgive me if my question seems odd. I'll try to be as thorough as possible.
I am creating a translation program.
this program has a menu activity, translate activity, addword activity.
The three activities are linked together via intents and they are
added in the manifest file.
In the translate activity I want to create a method for translating.
After I press the translate button, the program crashes.
public class VertaalActivity extends Activity {
private Button vertaal;
private Button terug;
private EditText ET_NL;
private EditText ET_EN;
private ArrayList<String>nlWoorden = new ArrayList<String>();
private ArrayList<String>enWoorden = new ArrayList<String>();
public void Vertaal(){
String woord = ET_NL.getText().toString();
if(nlWoorden.contains(woord)){
int i = nlWoorden.indexOf(woord);
ET_EN.setText(enWoorden.get(i));
}else{
ET_EN.setText("Woord niet gevonden");
}
}
public void ArrayVullen(){
nlWoorden.add("auto");
nlWoorden.add("bord");
nlWoorden.add("trein");
nlWoorden.add("spel");
nlWoorden.add("scherm");
nlWoorden.add("toetsenbord");
nlWoorden.add("foto");
enWoorden.add("car");
enWoorden.add("plate");
enWoorden.add("train");
enWoorden.add("game");
enWoorden.add("screen");
enWoorden.add("keyboard");
enWoorden.add("picture");
}
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.vertalerlayout);
terug = (Button)findViewById(R.id.terug);
vertaal = (Button)findViewById(R.id.vertalen);
ArrayVullen();
vertaal.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Vertaal();
/*
* Tested the toast and the toast shows the text
*
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
*/
}
});
terug.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(VertaalActivity.this,MenuActivity.class);
startActivity(intent);
}
});
}
}
I can't see that you get the EditTexts from your XML (like you do with the buttons). Before using ET_NL you need to do something like this:
ET_NL = (EditText)findViewById(R.id.etnl); // Or whatever id you've declared in your layout XML
Same thing goes for the ET_EN variable. Otherwise the will be null in your Vertaal() method, causing the app to crash.
Try this code before using the editText field
ET_NL= (EditText)findViewById(R.id.edittext1);
ET_EN = (EditText)findViewById(R.id.edittext2);
Related
How do I assign user input (from a TextView) into a variable then call that variable in another class?
From my MainActivity, I have the followingn where user input is taken:
Button confirm;
EditText inputField;
String typedChar;
char[] cars = typedChar.toCharArray();
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
confirm = (Button)findViewById(R.id.btConfirmInput);
inputField = (EditText) findViewById(R.id.etInputChars);
confirm.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
typedChar = inputField.getText().toString();
}
}
);
I'm trying to store the input and convert it to char
String typedChar;
char[] cars = typedChar.toCharArray();
Now I want to use cars in another class in the following method which print to a custom view:
private void drawText() {
for (int i = 0; i < txtPosByColumn.length; i++) {
canvas.drawText("" + cars[RANDOM.nextInt(cars.length)], i * fontSize, txtPosByColumn[i] * fontSize, paintTxt);
if (txtPosByColumn[i] * fontSize > height && Math.random() > 0.975) {
txtPosByColumn[i] = 0;
}
txtPosByColumn[i]++;
}
I'm however able to assign hardcoded value to cars like bellow:
private char[] chars = "010101".toCharArray();
but I want it come from user input
Anyone please kindly advice, guide. I know I'm doing things wrong but can't figure out...
PS: Noob here
You put your variable in an Intent like this:
confirm.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
typedChar = inputField.getText().toString();
char[] chars = typedChar.toCharArray();
Intent intent = new Intent(MyCurrentActivity.this, MySecondActivity.class);
intent.putExtra("somethingWithARelevantName", chars);
startActivity(intent);
}
}
);
And you get it in your second activity like this:
Intent intent = getIntent();
char[] chars = intent.getExtras().getCharArray("somethingWithARelevantName");
edit: if want your variable in a class that is not an activity, you can pass it in the constructor:
class MyClass{
char[] chars;
MyClass(char[] chars){
this.chars = chars;
}
}
You should specified what is the type of that other class.
If it is a simple Java class you can pass it as a field to your drawText(char[] array);
If however you are dealing with activities the :
In your first activity, before launching the other activity, use Extra intent to send data between activities as the answer show before.
I'm trying to make the button (R.id.buttonring) call any phone number entered in the textview called tvTelefon. However, when i click that button, my phone is trying to call "w4126848130,511290,549" instead of the phone number entered in the textview. Any ideas how come? I don't receive any error messages so I'm clueless! Thanks!
public class Activity2 extends Activity {
public static final String SPARAD_DATA = "sparadData";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
SharedPreferences sp = getSharedPreferences(SPARAD_DATA, Context.MODE_PRIVATE);
TextView tvRubrik = (TextView)findViewById(R.id.textViewrubrik);
tvRubrik.setText(sp.getString("rubrik", "Rubrik saknas"));
TextView tvNamn = (TextView)findViewById(R.id.textViewnamn);
tvNamn.setText(sp.getString("namn", "Namn saknas"));
TextView tvText = (TextView)findViewById(R.id.textViewtext);
tvText.setText(sp.getString("text", "Text saknas"));
final TextView tvTelefon = (TextView)findViewById(R.id.textViewtelefon);
tvTelefon.setText(sp.getString("telefon", "Telefon saknas"));
TextView tvPris = (TextView)findViewById(R.id.textViewpris);
tvPris.setText(sp.getString("pris", "Pris saknas"));
Button r = (Button)findViewById(R.id.buttonring);
r.setOnClickListener (new View.OnClickListener() {
Intent call = new Intent(Intent.ACTION_DIAL);
#Override
public void onClick(View v){
call.setData(Uri.parse("tel:" +tvTelefon));
startActivity(call);
}
});
}
}
Slight change might help you:
call.setData(Uri.parse("tel:" +tvTelefon));
It should be:
call.setData(Uri.parse("tel:" +tvTelefon.getText().toString()));
you are passing an object reference, get the string you put into it.
Actually, how I understand your posted code you can just take the phone number straight from your preferences. Try this:
call.setData(Uri.parse("tel:" + sp.getString("telefon", "")));
Instead of:
call.setData(Uri.parse("tel:" +tvTelefon));
I am very new to JAVA and android development and am trying to password protect my app.
I have tried to make it so that whenever a user presses the submit button it will start a new activity if the password is correct.
so far i have the following code:
for my button:
<Button
android:id="#+id/button_enterpassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/text_enterpassword"
android:layout_centerHorizontal="true"
android:layout_marginTop="262dp"
android:onClick="openMenu"
android:textSize="60sp"
android:text="#string/button_confirm"
/>
for my activity:
// This is the method called when the user presses the button
public void openMenu(View view) {
MyMethods compareText = new MyMethods();
boolean same = compareText.compareText();
if(same = true){
MyMethods openActivity = new MyMethods();
openActivity.callActivity();
}
}}
for my MyMethods class:
public class MyMethods extends Activity {
public void callActivity() {
Intent intent = new Intent(this , MainMenu.class);
startActivity(intent);
}
public boolean compareText() {
boolean same = false;
//assigning the name sumbitButton to the button from the UI
//Button sumbitButton = (Button) findViewById(R.id.button_enterpassword);
//Defines when the user has selected the button
// sumbitButton.setOnClickListener(new View.OnClickListener() {
//public void onClick(View v){
//assigning the name passwordEditText to the text inside the textbox
EditText passwordEditText = (EditText)
findViewById(R.id.text_enterpassword);
if(passwordEditText.getText().toString().equals("Test")){
same = true;
}
return same;
}
}
However whenever I press the button my program just crashes.
Cheers for your help!
There are a couple of points to notice:
MyMethods is extending Activity, but the way you're using it is unorthodox.
In openMenu(), your comparison is wrong, you're missing one = in
if (same = true) { //<---------- should be if (same == true) or if (same)
Remove your callActivity() and compareText() from MyMethods, and declare them in the class you will use them, that is in the class where you have openMenu(). I'd also rename compareText() to isPasswordValid(), to make it more clear.
Rewrite openMenu() to:
public void openMenu(View view) {
if (isPasswordValid()) {
callActivity();
}
}
You can also rewrite compareText():
public boolean isPasswordValid() {
EditText passwordEditText = (EditText) findViewById(R.id.text_enterpassword);
return passwordEditText.getText().toString().equals("Test");
}
Also, since you're launching another activity, make sure it's declared in AndroidManifest.
I am trying to create an application with a widget. When the user places the widget on the desktop a listview should come up with a list of items. The user selects an item then the widget is created with the respective text related to that item. I thought I should do this by showing a dialog in the Service but it throws me
Caused by: android.view.WindowManager$BadTokenException: Unable to add
window -- token null is not for an application
to the dialog_newitem.show(); line. For simplicity I am using now a simple alertdialog.
Is it the way to do this? I haven't found anyhing about this on the net.
public class UpdateWidgetService extends Service {
private static final String LOG = "de.vogella.android.widget.example";
public static String ACTION_WIDGET_CONFIGURE = "ConfigureWidget";
public static String ACTION_WIDGET_RECEIVER = "ActionReceiverWidget";
String value;
Dialog dialog_newitem;
EditText et_newitem;
#Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "UpdateWidgetService", Toast.LENGTH_SHORT).show();
dialog_newitem = new Dialog(this); //I tried UpdateWidgetService.this, too
dialog_newitem.setContentView(R.layout.dialog_productlists_grp_capitalized);
dialog_newitem.setTitle("Select");
dialog_newitem.setCancelable(true);
et_newitem = (EditText) dialog_newitem.findViewById(R.id.et_item_name);
Button btn_Save = (Button) dialog_newitem.findViewById(R.id.btn_save_pr);
btn_Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
value = et_newitem.getText().toString();
}
});
Button btn_Cancel = (Button) dialog_newitem.findViewById(R.id.btn_cancel_pr);
btn_Cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog_newitem.dismiss();
}
});
dialog_newitem.show(); //error
Toast.makeText(this, "value: " + value, Toast.LENGTH_SHORT).show();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
I have used this alertdialog in some other part of the code, and there it is working fine. I think it has something to do with the service.
You can't show a dialog in the service.
if you really want to show a dialog.
try to start an Activity and set the Activity's Theme to Theme.Dialog.
There is a demo in The ApiDemo Project
I know this thread is old, but thought it would be worth contributing anyway for future sufferers.
Although most will say its not recommended to launch dialogs directly from a service, the following workaround works for me. Use the ServiceDialogBuilder class below to build your AlertDialog. Unlike the AlertDialog.Builder, this will work with a Service context and show() can be called directly from a service without having to start a new activity.
Just be wary that this is a bit of a hack, so there may well be some unintended side effects from doing this.
Hope this helps
public class ServiceDialogBuilder extends AlertDialog.Builder {
public ServiceDialogBuilder(Context context) {
super(context);}
#Override
public AlertDialog create() {
AlertDialog dialog=super.create();
//Change dialog window type from TYPE_CHANGED to TYPE_SYSTEM_ALERT
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
return dialog;
}
#Override
public AlertDialog show() {
return super.show();
}}
Just make sure your dialog's window is set to SYSTEM_ALERT:
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
I'm trying to use Toast inside OnCLickListener. My code triggers the following error:
The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (new View.OnClickListener(){}, String, int)
This is my code:
Button register = (Button) findViewById(R.id.register);
register.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
EditText name = (EditText)findViewById(R.id.name);
String Lname = name.getText().toString();
Toast.makeText(this, Lname, Toast.LENGTH_SHORT).show();
}
});
As The Kenny said, this is refering to the View.OnClickListener instead of your Activity. Change this, to MyActivity.this.
For example,
public class MyActivity extends Activity {
// ... other code here
Toast.makeText(MyActivity.this, Lname, Toast.LENGTH_SHORT).show();
In this case, this refers to the instance of the anonymous subclass of View.OnClickListener. You have to refer to the this of the class where you create the anonymous class.
Use MyActivity.this as this refers to your onclickListener.
You can use getApplicationContext() as well. See the documentation.
Anywhere, just use the following:
((Activity) mContext).runOnUiThread(new Runnable() {
public void run() {
Toast my_toast = Toast.makeText(mContext, "YOUR TEXT OR STRING", Toast.LENGTH_LONG);
my_toast.setGravity(Gravity.CENTER, 0, 0);
my_toast.show();
}
});
You just need to define at the top of your activity (just after the onCreate):
mContext = this;
Also, see that I decomposed it a bit to be able to handle the gravity as I want (sometimes you may want the toast to appear at the center of the screen)...
Another approach to achieve your goal is to implement the OnClickListener interface. This way you implement the onClick() method in your Activity and you could thus assign this. In addition, you can assign this to multiple Buttons. You can distinguish these Buttons from each other by comparing their IDs via an appropriate if, respectively switch statement within the onClick() method.
public class MyActivity extends Activity implements OnClickListener{
// ...
protected void onCreate (Bundle savedInstanceState){
// ...
Button register = (Button) findViewById(R.id.register);
register.setOnClickListener(this);
}
public void onClick(View arg0) {
EditText name = (EditText) findViewById(R.id.name);
String text = name.getText().toString();
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
}
try this
public void onClick(View arg0) {
EditText name = (EditText)findViewById(R.id.name);
String Lname = name.getText().toString();
Toast.makeText(arg0.getContext(), Lname, Toast.LENGTH_SHORT).show();
}