1

I am trying to get a string to display from the strings.xml

opmStatusText is showing the correct Value from Strings.xml (Android Studio is displaying the value) but when I use it in txt = "Operational Status: " + opmStatusText; it is showing as NULL

in my App I get: Operational Status: null

What I'm I doing wrong?

Here is the entire class

package com.myapp.opm_status;

import android.content.Context;

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

public class OPMStatus  {
    public MainActivity.Status status;
    public String appliesto;
    public String location;
    public String txt;

    private static String opmStatusText;

    public static String getString(Context context) {

        opmStatusText = context.getResources().getString(R.string.statusTxt);

        return opmStatusText;
    }

    public OPMStatus(JSONObject obj) {
        try {
            this.appliesto = obj.getString("AppliesTo");
            this.location = obj.getString("Location");
            this.txt = obj.getString("ShortStatusMessage");
            String iconText = obj.getString("Icon");
            switch (iconText) {
                case "Unknown":
                    this.status = MainActivity.Status.Unknown;
                    break;
                case "Open":
                    this.status = MainActivity.Status.Open;
                    break;
                case "Alert":
                    this.status = MainActivity.Status.Alert;
                    break;
                default:
                    this.status = MainActivity.Status.Closed;
            }
        } catch (JSONException e) {
            e.printStackTrace();
            //txt = "Operational Status Unknown: Please ensure you have a connection to the Internet and then press Refresh to try again.";
            txt = "Operational Status: " + opmStatusText;
            this.status = MainActivity.Status.Unknown;
        }
    }
}

My MainActivity

package com.myapp.opm_status;

import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends ActionBarActivity {

    public static final String STATUS_URL = "http://www.wwopm.gov/json/operatingstatus.json"; //Entered wrong URL to get an unknown status for testing
    public static final int NOTIFICATION_ID = 493812;
    private static final String DEFAULT_POLLING_INTERVAL = "1";

    // Static form for access from broadcast receiver
    public static int getPersistentUpdateIntervalMins(Context ctx) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
        String minsStr = prefs.getString("updateIntervalMins", DEFAULT_POLLING_INTERVAL);
        return Integer.parseInt(minsStr);
    }

    ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setIcon(R.drawable.ic_launcher);
        listenRefresh();
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshStatus();
        // Wipe status of notification
        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.cancel(NOTIFICATION_ID);

        int minutes = getPersistentUpdateIntervalMins();
        Log.d("MainActivity", "Update interval is " + minutes);
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent i = new Intent(this, NotificationService.class);
        PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
        am.cancel(pi);
        // by my own convention, minutes <= 0 means notifications are disabled
        if (minutes > 0) {
            am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                    SystemClock.elapsedRealtime() + minutes * 60 * 1000,
                    minutes * 60 * 1000, pi);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            Intent intentSetPref = new Intent(getApplicationContext(), PrefActivity.class);
            startActivityForResult(intentSetPref, 0);
        }

        return super.onOptionsItemSelected(item);
    }

    // Executes a rest call to the url and updates visuals as well as persisted status
    void refreshStatus() {
        Log.d("MainActivity", "About to execute refresh");

        AsyncTask task = new AsyncTask() {
            @Override
            protected OPMStatus doInBackground(Object[] params) {
                return new OPMStatus(SyncRestClient.connect());
            }

            @Override
            protected void onPostExecute(final Object obj) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        OPMStatus opms = (OPMStatus) obj;
                        setStatusTextLocation(opms.location);
                        setStatusTextAppliesTo(opms.appliesto);
                        setStatusTextPersistent(opms.txt);
                        setStatusImage(opms.status);
                        setStatusText(opms.location, opms.appliesto, opms.txt, opms.status);
                    }
                });
            }
        };
        task.execute();
    }


    // Attach a listener to the refresh button
    private void listenRefresh() {
        Button refreshButton = (Button) findViewById(R.id.refreshButton);
        refreshButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshStatus();
            }
        });
    }

    // Set shared preferences status location
    void setStatusTextLocation(String location) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("statusLocation", location);
        editor.apply();
    }

    // Set shared preferences status Applies To
    void setStatusTextAppliesTo(String appliesto) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("statusAppliesTo", appliesto);
        editor.apply();
    }

    // Set shared preferences status text
    void setStatusTextPersistent(String txt) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("statusText", txt);
        editor.apply();
    }

    // Get shared preferences update interval in minutes
    int getPersistentUpdateIntervalMins() {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        String minsStr = prefs.getString("updateIntervalMins", DEFAULT_POLLING_INTERVAL);
        return Integer.parseInt(minsStr);
    }

    // This function sets the text of the textviews
    private void setStatusText(String location, String appliesto, String txt, Status status) {
        //TextView statusTitle = (TextView) findViewById(R.id.statusTitle);
        TextView statusLocation = (TextView) findViewById(R.id.statusLocation);
        TextView statusAppliesTo = (TextView) findViewById(R.id.statusAppliesToTxt);
        TextView statusText = (TextView) findViewById(R.id.statusText);
        statusLocation.setText(location);
        statusAppliesTo.setText(" " + appliesto);
        statusText.setText(txt);
        TextView timeText = (TextView) findViewById(R.id.currentTime);
        TextView statusPhrase = (TextView) findViewById(R.id.statusPhrase);

        DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
        Date date = new Date();
        timeText.setText(" " +  dateFormat.format(date));
        switch (status) {
            case Unknown:
                statusPhrase.setTextColor(getResources().getColor(android.R.color.holo_blue_light));
                break;
            case Open:
                statusPhrase.setTextColor(getResources().getColor(android.R.color.holo_green_dark));
                break;
            case Alert:
                statusPhrase.setTextColor(getResources().getColor(android.R.color.holo_orange_light));
                break;
            default:
                statusPhrase.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
        }
        Log.d("Debug", status.toString());
        statusPhrase.setText(getString(R.string.status) + " " + status.toString());

    }

    // This function will set the icon based on the current status
    private void setStatusImage(Status s) {
        ImageView statusImage = (ImageView) findViewById(R.id.statusImage);
        int resId;
        switch (s) {
            case Unknown:
                resId = R.drawable.status_unknown;
                break;
            case Open:
                resId = R.drawable.status_open;
                break;
            case Alert:
                resId = R.drawable.status_alert;
                break;
            default:
                resId = R.drawable.status_closed;
        }
        statusImage.setImageResource(resId);
    }

    public enum Status {Unknown, Open, Alert, Closed}
}
3
  • If you downgraded my question, please tell me why. I have already searched and this is how I ended up where I am at. I almost have it working, but it's not right. Commented Mar 8, 2015 at 14:26
  • 1
    Where are you calling your static getString() method? Does the String opmStatusText need to be static? Commented Mar 8, 2015 at 14:28
  • I am trying to keep from hard coding anything and trying to get the value from Strings.xml. I originally tried "txt = Resources.getSystem().getString(android.R.string.statusTxt)" but this didn't work either. So i found somowhere it said I had to have a Context, so I added the public static String getString(Context context). I hope that explains it. Commented Mar 8, 2015 at 14:40

2 Answers 2

1

Change your constructor public OPMStatus(JSONObject obj) to be:

public OPMStatus(JSONObject obj, Context context)
{
   Context thisContext = context;
       ... ...

   catch (JSONException e) {
        e.printStackTrace();
        //txt = "Operational Status Unknown: Please ensure you have a connection to the Internet and then press Refresh to try again.";
        txt = "Operational Status: " + getString(thisContext);
        this.status = MainActivity.Status.Unknown;
    }

}

modify your doInBackground as:

@Override
protected JSONObject doInBackground(Object[] params) {
            return SyncRestClient.connect();
}

@Override
protected void onPostExecute(JSONObject jsonObj) {

      OPMStatus opms = OPMStatus(jsonObj, this);           

      setStatusTextLocation(opms.location);
      setStatusTextAppliesTo(opms.appliesto);
      setStatusTextPersistent(opms.txt);
      setStatusImage(opms.status);
      setStatusText(opms.location, opms.appliesto, opms.txt, opms.status);
}
Sign up to request clarification or add additional context in comments.

4 Comments

When I tried this, my MainActivity get an error that OPMStatus can not be applied to JSONObject. I have Added my MainActivity for additional reference.
In your MainActivity, you should call OPMStatus(yourJson, this), right?
No, I'm not sure where to put this. OPMStatus(yourJson, this). I tried putting it in, return new OPMStatus(SyncRestClient.connect(), this) but it still gives an error.
Either I did not do it correctly or that did not work. Either way, you ans John pointed me in the right direction (See my solution below) . Thanks again.
0

This got me what I wanted.

package com.myapp.opm_status;

import android.content.Context;

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

import static com.myapp.opm_status.R.string.statusTxt;

public class OPMStatus {
    public MainActivity.Status status;
    public String appliesto;
    public String location;
    public String txt;

    public String opmStatusText;

    public OPMStatus(Context context) {
        opmStatusText = context.getString(statusTxt);
    }

    public OPMStatus(JSONObject obj) {

        try {
            this.appliesto = obj.getString("AppliesTo");
            this.location = obj.getString("Location");
            this.txt = obj.getString("ShortStatusMessage");
            String iconText = obj.getString("Icon");
            switch (iconText) {
                case "Unknown":
                    this.status = MainActivity.Status.Unknown;
                    break;
                case "Open":
                    this.status = MainActivity.Status.Open;
                    break;
                case "Alert":
                    this.status = MainActivity.Status.Alert;
                    break;
                default:
                    this.status = MainActivity.Status.Closed;
            }
        } catch (JSONException e) {
            e.printStackTrace();
            txt = "" + new OPMStatus(obj);
            this.status = MainActivity.Status.Unknown;
        }
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.