Cannot resolve symbol (any ID's) Android Studio - android

I'm a noob Android studio programmer (this is hour 2 of learning!) and I expect this is a real rookie error I'm making!
I've got a Plain Text field in my application and I would like to set the text of this dynamically. I've given the plain text field the ID of: "resultText". Here's what I try;
public void calcnums(View v)
{
int x=firstNum + seondNum;
resultText.setText("Result: " + x);
}
For some reason I get 'resultText' highlighted in red and the hover over message is; Cannot resolve symbol 'resultText'.
I have the feeling that I'm doing something wrong by using the ID, but I'm lost!
Full code as suggested in comments;
import android.app.Application;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.util.Random;
public class AddNumbers extends AppCompatActivity {
private int firstNum;
private int seondNum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_numbers);
}
public void calcnums(View v)
{
int x=firstNum + seondNum;
resultText.setText(String.format("Result: %d", x);
}
public void setNums(View v)
{
TextView tx= (TextView) findViewById(R.id.text);
Random r = new Random();
int x=r.nextInt(2) + 1; // r.nextInt(2) returns either 0 or 1
firstNum = x;
r = new Random();
x=r.nextInt(2) + 1;
seondNum = x;
num1.setText(""+firstNum);
num2.setText(""+seondNum);
}
}

It seems you need to declare the View resultText
Like,
EditText resultText = (EditText) findViewById(R.id.resultText);
Also make sure that the name you are using for the resultText View in xml is written correctly as provided in the method findViewById()
usually cannot resolve symbol means some problems in variable declarations.
I am too learning android and I stumbled upon this problem as well.

I don't have the whole snippet of your code.But the thing you might be missing is to point your EditText object to view in xml.
EditText resultText = (EditText) v.findViewById(R.id.result_edit_text);
<EditText
android:id="#+id/result_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/result_edit_text"
/>

Let's assume that we have an layout with an edittext
<EditText
android:id="#id/txt_user_email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="text" />
It has an ID. In your actitivy you must find and cast the EditText as follow:
EditText txtUserEmail = (EditText) findViewById(R.id.txt_user_email);
txtUserEmail.setText("klaus.dieter#lusty-swingers.de");

You need to find your text view in onCreate(), like that:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_numbers);
TextView tx= (TextView) findViewById(R.id.text);
}

Related

Android OnClickListener infinite button use problem

I am trying to make an simple button that will cooperate with TextView, array and method changer (in public class Change). However the application uses the method changer only twice (below). It should work on every click. The changer method is used for the change in displayed array.
1-click: 1 |
2-click: 4 |
3-click: 1 |
4-click: 1 |
...-click: 1 |
I don't know where is the problem.
My target solution should be 1,4,1,4,1,4 ...
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
String[] numbers = {"1", "2","3","4"};
private Button mButton;
int i = 0;
Change ch = new Change();
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.button2);
text = (TextView) findViewById(R.id.tv1);
ch = new Change();
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text.setText(numbers[0]);
numbers = ch.changer(numbers);
i++;
}
});
}
}
Change.java
public class Change {
String[] arraynew = new String[4];
public String[] changer(String[] array){
arraynew[0]=array[3];
arraynew[1]=array[2];
arraynew[2]=array[1];
arraynew[3]=array[0];
return arraynew;
}
}
The arraynew variable in your code is global - so it will not create a new array every time you call the changer method, only rearranges its contents.
Here comes the tricky part: When you call the method for the second time, the parameter is the same object as arraynew. So when you do arraynew[0]=array[3] it changes 4 to 1 on the first slot; but arraynew[3]=array[0] will copy that newly changed 1 to the third index (where it is still the same 1 you put there). It basically eliminates the 4, making it impossible to recover.
Solution: Make arraynew local. If you declare it in the method, it will never be the same array, so the issue won't appear.

Asdroid SDK Eclipse : Simple App gave Black Screen and Stopped?

First of all I'm totally new with Eclipse so my Code maybe full of errors *
Second I wrote a simple App about two buttons (Add,Sub) with One TextView , the idea is about click one of these buttons and then the TextView changes and gives a number (Add=+1 , Sub = -1) , I'm Sure Compiler gave No Errors
But I don't know why I have a lot of problems :
1-The Apk file is not generated in the bin folder .
2-I tried to Export it using Android tools , and then tried it on my mobile and it gave black Screen then stopped working.
3-I got 3 warnings in The Activity_Main.xml about buttons and textview "Hardcoded String Should use #String Resource "
I'm totally Confused , I don't know how to fix it i tried a lot and searched on the internet but i couldn't
Here is the Main_Activity.Java :
package com.example.counter;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
int Counter = 0;
Button A = (Button) findViewById(R.id.Add);
Button S = (Button) findViewById(R.id.Sub);
TextView C = (TextView) findViewById(R.id.Calculate);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
A.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Counter ++ ;
C.setText("Your Total Counter Is " + Counter);
}
});
S.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Counter -- ;
C.setText("Your Total Counter Is " + Counter);
}
});
}}
And here is the Activity_main.xml :
<TextView
android:id="#+id/Calculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="21dp"
android:text="Waiting To Calculate"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/Sub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/Add"
android:layout_alignBottom="#+id/Add"
android:layout_alignRight="#+id/Calculate"
android:text="Sub" />
<Button
android:id="#+id/Add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Calculate"
android:layout_below="#+id/Calculate"
android:layout_marginTop="66dp"
android:text="Add" />
The app suppose work even on API1 and Targeted API 17 (Jelly Bean) I tested it on Galaxy S3 Mini (have Android 4.2) and it crashed , tried simple app before with same settings and worked
*Any Help is Appreciated , thanks for your time and Sorry for make it Long *
The 2nd problem is on the View (e.g. Button, TextView) initialization.
Since they are declared and initialized at class scope, they are initialized before onCreate() (and thus setContentView()) is called. Because there is no layout inflated at the moment, the initialization will return null. Then, when setOnClickListener() is called, it will throw NullPointerException and crashes the app.
The solution is to move the initialization after setContentView() is called.
public class MainActivity extends Activity {
int Counter = 0;
Button A;
Button S;
TextView C;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
A = (Button) findViewById(R.id.Add);
S = (Button) findViewById(R.id.Sub);
C = (TextView) findViewById(R.id.Calculate);
A.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Counter++;
C.setText("Your Total Counter Is " + Counter);
}
});
S.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Counter--;
C.setText("Your Total Counter Is " + Counter);
}
});
}
}
For the 3rd problem, just as Juwee posted, you can define the String resources to be used in XML layout file (it can be used in the code too!).
Create an XML file in /values folder with <resources> root element (or just use strings.xml if it's already there). Then, you can declare a string resource with String value
Example
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="add">Add</string>
</resources>
Then, on the XML layout, you can refer it as android:text="#string/add" (Or in code as setText(R.string.add))
Since this is just only a warning, you can actually ignore it. But if you decide your app to support localization, or if you use the same String quite often, then it is better to define it as app's resource.
Third problem : About this property android:text="Sub" ,you can define the text in the resource file "string.xml",like <string name='subString'>sub</string>,then make reference to it.android:text="#string/R.string.subString" . Have a try .

Android- How can I show text selection on textview?

I am implementing a epub reading app where I am using textview for showing text of epub. I want to select text from textview when user long presses on textview and then do multiple operations on selected text of textview like highlight etc..
So, How can I show those cursors to user to select text whatever user wants.
*I dont want to use EditText and make it look like textview. May be overriding textview is prefered.
*I have attached screenshot to explain what I am looking for-
This is asked long time ago, when I had this problem myself as well. I made a Selectable TextView myself for my own app Jade Reader. I've hosted the solution to GitHub. (The code at BitBucket ties to the application, but it's more complete and polished.)
Selectable TextView (on GitHub)
Jade Reader (on BitBucket)
Using the following code will make your TextView selectable.
package com.zyz.mobile.example;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
public class MainActivity extends Activity {
private SelectableTextView mTextView;
private int mTouchX;
private int mTouchY;
private final static int DEFAULT_SELECTION_LEN = 5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// make sure the TextView's BufferType is Spannable, see the main.xml
mTextView = (SelectableTextView) findViewById(R.id.main_text);
mTextView.setDefaultSelectionColor(0x40FF00FF);
mTextView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
showSelectionCursors(mTouchX, mTouchY);
return true;
}
});
mTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mTextView.hideCursor();
}
});
mTextView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
mTouchX = (int) event.getX();
mTouchY = (int) event.getY();
return false;
}
});
}
private void showSelectionCursors(int x, int y) {
int start = mTextView.getPreciseOffset(x, y);
if (start > -1) {
int end = start + DEFAULT_SELECTION_LEN;
if (end >= mTextView.getText().length()) {
end = mTextView.getText().length() - 1;
}
mTextView.showSelectionControls(start, end);
}
}
}
It depends on the minimum Android version that you'd like to support.
On 3.0+, you have the textIsSelectable attribute on the TextView, which enables this behavior. E.g.:
<TextView android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="#dimen/padding_medium"
android:text="#string/hello_world"
android:bufferType="spannable"
android:textIsSelectable="true"
android:textSize="28dip"
tools:context=".MainActivity" />
Below that, you best bet is to use an EditText that looks and behaves like a TextView (apart from the slection thing). Or you can implement this feature yourself using spans.

Android - Simple program but still struggling

I used to have some experience with developing for android but I started up again after 6 months and forgot most of it. I am now using a macbook to do my developing on and had to set up Eclipse, the Android SDK and AVD all over again and I'm worried I messed something up.
When I start a new project with the default activity that displays "Hello World" on my screen the app runs fine. I then tried to put in two buttons that cause the text in a new TextView to change. But whenever I include the textView part I get a runtime error. When I comment it out, the app runs but obviously nothing happens. Based upon the tutorials I've been reading, this is the appropriate place and way to declare/create the textView but I can't figure out what's wrong. Any suggestions?
[Edit] I was messing around and found that I can make the mytext a field instead of a TextView and that worked. So in my onCreate(), I put
mytext = (TextField)findViewById(R.id.TextView1);
but that doesn't seem the right way to do things.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class IntroActivity extends Activity {
TextView myText = (TextView)findViewById(R.id.textView1);
//i've tried this with final added on to it as well (recommended by eclipse)
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setButtonClickListener();
}
private void setButtonClickListener() {
Button button1 = (Button)findViewById(R.id.button1);
Button button2 = (Button)findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
myText.setText("Hello");
}
});
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// myText.setText("Goodbye");
}
});
}
}
This:
TextView myText = (TextView)findViewById(R.id.textView1);
should be separated. The declaration should be at the same place:
private TextView myText;
But the assignment should come only after setContentView:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myText = (TextView)findViewById(R.id.textView1);
This is done since before setContentView, Dalvik doesn't know from which layout to take the view that matchs the id R.id.textView1

show the text of an EditText into a TextView

Describing the functionality of my application: I have put in a Relative Layout a TextView, an EditText and a button. All I am trying to do is: when the user writes something in the EditText and push the button, then the content of the EditText is appeared in the TextView(just like a chat-virtual chat). Everything works perfectly, but when the EditText is empty,and the button get pushed, an empty line is appeared in the TextView(and i don't want to..). Although I've tried to solve it using an if the empty line is still appearing in the TextView. I would be really greatfull, if you could help!!! Than you in advance!
Here is my code:
package teiath.android.appliacation;
import android.app.Activity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class M_chat extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/**Code for the scroll bars in the TextView. */
final TextView tv = (TextView)findViewById(R.id.TEXT_VIEW);
tv.setMovementMethod(new ScrollingMovementMethod());//for the scroll bars
/** Code for the scroll bars in the EditText. */
final EditText wr = (EditText)findViewById(R.id.EDIT_TEXT);
wr.setMovementMethod(new ScrollingMovementMethod());//for the scroll bars
final Button button = (Button) findViewById(R.id.btn1);//find the button by id in main.xml
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
String wrcontent = wr.getText().toString();//gets the text of the EditText and put it in "tvcontent" variable.
String tvcontent = tv.getText().toString();//gets the text of the textView and put it in "tvcontent" variable.
if (wrcontent!="")//if the EditText is not empty
{
//check if the TextView is empty or not
if (tvcontent!="")//If it is not empty...
{
tv.setText(tvcontent + "\n" + wrcontent);//add its current(TextView's text) text, new line and the text of the EditText as the new text of TextView.
//tv.setVisibility(0);//makes visible the textView with the cloud1.png background
wr.setText("");//set the text of the Edit Text as empty
//wrcontent = "";
}
else//if the TextView is empty...
{
tv.setText(wrcontent);//add the text of the editText as the new text of the TextView
wr.setText("");
}
}
/**if (wrcontent=="")
{
}*/
//finish();
}
});
}
}
Don't use !="" for String comparison. To check for empty text, use something like
if ( wrcontent != null && wrcontent.trim().length() == 0 ) {
Better yet, include Guava libraries in your code.

Categories

Resources