android view.findViewById and activity.findViewById, one cannot show the data - android

I've got a problem between view.findViewById and activity.findViewById.
Consisely it's when I use view.findViewById the data will not show and have no error report at all. And when I use the activity.findViewById , everything is fine. I dont know why or if I have made any mistake. Please give me some sugguestions.
MainActivity code
public class MainActivity extends AppCompatActivity {
ViewManager viewManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewManager=new ViewManager(this);
viewManager.setText("hello");
}
}
ViewManger Code
public class ViewManager {
private AppCompatActivity activity;
ViewManager(AppCompatActivity activity){
this.activity=activity;
}
public void setText(String text){
//in this way the word"hello" cannot be shown
View view= LayoutInflater.from(activity).inflate(R.layout.activity_main,null);
TextView textView=view.findViewById(R.id.tv);
//this way it works but i dont know why i m wrong above
//TextView textView=activity.findViewById(R.id.tv);
textView.setText("hello");
}
}

You are creating a separate view hierarchy which has no link with your activity layout so nothing will happen on screen
so you can set view reference as activity's layout
public void setText(String text){
View view= LayoutInflater.from(activity).inflate(R.layout.activity_main,null);
activity.setContentView(view);
//^^^^^^^^^^^^^^^^^^^^^^
TextView textView=view.findViewById(R.id.tv);
//this way it works but i dont know why i m wrong above
//TextView textView=activity.findViewById(R.id.tv);
textView.setText("hello");
}
and setContentView(R.layout.activity_main); no longer be needed

You're setting the text on a view in a layout that you do not show. Once you inflated R.layout.activity_main in ViewManger, you never add the view to the one that got inflated by the activity itself (the layout passed as a parameter to setContentView). The reason that it works with activity is that in that case, the activity will look in the view that was passed by setContentView, the layout that is visible.

The problem is Your activity's layout is already inflated by using this line:
setContentView(R.layout.activity_main);
So if you call in activity:
TextView textView=findViewById(R.id.tv);
textView.setText("hello");
It will work cause the parent of this view if the activity's layout.
The thing you are doing in your ViewManager is inflating a new view which is not bind to any component.So where you suppose to show the text View.
This will be the solution:
public void setText(String text){
TextView textView=activity.findViewById(R.id.tv);
textView.setText("hello");
}

Related

how to use two layouts in Recyclearview Android

i have already search web to find a solution.
i have two layouts in my activity and in first layout i have my recyclearview and in second i have a textview that i want to settext by clicking one of items in recyclear.
so in onBindViewHolder i added the click listener.
but i have no access to the second layout to settext.
i used layoutinflator and created view from that.
and i could get values like gettext() but settext() is not working with no error!!
how can i fix that?
UPDATE:
View v = View.inflate(context, R.layout.etelaie_activity, null);
TextView tt = (TextView) v.findViewById(R.id.etelaie_activity_title);
Toast.makeText(context, tt.getText().toString(), Toast.LENGTH_SHORT).show();
this.title = title;
this.context = context;
tt.setText("ff");
gettext() is working but settext wont apply.
You have to send callback from your Adapter to Activity. View of RecyclerView's item is different from View of Activity.
TextView tt = (TextView) v.findViewById(R.id.etelaie_activity_title);
You inflated View and accessing its default written text(might be a text which you put inside XML file) but where this View is shown on UI? You didn't set this View on UI.
Create an interface like:
public interface MyAdapterCallback {
void updateText(String text);
}
Implement this in your Activity:
public class YourActivity implements MyAdapterCallback {
. . .
#Override
void updateText(String text){
textView.setText(text);
}
. . .
}
Create adapter with:
Constructor(its parameter.. , MyAdapterCallback callback)
Inside onClick in adapter: call
callback.updateText(list.get(position))
Hope it helps!

Having problems setting up button of another layout

The problem is MainActivity starts with a setContentView with a layout.xml. We can add buttons or anything to the layout and code in in the MainActivity class but when I try to code the buttons of another layout in the same Activity the app forces stop . Whats wrong ?
Ok I found out that is because of the context.
When you try to change other activity you have to use layoutinflater. Example below
LayoutInflater inflater = getLayoutInflater();
View myLayout = inflater.inflate(R.layout.my_layout, null);
To work with widgets inside it like buttons or anything .
Button b = mylayout.findViewById(R.id.button);
b.setText("Successfully changed");
Now you can use myLayout as your changed layout.
Please sent me your Activities
What the text of problem ?
You may write next code to go to another activity
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),nameActivity.class));
}
});
Where button is name of your button
See that you xml-file doesnt have any mistakes
You are getting a crash because you are trying to access the layout when it is not inflated. In other words, you must call setContentView() on an Activity, or inflater.inflate() on a Fragment to instantiate the view and make the elements accessible for manipulation. So if you want to add buttons to another Activity, you would need to call its onCreate() and setContentView() before you can add buttons to it.
EDIT: In response to comments...
In order to access/manipulate/modify elements in a layout at runtime, they must first be instantiated, which happens when the view is inflated. So to add a button to an Activity at runtime, you would do it in the onCreate() method after calling setContentView() like this:
Keep in mind this is the onCreate() of your SECOND activity...not your main Activity. So your main activity would start this Activity, then the button would get created during the setup of the second Activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_second_activity;
Button button = new Button(this);
button.setText("Your New Button");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("NEW BUTTON", "I just clicked my new button!");
}
});
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.layout_in_your_second_activity);
relativeLayout.addView(button);
}
If you are using a Fragment to display your UI, you can't access your UI elements until you have inflated your layout, which happens in the onCreateView() method. So you would do something like this in your Fragment code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.your_fragment_layout, container, false);
RelativeLayout relativeLayout = (RelativeLayout) view.findViewById(R.id.container_layout_that_holds_button);
//You would get your context from an onAttach() Override
Button button = new Button(context);
button.setText("Your New Button");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("NEW BUTTON", "I just clicked my new button!");
}
});
relativeLayout.addView(button);
return view;
}
You're likely getting a NullPointerException when you try to manipulate your layouts before they are created. Keep in mind that even if you have an XML file with layouts specified within, the actual objects for those elements won't be created until the system decides it needs them, which happens when you actually try to display the view.

inflates 2 views using same xml:second view contains properties of first view

When changing the text of TextView of the first view, the textView's text of the second view shows the text of both TextViews, one on top of the other.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FrameLayout rl=(FrameLayout) findViewById(R.id.mainLayout);
View v1=LayoutInflater.from(this).inflate(R.layout.text_view, null);
View v2=LayoutInflater.from(this).inflate(R.layout.text_view, null);
TextView myTextView1= (TextView) v1.findViewById(R.id.myTextView);
TextView myTextView2= (TextView) v2.findViewById(R.id.myTextView);
myTextView1.setText("str1");
myTextView2.setText("str2");
rl.addView(v1);
rl.addView(v2);
}
I would guess the issue is because you are using a framelayout so the subviews will overlap. If you switch that framelayout to a linearlayout for example I imagine the results will be as you expect according to the textviews.
very simple.. 1. you have to use append property rather than settext in second textview
2nd you can use extras to pass using intent or use getter setter method like
public static void setstr_name(String str_name) {
GlobalVariable.str_name = str_name;
}
public static String getstr_name() {
return str_name;
}

Dynamically Add and Remove Views from Layout

I'm working on one demo project in that I had create one XML file containing some views like ImageView, EditText. I'm loading this XML file on FrameLayout at runtime. At one point I want to remove all that views and again want to display them, I used removeView() method on button click but it does not work for me,,Please tell me the right way to do it..
public class Demo extends Fragment implements OnClickListener, OnTouchListener{
//Declaration of framelayout
FrameLayout f;
//Declaration of imageview
ImageView imageview;
View view, framelayoutview;
File file;
EditText etcardname, EditTextUserName,EditTextUsesrMobNumber,EditTextUsesrEmailID,EditTextUsesrAddress;
TextView dialogtesting;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_modify_card ,container, false);
framelayoutview = inflater.inflate(R.layout.frame_layout_data ,container, false);
captureImageInitialization();
Initialize();
return view;
}
// Initialization of all views components
private void Initialize() {
f=(FrameLayout)view.findViewById(R.id.framelayout);
Button btneditcardreset=(Button)view.findViewById(R.id.buttonresetcard);
btneditcardreset.setOnClickListener(this);
Bundle bundle = this.getArguments();
int myInt;
myInt = bundle.getInt("position");
imageview=(ImageView)framelayoutview.findViewById(R.id.imageViewicon);
EditTextUserName=(EditText)framelayoutview.findViewById(R.id.modifycardeditTextusername);
EditTextUsesrMobNumber=(EditText)framelayoutview.findViewById(R.id.editTextmobilesnumber);
EditTextUsesrEmailID=(EditText)framelayoutview.findViewById(R.id.editTextemailid);
EditTextUsesrAddress=(EditText)framelayoutview.findViewById(R.id.editTextaddress);
imageview.setOnTouchListener(this);
EditTextUserName.setOnTouchListener(this);
EditTextUsesrMobNumber.setOnTouchListener(this);
EditTextUsesrEmailID.setOnTouchListener(this);
EditTextUsesrAddress.setOnTouchListener(this);
f.addView(framelayoutview);
}
#Override
public void onClick(View v){
if(v.getId()==R.id.buttonresetcard){
if(framelayoutview.getParent()!=null){
f.removeAllViews();
}
f.addView(framelayoutview);
}
}
Sorry to all I forgot to tell that I provided OnTouchListener so that I can move the views anywhere in Layout. So when I press reset button all Views should get move back to their original location means where they were at on first load..
you can use
imageview.setVisibility(View.GONE);
And
imageview.setVisibility(View.VISIBLE);
on particular event
If you had added your views dynamically to your FrameLayout then you can remove them.
Otherwise, if you showing your views from XML which are exist inside the frameLayout XML then you can't remove them but you can hide them from showing by setting setVisibility(View.GONE) or setVisibility(View.INVISIBLE).
Try this-
#Override
public void onClick(View v){
if(v.getId()==R.id.buttonresetcard){
if(framelayoutview.getParent()!=null){
f.setVisibility(View.GONE);
}
f.addView(framelayoutview);
}
}

Android: How to get a view given an activity inside a normal class?

I have a normal class (not an activity). Inside that class, I have a reference to an activity.
Now I want to access a view (to add a child) contained in the layout xml of that activity.
I don't know the name of the layout file of that activity. I only know the ID of the view, which I want to access (for example: R.id.my_view).
How can I do that?
Regarding the NullPointerException (which you should add to the question), always make sure you've called setContentView() in your Activity before trying to access a View defined in XML. Example usage:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
}
...
}
Then, somewhere,
ViewGroup group = (ViewGroup) context.findViewById(R.id.group); // In your example, R.id.my_view
The reason you need to have called setContentView() is that before it's called, your View(Group) doesn't exist. Because findViewById() is unable to find something that doesn't exist, it returns null.
As simple as that!
View view = activity.findViewById(R.id.my_view);
In case of the Layout:
LinearLayout layout = (LinearLayout) activity.findViewById(R.id.my_layoutId);
And to add the Views:
layout.addView(view);
You could make your method accept an Activity parameter and then use it to find the view by id.
Ex:
public class MyClass{
public void doSomething(Activity context){
TextView text=(TextView)context.findViewById(R.id.my_textview);
}
}
Then in your activity:
obj.doSomething(YourActivity.this);

Categories

Resources