从另一个类调用MainActivity的方法?

时间:2015-10-03 11:04:29

标签: java android

我想从另一个类调用void free_generic(void **pp) { assert(pp); if(pp != NULL) { free(*pp); *pp = NULL; } } while(cur) { free_generic(&cur->value); cur = cur->next; } 的方法。方法是:

MainActivity

另一个类用作 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); } 。 dateset方法调用datePicker的上述方法。

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 } 类的SharedPreferences值写入DatePickerFragment

编辑1:MainActivity

MainActivity

DatePickerFragment:

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

3 个答案:

答案 0 :(得分:1)

有几种方法:

  • 如果MainActivity存在且context!= null,则调用object的引用。 (如果你想让GC释放RAM,那就没那么好了)

  • 使函数静态并调用MainActivity.staticFunction(); (因各种原因而气馁)

  • 最好的方法是创建一个控制器类,并在需要时初始化它的对象。 call object.function();

答案 1 :(得分:1)

您可以在此处使用interface as callback机制。 我正在使用名称OtherClass用于具有以下示例的datepicker对话框的类:

在另一个类中定义一个接口,如下所示:

public interface DateChangeListener{
  public void onDateChange();
}

并添加在同一类中附加侦听器的方法

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

现在位于同一课程的onDateSet

if(mListener!=null){
     mListener.onDateChange();
}
在调用像此

这样的datepicker对话框之前,在主活动实现DateChangeListener界面中

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

这种方式只要在OtherClass中调用onDateSet方法,主活动的onDateSet方法也会被调用。

修改

像这样改变showDatePickerDialog方法:

public void showDatePickerDialog(View v){

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

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

答案 2 :(得分:0)

将此内容写入您要调用的片段

私有MainActivity mainActivity(){

$age = '';

db_con->query("UPDATE info SET myAge = ".$age." WHERE account_id = 1");

随着,

mainActivity()的setDate();

您可以在片段中调用main activity public方法