I have created a dynamic view which repeats for a specific times. The view has 2 textViews and 2 radio buttons with default values. I want to change the Text values from program but getting nullpointer exception, Here is my code:
LayoutInflater inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout scrollViewLinearlayout = (LinearLayout)findViewById(R.id.parent); // The layout inside scroll view
//int count=50;
for(int i = 0; i < Studentlist.length; i++){
String data = Studentlist[i];
String RollNum = data.split("--")[0];
String Name = data.split("--")[1];
LinearLayout layout2 = new LinearLayout(context);
layout2.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
View item = inflater.inflate(R.layout.item_layout, null, false);
layout2.addView(item);
layout2.setId(i);
TextView trollnum = (TextView)findViewById(R.id.RollNum);
trollnum.setText(RollNum);
TextView tname = (TextView)findViewById(R.id.Name);
tname.setText(Name);
scrollViewLinearlayout.addView(layout2);
Log.d("Id is: ", trollnum.getText().toString());
I am getting nullpointer at 'trollnum.setText(RollNum);'
How do i change the text in the View?
You are trying to find the view in the activity's layout where it doesn't exist instead of finding it in the layout you just inflated.
Replace
TextView trollnum = (TextView)findViewById(R.id.RollNum);
TextView tname = (TextView)findViewById(R.id.Name);
With
TextView trollnum = (TextView) item.findViewById(R.id.RollNum);
TextView tname = (TextView) item.findViewById(R.id.Name);
Related
So I have a messaging app where I read my database and render all the messages programatically. The thing is, when I am inside a different layout, I need to inflate those messages and edit them at will. For example,
val myView = inflater.inflate(R.layout.female_messaging_fragment, container, false)
...
val convLayout = myView.findViewById<LinearLayout>(R.id.conversations_layout)
val profileLayout = LinearLayout(context)
val recentMessage = TextView(context)
recentMessage.id = 5
val recentParams = LinearLayout.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT)
recentParams.setMargins(10, 0, 0, 0)
recentMessage.layoutParams = recentParams
recentMessage.textSize = 16f
if (didIsendLastMessage) {
val arrowIcon = ImageView(context)
Picasso.get().load(R.drawable.right_arrow).resize(50, 50).into(arrowIcon)
val imageParams = LinearLayout.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT)
imageParams.gravity = Gravity.CENTER
arrowIcon.layoutParams = imageParams
recentMessage.setText(mostRecentMessage)
arrowAndMessageLayout.addView(arrowIcon)
arrowAndMessageLayout.addView(recentMessage)
} else {
recentMessage.setText(mostRecentMessage)
arrowAndMessageLayout.addView(recentMessage)
}
nameLastmessageLayout.addView(arrowAndMessageLayout)
// Add namne and message to profile
profileLayout.addView(nameLastmessageLayout)
convLayout.addView(profileLayout)
And then in a different layout...
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.female_messaging_fragment, null);
TextView text = (TextView) v.findViewById(5);
text.setText("Something");
The thing is, text is always null, and I believe it is because I added the views programatically. What else can I do here? Thanks!
inflating female_messaging_fragment will return fresh new Layout view object of your xml that might be blank layout without any TextViews.
To get TextView object you need the object of Layout in which you had added the views.
For example as per your code you added recentMessage in arrowAndMessageLayout so to get the object of recentMessage you need the object of arrowAndMessageLayout and can get like below -
TextView text = arrowAndMessageLayout.findViewById(5);
OR
TextView text = convLayout.findViewById(5);
Inflating again will return fresh new container without your textview.
Hope this will help you.
I am trying to add an xml layout programmatically. It is giving error at time.setText(timeFormat); When I remove this line I get the default text value of TextView. Also I have checked that timeFormat is not null. Why am I getting this error?
Here's my code:
In onCreate(),
new GetContacts().execute();
addPost(timeFormat,message);
addPost() function:
public void addPost(String timef,String postmessage){
LayoutInflater i = getLayoutInflater();
View v = i.inflate(R.layout.list_item, null);
TextView time = (TextView)findViewById(R.id.time);
Log.d("TIME HAS COME", timeFormat);
time.setText(timeFormat);
TextView message1 = (TextView)findViewById(R.id.message);
message1.setText(message);
LinearLayout ll = (LinearLayout)findViewById(R.id.feedsLayout);
ll.addView(v);
}
I got one EditText and one TextView, and I want to update my TextView in each Iteration (ConsoleWindow is running in a loop; it gets called from a handler and thus is running on the UIthread).
The Problem is that my TextView only gets updated in the first round, and then it keeps the first entry for the rest of the runtime (although the dataString is a different one in each round):
private void ConsoleWindow(String dataString) {
LinearLayout layout = new LinearLayout(getApplicationContext());
if (first2) { //first2 is true when application is launched
// ONLY SET LAYOUT AND EDITTEXT IN FIRST RUN TO SAVE CAPACITY
// LINEAR LAYOUT
setContentView(layout);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setBackgroundColor(Color.parseColor("#000000")); // black
// EDITTEXT
EditText et = new EditText(getApplicationContext());
et.setHint("Enter Command");
layout.addView(et);
first2 = false;
}
// TEXTVIEW
TextView tv = new TextView(getApplicationContext());
tv.setText(dataString); // KEEPS THE SAME UNTIL THE 1ST ROUND
layout.addView(tv);
}
I already tried tv.invalidate() and tv.postInvalidate(), but that didn't have an effect. Could someone help me please?
Put tv a global variable.
private TextView tv;
After this, In your "onCreate()" method:
tv = new TextView(getApplicationContext());
And then:
private void ConsoleWindow(String dataString) {
LinearLayout layout = new LinearLayout(getApplicationContext());
if (first2) { //first2 is true when application is launched
// ONLY SET LAYOUT AND EDITTEXT IN FIRST RUN TO SAVE CAPACITY
// LINEAR LAYOUT
setContentView(layout);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setBackgroundColor(Color.parseColor("#000000")); // black
// EDITTEXT
EditText et = new EditText(getApplicationContext());
et.setHint("Enter Command");
layout.addView(et);
first2 = false;
}
// TEXTVIEW
tv.setText(dataString); // KEEPS THE SAME UNTIL THE 1ST ROUND
layout.addView(tv);
}
Please verify too, if dataString has some text, with something like this
Log.d(TAG , "dataString: " + dataString + "with first time? " + first2.toString());
Try to pass to the setContentView(layout); outside the if statement.Because I can't understand well Why you need this.
LinearLayout layout = new LinearLayout(getApplicationContext());
setContentView(layout);
When first2 is false, you are simply creating a new LinearLayout layout and then without inflating the layout, you are directly adding TextView tv to layout. That's why Textview is not visible.
private void ConsoleWindow(String dataString) {
LinearLayout layout;
TextView tv;
EditText et;
if (first2) {
layout = new LinearLayout(getApplicationContext());
setContentView(layout);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setBackgroundColor(Color.parseColor("#000000"));
// EDITTEXT
et = new EditText(getApplicationContext());
et.setHint("Enter Command");
layout.addView(et);
tv = new TextView(getApplicationContext());
layout.addView(tv);
first2 = false;
}
if(tv != null) {
tv.setText(dataString);
}
}
i am newbie in android and i m not getting how to produce this output:
Discipline name:1
{ complete for loop code execute from 0 to 9
}
then it will come outside and will update textview text:ie
Discipline name:2
and will enter inside For Loop
{
complete for loop code execute from 0 to 9
}
here is the java code:
public class SummaryDetailActivity extends Activity
{ TableLayout summaryDetailDisciplineTableLayout;
LayoutInflater mInflater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.summarydetail_view);
mInflater = getLayoutInflater();
summaryDetailDisciplineTableLayout = (TableLayout)findViewById(R.id.summaryDetail_disciplinetable);
//PLEASE SEE THESE LINE OF CODE:
for(int i=0;i<2;i++)
{
TextView disciplineTextView = (TextView)findViewById(R.id.summaryDetail_disciplinetext);
disciplineTextView.setText("discipline name: "+i);
for(int j=0;j<10;j++)
{TableRow disciplineRow = (TableRow) mInflater.inflate(R.layout.summarydetailrow_view,null);
TextView disciplineDeviceLabel = (TextView) disciplineRow.findViewById(R.id.summaryDetail_info1);
TextView disciplineQuantityLabel = (TextView)disciplineRow.findViewById(R.id.summaryDetail_hypen);
TextView disciplineLocationLabel = (TextView) disciplineRow.findViewById(R.id.summaryDetail_info2);
disciplineDeviceLabel.setText("device no." + j);
disciplineQuantityLabel.setText("quantity No." + j);
disciplineLocationLabel.setText("Location No." + j);
disciplineRow.setId(j);
summaryDetailDisciplineTableLayout.addView(disciplineRow);
}
}
}
}
this code is producing this output:
Why your code is not working the way you want. Is because this
TextView disciplineTextView = (TextView)findViewById(R.id.summaryDetail_disciplinetext);
is initiate as static view that can't be clone in your loop. That's why the value
of the discipline name is 1 not 0. The loop only update the value not clone the view.
You should do this
TextView disciplineTextView = new Textview(this);
disciplineTextView.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
disciplineTextView.setText("discipline name: "+i);
summaryDetailDisciplineTableLayout.addView(disciplineTextView);
for(int j=0;j<10;j++) {
-your code-
}
You should change the xml structure for better UI.
Hope this helps.
Here's how I would've done it.
Inside my XML code, I would create a LinearLayout and within that, a TableLayout.
After fetching the id of my TableLayout, I would dynamically create TableRows and TextViews. You can set their layouts using TableRow.LayoutParams or LayoutParams. You can simply set the text after that and just add them onto the TableRow that you add to TableLayout.
Hope this suggestion helps !
I think that in onCreate() you should use inflater first and then set the view that you have just inflated.
Try this:
View view = getLayoutInflater().inflate(R.layout.summarydetail_view, null);
setContentView(view);
Updated code snipped as asked:
int MovieNum=children.size();
String[] MovieName=new String[MovieNum];
String[] MovieCover=new String[MovieNum];
RadioGroup rg = new RadioGroup (this);
rg = (RadioGroup) findViewById(R.id.radioGroup1);
RadioButton rb[]= new RadioButton[children.size()];
//LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
//LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
//layout.addView(rg, p);
for (int i = 0; i < children.size(); i++)
{
Element movieAtt = (Element)doc.getRootElement().getChild("movies").getChildren("movie").get(i);
MovieName[i]=movieAtt.getAttributeValue( "Title" );
MovieCover[i]=movieAtt.getAttributeValue( "cover" );
ShowTime[i]=movieAtt.getAttributeValue( "showtime" );
TweetText+=" I will see "+movieAtt.getAttributeValue("Title");
System.out.println(TweetText);
//ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.rowlayout, R.id.label, MovieName);
//setListAdapter(adapter);
//String item = (String) getListAdapter().getItem(position);
rb[i] = new RadioButton(this);
rb[i].setText(movieAtt.getAttributeValue("Title"));
rg.addView(rb[i]);
//Calling this func to get Images
//LoadImageFromWebOperations(movieAtt.getAttributeValue( "cover" ));
}
}
}
catch (MalformedURLException e1)
{
e1.printStackTrace();
System.out.println("ErrorThrowedIs: "+e1);
Toast.makeText(getBaseContext(), e1.toString(),5);
}
}
public static Drawable LoadImageFromWebOperations(String url)
{
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}
catch (Exception e)
{
return null;
}
}
//Updated code ends here
I have to display 3 things in my list View. One is going to be a Radio button corresponding to every row. I can not use Radio group as i am not aware of the list length which is dynamically generated. So i can not set it as Radio group.
I wish to know how can i do the same.
Also what i am doing is, i want to get an image along in the same list for every row which is created from the path i get at runtime.
So during my program, i would get these values :
for (int i = 0; i < mvLen; i++)
{
Element movieAtt = (Element)doc.getRootElement().getChild("movies").getChildren("movie").get(i);
MovieName[i]=movieAtt.getAttributeValue( "Title" );
MovieCover[i]=movieAtt.getAttributeValue( "cover" );
ShowTime[i]=movieAtt.getAttributeValue( "showtime" );
Now clearly this is an string array of Movie
Names in MovieName and array of strings of URL for the cover of that movie. I wish to display all those images in front of the Movie Names. My list adapter and corrosponding XML file are listed as below. Can anyone suggest changes/hints for the same . I have been reading http://www.vogella.de/articles/AndroidListView/article.html as well. But could not figure out much to meet my requirements.
So. Create RadioGroup in your class RadioGroup radioGroup = new RadioGroup(this); and simply add radiobuttons to it when you filling content radioGroup.addView(radioButton);
Summary:
RadioGroup radioGroup = new RadioGroup(this);
//Cycle begin
RadioButton rButton = (RadioButton)findViewById(R.id.my_radiobutton);
// OR
RadioButton radioButton = new RadioButton(this);
radioButton .setText(R.string.radio_group_snack);
radioButton .setId(R.id.snack);
radioGroup.addView(rButton);
radioGroup.addView(radioButton);
//Cycle end
Example of custom adapter and getview method(it's 100% work code):
public class MyCustomAdapter extends ArrayAdapter<String> {
public MyCustomAdapter(Context context, int textViewResourceId,
String[] objects) {
super(context, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String[] users = getUsers(); //it returns list of users in String array
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.main, parent, false);
TextView label=(TextView)row.findViewById(R.id.label); //TextView decalred in my layout xml file
label.setText(users[position]);
ImageView icon=(ImageView)row.findViewById(R.id.icon); //ImageView decalred in my layout xml file
byte[] bb = getAvatar(users[position]); //some method where I get image for user. It not interesting for us so I cut it from here...
if(bb != null && bb.length != 0){
icon.setImageBitmap(BitmapFactory.decodeByteArray(bb, 0, bb.length)); //SET IMAGE FOR ROW
icon.setVisibility(View.VISIBLE); //SET VISIBILITY OF IMAGE
}
//RIGHT HERE YOU CAN MANIPULATE WITH YOUR RADIOBUTTONS. FOR EXAMPLE:
RadioButton rButton = (RadioButton)findViewById(R.id.my_radio_button);
radioGroup.addView(rButton); //WHERE radioGroup IS RADIOGROUP YOU INITIALIZED BEFORE;
return row;
}
}
}
And this is my onCreate method:
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
db.open();
String[] users = db.getUsersList();
ListView listView = getListView();
this.setListAdapter(new MyCustomAdapter(this, R.layout.main, users));
db.close();
}
For each row in the list get the radioButton and add it to the RadioGroup.
You might have to create all the radioButton's upfront and store them in a list.Set them in the ContentView depending on the position