Retrofit can't connect to hapi server localhost? - java

I'm building android apps using retrofit as my httprequest to connect to my hapi server. my server is working fine, I've test it on postman and my WebApps. But my retrofit can not connect to it. below is my code. For the sake of simplicity to read I delete lines that not necessary:
LoginActivity.java
package com.sianghee.reviu;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.ButterKnife;
import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import com.sianghee.reviu.interfaces.APIService;
import com.sianghee.reviu.lib.Session;
import com.sianghee.reviu.models.UserLogin;
import static com.sianghee.reviu.lib.Helper.returnError;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
public class LoginActivity extends Activity {
private static final String TAG = "LoginActivity";
private static final int REQUEST_SIGNUP = 0;
Session session;
public static final String BASE_URL = "localhost:3000";
private EditText emailText;
private EditText passwordText;
#BindView(R.id.btn_login) Button _loginButton;
#BindView(R.id.link_signup) TextView _signupLink;
// TODO: Init sewaktu pertama kali form diload
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
emailText = (EditText)findViewById(R.id.input_email);
passwordText = (EditText)findViewById(R.id.input_password);
}
// TODO: bind login and do login
#OnClick(R.id.btn_login)
public void submitLogin() {
login();
}
// TODO: bind signup and do register
....
public void login() {
Log.d(TAG, "Login");
if (!validate()) {
onLoginFailed();
return;
}
_loginButton.setEnabled(false);
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Authenticating...");
progressDialog.show();
String email = emailText.getText().toString();
String password = passwordText.getText().toString();
// TODO: Implement your own authentication logic here.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService api = retrofit.create(APIService.class);
UserLogin userLogin = new UserLogin(email, password);
Call<UserLogin> call = api.login(userLogin);
call.enqueue(new Callback<UserLogin>() {
#Override
public void onResponse(Call<UserLogin> call, Response<UserLogin> response) {
String result;
progressDialog.dismiss();
try {
result = response.body().toString();
if (returnError(result).isEmpty()) {
JSONObject obj;
obj = new JSONObject(result);
session.setLoginSession(obj.getString("scope"), obj.getString("token"));
Intent i = new Intent(LoginActivity.this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
.......
}
APIService.java
package com.sianghee.reviu.interfaces;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;
import com.sianghee.reviu.models.UserLogin;
/**
* Created by andy on 11/26/17.
*/
public interface APIService {
#POST("auth")
Call<UserLogin> login(#Body UserLogin auth);
}
UserLogin.java
package com.sianghee.reviu.models;
public class UserLogin {
String email;
String password;
public UserLogin(String email, String password) {
this.email = email;
this.password = password;
}
}
Whenever I clicked the login button, It's failed to connect to server. below is the logcat:
12-02 23:24:42.771 3660-3660/com.sianghee.reviu I/InstantRun: starting instant run server: is main process
12-02 23:24:43.116 3660-3690/com.sianghee.reviu D/OpenGLRenderer: HWUI GL Pipeline
12-02 23:24:43.213 3660-3660/com.sianghee.reviu I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
12-02 23:24:43.219 3660-3660/com.sianghee.reviu I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
[ 12-02 23:24:43.283 3660: 3690 D/ ]
HostConnection::get() New Host Connection established 0x896438c0, tid 3690
12-02 23:24:43.471 3660-3690/com.sianghee.reviu I/zygote: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
12-02 23:24:43.471 3660-3690/com.sianghee.reviu I/OpenGLRenderer: Initialized EGL, version 1.4
12-02 23:24:43.471 3660-3690/com.sianghee.reviu D/OpenGLRenderer: Swap behavior 1
12-02 23:24:43.471 3660-3690/com.sianghee.reviu W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
12-02 23:24:43.471 3660-3690/com.sianghee.reviu D/OpenGLRenderer: Swap behavior 0
12-02 23:24:43.473 3660-3690/com.sianghee.reviu D/EGL_emulation: eglCreateContext: 0x9b543860: maj 2 min 0 rcv 2
12-02 23:24:43.475 3660-3690/com.sianghee.reviu D/EGL_emulation: eglMakeCurrent: 0x9b543860: ver 2 0 (tinfo 0xa4a8f700)
12-02 23:24:43.527 3660-3690/com.sianghee.reviu D/EGL_emulation: eglMakeCurrent: 0x9b543860: ver 2 0 (tinfo 0xa4a8f700)
12-02 23:24:43.856 3660-3660/com.sianghee.reviu I/AssistStructure: Flattened final assist data: 1684 bytes, containing 1 windows, 5 views
12-02 23:24:49.113 3660-3673/com.sianghee.reviu I/zygote: Do partial code cache collection, code=30KB, data=26KB
12-02 23:24:49.113 3660-3673/com.sianghee.reviu I/zygote: After code cache collection, code=30KB, data=26KB
12-02 23:24:49.113 3660-3673/com.sianghee.reviu I/zygote: Increasing code cache capacity to 128KB
12-02 23:24:51.355 3660-3673/com.sianghee.reviu I/zygote: Do partial code cache collection, code=61KB, data=59KB
12-02 23:24:51.356 3660-3673/com.sianghee.reviu I/zygote: After code cache collection, code=61KB, data=59KB
12-02 23:24:51.356 3660-3673/com.sianghee.reviu I/zygote: Increasing code cache capacity to 256KB
12-02 23:24:54.016 3660-3673/com.sianghee.reviu I/zygote: Do full code cache collection, code=123KB, data=99KB
12-02 23:24:54.016 3660-3673/com.sianghee.reviu I/zygote: After code cache collection, code=107KB, data=66KB
12-02 23:24:56.503 3660-3660/com.sianghee.reviu D/LoginActivity: Login
12-02 23:24:56.573 3660-3673/com.sianghee.reviu I/zygote: Do partial code cache collection, code=114KB, data=93KB
12-02 23:24:56.573 3660-3673/com.sianghee.reviu I/zygote: After code cache collection, code=114KB, data=93KB
12-02 23:24:56.573 3660-3673/com.sianghee.reviu I/zygote: Increasing code cache capacity to 512KB
12-02 23:24:56.574 3660-3673/com.sianghee.reviu I/zygote: JIT allocated 56KB for compiled code of void android.view.View.<init>(android.content.Context, android.util.AttributeSet, int, int)
12-02 23:24:56.603 3660-3660/com.sianghee.reviu D/NetworkSecurityConfig: No Network Security Config specified, using platform default
12-02 23:24:56.803 3660-3660/com.sianghee.reviu W/error: java.net.ConnectException: Failed to connect to /127.0.0.1:3000
12-02 23:24:57.094 3660-3690/com.sianghee.reviu D/EGL_emulation: eglMakeCurrent: 0x9b543860: ver 2 0 (tinfo 0xa4a8f700)
12-02 23:24:57.126 3660-3690/com.sianghee.reviu D/EGL_emulation: eglMakeCurrent: 0x9b543860: ver 2 0 (tinfo 0xa4a8f700)
My server API Url for login is : http://127.0.0.1:3000/auth
notice that error from my Log.w() method before that say:
java.net.ConnectException: Failed to connect to /127.0.0.1:3000
Maybe this is just my common mistake, please help.

127.0.0.1 is your localhost / loopback address a of your Machine (on which server is hosted). 127.0.0.1 is mapped to the IP address of the machine, hence http://127.0.0.1:3000/auth is accessible from your machine only.
Now, in order to access http://127.0.0.1:3000/auth from any other machine (i.e. your phone in this case), your machine (server) and device (phone) should be on the same network (e.g same Wi-Fi) You need to access it via http://IPAddressOfYourMachine:3000/auth.
On MacOs / Linux you can find out the IP address using ifconfig command on a terminal. On a Windows machine the command is ipconfig. The IP address should be of the form of 192.168.x.y.
So the final BASE_URL should be something like http://192.168.x.y:3000

make sure that your phone(emulator) and your computer are in a same network
and use ip adress http://192.168.8.106:3030 for example, instead of http://localhost:3030

Retrofit hasn't any problem. The issue is in the BASE_URL for reaching from your android device to your server.
Please check your computer's local ip address that the server is installed in (ex: 192.168.1.103), then replace the BASE_URL with that such as following example
public static final String BASE_URL = "http://192.168.1.103:3000";

Related

W/System: Ignoring header X-Firebase-Locale because its value was null Android Firebase

I am facing this problem since 2 days and i didn't find any helpful solution, every time i signUp or SignIn using email, Password this what happen:
W/System: Ignoring header X-Firebase-Locale because its value was null.
response come after 4-5 minute.
I tried many emulators one of them worked fine and the other not,
emulators APIs:
33: didn't work
30: didn't work
28: Worked
26: didn't work
My Code:
package com.abdulghffar.gju_outgoings_app.fragments;
import static android.content.ContentValues.TAG;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.abdulghffar.gju_outgoings_app.R;
import com.abdulghffar.gju_outgoings_app.activites.MainActivity;
import com.abdulghffar.gju_outgoings_app.activites.authentication;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import javax.annotation.Nullable;
public class fragmentSignIn extends Fragment {
//Fields
TextView signUpTextView;
EditText emailField;
EditText passwordField;
//Buttons
Button signInButton;
//Firebase
private FirebaseAuth mAuth;
FirebaseFirestore db;
//Others
View view;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup parent, #Nullable Bundle savedInstanceState) {
// Defines the xml file for the fragment
view = inflater.inflate(R.layout.activity_fragment_sign_in, parent, false);
setup();
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Check email
if (emailField.getText().toString().matches("")) {
toast("Please enter your email");
return;
}
if ((!emailField.getText().toString().contains("#")) || (!emailField.getText().toString().contains(".com"))) {
toast("Invalid email format");
return;
}
//Check password
if (passwordField.getText().toString().matches("")) {
toast("Please enter your password");
return;
}
if(getActivity()!=null){
InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
signIn();
}
});
signUpTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
authentication registration = (authentication) getActivity();
fragmentSignUp fragmentSignUp = new fragmentSignUp();
assert registration != null;
registration.replaceFragment(fragmentSignUp);
}
});
return view;
}
// This event is triggered soon after onCreateView().
// Any view setup should occur here. E.g., view lookups and attaching view listeners.
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// Setup any handles to view objects here
// EditText etFoo = (EditText) view.findViewById(R.id.etFoo);
}
void setup() {
//Fields
signUpTextView = (TextView) view.findViewById(R.id.signUp);
emailField = (EditText) view.findViewById(R.id.emailField);
passwordField = (EditText) view.findViewById(R.id.passwordField);
//Buttons
signInButton = (Button) view.findViewById(R.id.signInButton);
//Firebase
mAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser != null) {
checkUserApproval(currentUser);
}
}
void signIn() {
String email = emailField.getText().toString();
String password = passwordField.getText().toString();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
checkUserApproval(user);
}
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithEmail:failure", task.getException());
}
}
});
}
void updateUI(int x) {
if (x == 0) {
Intent i = new Intent(getActivity(), MainActivity.class);
startActivity(i);
} else {
authentication authentication = (authentication) getActivity();
fragmentWaiting fragmentWaiting = new fragmentWaiting();
assert authentication != null;
authentication.replaceFragment(fragmentWaiting);
}
}
void toast(String message) {
Toast toast = Toast.makeText(view.getContext(), message, Toast.LENGTH_LONG);
toast.show();
}
private void checkUserApproval(FirebaseUser user) {
DocumentReference docRef = db.collection("Users").document(user.getUid());
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
if (document.get("approval").toString().matches("Not yet")) {
updateUI(1);
} else {
updateUI(0);
}
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
}
}
Run:
08/14 09:57:53: Launching 'app' on Pixel 5 API 26.
App restart successful without requiring a re-install.
$ adb shell am start -n "com.abdulghffar.gju_outgoings_app/com.abdulghffar.gju_outgoings_app.activites.authentication" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 10716 on device 'Pixel_5_API_26 [emulator-5554]'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/FirebaseApp: Device unlocked: initializing all Firebase APIs for app [DEFAULT]
I/FirebaseInitProvider: FirebaseApp initialization successful
W/zygote64: Skipping duplicate class check due to unrecognized classloader
I/DynamiteModule: Considering local module com.google.android.gms.measurement.dynamite:78 and remote module com.google.android.gms.measurement.dynamite:15
I/DynamiteModule: Selected local version of com.google.android.gms.measurement.dynamite
V/FA: onActivityCreated
V/FA: App measurement collection enabled
V/FA: App measurement enabled for app package, google app id: com.abdulghffar.gju_outgoings_app, 1:938336016999:android:1e16856c037883e29f12c2
I/FA: App measurement initialized, version: 68000
I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
I/FA: To enable faster debug mode event logging run:
adb shell setprop debug.firebase.analytics.app com.abdulghffar.gju_outgoings_app
D/FA: Debug-level message logging enabled
V/FA: Connecting to remote service
V/FA: Connection attempt already in progress
V/FA: Connection attempt already in progress
I/zygote64: Do partial code cache collection, code=29KB, data=26KB
I/zygote64: After code cache collection, code=27KB, data=25KB
I/zygote64: Increasing code cache capacity to 128KB
V/FA: Activity resumed, time: 4323080
I/FA: Tag Manager is not found and thus will not be used
D/OpenGLRenderer: HWUI GL Pipeline
V/FA: Connection attempt already in progress
V/FA: Connection attempt already in progress
D/: HostConnection::get() New Host Connection established 0x74aee132c0, tid 10768
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/OpenGLRenderer: Swap behavior 0
D/EGL_emulation: eglCreateContext: 0x74b99cb5a0: maj 3 min 0 rcv 3
D/EGL_emulation: eglMakeCurrent: 0x74b99cb5a0: ver 3 0 (tinfo 0x74b99ff900)
D/EGL_emulation: eglMakeCurrent: 0x74b99cb5a0: ver 3 0 (tinfo 0x74b99ff900)
D/FA: Connected to remote service
V/FA: Processing queued up service tasks: 5
I/zygote64: Do partial code cache collection, code=59KB, data=52KB
I/zygote64: After code cache collection, code=59KB, data=52KB
I/zygote64: Increasing code cache capacity to 256KB
V/FA: Inactivity, disconnecting from the service
W/View: dispatchProvideAutofillStructure(): not laid out, ignoring
I/AssistStructure: Flattened final assist data: 2264 bytes, containing 1 windows, 8 views
I/zygote64: Do full code cache collection, code=124KB, data=103KB
I/zygote64: After code cache collection, code=108KB, data=63KB
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
W/System: Ignoring header X-Firebase-Locale because its value was null.
W/System: Ignoring header X-Firebase-Locale because its value was null.
W/System: Ignoring header X-Firebase-Locale because its value was null.
W/System: Ignoring header X-Firebase-Locale because its value was null.
I/zygote64: Do partial code cache collection, code=123KB, data=83KB
I/zygote64: After code cache collection, code=123KB, data=83KB
I/zygote64: Increasing code cache capacity to 512KB
I/zygote64: Compiler allocated 6MB to compile void android.view.ViewRootImpl.performTraversals()
W/ContentValues: signInWithEmail:failure
com.google.firebase.FirebaseNetworkException: A network error (such as timeout, interrupted connection or unreachable host) has occurred.
at com.google.android.gms.internal.firebase-auth-api.zztu.zza(com.google.firebase:firebase-auth##21.0.6:17)
at com.google.android.gms.internal.firebase-auth-api.zzus.zza(com.google.firebase:firebase-auth##21.0.6:9)
at com.google.android.gms.internal.firebase-auth-api.zzut.zzl(com.google.firebase:firebase-auth##21.0.6:1)
at com.google.android.gms.internal.firebase-auth-api.zzuq.zzh(com.google.firebase:firebase-auth##21.0.6:25)
at com.google.android.gms.internal.firebase-auth-api.zzts.zzh(com.google.firebase:firebase-auth##21.0.6:1)
at com.google.android.gms.internal.firebase-auth-api.zzqh.zza(com.google.firebase:firebase-auth##21.0.6:2)
at com.google.android.gms.internal.firebase-auth-api.zzvb.zza(com.google.firebase:firebase-auth##21.0.6:16)
at com.google.android.gms.internal.firebase-auth-api.zzuh.zzs(com.google.firebase:firebase-auth##21.0.6:4)
at com.google.android.gms.internal.firebase-auth-api.zzrx.zzC(com.google.firebase:firebase-auth##21.0.6:5)
at com.google.android.gms.internal.firebase-auth-api.zztt.zzw(com.google.firebase:firebase-auth##21.0.6:8)
at com.google.android.gms.internal.firebase-auth-api.zztb.zzc(com.google.firebase:firebase-auth##21.0.6:1)
at com.google.android.gms.internal.firebase-auth-api.zzuu.run(com.google.firebase:firebase-auth##21.0.6:1)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
The problem only occurs when you use the emulator but on the actual device it's working and updating firebase authentication and realtime database as expected.
Update: Okay I still get this message, but everything is working again. I'm using a Ryzen CPU and installed the "android emulator hypervisor driver for amd processors". Together with the latest emulator patches, everything is working again.
I have the same problem and can only test an a real device since the emulator won't connect to Firebase after succesful Google Sign In.
Additionally I now upgraded my dependencies and the Anrdoird Target SDK.
Also the manifest containst the cleartext attribute.
Nonetheless this is currently not working.

My Music Player App is crashing again and again

Below i have pasted the code of MainActivity
package com.example.tunifi;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import java.io.File;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
ListView listView;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
Dexter.withContext(this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
//Toast.makeText(MainActivity.this, "Runtime permission given !", Toast.LENGTH_SHORT).show();
ArrayList<File> mySongs = fetchSongs(Environment.getExternalStorageDirectory());
String [] items = new String[mySongs.size()];
for (int i=0;i<mySongs.size();i++){
items[i] = mySongs.get(i).getName().replace(".mp3","");
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_expandable_list_item_1,items);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, PlaySong.class);
String currentSong = listView.getItemAtPosition(position).toString();
intent.putExtra("SongList",mySongs);
intent.putExtra("CurrentSong",currentSong);
intent.putExtra("Position",position);
startActivity(intent);
}
});
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
})
.check();
}
public ArrayList<File> fetchSongs(File file){
ArrayList arrayList = new ArrayList();
File [] songs = file.listFiles();
if (songs != null){
for (File myFile : songs){
if (!myFile.isHidden() && myFile.isDirectory()){
arrayList.addAll(fetchSongs(myFile));
}
else{
if (myFile.getName().endsWith(".mp3") && !myFile.getName().startsWith(".")){
arrayList.add(myFile);
}
}
}
}
return arrayList;
}
}
Below i have pasted the code of PlaySong
package com.example.tunifi;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.File;
import java.util.ArrayList;
public class PlaySong extends AppCompatActivity {
TextView textView;
ImageView previous, play, next;
ArrayList<File> songs;
MediaPlayer mediaPlayer;
String textContent;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_song);
textView = findViewById(R.id.textView);
previous = findViewById(R.id.previous);
play = findViewById(R.id.play);
next = findViewById(R.id.next);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
songs = (ArrayList) bundle.getParcelableArrayList("songs");
textContent = intent.getStringExtra("CurrentSong");
textView.setText(textContent);
position = intent.getIntExtra("Position",0);
Uri uri = Uri.parse(songs.get(position).toString());
mediaPlayer = MediaPlayer.create(this,uri);
mediaPlayer.start();
}
}
This is what my Logcat shows:
2021-08-13 13:05:25.898 23725-23725/? I/zygote: Not late-enabling -Xcheck:jni (already on)
2021-08-13 13:04:58.820 1538-23594/? I/AudioFlinger: AudioFlinger's thread 0xb1903c80 tid=23594 ready to run
2021-08-13 13:05:25.917 23725-23725/? W/zygote: Unexpected CPU variant for X86 using defaults: x86
2021-08-13 13:03:30.914 1697-2352/system_process W/ActivityManager: Slow operation: 566ms so far, now at getContentProviderImpl: done!
2021-08-13 13:05:25.898 23725-23725/? I/zygote: Not late-enabling -Xcheck:jni (already on)
2021-08-13 13:05:25.917 23725-23725/? W/zygote: Unexpected CPU variant for X86 using defaults: x86
2021-08-13 13:05:25.898 23725-23725/? I/zygote: Not late-enabling -Xcheck:jni (already on)
2021-08-13 13:05:25.917 23725-23725/? W/zygote: Unexpected CPU variant for X86 using defaults: x86
2021-08-13 13:05:26.244 23725-23749/com.example.tunifi D/OpenGLRenderer: HWUI GL Pipeline
2021-08-13 13:05:26.331 23725-23749/com.example.tunifi I/OpenGLRenderer: Initialized EGL, version 1.4
2021-08-13 13:05:26.332 23725-23749/com.example.tunifi D/OpenGLRenderer: Swap behavior 1
2021-08-13 13:05:26.334 23725-23749/com.example.tunifi W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
2021-08-13 13:05:26.334 23725-23749/com.example.tunifi D/OpenGLRenderer: Swap behavior 0
2021-08-13 13:05:26.382 23725-23749/com.example.tunifi D/EGL_emulation: eglCreateContext: 0xa0385120: maj 2 min 0 rcv 2
2021-08-13 13:05:26.405 23725-23749/com.example.tunifi D/EGL_emulation: eglMakeCurrent: 0xa0385120: ver 2 0 (tinfo 0xa0383280)
2021-08-13 13:05:26.544 23725-23749/com.example.tunifi D/EGL_emulation: eglMakeCurrent: 0xa0385120: ver 2 0 (tinfo 0xa0383280)
2021-08-13 13:05:28.347 23725-23725/com.example.tunifi D/AndroidRuntime: Shutting down VM
2021-08-13 13:05:28.351 23725-23725/com.example.tunifi E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.tunifi, PID: 23725
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tunifi/com.example.tunifi.PlaySong}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.ArrayList.get(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.ArrayList.get(int)' on a null object reference
at com.example.tunifi.PlaySong.onCreate(PlaySong.java:38)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Can someone please help me out in finding what is wrong and how to correct it, sice i am new to this android development world and i am really upset for this thing since i am trying from many days to correct it,but nothing is working. Thank You So Much in advance !
The trick is to read the stacktrace, it says :
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.ArrayList.get(int)' on a null object reference
So looks like songs is null when you try to get a value of that list, can you make sure that songs is initialized before calling the
Uri uri = Uri.parse(songs.get(position).toString());
Edit
Perhaps this is not the root cause of your bug but you are doing this
intent.putExtra("SongList",mySongs);
looks like you are sending your song list with this bundle name "SongList" but then you are trying to retrieve it with :
songs = (ArrayList) bundle.getParcelableArrayList("songs");
I guess it should be "SongList" instead of "songs"
change
songs = (ArrayList) bundle.getParcelableArrayList("songs");
to
songs = (ArrayList) bundle.getParcelableArrayList("SongList");
Uri uri = Uri.parse(songs.get(position).toString());
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.ArrayList.get(int)' on a null object reference
from this error,we can know the this arraylist is null,you should check it first

stuck in getting arraylist from another class in android

I’m making a project in which i get data through api and stored it in arraylist but when i return it, it is empty.
Can Anyone Help Me Out?
Here is the Main Activity
package com.example.trivia;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import com.example.trivia.Data.Async;
import com.example.trivia.Data.setQ;
import com.example.trivia.controller.AppController;
import com.example.trivia.model.question;
import org.json.JSONArray;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private CardView c;
private Button t_btn,f_btn;
private ImageButton next,prev;
private List<question>q;
private TextView set;
private int count=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
c=findViewById(R.id.cardView);
t_btn=findViewById(R.id.true_btn);
f_btn=findViewById(R.id.false_btn);
next=findViewById(R.id.next);
prev=findViewById(R.id.prev);
set=findViewById(R.id.setq);
//ArrayList<question> dummy = new ArrayList<question>();
//AppController.OnCreate();
q=new setQ().getData(new Async() {
#Override
public void finish(ArrayList<question> c) {
set.setText(c.get(count).getQ());
// Log.d("test", "onCreate: "+c);
}
});
Log.i("in main", "Main: "+q.size());
}
}
the code of setQ class
package com.example.trivia.Data;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.example.trivia.controller.AppController;
import com.example.trivia.model.question;
import org.json.JSONArray;
import org.json.JSONException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
public class setQ {
ArrayList<question> q =new ArrayList<question>();
JSONArray r;
private String url="https://raw.githubusercontent.com/curiousily/simple-quiz/master/script/statements-data.json";
public List<question> getData(final Async call) {
final JsonArrayRequest jarr = new JsonArrayRequest(Request.Method.GET, url, (JSONArray)null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
r=response;
for (int i = 0; i < response.length(); i++) {
try {
JSONArray a = response.getJSONArray(i);
question k = new question(a.getString(0), a.getBoolean(1));
//Log.i("list", "onResponse: "+k.getAns());
q.add(k);
// Log.i("response", "onResponse: " +a.get(0));
} catch (JSONException e) {
e.printStackTrace();
}
}
if(call!=null) {
call.finish( q);
}
//return q;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Log.i("error ",""+AppController.getInstance());
AppController.getInstance().addToRequestQueue(jarr);
return q;
// return q;
}
}
output
07/11 23:55:18: Launching 'app' on Pixel 3 API 21.
$ adb shell am start -n "com.example.trivia/com.example.trivia.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 15594 on device 'emulator-5554'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
I/error: com.example.trivia.controller.AppController#24777a64
***I/in main: Main: 0***
D/OpenGLRenderer: Render dirty regions requested: true
D/: HostConnection::get() New Host Connection established 0x7f28894105c0, tid 15594
D/Atlas: Validating map...
I/art: Background sticky concurrent mark sweep GC freed 5802(428KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 2MB/2MB, paused 8.789ms total 42.738ms
D/: HostConnection::get() New Host Connection established 0x7f28950b0e40, tid 15624
I/OpenGLRenderer: Initialized EGL, version 1.4
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/EGL_emulation: eglCreateContext: 0x7f2894773200: maj 3 min 1 rcv 4
D/EGL_emulation: eglMakeCurrent: 0x7f2894773200: ver 3 1 (tinfo 0x7f289470fe40)
E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da
E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008cdf
glUtilsParamSize: unknow param 0x00008824
D/OpenGLRenderer: Enabling debug mode 0
D/EGL_emulation: eglMakeCurrent: 0x7f2894773200: ver 3 1 (tinfo 0x7f289470fe40)
I/Choreographer: Skipped 62 frames! The application may be doing too much work on its main thread.
Implement the callback pattern.
Create a new Interface file:
Interface MyVolleyResponse {
void onResponse(JSONArray response);
void onError(VolleyError error);
}
Your activity should implement this, as follows:
public class MainActivity extends AppCompatActivity implements MyVolleyResponse {...}
Add the new methods to your activity:
void onResponse(JSONArray response) {
// process your response here, building your question array...
}
void onError(VolleyError error) {
// handle errors here...
}
Change your Volley responses within SetQ:
public void onResponse(JSONArray response) {
callback.onResponse(response);
}
public void onErrorResponse(VolleyError error) {
callback.onError(error);
}
Create a constructor within SetQ to set the callback:
private MyVolleyResponse callback;
SetQ(MyVolleyResponse callback) {
this.callback = callback;
}
Call this constructor in your activity with:
SetQ volley = new SetQ(this);
Change the signnature of getData to just:
void getData() {...}
And run the Volley call with volley.getData().
Remove all AsyncTask objects in your code, because Volley is already asynchronous.

Activity layout lagging behind until before next transition to another activity

The problem is that, during transition from firstActivity to thisServiceActivity, the screen will freeze and then turn black. If service has performed it process and send the broadcast and receive by the broadcast receiver of thisServiceActivity, then it will finally show the layout of the thisServiceActivity and quickly transition to ResultActivity.
Is it because there is something I do wrong in its UI thread? I try to find similar discussion to this problem but can't find it.
firstActivity class will start a new activity which is thisServiceActivity class. thisServiceActivity have a layout that show a progressbar and textview. At the same time, it will start a service class name as myForegroundService with pending intent notification.
If the process in the service completed, the service will send a local broadcast that will be pickup by thisServiceActivity using broadcast receiver and it then stop the service and transition to resultActivity and finish its activity.
public class firstActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first_activity);
}
//using button onclick
public void startActivity(View view) {
Intent startService = new Intent(this, thisServiceActivity.class);
startActivity(startService);
}
}
package example.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
public class thisServiceActivity extends AppCompatActivity {
Intent goToResult, stopMyService, startMyService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_this_service);
LocalBroadcastManager.getInstance(this).registerReceiver(myForegroundReceiver,
new IntentFilter("end-of-process"));
startService();
}
public void startService() {
startMyService = new Intent(this, myForegroundService.class);
ContextCompat.startForegroundService(this, startMyService);
}
public void stopService() {
stopMyService = new Intent(this, myForegroundService.class);
stopService(stopMyService);
}
#Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(myForegroundReceiver);
super.onDestroy();
}
private BroadcastReceiver myForegroundReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("onReceive", "Received");
stopService();
goToResult = new Intent(getApplication(), ResultActivity.class);
startActivity(goToResult);
finish();
}
};
}
package example.myapplication;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import java.util.concurrent.ExecutionException;
import static example.myapplication.App.CHANNEL_ID;
public class myForegroundService extends Service {
Boolean process;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("Service Running", "True");
Intent toThisServiceActivity = new Intent(this, thisServiceActivity.class);
PendingIntent servicePendingIntent = PendingIntent.getActivity(this, 0, toThisServiceActivity, 0);
Notification notify = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Sit back and relax, process is in progress")
.setContentText("You look more charming if you have patient, please wait")
.setContentIntent(servicePendingIntent)
.build();
startForeground(1, notify);
try {
process = new MyLoop().execute().get();
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
if (process) {
Intent killswitch = new Intent("end-of-process");
Log.i("Finish", "Service");
LocalBroadcastManager.getInstance(this).sendBroadcast(killswitch);
}
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private class MyLoop extends AsyncTask<Void, String, Boolean> {
#Override
protected Boolean doInBackground(Void... voids) {
for (int i = 0; i < 10; i++) {
publishProgress("i = " + i);
SystemClock.sleep(1000);
}
return true;
}
#Override
protected void onProgressUpdate(String... values) {
String value = values[0];
Log.i("Foreground Service", value);
}
}
}
Logcat output
02/25 17:41:41: Launching 'app' on Google.
$ adb shell am start -n "example.myapplication/example.myapplication.firstActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Waiting for process to come online...
Connected to process 5060 on device '-google-192.168.42.106:5555'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/Zygote: seccomp disabled by setenforce 0
I/e.myapplicatio: Late-enabling -Xcheck:jni
W/e.myapplicatio: Unexpected CPU variant for X86 using defaults: x86
D/libEGL: Emulator has host GPU support, qemu.gles is set to 1.
I/example.myapplication: type=1400 audit(0.0:1122): avc: denied { write } for comm=45474C20496E6974 name="property_service" dev="tmpfs" ino=9335 scontext=u:r:untrusted_app:s0:c96,c256,c512,c768 tcontext=u:object_r:property_socket:s0 tclass=sock_file permissive=1
type=1400 audit(0.0:1123): avc: denied { connectto } for comm=45474C20496E6974 path="/dev/socket/property_service" scontext=u:r:untrusted_app:s0:c96,c256,c512,c768 tcontext=u:r:init:s0 tclass=unix_stream_socket permissive=1
D/vndksupport: Loading /vendor/lib/egl/libGLES_emulation.so from current namespace instead of sphal namespace.
E/libEGL: load_driver(/vendor/lib/egl/libGLES_emulation.so): dlopen failed: library "/vendor/lib/egl/libGLES_emulation.so" not found
D/vndksupport: Loading /vendor/lib/egl/libEGL_emulation.so from current namespace instead of sphal namespace.
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/vndksupport: Loading /vendor/lib/egl/libGLESv1_CM_emulation.so from current namespace instead of sphal namespace.
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
D/vndksupport: Loading /vendor/lib/egl/libGLESv2_emulation.so from current namespace instead of sphal namespace.
D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
W/e.myapplicatio: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (light greylist, reflection)
W/e.myapplicatio: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist, reflection)
D/OpenGLRenderer: Skia GL Pipeline
D/: HostConnection::get() New Host Connection established 0xe7b6d5c0, tid 5087
I/RenderThread: type=1400 audit(0.0:1124): avc: denied { connectto } for path=006C6F63616C5F6F70656E676C scontext=u:r:untrusted_app:s0:c96,c256,c512,c768 tcontext=u:r:local_opengl:s0 tclass=unix_stream_socket permissive=1
W/: Unrecognized GLES max version string in extensions:
W/: Process pipe failed
I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
D/EGL_emulation: eglCreateContext: 0xe1fc8e20: maj 2 min 0 rcv 2
D/vndksupport: Loading /vendor/lib/hw/android.hardware.graphics.mapper#2.0-impl.so from current namespace instead of sphal namespace.
D/vndksupport: Loading /vendor/lib/hw/gralloc.vbox86.so from current namespace instead of sphal namespace.
E/EGL_emulation: tid 5087: eglSurfaceAttrib(1354): error 0x3009 (EGL_BAD_MATCH)
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xe1fc8d60, error=EGL_BAD_MATCH
I/Choreographer: Skipped 31 frames! The application may be doing too much work on its main thread.
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy#112c025
E/EGL_emulation: tid 5087: eglSurfaceAttrib(1354): error 0x3009 (EGL_BAD_MATCH)
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xe0846b60, error=EGL_BAD_MATCH
I/Service Running: True
I/Finish: Service
W/ViewRootImpl[thisServiceActivity]: Dropping event due to no window focus: KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_BACK, scanCode=0, metaState=0, flags=0x48, repeatCount=0, eventTime=7949110, downTime=7949110, deviceId=-1, source=0x101 }
W/ViewRootImpl[thisServiceActivity]: Cancelling event due to no window focus: KeyEvent { action=ACTION_UP, keyCode=KEYCODE_BACK, scanCode=0, metaState=0, flags=0x68, repeatCount=0, eventTime=7950511, downTime=7949110, deviceId=-1, source=0x101 }
I/Choreographer: Skipped 625 frames! The application may be doing too much work on its main thread.
I/chatty: uid=10096(example.myapplication) identical 7 lines
W/ViewRootImpl[thisServiceActivity]: Cancelling event due to no window focus: KeyEvent { action=ACTION_UP, keyCode=KEYCODE_BACK, scanCode=0, metaState=0, flags=0x68, repeatCount=0, eventTime=7950511, downTime=7949110, deviceId=-1, source=0x101 }
I/OpenGLRenderer: Davey! duration=10603ms; Flags=0, IntendedVsync=7941734767100, Vsync=7952151433350, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=7952160308707, AnimationStart=7952160414256, PerformTraversalsStart=7952161151710, DrawStart=7952165102838, SyncQueued=7952174190092, SyncStart=7952180127743, IssueDrawCommandsStart=7952180180543, SwapBuffers=7952293099225, FrameCompleted=7952343853615, DequeueBufferDuration=63000, QueueBufferDuration=161000,
I/Foreground Service: i = 0
i = 1
I/Foreground Service: i = 2
i = 3
I/OpenGLRenderer: Davey! duration=10618ms; Flags=0, IntendedVsync=7941734767100, Vsync=7952151433350, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=7952160308707, AnimationStart=7952160414256, PerformTraversalsStart=7952161151710, DrawStart=7952344526709, SyncQueued=7952345327938, SyncStart=7952355852722, IssueDrawCommandsStart=7952355900616, SwapBuffers=7952356170648, FrameCompleted=7952363877516, DequeueBufferDuration=148000, QueueBufferDuration=246000,
I/Foreground Service: i = 4
I/Foreground Service: i = 5
i = 6
i = 7
i = 8
I/Foreground Service: i = 9
I/onReceive: Received
Process 5060 terminated.
You're blocking the UI thread for 10 seconds by waiting for the result of your AsyncTask:
process = new MyLoop().execute().get();
The Javadoc for get() states:
Waits if necessary for the computation to complete, and then retrieves its result.
This is eliminating any advantage to running it on a background thread and causing your app to freeze. If you need to do something with the result, you should do it in AsyncTask.onPostExecute.

Recycler View updates when acticity resumed with Firebase Database android

I am trying to make a Blog App in android for my portfolio and I am having a problem. When I open the app the recycler view does not show anything but when I press the back button and open the app it updates the recycler view and this problem I am facing when running the app on real device I have tried running them in two emulators one is Nexus 5 and another Pixel 2 and they work fine and load the recycler view in first attempt only.
This is the activity's code:--
package raghuveer.singh.bhardwaj.blogapp;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import raghuveer.singh.bhardwaj.blogapp.Adapters.HomePostAdapter;
import raghuveer.singh.bhardwaj.blogapp.PostPackage.PostPOJO;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, HomePostAdapter.CustomItemClickListener {
public ArrayList<PostPOJO> mListOfPost = new ArrayList<>();
public ArrayList<String> topics = new ArrayList<>();
HomePostAdapter homePostAdapter;
private FirebaseAuth mAuth;
private Toolbar mToolbar;
private DrawerLayout mDrawer;
private NavigationView mNavView;
private RecyclerView mRecyclerView;
private ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
mProgressBar = (ProgressBar) findViewById(R.id.progressbar);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mNavView = (NavigationView) findViewById(R.id.nav_view);
mRecyclerView = (RecyclerView) findViewById(R.id.mRecyclerView);
setSupportActionBar(mToolbar);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this, mDrawer, mToolbar, R.string.open, R.string.close);
mDrawer.setDrawerListener(drawerToggle);
drawerToggle.syncState();
mNavView.setNavigationItemSelectedListener(this);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false);
homePostAdapter = new HomePostAdapter(mListOfPost, MainActivity.this, MainActivity.this);
mRecyclerView.setAdapter(homePostAdapter);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
}
#Override
protected void onStart() {
super.onStart();
Toast.makeText(this, "START", Toast.LENGTH_SHORT).show();
mListOfPost = new ArrayList<>();
topics = new ArrayList<>();
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference referenceTopic = database.getReference("Users").child(mAuth.getCurrentUser().getUid()).child("Topics");
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser != null) {
Toast.makeText(this, "Log inned with user " + currentUser.getEmail(), Toast.LENGTH_SHORT).show();
referenceTopic.orderByKey().addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dsp : dataSnapshot.getChildren()) {
topics.add(String.valueOf(dsp.getValue(String.class)));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
DatabaseReference referencePost = database.getReference("Posts");
referencePost.orderByKey().addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dsp : dataSnapshot.getChildren()) {
Log.d(MainActivity.class.getSimpleName(), dsp.child("topic").getValue().toString());
Iterator<String> iterator = topics.iterator();
while (iterator.hasNext()) {
String str = iterator.next();
if (dsp.child("topic").getValue().equals(str)) {
PostPOJO postPOJO = dsp.getValue(PostPOJO.class);
mListOfPost.add(postPOJO);
}
}
mProgressBar.setVisibility(View.INVISIBLE);
homePostAdapter.updateData(mListOfPost);
homePostAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
Intent intent = new Intent(this, SignUp.class);
startActivity(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void signOut() {
mAuth.signOut();
Intent intent = new Intent(this, SignUp.class);
startActivity(intent);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.sign_out:
signOut();
}
return true;
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.Profile:
Intent profileIntent = new Intent(this, Profile.class);
startActivity(profileIntent);
break;
case R.id.Topics:
Intent topicsIntent = new Intent(this, Topics.class);
startActivity(topicsIntent);
break;
}
return false;
}
public void startPostActivity(View view) {
Intent intent = new Intent(this, Post.class);
startActivity(intent);
}
#Override
public void onItemClick(int position) {
Intent intent = new Intent(this, Post.class);
Bundle bundle = new Bundle();
bundle.putSerializable("POJO", homePostAdapter.mListOfPost.get(position));
intent.putExtras(bundle);
startActivity(intent);
}
}
This is recycler view's code:--
package raghuveer.singh.bhardwaj.blogapp.Adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import raghuveer.singh.bhardwaj.blogapp.PostPackage.PostPOJO;
import raghuveer.singh.bhardwaj.blogapp.R;
/**
* Created by Lenovo on 03-12-2017.
*/
public class HomePostAdapter extends RecyclerView.Adapter<HomePostAdapter.viewHolder> {
public ArrayList<PostPOJO> mListOfPost;
private Context context;
CustomItemClickListener listener;
public interface CustomItemClickListener {
public void onItemClick(int position);
}
public HomePostAdapter(ArrayList<PostPOJO> mListOfPost, Context context,CustomItemClickListener customItemClickListener) {
this.mListOfPost = mListOfPost;
this.context = context;
this.listener = customItemClickListener;
}
#Override
public viewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_item,parent,false);
final viewHolder mViewHolder = new viewHolder(view);
return mViewHolder;
}
#Override
public void onBindViewHolder(viewHolder holder, int position) {
PostPOJO postPOJO = mListOfPost.get(position);
holder.titleTextView.setText(postPOJO.getTitle());
holder.subTitleTextView.setText(postPOJO.getSub_title());
Boolean wasImageSet=false;
Iterator<String> iterator = postPOJO.grouped_elements.iterator();
while (iterator.hasNext()){
String str = iterator.next();
if(str.startsWith("URL::")){
Picasso.with(context)
.load(str.substring(5))
.into(holder.headerImage);
wasImageSet = true;
break;
}
}
if(wasImageSet==false){
holder.headerImage.setImageDrawable(context.getResources().getDrawable(R.drawable.emptyimage));
}
holder.bind(position);
}
public void updateData(ArrayList<PostPOJO> postPOJOS){
this.mListOfPost = postPOJOS;
}
#Override
public int getItemCount() {
return mListOfPost.size();
}
public class viewHolder extends RecyclerView.ViewHolder{
private ImageView headerImage;
private TextView titleTextView;
private TextView subTitleTextView;
public viewHolder(final View itemView) {
super(itemView);
headerImage = (ImageView)itemView.findViewById(R.id.headerImage);
titleTextView = (TextView)itemView.findViewById(R.id.title);
subTitleTextView = (TextView)itemView.findViewById(R.id.sub_title);
}
public void bind(final int position){
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(position);
}
});
}
}
}
Log on emulator is:---
12-03 16:39:26.864 12822-12822/? I/zygote: Not late-enabling -Xcheck:jni (already on)
12-03 16:39:26.928 12822-12822/? W/zygote: Unexpected CPU variant for X86 using defaults: x86
12-03 16:39:27.113 12822-12822/raghuveer.singh.bhardwaj.blogapp W/zygote: Skipping duplicate class check due to unrecognized classloader
12-03 16:39:27.115 12822-12822/raghuveer.singh.bhardwaj.blogapp W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
12-03 16:39:27.119 12822-12822/raghuveer.singh.bhardwaj.blogapp W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
12-03 16:39:27.122 12822-12822/raghuveer.singh.bhardwaj.blogapp I/BiChannelGoogleApi: [FirebaseAuth: ] No Fallback module; NOT setting up for lazy initialization
12-03 16:39:27.170 12822-12843/raghuveer.singh.bhardwaj.blogapp W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
12-03 16:39:27.179 12822-12843/raghuveer.singh.bhardwaj.blogapp I/FirebaseAuth: [FirebaseAuth:] Loading module via FirebaseOptions.
12-03 16:39:27.179 12822-12843/raghuveer.singh.bhardwaj.blogapp I/FirebaseAuth: [FirebaseAuth:] Preparing to create service connection to gms implementation
12-03 16:39:27.207 12822-12822/raghuveer.singh.bhardwaj.blogapp D/FirebaseAuth: Notifying id token listeners about user ( sLZMm3S1o8TESyFjjy11mYEdVTG3 ).
12-03 16:39:27.245 12822-12822/raghuveer.singh.bhardwaj.blogapp D/FirebaseApp: com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
12-03 16:39:27.258 12822-12822/raghuveer.singh.bhardwaj.blogapp V/FA: Cancelling job. JobID: -2093232798
12-03 16:39:27.260 12822-12822/raghuveer.singh.bhardwaj.blogapp V/FA: Registered activity lifecycle callback
12-03 16:39:27.261 12822-12822/raghuveer.singh.bhardwaj.blogapp I/FirebaseInitProvider: FirebaseApp initialization successful
12-03 16:39:27.298 12822-12822/raghuveer.singh.bhardwaj.blogapp V/FA: onActivityCreated
12-03 16:39:27.329 12822-12846/raghuveer.singh.bhardwaj.blogapp V/FA: Collection enabled
12-03 16:39:27.330 12822-12846/raghuveer.singh.bhardwaj.blogapp V/FA: App package, google app id: raghuveer.singh.bhardwaj.blogapp, 1:967774314306:android:75a87ded59f6ecc8
12-03 16:39:27.346 12822-12846/raghuveer.singh.bhardwaj.blogapp I/FA: App measurement is starting up, version: 11717
12-03 16:39:27.346 12822-12846/raghuveer.singh.bhardwaj.blogapp I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
12-03 16:39:27.347 12822-12846/raghuveer.singh.bhardwaj.blogapp I/FA: To enable faster debug mode event logging run:
adb shell setprop debug.firebase.analytics.app raghuveer.singh.bhardwaj.blogapp
12-03 16:39:27.347 12822-12846/raghuveer.singh.bhardwaj.blogapp D/FA: Debug-level message logging enabled
12-03 16:39:27.400 12822-12846/raghuveer.singh.bhardwaj.blogapp V/FA: Connecting to remote service
12-03 16:39:27.493 12822-12846/raghuveer.singh.bhardwaj.blogapp V/FA: Connection attempt already in progress
12-03 16:39:27.525 12822-12822/raghuveer.singh.bhardwaj.blogapp I/DynamiteModule: Considering local module com.google.android.gms.firebase_database:4 and remote module com.google.android.gms.firebase_database:6
12-03 16:39:27.525 12822-12822/raghuveer.singh.bhardwaj.blogapp I/DynamiteModule: Selected remote version of com.google.android.gms.firebase_database, version >= 6
12-03 16:39:27.571 12822-12822/raghuveer.singh.bhardwaj.blogapp W/zygote: Skipping duplicate class check due to unrecognized classloader
12-03 16:39:27.639 12822-12846/raghuveer.singh.bhardwaj.blogapp V/FA: Connection attempt already in progress
12-03 16:39:27.640 12822-12846/raghuveer.singh.bhardwaj.blogapp V/FA: Activity resumed, time: 17890383
12-03 16:39:27.662 12822-12846/raghuveer.singh.bhardwaj.blogapp I/FA: Tag Manager is not found and thus will not be used
12-03 16:39:27.665 12822-12846/raghuveer.singh.bhardwaj.blogapp D/FA: Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=-3708820839437256875}]
12-03 16:39:27.669 12822-12850/raghuveer.singh.bhardwaj.blogapp D/OpenGLRenderer: HWUI GL Pipeline
12-03 16:39:27.674 12822-12849/raghuveer.singh.bhardwaj.blogapp D/NetworkSecurityConfig: No Network Security Config specified, using platform default
12-03 16:39:27.687 12822-12822/raghuveer.singh.bhardwaj.blogapp D/FirebaseApp: Notifying auth state listeners.
12-03 16:39:27.689 12822-12822/raghuveer.singh.bhardwaj.blogapp D/FirebaseApp: Notified 1 auth state listeners.
12-03 16:39:27.757 12822-12850/raghuveer.singh.bhardwaj.blogapp I/OpenGLRenderer: Initialized EGL, version 1.4
12-03 16:39:27.757 12822-12850/raghuveer.singh.bhardwaj.blogapp D/OpenGLRenderer: Swap behavior 1
12-03 16:39:27.757 12822-12850/raghuveer.singh.bhardwaj.blogapp W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
12-03 16:39:27.757 12822-12850/raghuveer.singh.bhardwaj.blogapp D/OpenGLRenderer: Swap behavior 0
12-03 16:39:27.758 12822-12846/raghuveer.singh.bhardwaj.blogapp V/FA: Connection attempt already in progress
12-03 16:39:27.780 12822-12850/raghuveer.singh.bhardwaj.blogapp D/EGL_emulation: eglCreateContext: 0xa6f84540: maj 3 min 0 rcv 3
12-03 16:39:27.797 12822-12850/raghuveer.singh.bhardwaj.blogapp D/EGL_emulation: eglMakeCurrent: 0xa6f84540: ver 3 0 (tinfo 0xa6f833e0)
12-03 16:39:27.799 12822-12850/raghuveer.singh.bhardwaj.blogapp E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008cdf
12-03 16:39:27.799 12822-12850/raghuveer.singh.bhardwaj.blogapp E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008cdf
12-03 16:39:27.799 12822-12850/raghuveer.singh.bhardwaj.blogapp E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008824
12-03 16:39:27.799 12822-12850/raghuveer.singh.bhardwaj.blogapp E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008824
12-03 16:39:28.009 12822-12850/raghuveer.singh.bhardwaj.blogapp D/EGL_emulation: eglMakeCurrent: 0xa6f84540: ver 3 0 (tinfo 0xa6f833e0)
12-03 16:39:28.093 12822-12850/raghuveer.singh.bhardwaj.blogapp D/EGL_emulation: eglMakeCurrent: 0xa6f84540: ver 3 0 (tinfo 0xa6f833e0)
12-03 16:39:28.138 12822-12850/raghuveer.singh.bhardwaj.blogapp D/EGL_emulation: eglMakeCurrent: 0xa6f84540: ver 3 0 (tinfo 0xa6f833e0)
12-03 16:39:28.177 12822-12846/raghuveer.singh.bhardwaj.blogapp D/FA: Connected to remote service
12-03 16:39:28.178 12822-12846/raghuveer.singh.bhardwaj.blogapp V/FA: Processing queued up service tasks: 4
12-03 16:39:29.645 12822-12832/raghuveer.singh.bhardwaj.blogapp I/zygote: Do partial code cache collection, code=30KB, data=30KB
12-03 16:39:29.645 12822-12832/raghuveer.singh.bhardwaj.blogapp I/zygote: After code cache collection, code=29KB, data=30KB
12-03 16:39:29.645 12822-12832/raghuveer.singh.bhardwaj.blogapp I/zygote: Increasing code cache capacity to 128KB
12-03 16:39:29.669 12822-12850/raghuveer.singh.bhardwaj.blogapp D/EGL_emulation: eglMakeCurrent: 0xa6f84540: ver 3 0 (tinfo 0xa6f833e0)
12-03 16:39:30.871 12822-12822/raghuveer.singh.bhardwaj.blogapp D/MainActivity: Cooking
12-03 16:39:30.883 12822-12822/raghuveer.singh.bhardwaj.blogapp D/MainActivity: Programming
12-03 16:39:30.944 12822-12822/raghuveer.singh.bhardwaj.blogapp W/Settings: Setting airplane_mode_on has moved from android.provider.Settings.System to android.provider.Settings.Global, returning read-only value.
12-03 16:39:31.061 12822-12832/raghuveer.singh.bhardwaj.blogapp I/zygote: Do partial code cache collection, code=34KB, data=54KB
12-03 16:39:31.063 12822-12832/raghuveer.singh.bhardwaj.blogapp I/zygote: After code cache collection, code=34KB, data=54KB
12-03 16:39:31.063 12822-12832/raghuveer.singh.bhardwaj.blogapp I/zygote: Increasing code cache capacity to 256KB
12-03 16:39:31.063 12822-12832/raghuveer.singh.bhardwaj.blogapp I/zygote: JIT allocated 71KB for compiled code of void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int)
12-03 16:39:31.063 12822-12832/raghuveer.singh.bhardwaj.blogapp I/zygote: Compiler allocated 4MB to compile void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int)
12-03 16:39:33.629 12822-12846/raghuveer.singh.bhardwaj.blogapp V/FA: Inactivity, disconnecting from the service
Log on real mobile is:--
12-03 16:41:11.099 2211-2211/? I/art: Late-enabling -Xcheck:jni
12-03 16:41:11.199 2211-2211/raghuveer.singh.bhardwaj.blogapp W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
12-03 16:41:11.203 2211-2211/raghuveer.singh.bhardwaj.blogapp W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
12-03 16:41:11.212 2211-2211/raghuveer.singh.bhardwaj.blogapp I/BiChannelGoogleApi: [FirebaseAuth: ] No Fallback module; NOT setting up for lazy initialization
12-03 16:41:11.222 2211-2211/raghuveer.singh.bhardwaj.blogapp D/FirebaseAuth: Notifying id token listeners about user ( sLZMm3S1o8TESyFjjy11mYEdVTG3 ).
12-03 16:41:11.223 2211-2232/raghuveer.singh.bhardwaj.blogapp W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
12-03 16:41:11.232 2211-2211/raghuveer.singh.bhardwaj.blogapp D/FirebaseApp: com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
12-03 16:41:11.242 2211-2232/raghuveer.singh.bhardwaj.blogapp I/FirebaseAuth: [FirebaseAuth:] Loading module via FirebaseOptions.
12-03 16:41:11.242 2211-2232/raghuveer.singh.bhardwaj.blogapp I/FirebaseAuth: [FirebaseAuth:] Preparing to create service connection to gms implementation
12-03 16:41:11.260 2211-2211/raghuveer.singh.bhardwaj.blogapp V/FA: Registered activity lifecycle callback
12-03 16:41:11.261 2211-2211/raghuveer.singh.bhardwaj.blogapp I/FirebaseInitProvider: FirebaseApp initialization successful
12-03 16:41:11.283 2211-2235/raghuveer.singh.bhardwaj.blogapp V/FA: Collection enabled
12-03 16:41:11.284 2211-2235/raghuveer.singh.bhardwaj.blogapp V/FA: App package, google app id: raghuveer.singh.bhardwaj.blogapp, 1:967774314306:android:75a87ded59f6ecc8
12-03 16:41:11.285 2211-2235/raghuveer.singh.bhardwaj.blogapp I/FA: App measurement is starting up, version: 11717
12-03 16:41:11.286 2211-2235/raghuveer.singh.bhardwaj.blogapp I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
12-03 16:41:11.286 2211-2235/raghuveer.singh.bhardwaj.blogapp I/FA: To enable faster debug mode event logging run:
adb shell setprop debug.firebase.analytics.app raghuveer.singh.bhardwaj.blogapp
12-03 16:41:11.286 2211-2235/raghuveer.singh.bhardwaj.blogapp D/FA: Debug-level message logging enabled
12-03 16:41:11.299 2211-2211/raghuveer.singh.bhardwaj.blogapp W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
12-03 16:41:11.302 2211-2235/raghuveer.singh.bhardwaj.blogapp V/FA: Connecting to remote service
12-03 16:41:11.309 2211-2211/raghuveer.singh.bhardwaj.blogapp V/FA: onActivityCreated
12-03 16:41:11.309 2211-2235/raghuveer.singh.bhardwaj.blogapp V/FA: Connection attempt already in progress
12-03 16:41:11.462 2211-2211/raghuveer.singh.bhardwaj.blogapp I/DynamiteModule: Considering local module com.google.android.gms.firebase_database:4 and remote module com.google.android.gms.firebase_database:6
12-03 16:41:11.462 2211-2211/raghuveer.singh.bhardwaj.blogapp I/DynamiteModule: Selected remote version of com.google.android.gms.firebase_database, version >= 6
12-03 16:41:11.476 2211-2211/raghuveer.singh.bhardwaj.blogapp W/ResourcesManager: Asset path '/system/framework/com.android.media.remotedisplay.jar' does not exist or contains no resources.
12-03 16:41:11.476 2211-2211/raghuveer.singh.bhardwaj.blogapp W/ResourcesManager: Asset path '/system/framework/com.android.location.provider.jar' does not exist or contains no resources.
12-03 16:41:11.526 2211-2235/raghuveer.singh.bhardwaj.blogapp V/FA: Connection attempt already in progress
12-03 16:41:11.526 2211-2235/raghuveer.singh.bhardwaj.blogapp V/FA: Activity resumed, time: 11707769
12-03 16:41:11.535 2211-2235/raghuveer.singh.bhardwaj.blogapp I/FA: Tag Manager is not found and thus will not be used
12-03 16:41:11.543 2211-2211/raghuveer.singh.bhardwaj.blogapp I/ViewRootImpl: CPU Rendering VSync enable = true
12-03 16:41:11.543 2211-2235/raghuveer.singh.bhardwaj.blogapp D/FA: Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=-7835563879800379359}]
12-03 16:41:11.546 2211-2241/raghuveer.singh.bhardwaj.blogapp D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
12-03 16:41:11.565 2211-2211/raghuveer.singh.bhardwaj.blogapp D/Atlas: Validating map...
12-03 16:41:11.574 2211-2211/raghuveer.singh.bhardwaj.blogapp D/FirebaseApp: Notifying auth state listeners.
12-03 16:41:11.574 2211-2211/raghuveer.singh.bhardwaj.blogapp D/FirebaseApp: Notified 1 auth state listeners.
12-03 16:41:11.577 2211-2211/raghuveer.singh.bhardwaj.blogapp I/ViewRootImpl: CPU Rendering VSync enable = true
12-03 16:41:11.633 2211-2235/raghuveer.singh.bhardwaj.blogapp V/FA: Connection attempt already in progress
12-03 16:41:11.638 2211-2241/raghuveer.singh.bhardwaj.blogapp I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: EGL 1.4 QUALCOMM build: Nondeterministic_AU_msm8909_LA.BR.1.2.5_RB2__release_AU (I9d3821c5ab)
OpenGL ES Shader Compiler Version: E031.25.03.04
Build Date: 02/24/16 Wed
Local Branch: mybranch18408715
Remote Branch: quic/LA.BR.1.2.5_rb2.32
Local Patches: NONE
Reconstruct Branch: NOTHING
12-03 16:41:11.639 2211-2241/raghuveer.singh.bhardwaj.blogapp I/OpenGLRenderer: Initialized EGL, version 1.4
12-03 16:41:11.652 2211-2241/raghuveer.singh.bhardwaj.blogapp D/OpenGLRenderer: Enabling debug mode 0
12-03 16:41:11.945 2211-2235/raghuveer.singh.bhardwaj.blogapp D/FA: Connected to remote service
12-03 16:41:11.945 2211-2235/raghuveer.singh.bhardwaj.blogapp V/FA: Processing queued up service tasks: 4
12-03 16:41:13.556 2211-2211/raghuveer.singh.bhardwaj.blogapp I/ViewRootImpl: CPU Rendering VSync enable = true
12-03 16:41:13.633 2211-2241/raghuveer.singh.bhardwaj.blogapp V/RenderScript: Application requested CPU execution
12-03 16:41:13.640 2211-2241/raghuveer.singh.bhardwaj.blogapp V/RenderScript: 0xb7a6a9d8 Launching thread(s), CPUs 4
12-03 16:41:14.419 2211-2211/raghuveer.singh.bhardwaj.blogapp D/MainActivity: Cooking
12-03 16:41:14.421 2211-2211/raghuveer.singh.bhardwaj.blogapp D/MainActivity: Programming
12-03 16:41:14.433 2211-2211/raghuveer.singh.bhardwaj.blogapp I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#f2c1b9f time:11295907
12-03 16:41:17.363 2211-2235/raghuveer.singh.bhardwaj.blogapp V/FA: Inactivity, disconnecting from the service
Try removing onStart method and copy the entire code to onCreate method.
OnStart is called several time during a lifecycle but onCreate is created once. So, you would want to put those firebase code in onCreate.
Its working on back button pressed and reopening the app because that's when onStart is called again.
I solved the problem through two steps:-
1)I moved the code of updating the recyclerview in oncreate.
2)I perfromed the post query i have completed populating the topic array list by pasting the post query and recycler view updation code after the for loop of data snapshot in ondatachange of topic query.
Yeah its bit confusing to explain.

Categories