Can't set text to the TextView - java

I am learning to develop apps for android from a book and after following the instructions I end up with the following. When I run the app the text from the setStartUpScreenText() object is not displayed.
MainActivity.java:
protected void setStartupScreenText(){
TextView planetNameValue = (TextView)findViewById(R.id.DataView1);
planetNameValue.setText(earth.planetName);
}
MainActivity.xml
<TextView
android:id="#+id/DataView1"
android:layout_toRightOf="#+id/TextView1"
android:layout_marginLeft="36dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

Make sure you call setContentView method before updating any view in the screen.

Make sure you call setStartupScreenText() method after setContentView in oncreate of the activity

Fist of all call the setStartUpScreenText() function from inside of setStartUpWorldValues() function (either in the beginning or in the end). You can also call this function inside the onCreate() methods after the setStartUpWorldValues() function.
Secondly replace the entire code of the setStartUpScreenText() function with the following code: (page 90, Learn Android App Development, publisher: Apress)
TextView planetNameValue = (TextView) findViewById(R.id.dataView1);
planetNameValue.setText(earth.planetName);
TextView planetMassValue = (TextView) findViewById(R.id.dataView2);
planetMassValue.setText(String.valueOf(earth.planetMass));
TextView planetGravityValue = (TextView) findViewById(R.id.dataView3);
planetGravityValue.setText(String.valueOf(earth.planetGravity));
TextView planetColoniesValue = (TextView) findViewById(R.id.dataView4);
planetColoniesValue.setText(String.valueOf(earth.planetColonies));
TextView planetPopulationValue = (TextView) findViewById(R.id.dataView5);
planetPopulationValue.setText(String.valueOf(earth.planetPopulation));
TextView planetMilitaryValue = (TextView) findViewById(R.id.dataView6);
planetMilitaryValue.setText(String.valueOf(earth.planetMilitary));
TextView planetBaseValue = (TextView) findViewById(R.id.dataView7);
planetBaseValue.setText(String.valueOf(earth.planetBases));
TextView planetForceFieldValue = (TextView) findViewById(R.id.dataView8);
planetForceFieldValue.setText(String.valueOf(earth.planetProtection));

protected void setStartUpWorldValues() {
earth.setPlanetColonies(1); //Set planet colonies to 1
earth.setPlanetMilitary(1); // set planet military to 1
earth.setColonyImmigration(1000); // set planet population to 1000
earth.setBaseProtection(100); // set Planet armed force to 100
earth.turnForceFieldOn(); // Turn on the planet force field
setStartUpScreenText() ;
TextView planetNameValue = (TextView)findViewById(R.id.dataView1);
planetNameValue.setText(earth.planetName);
TextView planetMassValue = (TextView)findViewById(R.id.dataView2);
planetMassValue.setText(String.valueOf(earth.planetMass));
TextView planetGravityValue = (TextView)findViewById(R.id.dataView3);
planetGravityValue.setText(String.valueOf(earth.planetGravity));
TextView planetColoniesValue = (TextView)findViewById(R.id.dataView4);
planetColoniesValue.setText(String.valueOf(earth.planetColonies));
TextView planetPopulationValue = (TextView)findViewById(R.id.dataView5);
planetPopulationValue.setText(String.valueOf(earth.planetPopulation));
TextView planetMilitaryValue = (TextView)findViewById(R.id.dataView6);
planetMilitaryValue.setText(String.valueOf(earth.planetMilitary));
TextView planetBasesValue = (TextView)findViewById(R.id.dataView7);
planetBasesValue.setText(String.valueOf(earth.planetBases));
TextView planetForceFieldValue = (TextView)findViewById(R.id.dataView8);
planetForceFieldValue.setText(String.valueOf(earth.planetProtection));
}
private void setStartUpScreenText() {
// TODO Auto-generated method stub
}

Related

How to get data from dynamically created EditText and TextView inside a linearlayout?

In my main.xml I have a LinearLayout:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/linearMain"
>
</LinearLayout>
Then, inside my Main.java I am retrieving values from the DB (name and price of an item). Then, I dynamically created my form using the below code:
Cursor cursor = mydb.getAllJuice();
lm = (LinearLayout) findViewById(R.id.linearMain);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
while (cursor.moveToNext()) {
int cid = cursor.getInt(0);
String id = Integer.toString(cid);
String name = cursor.getString(1);
String price = cursor.getString(2);
// Create LinearLayout
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
// Create TextView
TextView product = new TextView(this);
product.setText(name+" ");
ll.addView(product);
// Create TextView
TextView pricetxt = new TextView(this);
pricetxt.setText(" "+price);
ll.addView(pricetxt);
// Create TextView
TextView currency = new TextView(this);
currency.setText(" LL ");
ll.addView(currency);
// Create TextView
TextView qtylabel = new TextView(this);
qtylabel.setText("QTY ");
ll.addView(qtylabel);
EditText qty = new EditText(this);
qty.setMinLines(1);
qty.setMaxLines(3);
ll.addView(qty);
lm.addView(ll);
}
// Create LinearLayout
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
final Button btn = new Button(this);
// Give button an ID
int j = 122;
btn.setId(j+1);
btn.setText("Add To Cart");
// set the layoutParams on the button
btn.setLayoutParams(params);
//Add button to LinearLayout
ll.addView(btn);
//Add button to LinearLayout defined in XML
lm.addView(ll);
The user will be able to enter the number of items and consequently onClick of the button a TextView will be manipulated.
To fill this textview I will need to loop on all the items that were created to check the price and check how the number that the user entered. I tried using the below code, however I am not able to access the specific item that I want as I have in each row 2 TextView and 1 editText:
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// code will be here
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
total = 0 ;
View v1 = null;
for(int i=0; i<lm.getChildCount(); i++) {
v1 = lm.getChildAt(i);
}
}
});
How can I access the different element in the v1?
You can use tag parameter of your Views (TextView, EditText etc.): setTag(Object) . Tags are essentially an extra piece of information that can be associated with a view. They are most often used as a convenience to store data related to views in the views themselves rather than by putting them in a separate structure. Check Android documentation for more details.
P.S. Instead to use your approach, you can use RecyclerView (or older ListView) with ViewHolder. This already mentioned in comments.
Answer to your question:
The problem is that your "product", "pricetxt", "btn" variables are local variables and gets garbage collected after your current loop iteration is over.
Well you can implement view holder pattern in your project.
Create a class named ViewHolder
class ViewHolder{
LinearLayout ll;
TextView product;
TextView pricetxt ;
TextView currency ;
TextView qtylabel ;
EditText qty ;}
public ViewHolder(LinearLayout ll TextView product TextView pricetxt TextView currency TextView qtylabel EditText qty)
{
this.l1= l1;
this.product=product;
this.pricetxt=pricetxt;
this.currency = currency;
this.qtylabel = qtylevel;
this.qty = qty;
}
This class can hold all your data by passing all these parameters (qty, pricetxt, etc).
Now you have to maintain a List for this ViewHolder Object at the top. You can do this as-
List myList<ViewHolder> = new ArrayList<ViewHolder>();
At the end of every iteration, create and add the ViewHolder object;
You can do this as follows
ViewHolder currentView = new ViewHolder(l1.product,pricetxt,currency,qtylabel,qty);
myList.add(currentView);
myList.add(currentView);
You can access any ViewHolder object maintained inside the list at position "index" as
myList.get(index);
Or the EditText "qty" as
myList.get(index).qty;
In this way you can access your created EditTexts and TextView even after the loop iteration is over.
My Suggestion:- No one does it in this way. As suggested some guys over here you should you android implement recommended RecyclerView which is much more efficient than the current implementation. In cases you can even you ListView.

Cannot resolve method setText(java.lang.String)

I've looked at other questions similar to the error I'm getting, but I can't seem to figure out the issue here. All I'm trying to do is click a button and change a TextView's text.
My code is as follows:
public class FindBeerActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_beer);
}
//call when the user clicks the button
public void onClickFindBeer(View view) {
//Get a reference to the TextView
View brands = (TextView) findViewById(R.id.brands);
//Get a reference to the Spinner
Spinner color = (Spinner) findViewById(R.id.color);
//Get the selected item in the Spinner
String beerType = String.valueOf(color.getSelectedItem());
//Display the beers. This is where the error is
brands.setText(beerType);
}
}
and the XML
<TextView
android:id="#+id/brands"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/find_beer"
android:layout_alignStart="#id/find_beer"
android:layout_below="#id/find_beer"
android:layout_marginTop="18dp"
android:text="#string/brands" />
When I build I get: "error: cannot find symbol method setText(String)
I'm following a tutorial to the letter and I can't see where I've made a mistake, so I'd appreciate it if you guys could help me out! Thanks!
You can either change
View brands = (TextView) findViewById(R.id.brands);
to
TextView brands = (TextView) findViewById(R.id.brands);
OR change
brands.setText(beerType);
to
((TextView)brands).setText(beerType);
In either ways, you need to call the setText method on a TextView reference.
You are trying setText() method on a view object. You need to call it on a TextView object.so either change the declaration of brands to TextView or just wrap ur brands object to TextView before calling setText() over it.
Change
View brands = (TextView) findViewById(R.id.brands);
To
TextView brands = (TextView) findViewById(R.id.brands);

textview giving null pointer

I hate errors like this. I'm getting a null pointer. I know what it means. I just don't understand how i'm getting it since i know that the item it should be pointing to does exist. I'm creating a textview that will be updated by the opengl renderer. The textview provides a score. I've created the textview in XML and given it a 'id', then i reference it in my program and update it through the renderer. Icreate TextView variables globally then I initialize them in the onCreate() method. Then I created a method to set the text. Which is called inside of my renderer class.
Here is my java code
View r1;
TextView score3, score4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set app to full screen and keep screen on
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(Main.layout);//R.layout.gl_triallayout;
r1 = findViewById(Main.id);////R.id.gl_triallayout;
score3 = (TextView) findViewById(R.id.threeScore);
score4 = (TextView) findViewById(R.id.fourScore);
......
}
public int get3(int i){
score3.setText("Score" + String.valueOf(i));
((RelativeLayout) r1).bringChildToFront(findViewById(R.id.threeScore));
Log.i("i", String.valueOf(i));
return i;
}
XML code
<TextView
android:id="#+id/threeScore"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Score"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:textSize="30dp"
android:textColor="#ffff00"/>
Update
Main class
public void Trial(View v) {
layout = R.layout.gl_triallayout;
id = R.id.glTrialLayout;
gameType = 0;
Intent intent = new Intent(Main.this, OpenGLActivity.class);
startActivity(intent);
}
public void PlayGame(View v) {
layout = R.layout.gl_layout;
id = R.id.glLayout;
gameType = 1;
Intent intent = new Intent(Main.this, OpenGLActivity.class);
startActivity(intent);
}
I hate the idea of clutter stackoverflow with the same question so if the answer is immensely simple could you give it to me in the comments. then i could delete this.
Your
setContentView(Main.layout)
should be
setContentView(R.layout.filename)
In the above code, you should change your layout file name based on your need like R.layout.activity_main.
Same applies to,
r1 = findViewById(Main.id);////R.id.gl_triallayout;
What is r1?
If it's a button, it should be
r1 = (Button) findViewById(R.id.gl_triallayout);////R.id.gl_triallayout;
If it's a Editext,
r1 = (EditText) findViewById(R.id.gl_triallayout);////R.id.gl_triallayout
If it's a TextView,
r1 = (TextView) findViewById(R.id.gl_triallayout);////R.id.gl_triallayout
Also, In your XML layout, where's the view for score4 and r1?
I think you should start learning the basics of Android first.

How to get the value of a textview?

I tried:
TextView textView1 = (TextView) getActivity().findViewById(R.id.date);
String s1 = textView1.getText().toString();
but on the second line falls error:
java.lang.NullPointerException
at com.ancort.cryptophone.guitest.CAMyTest.testMail_000(CAMyTest.java:94)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:214)
at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:199)
at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:192)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:192)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:177)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1619)
Also, I tried
TextView textView1 = (TextView)findViewByID(R.id.date);
String s = textView1.getText().toString();
But in this case "findViewByID" red highlights with error"cannot resolve method findViewById(int)". I understandthat the class must be extends from Activity class, but my class extends from another class. How to get the value of a textview?
you are inside a Fragment if you are using getActivity, and probably, the view, is only part of the fragment itself.
change
TextView textView1 = (TextView) getActivity().findViewById(R.id.date);
with
TextView textView1 = (TextView) getView().findViewById(R.id.date);
if you are using that line after onCreateView
I think you are using Fragment. Inside onCreateView write
View view = inflater.inflate(R.layout.your_fragment_layout,container, false);
TextView textView1 = (TextView) view.findViewById(R.id.date);
Hope this will work. :)
I wanted get a value that was in TextView. The decision was simple:
TextView textView1 = (TextView) solo.getView(R.id.date); String s1 =
textView1.getText().toString();
Thank you all.

Setting ArrayList entries as ViewFlipper children

There are over 30 views to be displayed in my activity. Each one is a RelativeLayout with nested ImageView and some TextViews within (some of them are static, some of them are variable). Refactored to programmatic way of displaying results it looks like:
tbnImages = db.getTbnImages();
tbnNames = db.getTbnNames();
tbnExts = db.getTbnExts();
tbnDescs = db.getTbnDescs();
vf = (ViewFlipper) findViewById(R.id.viewFlipperTbnImages);
vf.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.left_in));
vf.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.left_out));
detector = new SimpleGestureFilter(this, this);
tbnImage = (ImageView) findViewById(R.id.tbnImage);
tbnName = (TextView) findViewById(R.id.tbnName);
tbnExt = (TextView) findViewById(R.id.tbnExt);
tbnDesc = (TextView) findViewById(R.id.tbnDesc);
How should I configure my ViewFlipper so that .showNext() and .showPrevious() methods would display proper views, including correct behaviour when launching method upon the last view (.showNext() redirects to the first view) and the first one (.showPrevious() presents the last view)?
public void onSwipe(int direction) {
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT:
vf.showPrevious();
break;
case SimpleGestureFilter.SWIPE_LEFT:
vf.showNext();
break;
}
All variables (ImageView picture and TextView texts) are taken from an ArrayList. How to set them as ViewFlipper children?
You need to generate all the 30 views and add them as children of the ViewFlipper. If all your views share one single layout, you should create a custom view to handle it.
public class CustomView extends RelativeLayout{
public CustomView(Context context, Uri imageUri, String tbnName, String tbnDescripton, String tbnDesc) {
super(context);
LayoutInflater.from(context).inflate(R.layout.your_layout_resource, this, true);
ImageView tbnImage = (ImageView) findViewById(R.id.tbnImage);
TextView tbnName = (TextView) findViewById(R.id.tbnName);
TextView tbnExt = (TextView) findViewById(R.id.tbnExt);
TextView tbnDesc = (TextView) findViewById(R.id.tbnDesc);
tbnImage.setImageURI(imageUri);
tbnName.setText(tbnName);
tbnImage.setText(tbnDescription);
tbnExt.setText(tbnDesc);
}
}
Where 'your_layout_resource' is your current RelativeLayout resource with a 'merge' element as a root. Then you just have to create all the views you need and add them to your ViewFlipper:
for(int i = 0; i<tbnImages.size(); i++){
vf.addView(new CustomView(context,
tbnImages.get(i),
tbnNames.get(i),
tbnDescripton.get(i),
tbnDescs.get(i)));
}
Anyway, 30 views are a lot of views. Are you sure a ViewPager wouldn't work for you?

Categories