Dynamically Creating Multiple TextViews in LinearLayout - android

I want to create multiple TextViews inside a LinearLayout.The following code builds successfully but gives a NullPointerException at the line root.addView(t[i]);
public class MainActivity extends ActionBarActivity {
TextView t[];
LinearLayout root;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
root=(LinearLayout)findViewById(R.id.master);
t=new TextView[10];
LinearLayout.LayoutParams dim=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
for(int i=0;i<10;i++)
{
t[i]=new TextView(this);
t[i].setLayoutParams(dim);
t[i].setText("YOHOHO: "+i);
root.addView(t[i]);
}
setContentView(root);
}
This really has no aim Iam just trying to learn things!

It's giving NPE because you are not setting your activity layout properly.
Do this
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.whereLinearLayoutMasterIs); // Add your layout here
root=(LinearLayout)findViewById(R.id.master);
t=new TextView[10];
LinearLayout.LayoutParams dim=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
for(int i=0;i<10;i++)
{
t[i]=new TextView(this);
t[i].setLayoutParams(dim);
t[i].setText("YOHOHO: "+i);
root.addView(t[i]);
}
}
NOTER.layout.whereLinearLayoutMasterIs is indicative, use your layout in which R.id.master is

The problem is that root is null - this is because you've not yet set your Activity's content view via setContentView.
You need to do something like this:
super.onCreate(...);
setContentView(R.layout.yourLayoutName);
root=(LinearLayout)findViewById(R.id.master);

Related

Android dynamic layout

I want to dynamically set the layout. I get a question (String type) as shown below :
Enter any two colors -------- and ---------
So using this string I have to create the view. Here the '---------' must be an EditText and the rest of the string can be a TextView. The blanks, i.e, EditText must appear inline as it appears in the question string. I am new to Android any suggestions would be helpful.
use this class for creating your dynamic views.may be it will help you.
public class MainActivity extends Activity {
LinearLayout l1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l1=(LinearLayout)findViewById(R.id.linear_layout);
LinearLayout layout=new LinearLayout(this);
layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
layout.setOrientation(LinearLayout.HORIZONTAL);
TextView text1=new TextView(this);
text1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
text1.setText("Enter any two colors");
EditText edt1=new EditText(this);
edt1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
edt1.setHint("COLOR1");
TextView text2=new TextView(this);
text2.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
text2.setText("and");
EditText edt2=new EditText(this);
edt2.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
edt2.setHint("COLOR2");
layout.addView(text1);
layout.addView(edt1);
layout.addView(text2);
layout.addView(edt2);
l1.addView(layout);
}
}

NullPointerException on TextView

I get a null pointer exception and the program crash on each time I want to update the highscore text using setText(). what causes this problem?
this code is when i set my layout, the layout is a part of the gameView using opengl, and I put the highscore textview on the upper left corner
public void onCreate(Bundle savedInstanceState) {
SFEngine.display = ((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();//ambl ukuran width height layar
super.onCreate(savedInstanceState);
gameView = new SFGameView(this);
gameView.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
RelativeLayout layout = new RelativeLayout(this);
layout.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
TextView textBox = new TextView(this);
textBox.setId(1);
textBox.setText("HIGH SCORE");
textBox.setBackgroundColor(Color.BLUE);
textBox.setWidth(SFEngine.display.getWidth()/2);
textBox.setHeight(50);
Button pauseButton = new Button(this);
pauseButton.setText("PAUSE");
pauseButton.setHeight(50);
pauseButton.setWidth(SFEngine.display.getWidth()/2);
pauseButton.setOnTouchListener(new OnTouchListener(){
public boolean onTouch(View v, MotionEvent e) {
//pause game
SFEngine.isPlaying = false;
Intent i1 = new Intent(SFGames.this, pause.class);
gameView.onPause();
startActivityForResult(i1,0);//hrs pk result soalny mw blk lg
return true;
}
});
RelativeLayout.LayoutParams lp_pause = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams lp_hs = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp_hs.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
lp_pause.addRule(RelativeLayout.ALIGN_PARENT_TOP);
lp_pause.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
textBox.setLayoutParams(lp_hs);
pauseButton.setLayoutParams(lp_pause);
layout.addView(gameView);
layout.addView(textBox);
layout.addView(pauseButton);
setContentView(layout);
and here is the setText code
public boolean onTouchEvent (MotionEvent event){//buat nerima input user
if(!SFEngine.isPlaying){
finish();
}
textBox.setText("High Score :" + SFEngine.score);//here is the source of the prob
.....
error log:
10-13 22:38:34.207: E/AndroidRuntime(528): FATAL EXCEPTION: main
10-13 22:38:34.207: E/AndroidRuntime(528): java.lang.NullPointerException
10-13 22:38:34.207: E/AndroidRuntime(528): at com.starfighter.SFGames.onTouchEvent(SFGames.java:136)
10-13 22:38:34.207: E/AndroidRuntime(528): at android.app.Activity.dispatchTouchEvent(Activity.java:2367)
UPDATE :
i've updated the source code so the textview declaration is outside of the onCreate, it seems to be working normally now..
You should define the text view as a class field in the activity, outside the onCreate:
TextView textBox;
public void onCreate(Bundle savedInstanceState) {
....
textBox = new TextView(this);
}
Your textBox is a local variable in the onCreate() method. I think you have a member variable with the same name, too. So you actually using the wrong one.
Try to remove TextView in your onCreate()
// in onCreate
textBox = new TextView(this);
textBox.setId(1);
textBox.setText("HIGH SCORE");
put TextView declaration outside of the onCreate()
TextView textBox;
public void onCreate(Bundle savedInstanceState) {
textBox = (TextView)findViewById(id.TextBoxNameFromLayout);
}
Your textbox should be defined as global variable.
like this
class MyActivity extends Activity{
TextView textBox = null;
#Override
public void onCreate(Bundle savedInstanceState) {
...
textBox = new TextView(this);

Android app Crash

Why is this:
public class HelpTab extends Activity
{
LinearLayout helpLayout; //was changed to LinearLayout helpLayout = new LinearLayout(this);
TextView helpText = new TextView(this);
Button tips = new Button(this);
Button walkThrough = new Button(this);
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
buttonCreator();
setContentView(helpLayout);
}
public void buttonCreator()
{
//Button featuress defined in here (setText("") and adding them to the layout, addView();)
}
Causing my program to crash?
I have looked at the code extensively and I can't put my finger on it, and the debugger also says source not found when it opens the new page tab thing to tell me what is happening.
Try calling setContentView(helpLayout); first and then buttonCreator();
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(helpLayout);
buttonCreator();
}
Assuming that you are trying to initialize your button inside buttonCreater() with respect to a button you have declared in your helplayout, you might run into Null Pointer Exception.

Remove all items inside linearlayout

I create a linearlayout that refes to an xml item. Inside this linearlayout i put some textview dynamically, so without taking them from the xml. Now i need to remove these textviews from the linearlayout. I tried this:
if(((LinearLayout) linearLayout.getParent()).getChildCount() > 0)
((LinearLayout) linearLayout.getParent()).removeAllViews();
but it doesn't work.
How can i do?
Thanks, Mattia
Why you wrote linearLayout.getParent()?
You should call this directly on LinearLayout:
linearLayout.removeAllViews();
Hi Please try this code its working for me
public class ShowText extends Activity {
/** Called when the activity is first created. */
LinearLayout linearLayout;
TextView textView,textView1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView=new TextView(this);
textView1=new TextView(this);
textView.setText("First TextView");
textView1.setText("First TextView");
linearLayout=(LinearLayout) findViewById(R.id.mn);
linearLayout.addView(textView);
linearLayout.addView(textView1);
linearLayout.removeAllViews();
}
}

Add button to a layout programmatically

I'm having trouble adding a button to a layout that I've created in XML. Here's what I want to achieve:
//some class
else {
startActivity(new Intent(StatisticsScreen.this, ScreenTemperature.class));
}
////
//ScreenTemperatureClass
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//this is where I call another class that
//displays a nice graph
setContentView(new GraphTemperature(getApplicationContext()));
}
I want to add a Button to this new screen so that it'll appear below the graph.
I've tried creating a LinearLayout view, then create a Button and add it to this view but I just get NullPointerExceptions..
Any help would be appreciated. Thanks
EDIT#1
Here's what I've tried using that created a NullPointerException and 'force close':
Button buybutton;
LinearLayout layout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GraphTemperature(getApplicationContext()));
layout = (LinearLayout) findViewById(R.id.statsviewlayout);
Button buyButton = new Button(this);
buyButton.setText(R.string.button_back);
buyButton.setLayoutParams(new LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
layout.addView(buyButton);
}
And here's the logcat error:
ERROR/AndroidRuntime(293): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.weatherapp/com.weatherapp.ScreenTemperature}: java.lang.NullPointerException
ERROR/AndroidRuntime(293): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
ERROR/AndroidRuntime(293): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
ERROR/AndroidRuntime(293): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
ERROR/AndroidRuntime(293): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
theres abviously more lines to do with this error in logcat, not sure if you want it?
EDIT#2
So i tried bhups method:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GraphTemperature GT = new GraphTemperature(getApplicationContext());
layout = (LinearLayout) findViewById(R.id.statsviewlayout);
Button buyButton = new Button(this);
buyButton.setText(R.string.button_back);
buyButton.setLayoutParams(new LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
layout.addView(GT); // line 27
layout.addView(buyButton);
setContentView(layout);
}
This method produced the same logcat error as above, NullPointerException, indicating it was something to do with line no. 27 which is the layout.addView line of code. Any ideas? Thanks again
If you just have included a layout file at the beginning of onCreate() inside setContentView and want to get this layout to add new elements programmatically try this:
ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);
then you can create a new Button for example and just add it:
Button bt = new Button(this);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
linerLayout.addView(bt);
This line:
layout = (LinearLayout) findViewById(R.id.statsviewlayout);
Looks for the "statsviewlayout" id in your current 'contentview'. Now you've set that here:
setContentView(new GraphTemperature(getApplicationContext()));
And i'm guessing that new "graphTemperature" does not set anything with that id.
It's a common mistake to think you can just find any view with findViewById. You can only find a view that is in the XML (or appointed by code and given an id).
The nullpointer will be thrown because the layout you're looking for isn't found, so
layout.addView(buyButton);
Throws that exception.
addition:
Now if you want to get that view from an XML, you should use an inflater:
layout = (LinearLayout) View.inflate(this, R.layout.yourXMLYouWantToLoad, null);
assuming that you have your linearlayout in a file called "yourXMLYouWantToLoad.xml"

Categories

Resources