Problem in Context and Sharedpreferences on android with service

Asked

Viewed 108 times

4

I’m trying to create a service on android, it is ready however in running the application to. If I comment on the variables ctx and prefs, it works but I need them, can you tell me if there is something wrong that I haven’t seen ? I have been for a long time and honestly do not find the problem. Follow below the code

Note: Everything is already in the manifest.

import java.sql.Timestamp;

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

import br.newm.alvomobile.database.EtapaPersistencia;
import br.newm.alvomobile.database.OSPersistencia;
import br.newm.alvomobile.webservice.OSWebService;
import br.newm.biblioteca.utils.AndroidUtils;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.util.Log;
public class DownloadManager extends Service implements Runnable{
   private Context ctx = getApplicationContext();
   private SharedPreferences prefs;
   private int id_usuario;
   private OSWebService oswebservice;
   private OSPersistencia ospersistencia;
   private String TAG = "DOWNLOAD-SERVICE";
}
  • Try to get the context in some Service method, such as onBind.

1 answer

4


Removes only the variable ctx and uses the getApplicationContext() of the Service class where necessary. Ex.:

public void test(){
     TextView textView = new TextView(getApplicationContext());
}
  • and as for Sharedpreferences ?

  • Compiling code with prefs attribute (variable) that will not give error.

  • Thanks man, it worked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.