Not a duplicate: my question is simpler than all of the others.
I've been trying to follow the android hello world tutorial, and I can't get the very first example to work.
This is my code:
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloAndroid 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");
setContentView(tv);
}
}
As you can see, I copied and pasted directly out of the tutorial.
The problem is, that instead of displaying Hello, Android, it displays whatever is in the layout/main.xml file. If that file doesn't exist, it closes without displaying anything.
WHY IS THIS NOT WORKING?
As I've copied this directly from the official docs, I have no idea where to even start trying to debug it. Any pointers or suggestions you can give will be greatly appreciated!
Edit: posting my main.xml as requested
<?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, HelloAndroid"
/>
</LinearLayout>
Note that this was created automatically when I started the project, I didn't put it there.
Why do you have two TextViews with the same text? You shouldn't be doing this, if you're only going to use one, then only use one.
You XML is fine as is, but your Activity code needs to change:
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Heres an explanation of what you were doing...
You were building a TextView dynamically and setting the ContentView to that TextView is fine, but it was not your original intention. Your original intention or the original intention of the sample was to use the layout file and then set the contentview of that activity to that layout file, not just that textview.
Update
In lieu of what the OP said, he does want to build a TextView instance dynamically and apply it to the screen. If this is the case then you have to...:
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.FILL_PARENT));
tv.setText("Hello, Android");
setContentView(tv);
}
}
The only difference here is that the TextView has properties that are defining how it will appear on the screen. You can either user FILL_PARENT or WRAP_CONTENT.
you haven't set the xml file or layout in your application. You are directly calling the view.You need to call your view under layout.
Syntax: setContentView(R.layout.your xml file name);
Regarding the question about logcat, you'll find it in the Debug perspective in Eclipse. It's the log of error messages from system and user code.
Try this: You don't need to do setContentView at end. If you do that, it will override with what you have in XML.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourxmlfile);
TextView tv = (TextView)findViewById(R.id.helloText);
tv.setText("Hello, Android");
}
<TextView
android:id="#+id/helloText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, HelloAndroid" />
Related
I want to change the resource of an image view from a variable in android studio.
Let me explain you, i have first activity "selector activity" which has 21 images, on every image click, a variable god_name is changed to the particular god, now i am sending that variable using putExtra, now i want that to change the resource of an ImageView in MainActivity depending on the variable, for example if the variable is "two", then i want to change the resource to "R.drawable.two".
Something like that, I have some experience in python so I used f strings there, here can I do something?
MainActivity.class
(Note-I have not Included imports so the code is allowed to be uploaded.)
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String god_name = getIntent().getExtras().getString("chosen_god").toString();
ImageView god = findViewById(R.id.god);
god.setImageResource();
}
}
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black"
tools:context=".MainActivity">
<ImageView
android:id="#+id/god"
android:layout_width="413dp"
android:layout_height="496dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.666"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
app:srcCompat="#mipmap/hanuman" />
</androidx.constraintlayout.widget.ConstraintLayout>
I can use multiple if conditions and switch case statement but that would be so much large as I would have to write it 21 times so it is very difficult!
Thanks in advance for anyone kind of help!
That sounds like you need to use the resources.getIdentifier() to make this work.
I wrote once an answer to a related topic: https://stackoverflow.com/a/4865350/180538
Anyway what you need is to pass the name of the resource and then resolve the identifier to use it. So something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// make sure that god_name is the name of the resource, so AFTER R.mipmap.[resourceName]
// so for R.mipmap.two you need to pass "two" as "chosen_god" extra
String god_name = getIntent().getExtras().getString("chosen_god").toString();
ImageView god = findViewById(R.id.god);
int resId = getResources().getIdentifier(god_name, "mipmap", getPackageName());
god.setImageResource(resId);
}
A simple ListActivity containing a TextView and a ListView objects works fine if screen is not rotating.
Problem description. When running the app for the first time, TextView myText shows -1. It works. When clicking on different items myText sets/shows the value of the selected item id (or position). So, it works as well. On a certain moment, when for example item Two is selected and myText shows 2 I rotate the screen and myText becomes -1 (because onCreate triggers again), so it means, the ListView myList clears selection, but item Two still remains selected (painted as a checked RadioButton). What's the problem? (P.S. Same thing happens to GridView).
Here is my source-code:
activity_test.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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:fitsSystemWindows="true"
tools:context=".TestActivity">
<include layout="#layout/content_test" />
</android.support.design.widget.CoordinatorLayout>
content_test.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".TestActivity">
<TextView
android:id="#+id/myText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ListView
android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/myText"
android:choiceMode="singleChoice"/>
</RelativeLayout>
TestActivity.java
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class TestActivity extends ListActivity {
static String[] items = {"Zero", "One", "Two"};
TextView myText;
ListView myList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
myList = (ListView) findViewById(android.R.id.list);
setListAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_single_choice, items));
myText = (TextView) findViewById(R.id.myListViewSelectedText);
myText.setText(String.valueOf(myList.getSelectedItemPosition()));
}
#Override
public void onListItemClick(ListView parent, View view, int position, long id) {
myText.setText(String.valueOf(position));
}
}
try this one
<activity
android:name=".TestActivity"
android:label="#string/title_activity_test"
android:theme="#style/AppTheme"
android:configChanges="orientation|keyboardHidden|screenSize"/>
When a configuration change occurs, all activities will be recreated to ensure that the correct resources are used.
One way to preserve the state that you need, is to override onSaveInstanceState() putting all data you want to the provided Bundle parameter. Then, when the activity gets recreated, you can extract the saved values from the provided Bundle parameter in onCreate().
Just save the index of the selected list element, and then set it back when recreating.
Saving instance is more complicated process, #danail-alexiev is correct, in some cases you've save data manually and than restore it.
But why Checkbox stays checked? In short it's because it has own implementation of onSaveInstanceState that handles it. And there is some magic that calls it and map this Parcelable data with view id. You can do simple experiment, create empty app, in layout add EditText, without id - run it, put some text, change orientation, boom - data missing. Then retry with id.
You can find great explanation here: Saving instance state
I created a normal button in main.XML and in Java I added added a Toast message when clicking it. My problem is I need to hide it when clicked, but that involves R.id.main or something like that. The problem is I get the error "Unknown entity 'id'". Am I missing imports?
Imports:
package com.redstonelamp.DroidRedstoneLamp;
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.view.View. *;
Code:
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void confirmClicked(View view){
Toast.makeText(getApplicationContext(), "Please choose a version to download",
Toast.LENGTH_LONG).show();
}
}
If you want to hide your button you have two possibilities :
1. With a Listener
Let's say you have this XML file :
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
In your main class you will need to retrieve your Button and subscribe your MainActivity to the click event of this button.
MainActivity
public class MainActivity extends Activity implements View.onClickListener
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// this will inflate all the UI elements you have added
// in your main.xml file
setContentView(R.layout.main);
// here you retrieve the button in the layout by its ID
Button myButton = findViewById(R.id.my_button);
// here you tell your button he should propagate the
// Click event to this Activity.
myButton.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
// here you handle the click
// the view parameter is the view that was clicked
// therefore your button :)
// so all you have to do is to set it's visibility
view.setVisibility(View.INVISIBLE);
}
}
2. Directly by naming the method
The mechanism behind is the same but this one allows you to have a custom method name. To do this you will have to add a field in the XML file named : onClick.
This field will contain the name of the method that will handle the click.
This method has to be implemented in the Activity / Fragment in which you have inflated this Button (with the setContentView method).
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="myOnClickMethod" />
</LinearLayout>
Then in your MainActivity :
MainActivity
public class MainActivity extends Activity implements View.onClickListener
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// this will inflate all the UI elements you have added
// in your main.xml file
setContentView(R.layout.main);
}
public void myOnClickMethod(View view)
{
// here you handle the click
// the view parameter is the view that was clicked
// therefore your button :)
// so all you have to do is to set it's visibility
view.setVisibility(View.INVISIBLE);
}
}
Hope this will help you.
Cheers
I'm an amateur developer creating a short app and I'm having trouble using both the XML file for a particular activity along with Activity's Java method "setContentView". I need the method because I am generating numbers from a computation and the number generated is variable depending on different parameters. Therefore, each time I call the computation I have to call:
textView.setText(message + " is " + output);
setContentView(textView);
But I also created several buttons on the Activity's XML page which I would also like to show up on the Activity's page. For example, this is one of the buttons I created:
<Button
android:layout_marginTop="100dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_quit"
android:onClick=".quit" />
However, if I call:
setContentView(R.layout.activity_compute_number);
after the set content view for the variable text message I mentioned earlier, the XML file overrides the text message and the text message never shows up and vice versa if I call the two setContentView methods the other way around. How do I get them both to render on the Activity screen simultaneously?
In your activity_compute_number.xml, you should assign an id to your button and textview. This way you can reference your button and textView.
<Button
android:id="#+id/button_compute"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:onClick=".quit"
android:text="#string/button_quit" />
<TextView
android:id="#+id/textView_answer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp" />
Notice the android:id="#+id/button_compute" and android:id="#+id/textView_answer". This gives this button and textview id's called button_compute and textView_answer respectively.
Then change your onCreate to the following:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnCompute = (Button)findViewById(R.id.button_compute);
TextView tvAnswer = (TextView)findViewById(R.id.textView_answer);
btnCompute.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
* DO COMPUTATION here
*/
tvAnswer.setText(answer);
}
});
}
In onCreate() method you set your view to show the layout in your activity_compute_number.xml by calling setContentView() only once. You reference your button and textview by findViewById specifying the id's you have set in your xml.
Please read the docs of the method setContentView(). In onCreate() method you can use setContentView() once only. So, you should add a TestView in your XML file OR can use this,TextView txt = new TextView(this) in your activity.
I have a subclass of ListView. My only problem is I can't get it to work (not the listview code, but the code to use the listview. Android won't inflate it (app crashes). I'm sure there is a simple way to get this to work, but I don't know how.
PullToRefreshListView list;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.cliplistmain);
context = this;
list = (PullToRefreshListView)findViewById(R.id.clipListMain);
list.setOnItemClickListener(this);
list.setOnScrollListener(this);
list.setOnRefreshListener(new OnRefreshListener(){
#Override
public void onRefresh()
{
ClipStore.getInstance().getClips(SugarLoafContext.currentCamera);
}
});
Button btn = (Button)findViewById(R.id.findclipsbtn);
btn.setOnClickListener(this);
SugarLoafContext.lastView = SugarLoafContext.LAST_VIEW_CLIP_LIST;
}
Here is my xml:
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/clipListMain" >
This is only a part of your layout xml file right, so you do have header and namespace information in your XML.
I guess you get a ClassCastException or similar right? Since you've got a ListView in your xml but cast it into your PullToRefreshListView class.
Your layout xml (i.e. ./res/layout/foo.xml) should be something like
<?xml version="1.0" encoding="utf-8"?>
<com.yourpackage.foo.PullToRefreshListView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/com.yourpackage.foo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/clipListMain" />
IMO you forget about adding this subclass name to xml config