I'm actually trying to build my first android app, and I just encountered a problem I can't figure out.
I have in my XML two views, one is a plain basic TextView :
<TextView
android:id="#+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
and the other one is a custom class I built :
<com.package.testpanel.Panel
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
The code of this "Panel" is quite simple :
public class Panel extends View implements OnTouchListener, OnGestureListener {
TextView tv;
public Panel(Context context, AttributeSet attrs) {
super(context, attrs);
tv = (TextView) findViewById(R.id.tv);
if (tv != null) {
tv.setText("Text changed");
}
}
}
(I have of course implemented all the Listeners method)
As you can see in my constructor, I'm just trying to change the TextView's text from my Panel, and it won't work. If I don't put the "if (tv != null)" condition, the app just
crash at launch.
I tried putting this piece of code in one of the listener's method instead of the constructor, and it's the same result : nothing happen or it crashes without the if condition.
If I put the exact same code in the Activity's onCreate, it works perfectly, but my goal is to change the text/properties of the TextView based on the touch and gesture listener on my panel.
I'm really new to this android SDK, I have yet to try how to debug an app, but for now I would just like to know why this simple code isn't working.
So if anyone has an idea as why I can't do that, or a work-around, I'd be much obliged !
Yes. We should first load the main layout before trying to get the sub-view. This is usually with following statement:
setContentView(R.layout.your_layout);
Please refer to http://developer.android.com/reference/android/app/Activity.html
Also I suggest you firstly spend some time on the basic concept before trying to create complicated app. This will save you lots of time to finger out those questions.
AddsetContentView(R.layout.your_filename_with_textview); before tv = (TextView) findViewById(R.id.tv);
Related
I'm completely new to Android programming, so I'm not really sure what I should be searching for. I have a LinearLayout element on one of my activities.
<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="wrap_content"
android:layout_marginTop="15dp"
android:id="#+id/comment_area"
android:orientation="vertical"/>
I have a JSON array of comments (userName, commentText, commentDate) that I want to add into this LinearLayout though a loop. I created a comment_view.xml layout and created a CommentWidget class extending LinearLayout. Frankly I have no idea if this is the correct approach, and I don't think it is because I can't get the comments to load in.
My class is
public class CommentWidget extends LinearLayout {
private String text;
public void setText(String text) {
this.text = text;
}
public CommentWidget(Context context){
super(context);
}
public CommentWidget(Context context,AttributeSet attrs){
super(context,attrs);
}
#Override
protected void onFinishInflate(){
super.onFinishInflate();
TextView textView=(TextView) findViewById(R.id.comment_text);
textView.setText(text);
}
}
My widget layout is
<?xml version="1.0" encoding="utf-8"?>
<com.myproject.CommentWidget xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/comment_text"/>
</com.myproject.CommentWidget>
Inside my loop on the activity I was calling:
CommentWidget w = new CommentWidget(this);
w.setText(comment.getText());
mtxtArea.addView(w);
But nothing shows up. Can someone point me in the right direction? I'm correctly receiving the JSON into an array already.
Update: Answer
Windsurfer's answer below set me on the right track to use a ListView for what I am trying to accomplish. Using his links and some searching I found out that extending the ArrayAdapter is the most appropriate for JSON type data. I ended up following the tutorial at the following link
https://devtut.wordpress.com/2011/06/09/custom-arrayadapter-for-a-listview-android/
You can very well extend the LinearLayout to do this, but Android already has a couple of widgets designed for this. I believe you're looking for a ListView to display an array of data. Rather than creating a new widget, take a look at how a ListView works. A ListView uses an adapter to bind data to it. You will still have to design the layout for a single comment item, but a lot of the heavy lifting is done by the ListView and it's adapter.
Here are some links to get you started:
http://developer.android.com/guide/topics/ui/layout/listview.html
http://www.vogella.com/tutorials/AndroidListView/article.html
Take a look at this link by Romain Guy who introduces ListViews too.
I need to exchange data between activity and it's layout xml in Android. But I do not find a way to do this in Android. For example, views and controller in mvc pattern always has a way to exchange data between. So I am wondering is there any way to exchange data between them to should I refresh my mind and realize there is no such way?
use below code to get value from layout in your activity
String value;
EditText editText= (EditText) findViewById(R.id.editText);
value=editText.getText();
code in xml example:
<ImageView
android:id="#+id/image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
in java class (like onCreate()):
ImageView image = (ImageView) findViewById(R.id.image_view);
Then you can do what you want with image
I believe you're unsure exactly what you're asking. If you want to exchange information, such as ID or text entered into a textfield then any good android tutorial should be-able to demonstrate this. Considering your last comment I think you're talking about GET and POST based technologies which can be done usingREST andSOAP, or both if you want.
This questions answer has a good implementation and definition of what both of these webservices are.
P.S. If this is what you're looking for then upvote that answer.
As some additional info, the "view" (XML Layout file) gets set by your activity initially on your activity's onCreate method. Right after you call it's parent method (super.onCreate()).
To maintain scope throughout the activity I tend to declare all the layout widgets that I need to the activity to interact with outside of any methods and within the class.
TextView textWelcomeMessage;
public void MyActivity(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// before calling setContentView() we have the option to change
// window features ex requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_my_activity);
// Now to set the textview
textWelcomeMessage = (TextView) findViewById(R.id.textWelcomeMessage);
// Set some data
textWelcomeMessage.setText("Hello, welcome to my activity");
}
It's not exactly like traditional php style mvc since static typing changes thing up a bit and we have to worry about scope. But the core principles can still apply as far as data abstraction and separation go. Hope this helps =)
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.)
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);
This should be simple, but driving my crazy.
I have the following in my layout, not problems.
<TextView
android:id="#+id/birdinfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#00009c"
android:text="The Robin is a popular bird"
/>
Then I have these arrays which are set up with the list of string resources I have
private Integer[] DetailIds = {
R.string.barnaclegoose,
R.string.barnowl,
R.string.bewicksswan,
R.string.blackbird,
R.string.blackcap_male};
So I simply want to do this!
TextView detail = (TextView)findViewById(R.id.birdinfo);
detail.setText(DetailIds[0]);
setContentView(R.layout.main);
But this causes a force close error.
The string resource looks like this ( without header and footer info of course
<string name="barnaclegoose">What a wonderful goose!</string>
Added to this problem is if I use the resource directly to the resource
detail.setText(R.string.barnaclegoose);
For example, I still get a null exception! I'm sure I've done this before, but maybe I'm missing the obvious???
Any ideas appreciated.
( Eclipse, Android 1.5, Emulator with 1.5 )
I realize this is very old, but it came up in a search... Anyways, you need to call setContentView() before findViewById() etc:
setContentView(R.layout.main);
TextView detail = (TextView)findViewById(R.id.birdinfo);
detail.setText(DetailIds[0]);
your problem is for this line setContentView(R.layout.main);
at first you must define this this line then setText your textView
Thanks for the answer. but if you mean R.string.barnaclegoose for example, this is an integer value for the ID pointing to the string itself in the resource.
Anyway, I finally got it working by just creating the view inline instead of using an resource view.
For example
TextView t= new TextView(ctx);
t.setId(2);
t.setTextColor(Color.BLACK);
t.setText(DetailIds[bird]);
mLinearLayout.addView(t,params);
mLinearLayout.setBackgroundColor(Color.WHITE);
setContentView(mLinearLayout);
And that works perfectly.