EditText Android can't create object by id - android

I am trying to access the editText that is in the box... I am trying to create a object for it, but for some reason it is not working, I am really really new to Android so be it's a little confusing for me.
package com.example.myfirstapp;
import android.os.Bundle;
import android.app.Activity;
import android.text.TextWatcher;
import android.widget.EditText;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText txt = new (EditText) findViewByID(R.id.editText1);
}
}
and here is the XML
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="10"
android:inputType="numberPassword" >
<requestFocus />
</EditText>
I am getting a syntax error on new and method is undefined for findViewByID for type MainActivity

Just remove the new:
EditText txt = (EditText) findViewById(R.id.editText1);
This actually is a cast, meaning you tell the compiler that the object that is returned by findViewById not only is a View, which the method is declared to return, but a specific subclass of View called EditText.
This line does not actually create a new View, but picks a View out of the Activity's content view you set by calling setContentView().
The id you pass as the function's argument is used to identify the View that you want to be picked out of the content view.

Try this.
EditText txt = (EditText) findViewByID(R.id.editText1);

Related

New to coding, app keeps crashing on start up

I'm trying to have a text field and a text view, and set the text view text to whatever is on the the field.
This is my code:
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView helloMessage = (TextView) findViewById(R.id.hello); //define textView to show the message
EditText nameField = (EditText) findViewById(R.id.Name); // Text field to get the name from
String getName = nameField.getText().toString(); // set a variable with the text field's value
helloMessage.setText(getName); // set text on the hello textview to be the name.
}
}
activity_main.xml:
<LinearLayout 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:background="#B388FF"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/Name" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/hello"/>
</LinearLayout>
Thanks in advance for any sort of help!
Brother you need to setContentView(R.layout.activity_main); before finding any other view
You forgot to add setContentView(R.layout.activity_main) to onCreate()

Android button IllegalStateException with onClick(MainActivity)

Brand new to android. I have a button that is supposed to trigger an onClick method that is an override of the onClick method used with the onClickListener. The problem is that when I press the button an IllegalStateException is thrown saying that the onClick(MainActivity), as defined in the XML of the button, method cannot be found.
The code below is the code that throws the IllegalStateException. However if I change the XML of the button to android:onClick="onClick" then the button works completely fine. Why is this?
Button XML:
<Button
android:text="Accept"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="84dp"
android:id="#+id/button2"
android:onClick="onClick (MainActivity)" />
MainActivity Code:
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements View.OnClickListener{
private TextView textView;
private EditText username;
private EditText password;
private Button accept;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView3);
username = (EditText) findViewById(R.id.editText);
password = (EditText) findViewById(R.id.editText2);
accept = (Button) findViewById(R.id.button2);
}
public void logIn(View view)
{
Log.i("testUsername", username.getText().toString());
Log.i("testPassword", password.getText().toString());
}
#Override
public void onClick(View view)
{
if((Button)view == accept)
{
Log.i("testUsername", username.getText().toString());
Log.i("testPassword", password.getText().toString());
}
}
}
Why is this?
Because android:onClick="onClick" is correct syntax. None of the following are correct syntax:
android:onClick="onClick (MainActivity)"
android:onClick="onClick (View)"
android:onClick="onClick(View)"
android:onClick="onClick and anything else"
Quoting the documentation for android:onClick:
Name of the method in this View's context to invoke when the view is clicked. This name must correspond to a public method that takes exactly one parameter of type View. For instance, if you specify android:onClick="sayHello", you must declare a public void sayHello(View v) method of your context (typically, your Activity).
OK, with the help of #HappyRavi on Twitter, I was able to reproduce the problem. It's an IDE bug that you will encounter if you do things in a certain order:
Add the method that you want to route the click event to
Drag the Button into the GUI editor
Click the onClick drop-down in the Properties pane of the GUI editor
Doing things in a different order will not reproduce the problem.
With luck, they can get this fixed in some patch release for Android Studio 2.3.
It should be implemented like below
<Button
android:text="Accept"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="84dp"
android:id="#+id/button2"
android:onClick="buttonClickHandler" />//name of method should be given here
And add the method in Activity file
public void buttonClickHandler(View view) {
//handle button click here
}
This will work only when method is added in Activity class and not with Fragment

java.lang.RuntimeException: Unable to start activity(TextView is null)

I am trying to add custom fonts in my android app.
LoginActivity.java
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
import android.app.Activity;
import android.widget.TextView;
import android.graphics.Typeface;
public class LoginActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button login = (Button) findViewById(R.id.login);
Button signup = (Button) findViewById(R.id.signup);
TextView username = (TextView) findViewById(R.id.username);
Typeface custom_font = Typeface.createFromAsset(this.getAssets(), "fonts/smartwatch.ttf");
username.setTypeface(custom_font);
login.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
Intent loginOnlyIntent = new Intent(view.getContext(), LoginOnlyActivity.class);
startActivity(loginOnlyIntent);
}
});
signup.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
Intent signUpIntent = new Intent(view.getContext(), Signup.class);
startActivity(signUpIntent);
}
});
}
}
I am getting the error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example/com.example.LoginActivity}: java.lang.NullPointerException
I have added assests folder in the src/main folder too.In the assests folder is fonts folder in which I have font file smartwatch.tff
I have checked almost every answer available on SO but nothing worked so far for me.
update:
After using Debugger, I found that
TextView username = (TextView) findViewById(R.id.username);
returns null and hence the NPE.
Adding layout file :
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="155.0dip"
android:paddingTop="200.0dip"
android:paddingRight="4.0dip"
android:paddingBottom="1.0dip"
android:layout_below="#+id/TextView02">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/UserName"
android:id="#+id/username"/>
<EditText
android:id="#+id/edit_phone"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:inputType="number"
android:hint=" "/>
</LinearLayout>
Please help me why textview username is null
Your code works fine for me.
In LinearLayout you provided missing buttons, but I think you have added them in your project. In addition, I have error because you have omitted the XML namespace
xmlns:android="http://schemas.android.com/apk/res/android"
into Linear Layout.
Try to Invalidate and restart project, It 's strange the null pointer problem on TextView, You've done all right, unless the problem lies elsewhere.
Make sure you have created the Assets folder doing:
Right click on "app" folder, new --> Folder --> Assets Folder

Show String from EditText

I want to show TextView editable like the app "Google Keep" but
EditText text = (EditText)findViewById(R.id.edittext);
String value = text.getText().toString();
didn't work
Hello I've made a example that I think you can use:
Layout:
<LinearLayout 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:orientation="vertical"
>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textColor="#FF0000"
android:text="#string/hello_world" />
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/getInfoButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GET INFO"
android:layout_gravity="center_horizontal"
/>
</LinearLayout>
MainActivity
package com.example.testedittext;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView info;
private EditText input;
private Button getInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
info = (TextView) findViewById(R.id.textView);
input = (EditText)findViewById(R.id.editText);
getInfo = (Button)findViewById(R.id.getInfoButton);
getInfo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String inputText = input.getText().toString();
info.setText(inputText);
}
});
}
}
Here is the output:
Hope this helps,
Cheers
That is the correct syntax for getting the text in string format of an edittext.
The value of String "value" is actually "" right now because you called
text.getText().toString();
IMMEDIATELY after EditText text was instantiated. As you can imagine, the moment it was created, there was no text inside it, so that's why "value" has an empty string.
If you want to retrieve the value of the edittext at a specific call, I'd recommend adding a button in your xml layout, and in your code, add this:
Button button = (Button) findViewById(R.id.somebutton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text.getText().toString();
}
});
This will get the current String value of the edittext when you click on the button.
You have to use the value String somewhere else it will tell you that its not used.
Then you have to use that piece of code at a point of time where you have had a change to set the value of that ediettext.

Null pointer exception in TextView

This is my layout
<?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"
android:orientation="vertical" >
<TextView
android:id = "#+id/postQues"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Post A Question" />
<TextView
android:id="#+id/postAnswer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:text="Post Your Answer" />
<Button
android:id="#+id/submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:clickable="true"
android:text="Submit" />
</RelativeLayout>
This is my activity:
package com.qstack.quizbox;
import roboguice.activity.RoboActivity;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView;
import android.content.DialogInterface;
import android.view.View.OnClickListener;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.app.main.R;
#ContentView(R.layout.q_box)
public class QuizBox extends RoboActivity {
#InjectView(R.id.postQues) TextView postQues;
#InjectView(R.id.postAnswer) EditText postAnswer;
//#InjectView(R.id.submit) Button submitA;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
PostQuestion postQuestion = new PostQuestion();
postQues.setText(postQuestion.postQuestion());
submitA.setOnClickListener(submitAnswerListener);
}
private OnClickListener submitAnswerListener = new OnClickListener() {
//onClick view
public void onClick(View v) {
String answer;
answer = postA.getText().toString();
CheckAnswer checkAnswer = new CheckAnswer();
if (answer == checkAnswer.checkAnswer()) {
postA.setText("Correct");
}
}
};
}
I am getting a null pointer exception at line number 48, caused because postQues = null. When I remove postAnswer from the code, there is no null pointer exception. I've cleaned my project and all that. Any help
I can't comment yet on your answers, but people miss the point: he, like me, is using RoboGuice to inject views and stuff.
The sole purpouse of this framework is to avoid the boiler-plate part on onCreate() where you won't need to use setContentView and findViewById() anymore !
As to why he gets a NullePointerException, I don't know. I happen to have the same issue on one of my activies although it works just fine on all the other...
[EDIT]
I found the solution : I mixed up the type of two views.
If you put setContentView() where it is supposed to be, you will get the error.
The application wil say it cannot assign. Because the type doesn't match.
Therefore you get a nice
java.lang.RuntimeException: Unable to start activity ComponentInfo
But if you use RoboGuice framework, you get such error (well in my case I did not). However, all you views will all be null.
Hope it will help someone someday.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourxml); // you have missed this.....
PostQuestion postQuestion = new PostQuestion();
postQues.setText(postQuestion.postQuestion());
submitA.setOnClickListener(submitAnswerListener);
}
I had the same issue, and followed Mackovich's suggestions. He's right in pointing out that you don't need setContentView() with RoboGuice, as long as you annotate your activity with #ContentView.
In my case, the issue was caused by the fact that I had replaced an AutoCompleteTextView with an EditText, but forgot to make the same replacement in the activity with corresponding #InjectView. This was causing my NullPointerException.
Again, like Mackovich said, if I use setContentView() instead of #ContentView, the stacktrace gives me a more useful message:
Caused by: java.lang.IllegalArgumentException: Can't assign class android.support.v7.internal.widget.TintEditText value android.support.v7.internal.widget.TintEditText#426ce048 to class android.widget.AutoCompleteTextView field usernameTextView
I guess that's an argument against using Roboguice's #ContentView, at least until a fix is made in order to show the correct stacktrace.
You need to call setContentView(R.layout.the_xml) first (right after super.onCreate()). Otherwise RoboGuice doesn't know what to inject into your variables!
You forgot the following line in your code,
setContentView(R.layout.main);
which should be after this line of onCreate() method
super.onCreate(savedInstanceState);
you have missed that line
setContentView(R.layout.xml_filename);

Categories

Resources