How to read a method codes from another activity in my activity? - java

I want to call a method from another activity in my activity. I tried this codes but my app is crashed! :
SecondActivity:
package com.mycompany.myapp;
import android.app.*;
import android.os.*;
import android.widget.*;
public class SecondActivity extends Activity
{
public void toast()
{
Toast.makeText(getApplicationContext(),"hello",50).show();
}
}
MainActivity:
package com.mycompany.myapp;
import android.app.*;
import android.os.*;
import com.mycompany.myapp.*;
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SecondActivity s=new SecondActivity();
s.toast();
}
}
What the problem?! Please help me. Thanks.

I think you are confusing the Java class and Activity. If you want to declare the methods which don't need a layout and activity stuff, create a java class and have public methods.
1) MainActivity - Activity Class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ToastClass toastClass = new ToastClass();
toastClass.toast(getApplicationContext(), "Hey dude!!");
}
}
2) ToastClass - java class
public class ToastClass {
public void toast(Context context, String msg) {
Toast.makeText(context ,"hello",Toast.LENGTH_SHORT).show();
}
}
Hope, it helps!

You do not instantiate activities, but starts them with an intent
Intent intentSecondActivity = new Intent(this,SecondActivity.class);
intentSecondActivity.putExtra("methodToStart","toast");
startActivity(intentScheduleActivity);
In the secondActivity read the extras and start the method:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.secondActivity);
String method = getIntent().getStringExtra("method");
if (method.equals("toast"){
toast();
}
}
Alternatively you might want to study fragments.

Related

How to fix "error: cannot find symbol method startActivity(Intent)" in a class of Listener?

I can make an Intent to open other Activity with writing the code in MainActivity.java.
Then I try to make an Intent using a class and called it in MainActivity.java. But it becomes error.
How to solve this problem?
When I write startActivity(numberIntent); in MainActivity.java there is no error but when I move this line of code to NumbersClickListener.java
Errors come:
error: cannot find symbol method startActivity(Intent)
error: not an enclosing class: MainActivity
This my code
In MainActivity.java
package com.example.android.*****;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.TextViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NumbersClickListener clickListener = new NumbersClickListener();
TextView numbers = (TextView)findViewById(R.id.numbers);
numbers.setOnClickListener(clickListener);
}
in NumbersClickListener.java
package com.example.android.*****;
import android.content.Intent;
import android.view.View;
android.widget.Toast first
import android.widget.Toast;
OnClickListener should be written in capital letter
public class NumbersClickListener implements View.OnClickListener {
#Override
public void onClick(View view) {//.makeText(view.getContext(),
"open the list of numbers", Toast.LENGTH_SHORT).show();
Intent numberIntent = new Intent(MainActivity.this,
NumbersActivity.class);
startActivity(numberIntent);
}
}
error: cannot find symbol method startActivity(Intent)” in a class of Listener?
Because if startActivity(Intent) is a method of activity and its required call from context
If you want call startActivity(Intent) outside activity you need to use
Context.startActivity(numberIntent);
Use this
view.getContext().startActivity(numberIntent);
instead of this
startActivity(numberIntent);
SAMPLE CODE
public class NumbersClickListener implements View.OnClickListener {
#Override
public void onClick(View view) {
Intent numberIntent = new Intent(view.getContext(),
NumbersActivity.class);
view.getContext().startActivity(numberIntent);
}
}
You are defining NumbersClickListener in a separate java file. It has no way compiler will know that when u call startActivity you are referring to the Activity.startActivity
Unless you have a deeper purpose for NumbersClickListener.java, simply do inline declaration of View.Listener will do
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NumbersClickListener clickListener = new NumbersClickListener();
TextView numbers = (TextView)findViewById(R.id.numbers);
numbers.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent numberIntent = new Intent(MainActivity.this,NumbersActivity.class);
startActivity(numberIntent);
}
});
}
In place MainActivity.this, use its context.
Intent numberIntent = new Intent(context, NumbersActivity.class);
startActivity(numberIntent);
Notice the changes I have made
MainActivity.java
package com.example.android.*****;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.TextViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NumbersClickListener clickListener = new NumbersClickListener(MainActivity.this); // Context while creating ClickListener Object
TextView numbers = (TextView)findViewById(R.id.numbers);
numbers.setOnClickListener(clickListener);
}
NumbersClickListener.java
package com.example.android.*****;
import android.content.Intent;
import android.view.View;
import android.widget.Toast;
public class NumbersClickListener implements View.OnClickListener {
Context context;
NumbersClickListener(Context c){
this.context = c;
}
#Override
public void onClick(View view) {
Intent numberIntent = new Intent(context, NumbersActivity.class);
startActivity(numberIntent);
}
}
To startActivity you need Context.
It will be like this context.startActivity()
In MainActivity it is not giving error because Activity internally extends Context.
NumbersClickListener is not extended Context.
So, you can start activity using View context
Replace startActivity(numberIntent) with
view.getContext().startActivity(numberIntent);
inside your NumberClickListener class you can do the following
Context context = view.getContext();
Intent numberIntent = new Intent (context, NumberActivity.class);
context.startActivity(numberIntent);
By using this code you can use your NumberClickListener with any other activity.
happy codding :)

What's wrong with my code, please help me [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
MainActivity.java:
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
int currentPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyListener myListener = new MyListener();
Button startButton = (Button) findViewById(R.id.start);
startButton.setOnClickListener(myListener);
Button pauseButton = (Button) findViewById(R.id.pause);
pauseButton.setOnClickListener(myListener);
}
}
MyListener.java:
import android.media.MediaPlayer;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MyListener extends AppCompatActivity implements View.OnClickListener{
MediaPlayer musicPlayer = MediaPlayer.create(this, R.raw.sound_file);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_listener);
}
#Override
public void onClick(View v){
switch(v.getId()){
case R.id.start:
musicPlayer.start();
break;
case R.id.pause:
musicPlayer.pause();
break;
}
}
}
Logcat shows the following error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.musicplayer/com.example.android.musicplayer.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
I am trying to create an app that plays audio from my res/raw file, but there seems to be something wrong with my code as it is not working, please help me.
Firstly, your MediaPlayer instance should reside within MainActivity, not MyListener, and MyListener should not extend an activity. In fact, you should move all of your code from MyListener into MainActivity, I don't really see a purpose for it in the snippet you've provided.
Secondly, You're creating your MediaPlayer outside of the Activity Lifecycle, while still trying to pass a Context to it:
public class MainActivity extends AppCompatActivity {
MediaPlayer musicPlayer = MediaPlayer.create(this, R.raw.sound_file);
...
}
The activity has no Context (this) until the Activity Lifecycle has started, the way you've written it above is equivalent to defining musicPlayer in a constructor:
public class MainActivity extends AppCompatActivity {
MediaPlayer musicPlayer;
public MyListener() {
musicPlayer = MediaPlayer.create(this, R.raw.sound_file);
}
...
}
This will also fail as the Activity Lifecycle has not yet started. What you need to do is declare musicPlayer as a member of the class, and then create an instance in onCreate() where the Context will have been initialsed:
public class MainActivity extends AppCompatActivity {
MediaPlayer musicPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_listener);
musicPlayer = MediaPlayer.create(this, R.raw.sound_file);
}
...
}
To address your comment, here's an example of how it could all fit in to your MainActivity using lambdas:
public class MainActivity extends AppCompatActivity {
int currentPosition;
MediaPlayer musicPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
musicPlayer = MediaPlayer.create(this, R.raw.sound_file);
Button startButton = (Button) findViewById(R.id.start);
startButton.setOnClickListener(view -> musicPlayer.start());
Button pauseButton = (Button) findViewById(R.id.pause);
pauseButton.setOnClickListener(view -> musicPlayer.pause());
}
}

OnSharedPreferenceChangeListener Won't Work?

I am trying to change the application background color, and the font type via theme when a preference is changed in the prefs area.
So far I have the preferences working but when I put the listener in, it just does not get called. I am testing using toasts to see if it appears.
My Code:
package alertssystem.lsa13tafeproj.lsa13.resistorcalculator;
import android.app.ActionBar;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.widget.RelativeLayout;
import android.widget.Toast;
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
public class Prefs extends PreferenceActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new PreferencesFragment()).commit();
}
#Override
public void onBackPressed()
{
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
public static class PreferencesFragment extends PreferenceFragment
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
}
}
}
There is no changeListener in above code as none of the solutions I found worked, can someone please tell me how I can implement this into this.
The user clicks on the ListPreference and it has the 2 options I have inserted, but nothing happens when new option is selected.
This works for me:
public class MyPreferenceFragment extends PreferenceFragment implements
OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
PreferenceManager.getDefaultSharedPreferences(getActivity()).registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onDestroy() {
PreferenceManager.getDefaultSharedPreferences(getActivity()).unregisterOnSharedPreferenceChangeListener(this);
super.onDestroy();
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// Toast
}
}
Make sure you register your listener before changing the pref, and not unregistering it until you do.

How to use a different class from an application's activity?

I created a Java file in the same package as my main activity with a class named sup.
Now, I need to use this class in the main activity file.
mainActivity.java:
package com.example.phy.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
sup mola = new sup(this);
mola.as();
}
sup.java:
package com.example.phy.myapplication;
import android.content.Context;
import android.widget.Toast;
public class sup {
public sup(Context context){
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
void as(Context context){
CharSequence text = "as method";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
Do I have to import the class into mainActivity? How?
sup class and MainActivity class are located in the same package, so you dont need to import anything, BUT you are calling a method of the classs sup in no defined scope... it would be better if you move this
sup mola = new sup(this);
mola.as();
inside of the on create method so like:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sup mola = new sup(this);
mola.as();
}
}
Import is not needed if MainActivity and sup class have the same package name
There's a missing parameter in mola.as();
It needs to be: mola.as(this);

Runtime error while switching between activities in Android

I got a runtime error when I press the button that should change the activity:
package com.example.LocationTracker;
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button;
public class LocationTracker extends Activity{ /** Called when the activity is first created. */
Button btn_Tracker;
Button btn_Display_Map;
Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = getApplicationContext();
btn_Tracker = (Button)findViewById(R.id.btn_Tracker);
btn_Tracker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//setContentView(R.layout.trackeractivity);
Intent myIntent1 = new Intent(view.getContext(), TrackerActivity.class);
context.startActivity(myIntent1);
}});
}
class TrackerActivity extends Activity {
//Your member variable declaration here
// Called when the activity is first created.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trackeractivity);
}
}
I added everything right in the maniefest file
<activity android:name=".TrackerActivity" android:label="#string/app_name"/>
<activity android:name=".DisplayMapActivity" android:label="#string/app_name"/>
</application>
Any idea?
I think TrackerActivity needs to be public, which means it will need to be in its own file as well.
You shouldn't be using getApplicationContext() to start activities. Every activity is a context, so having a member instance of Context should not be necessary. Try re-writing the onClick method of your OnClickListener like this
public void onClick(View view) {
Intent myIntent1 = new Intent(LocationTracker.this, TrackerActivity.class);
LocationTracker.this.startActivity(myIntent1);
}});
Also, refer to this documentation for when to use the application context.

Categories