There is a widget for Android. The essence of his work: JSON from the site and display some data. The widget has an activity through which, when the widget is installed, you can drive in user data and save it in Shared Preferences .

The code below allows you to call the Preferences value in the class of the Widget itself. But I need this value to be passed to the HTTPRequestThread2 class (we call it from the widget) that accesses the site JSON.

Here is the code for the widget itself.

 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 } } 

Activity Code for storing entered values ​​in 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)); } } 

The code of the class where the request to the URL is executed and where to get the saved value from the 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(); } } 
  • 3
    Well, what, through the constructor of this class, when creating an instance, is it not possible to pass on anything? and why do you need to read from preferences in a certain class, if in the widget, from where you call this class there is already a received value, why not pass it on? - pavlofff
  • @pavlofff, maybe easier. I even tried to repeat in the HTTPRequestThread2 class the string that calls the value to the CharSequence variable widgetText = NHwidgetConfigureActivity.loadTitlePref (context, appWidgetId); The problem is that I do not understand why this is not working. - Dmitry

0