I am totally new at Android Studio.
I am trying to write simple application with 2 screens and passing info from screen 1 to screen 2.
This is the code of the Second activity.
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
if(getIntent().hasExtra("com.gmail.zionrevi.SOMETHING")) {
String text = getIntent().getExtras().get("com.gmail.zionrevi.SOMETHING").toString();
TextView tv = (TextView)findViewById(R.id.textview);
tv.setText(text);
}
}
}
when i am running it i am getting the following Run Time exception:
E/AndroidRuntime: FATAL EXCEPTION: main
android.support.constraint.ConstraintLayout cannot be cast to android.widget.TextView
on the following line
TextView tv = (TextView)findViewById(R.id.textview);
What i am doing wrong?
can someone help me please?
You are trying to cast ConstraintLayout into TextView which cannot succeed. They are two completly different view.
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="#+id/textView"
android:layout_height="match_parent">
You need to set TextView in you xml layout or change ConstraintLayout id to some other id and set TextView id to textView
Part of learning Android is understanding the errors. When you're told that typeX cannot be cast to typeY it almost always means you're attempting to cast something to the wrong type.
In this case, it appears to be occurring here TextView tv = (TextView)findViewById(R.id.textview);. When you do something such as (TextView)findViewById(R.id.textview), you're casting whatever is returned by findViewById(...) to a TextView. If that ID you pass to the function is not a TextView, you will get a ClassCastException
In your case, very likely, you have a ConstrainLayout in your .xml file for this activity that has an ID of textview.
welcome at android programming ..
i think that your R.id.textview refers to [ConstraintLayout]
you should set your [textview] id to be [#+id/textview] and of course clear it from yourConstraintLayout .. and it will be
solved :)
happy programming
Related
Whenever I want to find my grid layout by ID my app crashes immediately upon starting. It is not a typo (I don't get any compiling errors).
It is the first thing I have declared in onCreate method so it doesn't crash because some other method would try to do something with the layout before the findViewById is called.
What could be the cause?
(I tried changing its ID, name... didn't work)
Part of the code:
public class MainActivity extends AppCompatActivity {
TextView countdownView, expressionView, scoreView, resultView, goView;
LinearLayout linearLayout;
GridLayout gridLayout;
CountDownTimer countDownTimer;
Random randomGenerator;
Button startGameButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridLayout = findViewById(R.id.gridLayout);
//other code here}
replace your line by this
androidx.gridlayout.widget.GridLayout gridLayout = findViewById(R.id.gridLayout);
I had to change casting from this:
GridLayout gridLayout = findViewById(R.id.gridLayout);
To this:
android.support.v7.widget.GridLayout gridLayout = findViewById(R.id.gridLayout);
findViewbyId is changed in android studio 3.*
refer
findViewById() signature change
All instances of the findViewById() method now return <T extends View> T instead of View. This change has the following implications:
This may result in existing code now having ambiguous return type, for example if there is both someMethod(View) and someMethod(TextView) that takes the result of a call to findViewById().
When using Java 8 source language, this requires an explicit cast to View when the return type is unconstrained (for example, assertNotNull(findViewById(...)).someViewMethod()).
Overrides of non-final findViewById() methods (for example, Activity.findViewById()) will need their return type updated.
EditText message=super.findViewById(R.id.txtmessage);
I am a new android learner. Directly trying codes of videos in my learning
Either cast it like A.El Saeed mentioned in his answer
gridLayout = (GridLayout)findViewById(R.id.gridLayout);
or post your XML code also because sometime, it may possible that there will be some typo in your XML code or maybe you are using different grid layout id than defined in the XML
Change it
from
gridLayout = findViewById(R.id.gridLayout);
to
gridLayout = (GridLayout) findViewById(R.id.gridLayout);
You should cast the result from findViewById function
I'm trying to change my TextView text from the code.
This is what my xml looks like:
XML:
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal" />
And the code:
TextView tv1 = (TextView)findViewById(R.id.textView1);
tv1.setText("Hello");
setContentView(tv1);
I'm getting an error on my device and the application stops.
I tried to show a TextView (not connected to an XML TextView) and it worked.
Your approach is incorrect. I think it will be Null Pointer Exception (next time post log cat)
You need to specify the layout you are using first, before finding views.
Java:
// Specify the layout you are using.
setContentView(R.layout.yourlayout);
// Load and use views afterwards
TextView tv1 = (TextView)findViewById(R.id.textView1);
tv1.setText("Hello");
Kotlin:
// Specify the layout you are using.
setContentView(R.layout.yourlayout)
// Load and use views afterwards
val tv1: TextView = findViewById(R.id.textView1)
tv1.text = "Hello"
Click Here to study exactly you want to know
remove this.. setContentView(tv1);
I got the same problem. My app was stopping too.
Actually, I was writing the code outside of the function/method. So to fix this problem, these lines
TextView tv1 = (TextView)findViewById(R.id.textView1);
tv1.setText("Hello");
must be inside a function/method. (can be user defined)
(I am new to android studio so I don't know the reason behind the problem but I only know how to fix this. Maybe this helps new ones despite this question being 8 years old.)
Why can't I use setContentView(R.layout.main) in last line without setContentView(tv)? Please explain this to me.
package com.mue.helloworld;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloWorldActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("Hello, Android i am suvankar");
setContentView(tv);
}
}
You have to define the textview in the R.layout.main ( a xml file) this file contains the information of the objects in the activity.
if you are using eclipse you can simple drag and drop a textview, just open the main file.
(folder res -> layout -> main.xml)
then yo have to call it in your program:
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.tv); //<-- yo have to use the same ID that is in the main.xml file
and then you can set the text. all of this in the oncreate function.
tv.setText("Hello, Android i am suvankar");
Well, I hope I've helped. is my first response here
You shouldn't call setContentView() twice in your onCreate. Either call setContentView(R.layout.main) or call setContentView(tv) but not both. I would prefer the first of the two... but you need to make sure the TextView is declared in your layouts XML.
Lets first try to understand what setContentView() method does. Basically setContentView() places your UI on your Activity. Now to create a UI component for your Activity, you can either use xml resource (e.g. R.layout.main) or you can obtain an instance of the UI component in your code and dynamically add it to your Activity. For example
TextView tv = new TextView(this);
tv.setText("Hello, Android i am suvankar");
setContentView(tv);
In your case you created an instance of the TextView tv, set some text to it and added that to your Activity. Here you dont need to use setContentView(R.layout.main). However if you have a xml layout (main.xml) in your layouts folder like the following:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World"
/>
</LinearLayout>
and at the bottom of your application you write setContentView(R.layout.main), your should see a black screen with Hello World written on it. This is because here you created a TextView instance, set some text to it, but did not place it to your activity by calling
setContentView(tv), rather you added a completely different layout resource. If you use setContentView(tv) and at the end of your onCreate() you add setContentView(R.layout.main) then again you will see Hello World instead of "Hello, Android i am suvankar" because at the end you replaced your UI resource. However, if you forget to add your xml resource and call 'setContentView(R.layout.main)' compiler will issue an error for not finding the xml resource specified.
Well basicly I have a textview and when the application is created it sets a string as the textviews text not hard, but I get a force close error when I run the app on my phone.
TextView sdcard=(TextView)findViewById(R.id.sd_textview);
sdcard.setText(R.string.not_mounted);
Then I have a error on a togglebutton also
ToggleButton silent=(ToggleButton)findViewById(R.id.silentbutton);
silent.setChecked(false);
And I have errors for all my other buttons/textviews can anyone help, please?!
EDIT:
I cant post pics because I am a new member, :(
Link to imgshack http://imageshack.us/photo/my-images/849/unledggp.png/
If code for the whole textview snippet.
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_UNMOUNTED)) {
TextView sdcard=(TextView)findViewById(R.id.sd_textview);
sdcard.setText(R.string.not_mounted);
}
OnCreate Function
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkSD();
checkRing();
checkWifi();
checkBt();
}
Look for all instances of sd_textview and make sure the one that you're trying to reference is a TextView. If you want more clarity you can debug your code and see what object is actually being returned by not casting into a TextView:
View sdcard = findViewById(R.id.sd_textview); //debug this
//you can also log the View object to see the type
Log.d("Test", "" + sdcard);
Looking at your error log (assuming its the right error log) you have a ClassCastException in the checkWifi method. Edit your question and include ALL of the onCreate method and all of the checkWifi method, but I expect you are using the same id for multiple views.
Two things I can think of (although seeing more code would help).
Make sure you have called setContentView(R.layout.main) (or whatever your layout file is called). Do this BEFORE any attempt to use findViewById(...).
Secondly sdcard.setText(R.string.not_mounted); in this statement R.string.not_mounted is a resource ID (int) and not a string. You would need to use...
sdcard.setText(getString(R.string.not_mounted));
Is there anywhere that I can find documentation on the scope of the XML files? I have an app I am currently working on and have been struggling with getting a feature to work and it seems that the problem I am having is that I am trying to access an element in an XML file that must be out of scope. To simplify the layout, my project has main.xml, sub.xml, main.java, and sub.java files in it. As you can probably guess, main.java works with main.xml and sub.java is working with the elements in sub.xml. Here's where the issue comes in, I have a TextView element that is created in main.xml that I would like to modify the text in, but the action that would trigger it will occur in sub.java. I can't figure out how to change it from sub.java, and I can't figure out how to move the element into sub.xml. The code I am using is pretty simple:
TextView titleText = (TextView) findViewById(R.id.myTitle);
titleText.setText(filePath);
I get a FC every time I run the app, but if I move the code into main.java, it runs flawlessly. If anyone can offer any ideas, or point me in the direction of some documentation that would explain what java files can access what elements in which xml files, that would be awesome! Sorry for the novel, but I'm just struggling to get the point across. Thanks.
try like this Bryan in Main.xml file it works with no issue...........Declare first & then Initialize it...
public class Main extends Activity {
static TextView tv;
static Button submit;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
tv = (TextView) findViewById(R.id.header_text1);
}
}
Activity.findViewById(int) only works if that view is in the activity's layout. So no, you can't refer to a view in main.xml because that layout doesn't apply to sub.
Do you have any TextViews in sub.xml called myTitle?
You can access the the textview of main.java(main.xml) in submain.java as follows
In main.java write the following code
static TextView titleText = (TextView) findViewById(R.id.myTitle);
titleText.setText(filePath);
and u can access this submain.java as
Main.titleText.setText(filePath);