How to give linearlayout Context - java

I have a problem with my current project in android studio.
I am trying to write some code, which creates new TextViews and ImageViews for a new activity.
This code and the new activity should start if a button is clicked.
To add the new Viewers, I try to access the existing LinearLayout in the xml-file of the new activity. But it always says that I try to "invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference"
So my question is how can I give the Linear Layout some context?
Here is my onClick-method. The parseXML()-method creates the new Viewers by parsing an XML-file.
public void onClick(View view) {
linearLayout= findViewById(R.id.linearLayoutArtikel);
parseXML();
Intent intent= new Intent(this, ArtikelActivity.class);
startActivity(intent);
}
EDIT
Thanks for your suggestions, moving the code to the new Activity solved the problem!

LinearLayout is part of ArtikelActivity if you are trying to access it from anyother activity then you will get that message. So move your code to ArtikelActivity. This is gonna work surely.

Related

What is onAdDismissedFullScreenContent on Android Studio?

Is the function onAdDismissedFullScreenContent() working when the user closes the add or it works when the ad did not appear? I do not understand very well the meaning of dismissed in this context. The second question is, is it mandatory to put inside this onAdDismissedFullScreenContent function the following code? What is the intention of the following code? Could I put nothing on this function? Thanks in advance
onAdDismissedFullScreenContent(){
Intent intent = new Intent(getApplicationContext(), Activity.class);
startActivity(intent);
}
For the first question
Yes, this method onAdDismissedFullScreenContent() is user closes the full screen ad content.
And if the ad failed to show full screen content the method
onAdFailedToShowFullScreenContent(AdError adError) will be called.
You can check the public method summery for FullScreenContentCallback here
And for your second question,
No, it's not mandatory to set anything inside these functions.
and the code
Intent intent = new Intent(getApplicationContext(), ActivityWorkout.class);
startActivity(intent);
will open an activity called ActivityWorkout when the ad is closed.
I hope I answered your questions, Happy coding.
Intent intent = new Intent(currentActivity, home.class);
currentActivity.startActivity(intent);

How to maintain binding on Fragment -> Intent -> Back to Fragment

I am using a Fragment and within my Fragment, I am starting a new Intent to access the device's settings. When I select the 'Back' button from the Android device, my bindings do not reflect in my View. The ViewModel properties are correct when I debug but the View doesn't reflect live data updates anymore. This only happens when I open the Intent
I am opening the Intent here:
private View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
I am using the ObservableFields in my ViewModel so I think it's working correctly as I mentioned before - the data is correct on the debugger, just not reflected in the View if I go into the Intent. The View will reflect any changes if I do not go into the Intent. Do I need to Override the onResume method?
As the doc says,
the fields should be declared final in your data model because bindings only detect changes in the field's value, not of the field itself
Please check this statement. If if didn't fix your problem, can you post some additionnal code as your data model class, and how you use it in your fragment?
Hope it helps.

How do I change the main xml file from another activity?

I am very new to Java. I am doing a school project at the moment and I have my main activity, then I have a settings activity. I am trying to modify the xml from the main activity with the settings activity. I am able to modify the settings xml file with the settings.java, but I would like to modify the main activity xml with settings.java
public class Settings extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
// Get the Intent that started this activity and extract the string
Switch switchButton;
final RelativeLayout mRelativeLayout = (RelativeLayout) findViewById(R.id.activity_settings);
final RelativeLayout mRelativeLayoutMain = (RelativeLayout) findViewById(R.id.activity_main);
switchButton = (Switch) findViewById(R.id.switch1);
switchButton.setChecked(true);
switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean bChecked) {
if (bChecked) {
mRelativeLayoutMain.setBackgroundColor(Color.GRAY);
mRelativeLayout.setBackgroundColor(Color.GRAY);
} else {
mRelativeLayoutMain.setBackgroundColor(Color.WHITE);
mRelativeLayout.setBackgroundColor(Color.WHITE);
}
}
});
if (switchButton.isChecked()) {
mRelativeLayoutMain.setBackgroundColor(Color.GRAY);
mRelativeLayout.setBackgroundColor(Color.GRAY);
} else {
mRelativeLayoutMain.setBackgroundColor(Color.WHITE);
mRelativeLayout.setBackgroundColor(Color.WHITE);
}}
public void toast1(View view) {
android.widget.Toast.makeText(this, "Created by Cody Walls and Tommy Serfas", android.widget.Toast.LENGTH_LONG).show();
}
/*public void switch1(View view) {
ScrollView mScrollView = (ScrollView) findViewById(R.id.scrollView);
mScrollView.setBackgroundColor(Color.GRAY);
}*/
}
In the Code I am trying to change the background of the main activity xml with :
mRelativeLayoutMain.setBackgroundColor(Color.GRAY);
and when I run the app and click the intent it will crash with the error:
"java.lang.NullPointerException: Attempt to invoke virtual method
'void android.widget.RelativeLayout.setBackgroundColor(int)' on a null
object reference"
I think the easiest way is to create an PreferenceManager.SharedPreferences, in which I recommend you to store current app data. This will help you not to loose any changes in app after you exit the it. Here is short instructions:
Create button in settings activity which will change something in main activity.
Create onClickListener for your button.
Use .SharedPreferences to store was you button clicked or not. (I recommend storing boolean variables, this way you can store was button clicked or not.)
I both of your activities in onCreate method call .getSharedPreferences to read saved app values. (I mean to read was the button clicked or not.)
Use app values you got from 4. to change any element in activity. (For example if you stored that button was clicked, then change some TextView text or etc.)
I hope you understood the idea.
Link to the Android developer tutorial about App key values storing & saving
Link to the StackOverflow much easier explanation & examples
There are a couple of ways of doing this (Some of which depends on how you are switching back and forth from each activity). It also depends on what things you are changing.
From your settings page, as you are changing different settings, you'll save this content within Preferences. (You can see more how to use Preferences here: https://examples.javacodegeeks.com/android/core/ui/settings/android-settings-example/ or by just Googling it).
On you main activity, depending on how you come back to it (onStart most likely), you can setup the things you need to programmatically.
So, you may need to do a little research on the Android lifecycle and how each cycle works (https://developer.android.com/guide/components/activities/activity-lifecycle.html), how to program the UI programmatically through Java (http://startandroid.ru/en/lessons/220-lesson-16-creating-layout-programmatically-layoutparams.html), and the Preferences Android library to save certain settings.
The xml isn't meant to be "altered". You can change the UI programmatically. It's possible to build an Android app without any xml. When Android was first built, it didn't use the xml to create the UI. It was all done through Java. It was then added to use xml to create your activities or fragments or any UI component. This made things easier for more static activities or activities with very little dynamic content.

In android Studio, I want when i click on button , next activity/fragment should come from right side

In android Studio, I want when i click on button , next activity/fragment should come from right side and present activity sholud gone left.I implimented its working on Activity but not on adapters is showing error.
holder.questions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(DoctorsProfile.this,Questions.class);
i.putExtra("DOCTOR_ID",doctor_id);
startActivity(i);
overridePendingTransition( R.anim.slide_in_right_up, R.anim.slide_out_right_up);
}
});
overridePendingTransition is working on Activity but not working on Adapters of Recyclerview and Listview, Please tell any other option. I want when i click on recyclerview item next Activity should navigate or come from right side by using overridePendingTransition.
Fragment fragment = Fragment.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.fragment_slide_left_enter,
R.anim.fragment_slide_left_exit, R.anim.fragment_slide_right_enter,
R.anim.fragment_slide_right_exit);
Utils.addFragmentToActivity(fragmentTransaction, Fragment, R.id
.content_frame);
This tip features how to change Android’s default animation when switching between Activities.
The code to change the animation between two Activities is very simple: just call the overridePendingTransition() from the current Activity, after starting a new Intent. This method is available from Android version 2.0 (API level 5), and it takes two parameters, that are used to define the enter and exit animations of your current Activity.
Here’s an example:
//Calls a new Activity
startActivity(new Intent(this, NewActivity.class));
//Set the transition -> method available from Android 2.0 and beyond
overridePendingTransition(R.anim.slide_in_right_up, R.anim.slide_out_right_up);
These two parameters are resource IDs for animations defined with XML files (one for each animation). These files have to be placed inside the app’s res/anim folder. Examples of these files can be found at the Android API demo, inside the anim folder.
for example code visit http://www.christianpeeters.com/android-tutorials/tutorial-activity-slide-animation/#more-483
Change like this code you must be passing activity as context in adapter
holder.questions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(DoctorsProfile.this,Questions.class);
i.putExtra("DOCTOR_ID",doctor_id);
Activity activity = (Activity) context;
activity.startActivity(i);
activity.overridePendingTransition(R.anim.slide_in_right_up, R.anim.slide_out_right_up);
}
});
Note : Context is the Base Object of Activity
Update :
I have checked the accepted answer but hope you understand that it will be called everytime when your activity get launched and thats not supposed to be best practice. I am suggesting better approach if you want to follow the accepted answer .
Alternative :
Pass one parameter in bundle to new activity to make sure that transition coming from that specific adapter so double transation should not happen when you are coming rom any other activity also.
There is a easy way to do this. just put overridePendingTransition on your OnCreate method of next Activity/Fragment.So that when next Activity will come it will come according to your choice.Need not add overridePendingTransition on adapters.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ask_question);
overridePendingTransition( R.anim.slide_in_right_up, R.anim.slide_out_right_up);
}

How Do I Play Sound from another java activity?

As we know the main activity in Android, Eclipse is called MainActivity.java
Actually I have two activites, the second one is: Page2Activity.java
And I have a Page2.xml too for the layout.
I would like to know how can I switch to Page2Activity.java when pushing a button? Because only Page2.xml shows up, and when I click on a button to play a sound nothing happens on the second page.
MainActivity.java
...
bpage2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
setContentView(R.layout.page2);
}
});
...
When I push this button, page2.xml shows up, but it contains sound from Page2Activity.java and when I hit a button the sounds won't play. Could you please tell me how can I load Page2Activity.java with layout page 2?
Regards,
Henrik
You have to fire an event on click action for the button and start page2 Activity on it's listener.
bpage2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, Page2Activity.class);
startActivty(i);
});
Why don't you start the other activity Page2Activity when you click on yout bpage2-Button?
Put this in your listener instead of setContentView(R.layout.page2); :
Intent intent = new Intent(this, Page2Activity.class);
startActivity(intent);
Calling setContentView() sets the layout of your activity - that's why you see the other layout after clicking the button. So what you do is just switching the layout but the logic (e.g. attached listeners) is missing and needs to be implemented. That's why the sound doesn't play. The layout coexists with the logic but it's independant from the logic. Including a xml-layout doesn't mean you include the logic too.
Check out the Fragments http://developer.android.com/guide/components/fragments.html.
In addition take a look on this introduction on how to start an activity from another one: http://developer.android.com/training/basics/firstapp/starting-activity.html .
Maybe you should even start here http://developer.android.com/guide/components/activities.html :)
Good luck.

Categories