Search code examples
androidclassmethodsgetter-setter

Calling a Method From Another Activity


Well, I tried the classic method call strategies but wasn't able to succeed. What I want is to call getDayOfTheWeek() and other get methods from Daily to Receive.

MainActivity.java

public class MainActivity extends AppCompatActivity {

public static final String TAG = MainActivity.class.getSimpleName();
public static final String DAILY_FORECAST = "DAILY_FORECAST";
public static final String HOURLY_FORECAST = "HOURLY_FORECAST";
private Forecast mForecast;
NotificationManager notificationManager;
boolean isNotificActive = false;
int notifID = 33;

@Bind(R.id.timeLabel)
TextView mTimeLabel;
@Bind(R.id.tempLabel)
TextView mTempLabel;
@Bind(R.id.humidityValue)
TextView mHumidityValue;
@Bind(R.id.precipValue)
TextView mPrecipValue;
@Bind(R.id.summaryLabel)
TextView mSummaryLabel;
@Bind(R.id.windSpeedValue)
TextView mWindSpeedValue;
@Bind(R.id.relativeLayout)
RelativeLayout mRelativeLayout;
@Bind(R.id.container)
SwipeRefreshLayout mSwipeRefreshLayout;
@Bind(R.id.locationLabel)
TextView mLocationLabel;
@Bind(R.id.notifButton)
ImageButton mNotifButton;

double latitude;
double longitude;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    final GPSTracker gpsTracker = new GPSTracker(this);
    Calendar calendar = Calendar.getInstance();

    mSwipeRefreshLayout.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.CYAN);
    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            }, 1750);
            gpsTracker.getLocation();
            double x = gpsTracker.getLatitude();
            double y = gpsTracker.getLongitude();
            if (x == 0.00 || y == 0.00) {
                Toast.makeText(MainActivity.this, "Location is not enabled", Toast.LENGTH_LONG).show();
            } else {
                getForecast(gpsTracker);
            }
        }
    });
    double x = gpsTracker.getLatitude();
    double y = gpsTracker.getLongitude();
    if (x == 0.00 || y == 0.00) {
        gpsTracker.showSettingsAlert();
    } else {
        getForecast(gpsTracker);
    }
    setAlarm(calendar);
}

public void showNotification(View view) {

    Currently currently = mForecast.getCurrently();
    NotificationCompat.Builder notificBuilder = new NotificationCompat.Builder(this)
            .setContentTitle("Weather")
            .setContentText(currently.getSummary() + " and Temperature: " + currently.getTemperature())
            .setTicker("Current Weather")
            .setSmallIcon(R.drawable.clear_nighticon);

    Intent moreInfoIntent = new Intent(this, MainActivity.class);

    TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(this);

    taskStackBuilder.addParentStack(MainActivity.class);

    taskStackBuilder.addNextIntent(moreInfoIntent);

    PendingIntent pendingIntent = taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    notificBuilder.setContentIntent(pendingIntent);

    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(notifID, notificBuilder.build());

    isNotificActive = true;
}

public void stopNotification(View view) {

    if(isNotificActive) {
        notificationManager.cancel(notifID);
    }
}

public void setAlarm(Calendar calendar) {


    Intent alertIntent = new Intent(this, Receiver.class);
    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alertIntent, 0);

    calendar.set(Calendar.HOUR_OF_DAY, 21);
    calendar.set(Calendar.MINUTE, 26);

    am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),24*60*60*1000, pendingIntent);
}

@Override
protected void onStart() {
    super.onStart();
    GPSTracker gpsTracker = new GPSTracker(this);
    gpsTracker.getLocation();
    double x = gpsTracker.getLatitude();
    double y = gpsTracker.getLongitude();
    if (x == 0.00 || y == 0.00) {

    } else {
        getForecast(gpsTracker);
    }
}

@Override
protected void onRestart() {
    super.onRestart();
}

public void getForecast(final GPSTracker gpsTracker) {

    latitude = gpsTracker.getLatitude();
    longitude = gpsTracker.getLongitude();
    String apiKey = "7d22cdb138cd70f2e9e8d2006cd0461c";
    String forecastUrl = "https://api.forecast.io/forecast/" + apiKey
            + "/" + latitude + "," + longitude;

    if (isNetworkAvailable()) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(forecastUrl).build();

        Call call = client.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                alertUserAboutError();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                try {
                    String jsonData = response.body().string();
                    Log.v(TAG, jsonData);
                    if (response.isSuccessful()) {
                        mForecast = parseForecastDetails(jsonData);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                updateDisplay(gpsTracker);
                            }
                        });
                    } else {
                        alertUserAboutError();
                    }
                } catch (IOException |
                        JSONException e
                        )

                {
                    Log.e(TAG, "Exception caught: ", e);
                }
            }
        });
    } else {
        gpsTracker.showSettingsAlert2();
    }
}

private void updateDisplay(GPSTracker gpsTracker) {

    Currently currently = mForecast.getCurrently();

    String area = gpsTracker.getSubLocality(this);
    String city = gpsTracker.getAdminArea(this);
    String country = gpsTracker.getCountryName(this);
    mLocationLabel.setText(area + "\n" + city + ", " + country);
    mTempLabel.setText(currently.getTemperature() + "");
    mTimeLabel.setText(currently.getFormattedTime());
    mHumidityValue.setText((int) (currently.getHumidity()) + "%");
    mPrecipValue.setText((int) (currently.getPrecipChance()) + "%");
    mSummaryLabel.setText(currently.getSummary());
    mWindSpeedValue.setText((int) (currently.getWindSpeed()) + "");
    Drawable drawable = getResources().getDrawable(currently.getBackgroundId());
    mRelativeLayout.setBackground(drawable);
}

private Forecast parseForecastDetails(String jsonData) throws JSONException {
    Forecast forecast = new Forecast();

    forecast.setCurrently(getCurrentlyDetails(jsonData));
    forecast.setHourlyForecast(getHourlyForecast(jsonData));
    forecast.setDailyForecast(getDailyForecast(jsonData));

    return forecast;
}

private Daily[] getDailyForecast(String jsonData) throws JSONException {
    JSONObject forecast = new JSONObject(jsonData);
    String timezone = forecast.getString("timezone");
    JSONObject jsonDaily = forecast.getJSONObject("daily");
    JSONArray data = jsonDaily.getJSONArray("data");

    Daily[] days = new Daily[data.length()];

    for (int i = 0; i < data.length(); i++) {
        JSONObject daily = data.getJSONObject(i);
        Daily day = new Daily();

        day.setSummary(daily.getString("summary"));
        day.setTempMax(daily.getDouble("temperatureMax"));
        day.setTempMin(daily.getDouble("temperatureMin"));
        day.setIcon(daily.getString("icon"));
        day.setTime(daily.getLong("time"));
        day.setTimezone(timezone);

        days[i] = day;
    }
    return days;
}

private Hourly[] getHourlyForecast(String jsonData) throws JSONException {
    JSONObject forecast = new JSONObject(jsonData);
    String timezone = forecast.getString("timezone");
    JSONObject jsonHourly = forecast.getJSONObject("hourly");
    JSONArray data = jsonHourly.getJSONArray("data");

    Hourly[] hours = new Hourly[data.length()];

    for (int i = 0; i < data.length(); i++) {
        JSONObject hourly = data.getJSONObject(i);
        Hourly hour = new Hourly();

        hour.setSummary(hourly.getString("summary"));
        hour.setTemp(hourly.getDouble("temperature"));
        hour.setIcon(hourly.getString("icon"));
        hour.setTime(hourly.getLong("time"));
        hour.setHumidity(hourly.getDouble("humidity"));
        hour.setWindSpeed(hourly.getDouble("windSpeed"));
        hour.setTimezone(timezone);

        hours[i] = hour;
    }
    return hours;
}

private Currently getCurrentlyDetails(String jsonData) throws JSONException {
    JSONObject forecast = new JSONObject(jsonData);
    String timezone = forecast.getString("timezone");
    JSONObject currently = forecast.getJSONObject("currently");

    Currently currentWeather = new Currently();
    currentWeather.setHumidity(currently.getDouble("humidity"));
    currentWeather.setTime(currently.getLong("time"));
    currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
    currentWeather.setSummary(currently.getString("summary"));
    currentWeather.setTemperature(currently.getDouble("temperature"));
    currentWeather.setWindSpeed(currently.getDouble("windSpeed"));
    currentWeather.setTimeZone(timezone);
    currentWeather.setBackgroundId(currently.getString("icon"));

    Log.d(TAG, currentWeather.getFormattedTime());

    return currentWeather;
}

private boolean isNetworkAvailable() {
    ConnectivityManager manager = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();
    boolean isAvailable = false;
    if (networkInfo != null && networkInfo.isConnected()) {
        isAvailable = true;
    }
    return isAvailable;
}

private void alertUserAboutError() {
    AlertDialogFragment dialog = new AlertDialogFragment();
    dialog.show(getFragmentManager(), "error_dialog");
}

@OnClick(R.id.dailyButton)
public void startDailyActivity(View view) {
    GPSTracker gpsTracker = new GPSTracker(this);
    double x = gpsTracker.getLatitude();
    double y = gpsTracker.getLongitude();
    if (isNetworkAvailable()) {
        if (x == 0.00 || y == 0.00) {
            Toast.makeText(MainActivity.this, "Please enable Location services", Toast.LENGTH_LONG).show();
        } else {
            Intent intent = new Intent(this, DailyForecastActivity.class);
            intent.putExtra(DAILY_FORECAST, mForecast.getDailyForecast());
            startActivity(intent);
        }
    } else {
        Toast.makeText(this, "Please enable Network services", Toast.LENGTH_LONG).show();
    }
}

@OnClick(R.id.hourlyButton)
public void startHourlyActivity(View view) {
    GPSTracker gpsTracker = new GPSTracker(this);
    double x = gpsTracker.getLatitude();
    double y = gpsTracker.getLongitude();
    if (isNetworkAvailable()) {
        if (x == 0.00 || y == 0.00) {
            Toast.makeText(MainActivity.this, "Please enable Location services", Toast.LENGTH_LONG).show();
        } else {
            Intent intent = new Intent(this, HourlyForecastActivity.class);
            intent.putExtra(HOURLY_FORECAST, mForecast.getHourlyForecast());
            startActivity(intent);
        }
    } else {
        Toast.makeText(this, "Please enable Network services", Toast.LENGTH_LONG).show();
    }
}
}

Daily.java:

public class Daily implements Parcelable{

private long mTime;
private String mSummary;
private double mTempMax;
private String mIcon;
private String mTimezone;
private double mTempMin;

public String getDayOfTheWeek() {
    SimpleDateFormat formatter = new SimpleDateFormat("EEEE");
    formatter.setTimeZone(TimeZone.getTimeZone(mTimezone));
    Date dateTime = new Date(mTime * 1000);
    return formatter.format(dateTime);
}

public double getTempMin() {
    double celciusTemp = 100 * (mTempMin - 32) / 180;
    return (int)Math.round(celciusTemp);
}

public void setTempMin(double tempMin) {
    mTempMin = tempMin;
}

public long getTime() {
    return mTime;
}

public void setTime(long time) {
    mTime = time;
}

public String getSummary() {
    return mSummary;
}

public void setSummary(String summary) {
    mSummary = summary;
}

public double getTempMax() {
    double celciusTemp = 100 * (mTempMax - 32) / 180;
    return (int)Math.round(celciusTemp);
}

public void setTempMax(double tempMax) {
    mTempMax = tempMax;
}

public String getIcon() {
    return mIcon;
}

public void setIcon(String icon) {
    mIcon = icon;
}

public String getTimezone() {
    return mTimezone;
}

public void setTimezone(String timezone) {
    mTimezone = timezone;
}

public int getIconId(){
    return Forecast.getIconId(mIcon);
}


@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeLong(mTime);
    dest.writeString(mSummary);
    dest.writeDouble(mTempMax);
    dest.writeDouble(mTempMin);
    dest.writeString(mIcon);
    dest.writeString(mTimezone);
}

private Daily(Parcel in){
    mTime = in.readLong();
    mSummary = in.readString();
    mTempMax = in.readDouble();
    mTempMin = in.readDouble();
    mIcon = in.readString();
    mTimezone = in.readString();
}

public Daily(){

}

public static final Creator<Daily> CREATOR = new Creator<Daily>() {
    @Override
    public Daily createFromParcel(Parcel source) {
        return new Daily(source);
    }

    @Override
    public Daily[] newArray(int size) {
        return new Daily[size];
    }
};
}

Receive.java:

public class Receiver extends BroadcastReceiver{

    Daily day = new Daily();

    @Override
    public void onReceive(Context context, Intent intent) {

    createNotification(context,
            day.getDayOfTheWeek(),
            day.getSummary() + " and Max: " + day.getTempMax() + " Min: " + day.getTempMin(),
            "Your Daily Weather");

    }

    public void createNotification(Context context, String msg,
                                  String msgText, String msgAlert) {
            PendingIntent pi = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);

            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(day.getIconId())
            .setContentTitle(msg)
            .setContentText(msgText)
            .setTicker(msgAlert);

            mBuilder.setContentIntent(pi);
            mBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);
            mBuilder.setAutoCancel(true);

            NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            mNotificationManager.notify(1, mBuilder.build());
    }
}

See, the problem is even though this is correct way to call in many cases, this one fails. I have no idea what the problem is, I declared a Daily variable, used it to call the methods, those getBLA() methods return String so it's okay too... Note that other get methods also exist in Daily.java, but I just wanted to focus on one of them. None of them work. Would really appreciate any help. Also if there are no errors in these codes, I can provide the whole thing. Just let me know please.

DayAdapter.java

public class DayAdapter extends BaseAdapter{

private Context mContext;
private Daily[] mDays;

public DayAdapter(Context context, Daily[] days){
    mContext = context;
    mDays = days;
}
@Override
public int getCount() {
    return mDays.length;
}

@Override
public Object getItem(int position) {
    return mDays[position];
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;

    if (convertView == null){
        // brand new
        convertView = LayoutInflater.from(mContext).inflate(R.layout.daily_list_item, null);
        holder = new ViewHolder();
        holder.iconImageView = (ImageView) convertView.findViewById(R.id.iconImageView);
        holder.tempLabel = (TextView) convertView.findViewById(R.id.tempLabel);
        holder.dayLabel = (TextView) convertView.findViewById(R.id.dayNameLabel);

        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    Daily day = mDays[position];

    holder.iconImageView.setImageResource(day.getIconId());
    holder.tempLabel.setText(((int)day.getTempMax()) + "/" + ((int)day.getTempMin()));

    if (position == 0){
        holder.dayLabel.setText("Today");
    } else {
        holder.dayLabel.setText(day.getDayOfTheWeek());
    }
    return convertView;
}

private static class ViewHolder {
    ImageView iconImageView;
    TextView tempLabel;
    TextView dayLabel;
}
}

DailyForecastActivity.java

public class DailyForecastActivity extends AppCompatActivity {

private Daily[] mDays;

String dayoftheweek;
@Bind(android.R.id.list)
ListView mListView;
@Bind(android.R.id.empty)
TextView mEmptyTextView;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_daily_forecast);
    ButterKnife.bind(this);

    GPSTracker gpsTracker = new GPSTracker(this);
    TextView mLocationLabel = (TextView) findViewById(R.id.locationLabel);
    Intent intent = getIntent();

        Parcelable[] parcelables = intent.getParcelableArrayExtra(MainActivity.DAILY_FORECAST);
        mDays = Arrays.copyOf(parcelables, parcelables.length, Daily[].class);
        DayAdapter adapter = new DayAdapter(this, mDays);
        mListView.setAdapter(adapter);
        mListView.setEmptyView(mEmptyTextView);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String dayOfTheWeek = mDays[position].getDayOfTheWeek();
                String condition = mDays[position].getSummary();

                if (mDays[position].getSummary().contains("Mixed")) {
                    condition = "There will be Mixed Precipitation";
                }
                if (mDays[position].getSummary().contains("Snow")) {
                    condition = "There will be Snow";
                }
                if (mDays[position].getSummary().contains("Partly cloudy")) {
                    condition = "It will be Partly Cloudy";
                }
                if (mDays[position].getSummary().contains("Light rain")) {
                    condition = "There will be Light Rain";
                }
                if (mDays[position].getSummary().contains("Rain")) {
                    condition = "There will be Rain";
                }
                String message = String.format("%s Summary: %s", dayOfTheWeek, condition);
                Toast.makeText(DailyForecastActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        });

        String area = gpsTracker.getSubLocality(this);
        String city = gpsTracker.getAdminArea(this);
        String country = gpsTracker.getCountryName(this);
        mLocationLabel.setText(area + ", " + city + ", " + country);
}
}

Solution

  • In your Daily class, you've declared the variables

    private long mTime;
    private String mSummary;
    private double mTempMax;
    private String mIcon;
    private String mTimezone;
    private double mTempMin;
    

    I see that you create a new instance of Daily in your createNotification method and start calling the get methods.

    But, where are the values set for all those declared variables? They are still null when you call the get methods for each in the createNotification method.

    Are you missing a method call in between to set these values? You should probably create a constructor in the Daily class which sets the values for all these variables before you start getting them?

    How to write the constructor:

    public class Daily implements Parcelable{
    
    private long mTime;
    private String mSummary;
    private double mTempMax;
    private String mIcon;
    private String mTimezone;
    private double mTempMin;
    
    //constructor
    public Daily(long mTime, String mSummary, double mTempMax, String mIcon, String mTimezone, double mTempMin) {
         this.mTime =  mTime;
         this.mSummary = mSummary;
         this.mtempMax = mTempMax;
         ...
         ...
         ...
    
    }
    
    // rest of your code below this as it is
    

    And now create your instance for Daily Class like this:

    Daily day = new Daily(3131313, "Summary",  107, "icon", "timezone", 91);
    // replace these hardcoded values with sensible values from your data source
    

    Alternatively create a constructor with no arguments and get the values to initialize the variables directly in your constructor. However it works for you.

    After this your code should work fine.