"Cannot access database on the main thread since it may potentially lock the UI for a long period of time" but when i allow room to execute queries on main thread then it doesn't give error
// MyIntentService.java:
public class MyIntentService extends IntentService {
String URL = "http://192.168.1.102/android/Document%20Sharing/getServerData.php";
String course;
AppDatabase appDatabase;
public MyIntentService() { super("MyIntentService"); }
@Override
public void onCreate() {
Log.i("tagg","onCreate");
super.onCreate();
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
appDatabase = AppDatabase.getAppDatabase(this);
course = intent.getStringExtra("course");
getServerData();
Log.i("tagg","onHandleIntentBefore");
}
private void getServerData() {
Log.i("tagg","here");
final RequestQueue requestQueue = Volley.newRequestQueue(this);
final StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Gson gson = new Gson();
IT_Subjects[] itSubjects = gson.fromJson(response, IT_Subjects[].class);
appDatabase.itSubjectsDao().insertAll(itSubjects);
//Log.i("tagg", response);
Log.i("tagg","here");
requestQueue.stop();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(MyIntentService.this, error.toString(), Toast.LENGTH_LONG).show();
requestQueue.stop();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> prams = new HashMap<>();
prams.put("course", course);
return prams;
}
};
requestQueue.add(stringRequest);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
Log.i("tagg","onStartCommand");
return super.onStartCommand(intent,flags,startId);
}
@Override
public void onDestroy() {
Log.i("tagg","onDestroy");
AppDatabase.destroyInstance();
super.onDestroy();
}
}
//AppDatabase.java
@Database(entities = IT_Subjects.class, version = 1 )
public abstract class AppDatabase extends RoomDatabase {
public abstract IT_SubjectsDao itSubjectsDao();
private static AppDatabase INSTANCE;
public static AppDatabase getAppDatabase(Context context) {
if (INSTANCE == null) {
INSTANCE =
Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "IT_Students")
.build();
}
return INSTANCE;
}
public static void destroyInstance() {
INSTANCE = null;
}
}