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

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);

Related

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

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.

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());
}
}

Show ProgressDialog from outside class

I want show a ProgressDialog on the current activity from an outside class, other than passing the variable into the outside class or using a static variable like other answered questions. Is it possible? Here is some simple test code that might help illustrate what I want to do:
MainActivity.java
package com.example.test;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.example.test.test2;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void buttonPressed( View view) {
test2 T2;
T2 = new test2();
Log.d("button", "pressed");
T2.change();
}
}
And test2.java
package com.example.test;
import android.app.ProgressDialog;
public class test2 {
ProgressDialog mDialog;
public void change() {
mDialog = new ProgressDialog(this);
mDialog.setMessage("Testing");
mDialog.setCancelable(true);
mDialog.show();
}
}
When the button is pressed, the funtion buttonPressed is called which calls the test2 class to show a ProgressDialog on the Main Activity.
I think it all relies on the context in mDialog = new ProgressDialog(this);, like somehow it needs to be told the current activity? But I'm new to Java so it's just a guess.
A possible solution is to change the method passing the current Activity as a parameter from Test2:
public void change(Context context) {
mDialog = new ProgressDialog(context);
mDialog.setMessage("Testing");
mDialog.setCancelable(true);
mDialog.show();
}
And then in class MainActivity do this call:
public void buttonPressed( View view) {
test2 T2;
T2 = new test2();
Log.d("button", "pressed");
T2.change(this);
}

How can make a relation between 2 class in one program?(android)

I must write a program with android which can find other ssid's and show them. I desinged it with 2 xml pages. I create an imagebutton in page2 and want to make a relation between imagebutton and searching method. It means i want to click on imagebutton and seaching method begin it's work and search ssid's and show them...
My problem is, I download my search method and because of that i can not recognize which method i must call on my setonclick method that i write for an imagebutton in second page? I try to create another class seperately for search method and call it from the second class of page2.
but i dont know how can i make a relation between these 2 calss(i mean the second and third class). Or i must write the method of searching and on click of my imagebutton in one class?
Thanks for your suggestion.this is the code that i was copy:
import java.util.Date;
import java.util.List;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class wifiScan extends Activity {
private class WifiReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context c, Intent intent) {
List<ScanResult> results = wifi.getScanResults();
Date tempDate=new Date();
String info=testNumber+" "+(tempDate.getTime()-testDate.
getTime()) +" "+results.size();
Log.i("wifiScan", info);
wifiText.setText(info);
testNumber++;
testDate=new Date();
wifi.startScan();
}
}
private TextView wifiText;
private WifiManager wifi;
private WifiReceiver receiver;
private Date testDate;
private static int testNumber=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
testNumber=0;
wifiText = (TextView) findViewById(R.id.wifiText);
receiver=new WifiReceiver();
registerReceiver(receiver, new IntentFilte
(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
wifi =(WifiManager)getSystemService(Context.WIFI_SERVICE);
if(!wifi.isWifiEnabled()){
wifi.setWifiEnabled(true);
}
startScan();
}
#Override
public void onStop(){
super.onStop();
finish();
}
public void startScan(){
testDate=new Date();
wifi.startScan();
}
}
you_image_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(this, wifiScan.class);
getApplicationContext().startActivity(i);
}
});

Categories