Как вызвать SharedPreferences в произвольном классе

447
17 января 2017, 23:17

Есть виджет для Андроида. Суть его работы: парсить JSON с сайта и выводить некоторые данные. Виджет имеет активность, через которую при установке виджета можно вбить пользовательские данные и сохранить их в Shared Preferences.

Нижеприведенный код позволяют вызвать значение Preferences в клаcсе самого Виджета. Но мне нужно, чтобы это значение передавалось в класс HTTPRequestThread2 (его мы вызываем из виджета) который обращается к JSON сайта.

Вот код самого виджета.

public class NHwidget extends AppWidgetProvider {
private static final String SYNC_CLICKED    = "nhwidget_update_action";
private static final String WAITING_MESSAGE = "Обновляем";
private static final String NOCONNECTING_MESSAGE = "Нет\nподключения";
public static final int httpsDelayMs = 300;
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                            int appWidgetId) {
    CharSequence widgetText = NHwidgetConfigureActivity.loadTitlePref(context, appWidgetId);
    // Construct the RemoteViews object
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.nhwidget);
    views.setTextViewText(R.id.appwidget_text, widgetText);
    // Instruct the widget manager to update the widget
    appWidgetManager.updateAppWidget(appWidgetId, views);
    String output2;
    // Запускаем отдельный поток для получения данных с сайта
    HTTPRequestThread2 thread2 = new HTTPRequestThread2();
    thread2.start();
    try {
        while (true) {
            Thread.sleep(300);
            if(!thread2.isAlive()) {
                output2 = thread2.getInfoString();
                break;
            }
        }
    } catch (Exception e) {
        output2 = "";
    }
    //выводим в виджет результат
    views.setTextViewText(R.id.appwidget_text_balance, output2);
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    // There may be multiple widgets active, so update all of them
    for (int appWidgetId : appWidgetIds) {
        updateAppWidget(context, appWidgetManager, appWidgetId);
    }
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
    // When the user deletes the widget, delete the preference associated with it.
    for (int appWidgetId : appWidgetIds) {
        NHwidgetConfigureActivity.deleteTitlePref(context, appWidgetId);
    }
}
@Override
public void onEnabled(Context context) {
    // Enter relevant functionality for when the first widget is created
}
@Override
public void onDisabled(Context context) {
    // Enter relevant functionality for when the last widget is disabled
}
}

Код Активности для сохранения введенных значений в Preferences:

import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class NHwidgetConfigureActivity extends Activity {
private static final String PREFS_NAME = "com.test.nhmonitor.NHwidget";
private static final String PREF_PREFIX_KEY = "appwidget_";
int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
EditText mAppWidgetText;
View.OnClickListener mOnClickListener = new View.OnClickListener() {
    public void onClick(View v) {
        final Context context = NHwidgetConfigureActivity.this;
        // When the button is clicked, store the string locally
        String widgetText = mAppWidgetText.getText().toString();
        saveTitlePref(context, mAppWidgetId, widgetText);
        // It is the responsibility of the configuration activity to update the app widget
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
        NHwidget.updateAppWidget(context, appWidgetManager, mAppWidgetId);
        // Make sure we pass back the original appWidgetId
        Intent resultValue = new Intent();
        resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
        setResult(RESULT_OK, resultValue);
        finish();
    }
};
public NHwidgetConfigureActivity() {
    super();
}
// Write the prefix to the SharedPreferences object for this widget
static void saveTitlePref(Context context, int appWidgetId, String text) {
    SharedPreferences.Editor prefs = context.getSharedPreferences(PREFS_NAME, 0).edit();
    prefs.putString(PREF_PREFIX_KEY + appWidgetId, text);
    prefs.apply();
}
// Read the prefix from the SharedPreferences object for this widget.
// If there is no preference saved, get the default from a resource
static String loadTitlePref(Context context, int appWidgetId) {
    SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
    String titleValue = prefs.getString(PREF_PREFIX_KEY + appWidgetId, null);
    if (titleValue != null) {
        return titleValue;
    } else {
        return context.getString(R.string.appwidget_text);
    }
}
static void deleteTitlePref(Context context, int appWidgetId) {
    SharedPreferences.Editor prefs = context.getSharedPreferences(PREFS_NAME, 0).edit();
    prefs.remove(PREF_PREFIX_KEY + appWidgetId);
    prefs.apply();
}
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    // Set the result to CANCELED.  This will cause the widget host to cancel
    // out of the widget placement if the user presses the back button.
    setResult(RESULT_CANCELED);
    setContentView(R.layout.nhwidget_configure);
    mAppWidgetText = (EditText) findViewById(R.id.appwidget_text);
    findViewById(R.id.add_button).setOnClickListener(mOnClickListener);
    // Find the widget id from the intent.
    Intent intent = getIntent();
    Bundle extras = intent.getExtras();
    if (extras != null) {
        mAppWidgetId = extras.getInt(
                AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
    }
    // If this activity was started with an intent without an app widget ID, finish with an error.
    if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
        finish();
        return;
    }
    mAppWidgetText.setText(loadTitlePref(NHwidgetConfigureActivity.this, mAppWidgetId));
}
}

Код класса, где выполняется запрос к URL и где нужно получить сохраненное значение из Preferences:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
class HTTPRequestThread2 extends Thread{
private static final String urlString = "https://btc-e.nz/api/3/ticker/";
String getInfoString() {
    return output2;
}
private String output2 = "";
private void requestPrice() {
    try {
        URL url = new URL(urlString);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        output2 = JSONParser.getPrice(response.toString());
    } catch (Exception e) {
        output2 = "";
    }
}
@Override
public void run() {
    requestPrice();
}
}
READ ALSO
setAdapter долго загружает данные

setAdapter долго загружает данные

ЗдравствуйтеИмеется кастомный CursorAdapter

356
Не работает слушатель на SharedPreferences

Не работает слушатель на SharedPreferences

Не могу понять почему не работает слушатель на SharedPreferencesПожалуйста подскажите что сделал не так?

379
Как организовать подгрузку элементов?

Как организовать подгрузку элементов?

Есть лента которая реализована при помощи RecyclerView, заполняю её при помощи AsyncTask

755