learner
learner

Reputation: 4818

Calling a method of the MainActivity from another class?

I want to call a method of MainActivity from another class. The method is:

 public void setDate() {
    final Calendar c = Calendar.getInstance();
    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day = c.get(Calendar.DAY_OF_MONTH);

    Toast.makeText(this, "I am in on resume", Toast.LENGTH_LONG).show();


    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    date = sharedPreferences.getString("DATE_OF_JOURNEY", null);
    if (date == null) {
        sharedPreferences.edit().putString("DATE_OF_JOURNEY", day + "/" + month + "/" + year).apply();
        date = day + "/" + month + "/" + year;
    }

    date_text.setText(date);
}

The other class is used as a datePicker. The dateset method is calling the above method of the MainActivity.

 public void onDateSet(DatePicker view, int year, int month, int day) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());

    Toast.makeText(getContext(),"The date is: " + year + month + day ,Toast.LENGTH_LONG).show();

    sharedPreferences.edit().putString("DATE_OF_JOURNEY", day + "/" + month+"/"+ year).apply();
    mainActivity.setDate();
    // Do something with the date chosen by the user
}

Basically, I want to get SharedPreferences value written by DatePickerFragment class to the MainActivity.

Edit 1: MainActivity:

package com.example.shiza.cube26;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.prefs.PreferenceChangeEvent;

public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;
    TextView date_text;
    String date;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        String url = "https://cube26-1337.0x10.info/stations";

        date_text = (TextView) findViewById(R.id.date);



//        new fetchData().execute(url);


    }

    public void setDate() {
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        Toast.makeText(this, "I am in set date.", Toast.LENGTH_LONG).show();


        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

        date = sharedPreferences.getString("DATE_OF_JOURNEY", null);
        if (date == null) {
            sharedPreferences.edit().putString("DATE_OF_JOURNEY", day + "/" + month + "/" + year).apply();
            date = day + "/" + month + "/" + year;
        }


        date_text.setText(date);
    }


    @Override
    protected void onResume() {
        super.onResume();


    }

    public class fetchData extends AsyncTask<String, Void, String> {
        ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar_timer);

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected String doInBackground(String... params) {
            BufferedReader reader = null;
            try {
                URL url = new URL(params[0]);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                StringBuilder sb = new StringBuilder();

                reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

                String line;

                while ((line = reader.readLine()) != null) {
                    sb.append(line + '\n');

                }

                return sb.toString();

            } catch (MalformedURLException e) {
                e.printStackTrace();
                return null;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            progressBar.setVisibility(View.GONE);

            try {
                JSONObject json = new JSONObject(s);

                JSONArray jsonArray = json.names();

                for (int i = 0; i < jsonArray.length(); i++) {
                    Toast.makeText(getApplicationContext(), jsonArray.getInt(i), Toast.LENGTH_LONG).show();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
            try {
                JSONArray jsonArray = new JSONArray(s);

                for (int i = 0; i < jsonArray.length(); i++) {
                    Toast.makeText(getApplicationContext(), jsonArray.getString(i), Toast.LENGTH_LONG).show();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


    public void showDatePickerDialog(View v) {

        DatePickerFragment datePickerFragment = new DatePickerFragment();
        datePickerFragment.setDateChangeListener(new DatePickerFragment.DateChangeListener(){
            public void onDateChange(){
                setDate();
            }
        });

        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }
}

DatePickerFragment:

package com.example.shiza.cube26;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;
import android.widget.Toast;

import java.util.Calendar;

/**
 * Created by Shiza on 04/10/2015.
 */
public class DatePickerFragment extends DialogFragment
        implements DatePickerDialog.OnDateSetListener {

    private DateChangeListener mListener;
    public void setDateChangeListener(DateChangeListener listener){
        mListener = listener;
    }

    public interface DateChangeListener{
        public void onDateChange();
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());

        Toast.makeText(getContext(),"The date is: " + year + month + day ,Toast.LENGTH_LONG).show();

        sharedPreferences.edit().putString("DATE_OF_JOURNEY", day + "/" + month+"/"+ year).apply();
        if(mListener!=null){
            mListener.onDateChange();
        }
        // Do something with the date chosen by the user
    }
}

Upvotes: 2

Views: 2961

Answers (3)

Ajay Pandya
Ajay Pandya

Reputation: 2457

Write this in your fragment from which you want to call

private MainActivity mainActivity() {

    return (MainActivity) getActivity();
}

And with,

mainActivity().setDate();

You can call main activity public method inside your fragment

Upvotes: 0

Rahul Tiwari
Rahul Tiwari

Reputation: 6978

you can use interface as callback mechanism here. I am using name OtherClass for class which is having datepicker dialog for following example:

define an interface in the other class like this:

public interface DateChangeListener{
  public void onDateChange();
}

and add method for attaching listener in same class

private DateChangeListener mListener;
public void setDateChangeListener(DateChangeListener listener){
   mListener = listener;
}

now inside your onDateSet of same class call

if(mListener!=null){
     mListener.onDateChange();
}

on in your main activity implement DateChangeListener interface before calling for datepicker dialog like this

   otherclassInstance.setDateChangeListener(new OtherClass.DateChangeListener(){
       @override
       public void onDateChange(){
           setDate();
       }
    });

this way whenever onDateSet method will get called in OtherClass, onDateSet method of main activity will also get called.


Edit

Change showDatePickerDialog method like this:

public void showDatePickerDialog(View v) {

    DatePickerFragment datePickerFragment = new DatePickerFragment();
    datePickerFragment.setDateChangeListener(new DatePickerFragment.DateChangeListener(){
        public void onDateChange(){
            setDate();
        }
    });

    datePickerFragment .show(getSupportFragmentManager(), "datePicker");
}

Upvotes: 1

Karan
Karan

Reputation: 2130

there are couple of ways:

  • If MainActivity is present and context!=null then call on object's reference. (not so good way if you want GC to free RAM)

  • Make function static and call MainActivity.staticFunction(); (discouraged for various reasons)

  • Best way is to make a controller class and init its object when required. call object.function();

Upvotes: 1

Related Questions