i've got a "simple" question:
How do i pass a view from an Activity to another?
In my case:
I've got a MainActivity with setContentView(R.layout.activity_main); In this activity_main i've declared a Relativelayout, whose Backgroundcolor I wanna change from another Activity, that gets its setContentView from an .xml file, where you cant find this RelativeLayout. How do i do that?
Thanks for the quick answer!
MainActivity.java
public class MainActivity extends AppCompatActivity{
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null) {
//Save the text of the editText
bringer = savedInstanceState.getString("bringer");
input.setText(bringer);
//Save the Listview
content = savedInstanceState.getStringArrayList("content");
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, content);
layout = (ListView) findViewById(R.id.layout);
layout.setAdapter(adapter);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putStringArrayList("content", content);
outState.putStringArrayList("list", list);
bringer = input.getText().toString();
outState.putString("bringer", bringer);
}
Second Activity:
public class pop extends Activity {
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Thats where it fails, because it couldnt get the parent-
view.
finish();
}
});
sure.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
}
The short answer is that you can't pass a View between activities.
If you have a View in ActivityOne that you want to modify based on the user's actions in ActivityTwo, then you should have ActivityOne launch ActivityTwo using startActivityForResult().
ActivityTwo can then call the setResult() method, and ActivityOne can implement onActivityResult() to receive that info.
Related
I'm trying to call fragment function from dialogfragment. My application is based on navigation drawer which contains container for fragments. At one of my fragments I make retrofit request and I also can open dialogfragment from this fragment. But I faced with one very serious problem - I can't get SharedPreferences after calling fragment function from dialogFragment. Here how I call this method:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
JobList jobList = new JobList();
jobList.testFunction();
}
});
and here is my testFunction():
public void testFunction() {
sp = Objects.requireNonNull(getActivity()).getSharedPreferences("app_data", 0);
Log.w("MY_tag", sp.getString("access_token", ""));
}
my testFunction contains only experimental logs, because I try to get data from sharedpreferences but I get only error:
java.lang.NullPointerException
after putting breakpoint I understood that I can't receive any context for getting sharedPreferences. I can't understand how to solve my problem, and I will be happy if smb help me with the solution.
please try as follows
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
JobList jobList = new JobList();
jobList.testFunction(view);
}
});
public void testFunction(View view) {
sp = Objects.requireNonNull(view.getContext()).getSharedPreferences("app_data", 0);
Log.w("MY_tag", sp.getString("access_token", ""));
}
Easy and Recommended way:
First make a callback in fragment: How?
interface DialogCallBack{
void callback(View view);
}
implement interface on your fragment, and when you create constructor for your dialogfragment, just pass the callback for that fragment.
Then in your dialogFragment:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
listener.callback(view);
}
});
listener call interface method which is implemented on fragment. So do this inside your fragment:
#override
callback(View view){
testFunction(view);
}
My app uses one activity and many fragments, the activity which extends AppCompatActivity inflates an xml file which has a LinearLayout among
other ViewGroups, the purpose of this LinearLayout is to hold 3 buttons not all are visible at start.
In code, I change the view of LinearLayout and
the view and texts of some of its buttons depending on the action taken in the current fragment. However their state is not maintained when the
activity is reCreated after phone home key press.
Saving visibility and text of each button every time one gets chnaged in SharedPreferences is too misssy, so I tried the below code but failed.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mMainButtons_LL != null) {
mMainButtons_LL = (LinearLayout) savedInstanceState.getSerializable("mainButtons");
} else {
mMainButtons_LL = (LinearLayout) findViewById(R.id.main_buttons_LL);
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("mainButtons", (Serializable) mMainButtons_LL);
}
Change your code to something like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.id.your_layout); // << replace your layout id here
mMainButtons_LL = (LinearLayout) findViewById(R.id.main_buttons_LL);
if (savedInstanceState != null) {
mMainButtons_LL.setVisibility(savedInstanceState.getInt("visibility"));
mMainButtons_LL.setText(savedInstanceState.getString("text");
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("visibility", mMainButtons_LL.getVisibility());
outState.putString("text", mMainButtons_LL.getText.toString());
}
image123(ImageView) works normal but when it comes to ONclickListener it does not work even after using different methods of Calling the listener.
I put func(),which contain findviewbyid of image123 (ImageView) just after SetContentView() and it works fine .OnclickListener of image123 does not works when func() is in OnClicklistener of Reset Button as Shown in the Code.
Problem:
How can i call the func() in reset button onclicklistener as well as in start at Oncreate() Activity?
It catch an exception shown in Log cat
- Exception at Onclick Listener" ,"java.lang.NullPointerException
public class MainActivity extends Activity {
ImageView image123;
int[] resultid=new int[25];
Button buttonExit;
Button buttonreset;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonreset=(Button) findViewById(R.id.button_reset);
buttonExit=(Button) findViewById(R.id.button_exit);
v1=(TextView)findViewById(R.id.name);
v2=(TextView)findViewById(R.id.fruit_count);
//--------------------------Exit Button---------------------------
buttonExit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
//*******************Exception comes here*********************
try{
image123.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.d("Listner Called", "Listner Called");
}
});
}
catch(Exception e)
{
Log.d("Exception at onclickListener", e.toString());
}
buttonreset.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
func();
}});
}
void func()
{
String as=null;
int resultid;
SecureRandom random=new SecureRandom();
image123=new ImageView(this);
as=("img"+1).toString();
resultid=getResources().getIdentifier(as, "id","com.example.selectiongame" );
Log.d(as, ""+resultid);
image123=(ImageView) findViewById(resultid);
as="drawable"+(random.nextInt(3)+1);
resultid = getResources().getIdentifier(as, "drawable", "com.example.selectiongame");
Log.d(as, ""+resultid);
image123.setImageResource(resultid);
}
Try creating an array of ResIDs and an array of ImageViews. Then do something like this instead of initializing them with findViewById()...
for(int i = 0; i < res_arr.length; i++)
{
images[i] = new ImageView(this);
images[i].setImageResource(res_arr[i]);
images[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Button_Clicked", "Button Clicked");
}
});
}
You must not findviewbyid() of an ImageView in some other function other than Oncreate(Bundle b) or Some Listener(e.g OnclickListener ,onselectionchange etc) . if you want to findviewbyid(...) of a view in a function other than Oncreate ,Atleast Call that function once after SetContentView() and other prerequisite Findviewbyid(...).
2.
In order to Refresh your Activity ,when you can not use function containing findviewbyid(...) of ImageView,like in my case, in body some button(e.g Refresh ,Reset) OnclickListner .You must write the following code
buttonreset.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Bundle newBundle=new Bundle();
onCreate(newBundle);
//func(); >>We can not use this func() here if we are using it in Oncreate(...) in case of Array of ImageView
}});
}
For views other than Imageview ,Maybe Regular Line of Code work ...But in case of ImageView or Array of ImageView ....These things must be kept in mind and Simply Oncreate() must be used to Refresh.
I'm new in Android development and I wanted to make application that has header, body and footer and by clicking on one of the buttons in footer some layout will be loaded into body. I used some kind of "MasterPage" as described here.
When the button is pressed neither new_exercise layout nor exercises layout is loaded. Why? Maybe instead of all of this I should use any kind of tabs? Or maybe I can't inflate layout and should create new activity?
Here the code of the BaseActivity and NewExercise activity:
public class BaseActivity extends Activity{
LinearLayout linBaseBody;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.base_layout);
linBaseBody = (LinearLayout)findViewById(R.id.base_body);
initButtons();
}
#Override
public void setContentView(int id) {
LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(id, linBaseBody);
}
private void initButtons()
{
Button btn1 = (Button) findViewById(R.id.newEx);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
setContentView(R.layout.new_exercise);
}
});
Button btn2 = (Button) findViewById(R.id.showAllEx);
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
setContentView(R.layout.exercises);
}
});
}
public class NewExercise extends BaseActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.new_exercise);
}
}
public class Exercises extends BaseActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.exercises);
}
}
How your code is written, it would make more sense to use a new Activity. However, If you wanted to keep all of the view in one Activity, you could walk through all of your layouts calling mLayout.setVisible(View.VISIBLE); or you could use ViewStubs.
As to answer your question, why, what you are doing is adding the view (and their layouts) directly to your already created and inflated content view (the one you created in onCreate). You will need to clear the Activities contentView first to see the changes you are making with the button.
I am trying to run a test program that allows a user to click a button and move to a different screen. I have the Home(First Activity) and Away(Second Activity) classes and a xml file specifying the layout for each. My source code is as follows:
public class Home extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button create = (Button)findViewById(R.id.create);
create.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Intent intent = new Intent(Home.this, Away.class);
startActivity(intent);
}
});
setContentView(R.layout.main);
}
}
And Away.java
public class Away extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.away);
}
}
I get a NullPointerException in the DDMS trace
at Home.onCreate(line 17)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java: 2627)
Anyone see anything in my code that may be causing this?
findViewById() traverses the view hierarchy set up when setContentView() inflates your layout. You cannot retrieve a reference to a view in your XML before you have called setContentView(). Change your onCreate() method in Home to look like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Call me first
setContentView(R.layout.main);
Button create = (Button)findViewById(R.id.create);
create.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Intent intent = new Intent(Home.this, Away.class);
startActivity(intent);
}
});
}
Otherwise, findViewById() will return null because there are no views in the tree...thus, a view with your requested id value doesn't exist.
Hope that helps!
If the findViewById call can't find the actual thing you are looking for, it could return a null object and cause the call to setOnClickListener to throw an NPE. Are you sure you've got the right ID (R.id.create) specified?