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.
Related
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.
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.
I am using text to speech engine in my App. It works fine on emulator Nexus 6 with API 23 and higher. But on emulator Nexus 6 with API 22 it does not speak.
Both emulators use Pico TTS as preferred engine.
My activity layout contains only one button "Speak".
This is my activity code:
public class MainActivity extends AppCompatActivity {
private TextToSpeech mTTS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button speakBtn = findViewById(R.id.button);
speakBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speak();
}
});
mTTS = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = mTTS.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language not supported");
}
mTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
Log.d("TTS", "onStart called, utteranceId = " + utteranceId);
}
#Override
public void onDone(String utteranceId) {
Log.d("TTS", "onDone called, utteranceId = " + utteranceId);
}
#Override
public void onError(String utteranceId) {
Log.d("TTS", "onError called, utteranceId = " + utteranceId);
}
});
} else {
Log.e("TTS", "Initialization failed");
}
}
});
}
private void speak() {
Log.d("TTS", "speak() method called");
HashMap<String, String> map = new HashMap<>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "greeting");
mTTS.speak("hello", TextToSpeech.QUEUE_FLUSH, map);
}
}
This is all logs from emulator Nexus 6 API 22:
02-18 13:54:09.942 9739-9739/? E/libprocessgroup: failed to make and chown /acct/uid_10059: Read-only file system
02-18 13:54:09.943 9739-9739/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
02-18 13:54:09.943 9739-9739/? I/art: Not late-enabling -Xcheck:jni (already on)
02-18 13:54:09.961 9739-9748/? E/art: Failed sending reply to debugger: Broken pipe
02-18 13:54:09.961 9739-9748/? I/art: Debugger is no longer active
02-18 13:54:09.992 9739-9739/? 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
02-18 13:54:10.001 9739-9739/? I/art: Rejecting re-init on previously-failed class java.lang.Class
02-18 13:54:10.001 9739-9739/? I/art: Rejecting re-init on previously-failed class java.lang.Class
02-18 13:54:10.064 9739-9739/? I/TextToSpeech: Sucessfully bound to com.svox.pico
02-18 13:54:10.072 9739-9757/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
02-18 13:54:10.074 9739-9739/? D/Atlas: Validating map...
02-18 13:54:10.093 9739-9739/? I/TextToSpeech: Connected to ComponentInfo{com.svox.pico/com.svox.pico.PicoService}
02-18 13:54:10.096 9739-9758/? I/TextToSpeech: Set up connection to ComponentInfo{com.svox.pico/com.svox.pico.PicoService}
02-18 13:54:10.111 9739-9757/? I/OpenGLRenderer: Initialized EGL, version 1.4
02-18 13:54:10.111 9739-9757/? W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
02-18 13:54:10.128 9739-9757/? D/EGL_emulation: eglCreateContext: 0xae434e20: maj 2 min 0 rcv 2
02-18 13:54:10.131 9739-9757/? D/EGL_emulation: eglMakeCurrent: 0xae434e20: ver 2 0
02-18 13:54:10.134 9739-9757/? D/OpenGLRenderer: Enabling debug mode 0
02-18 13:54:10.174 9739-9757/? D/EGL_emulation: eglMakeCurrent: 0xae434e20: ver 2 0
02-19 09:32:25.570 9739-9739/com.example.ttsapp D/TTS: speak() method called
Figured out how to solve the problem. Everything works if launch the emulator not via Debugging or Execution but from AVD Manager after starting Android Studio.
No setter/field for mblogBegginer found on class class com.mahmoudradwan.e_news.Blog I defined setters in Blog class already But it gives me error Setters and getters generated by android studio
Tried all answers found in the forum
Any one can Help me ??
It's My second post because i didn't get any helpful response
My blog object class
package com.mahmoudradwan.e_news;
/**
* Created by Mahmoud Radwan on 16/08/2018.
*/
public class Blog {
private static String mtitle;
private static String mblogBegginer;
private String mblogIntermediate;
private String mblogAdvanced;
private static String mImageurl;
private String mAudioBegginersurl;
private String mAudioIntermediateurl;
private String mAudioAdvancedurl;
public Blog() {
}
public static String getMtitle() {
return mtitle;
}
public static void setMtitle(String mtitle) {
Blog.mtitle = mtitle;
}
public static String getMblogBegginer() {
return mblogBegginer;
}
public static void setMblogBegginer(String mblogBegginer) {
Blog.mblogBegginer = mblogBegginer;
}
public String getMblogIntermediate() {
return mblogIntermediate;
}
public void setMblogIntermediate(String mblogIntermediate) {
this.mblogIntermediate = mblogIntermediate;
}
public String getMblogAdvanced() {
return mblogAdvanced;
}
public void setMblogAdvanced(String mblogAdvanced) {
this.mblogAdvanced = mblogAdvanced;
}
public static String getmImageurl() {
return mImageurl;
}
public static void setmImageurl(String mImageurl) {
Blog.mImageurl = mImageurl;
}
public String getmAudioBegginersurl() {
return mAudioBegginersurl;
}
public void setmAudioBegginersurl(String mAudioBegginersurl) {
this.mAudioBegginersurl = mAudioBegginersurl;
}
public String getmAudioIntermediateurl() {
return mAudioIntermediateurl;
}
public void setmAudioIntermediateurl(String mAudioIntermediateurl) {
this.mAudioIntermediateurl = mAudioIntermediateurl;
}
public String getmAudioAdvancedurl() {
return mAudioAdvancedurl;
}
public void setmAudioAdvancedurl(String mAudioAdvancedurl) {
this.mAudioAdvancedurl = mAudioAdvancedurl;
}
Blog(String mtitle, String mblogBegginer, String mblogIntermediate, String mblogAdvanced,
String mImageurl, String mAudioBegginersurl, String mAudioIntermediateurl, String mAudioAdvancedurl) {
this.mtitle = mtitle;
this.mblogBegginer = mblogBegginer;
this.mblogIntermediate = mblogIntermediate;
this.mblogAdvanced = mblogAdvanced;
this.mImageurl = mImageurl;
this.mAudioBegginersurl = mAudioBegginersurl;
this.mAudioIntermediateurl = mAudioIntermediateurl;
this.mAudioAdvancedurl = mAudioAdvancedurl;
}
}
Articles explore class
package com.mahmoudradwan.e_news;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.ListView;
import com.google.firebase.database.ChildEventListener;
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 java.util.ArrayList;
import java.util.List;
public class ArticlesExplore extends AppCompatActivity {
FirebaseDatabase firebaseDatabase ;
DatabaseReference blogReference ;
ValueEventListener valueEventListener ;
ListView listView ;
RecyclerViewAdapter adapter ;
List<Blog> articles = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_articles_explore);
adapter = new RecyclerViewAdapter(this, R.layout.article_row, articles);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
firebaseDatabase = FirebaseDatabase.getInstance();
blogReference = firebaseDatabase.getReference().child("Article");
blogReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Blog blog = dataSnapshot.getValue(Blog.class);
adapter.add(blog);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Log
08-20 15:08:06.597 5140-5140/? W/zygote: Unexpected CPU variant for X86 using defaults: x86
08-20 15:08:07.483 5140-5140/com.mahmoudradwan.e_news V/FA: Registered activity lifecycle callback
08-20 15:08:07.519 5140-5140/com.mahmoudradwan.e_news D/FirebaseApp: com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
08-20 15:08:07.520 5140-5140/com.mahmoudradwan.e_news I/FirebaseInitProvider: FirebaseApp initialization successful
08-20 15:08:07.521 5140-5140/com.mahmoudradwan.e_news I/InstantRun: starting instant run server: is main process
08-20 15:08:07.598 5140-5162/com.mahmoudradwan.e_news V/FA: Collection enabled
08-20 15:08:07.598 5140-5162/com.mahmoudradwan.e_news V/FA: App package, google app id: com.mahmoudradwan.e_news, 1:765020936650:android:fd8001655cf26b78
08-20 15:08:07.599 5140-5162/com.mahmoudradwan.e_news I/FA: App measurement is starting up, version: 12780
08-20 15:08:07.599 5140-5162/com.mahmoudradwan.e_news I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
08-20 15:08:07.600 5140-5162/com.mahmoudradwan.e_news I/FA: To enable faster debug mode event logging run:
adb shell setprop debug.firebase.analytics.app com.mahmoudradwan.e_news
08-20 15:08:07.600 5140-5162/com.mahmoudradwan.e_news D/FA: Debug-level message logging enabled
08-20 15:08:07.686 5140-5162/com.mahmoudradwan.e_news I/zygote: IncrementDisableThreadFlip blocked for 5.170ms
08-20 15:08:07.701 5140-5140/com.mahmoudradwan.e_news V/FA: onActivityCreated
08-20 15:08:07.766 5140-5162/com.mahmoudradwan.e_news V/FA: Connecting to remote service
08-20 15:08:07.841 5140-5162/com.mahmoudradwan.e_news V/FA: Connection attempt already in progress
08-20 15:08:08.075 5140-5162/com.mahmoudradwan.e_news I/FA: Tag Manager is not found and thus will not be used
08-20 15:08:08.088 5140-5162/com.mahmoudradwan.e_news D/FA: Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=3366437205721944027}]
08-20 15:08:08.095 5140-5167/com.mahmoudradwan.e_news D/OpenGLRenderer: HWUI GL Pipeline
08-20 15:08:08.158 5140-5162/com.mahmoudradwan.e_news V/FA: Connection attempt already in progress
08-20 15:08:08.158 5140-5162/com.mahmoudradwan.e_news V/FA: Connection attempt already in progress
08-20 15:08:08.163 5140-5162/com.mahmoudradwan.e_news V/FA: Activity resumed, time: 5862461
08-20 15:08:08.226 5140-5167/com.mahmoudradwan.e_news I/zygote: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
08-20 15:08:08.227 5140-5167/com.mahmoudradwan.e_news I/OpenGLRenderer: Initialized EGL, version 1.4
08-20 15:08:08.227 5140-5167/com.mahmoudradwan.e_news D/OpenGLRenderer: Swap behavior 1
08-20 15:08:08.230 5140-5167/com.mahmoudradwan.e_news W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
08-20 15:08:08.230 5140-5167/com.mahmoudradwan.e_news D/OpenGLRenderer: Swap behavior 0
08-20 15:08:08.250 5140-5167/com.mahmoudradwan.e_news D/EGL_emulation: eglCreateContext: 0xf19aff60: maj 2 min 0 rcv 2
08-20 15:08:08.284 5140-5167/com.mahmoudradwan.e_news D/EGL_emulation: eglMakeCurrent: 0xf19aff60: ver 2 0 (tinfo 0xf199b8a0)
08-20 15:08:08.445 5140-5167/com.mahmoudradwan.e_news D/EGL_emulation: eglMakeCurrent: 0xf19aff60: ver 2 0 (tinfo 0xf199b8a0)
08-20 15:08:08.640 5140-5162/com.mahmoudradwan.e_news D/FA: Connected to remote service
08-20 15:08:08.643 5140-5162/com.mahmoudradwan.e_news V/FA: Processing queued up service tasks: 4
08-20 15:08:14.009 5140-5162/com.mahmoudradwan.e_news V/FA: Inactivity, disconnecting from the service
08-20 15:08:27.008 5140-5162/com.mahmoudradwan.e_news V/FA: Recording user engagement, ms: 18944
08-20 15:08:27.011 5140-5162/com.mahmoudradwan.e_news V/FA: Connecting to remote service
08-20 15:08:27.019 5140-5162/com.mahmoudradwan.e_news V/FA: Activity paused, time: 5881404
08-20 15:08:27.027 5140-5162/com.mahmoudradwan.e_news D/FA: Logging event (FE): user_engagement(_e), Bundle[{firebase_event_origin(_o)=auto, engagement_time_msec(_et)=18944, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=3366437205721944027}]
08-20 15:08:27.048 5140-5140/com.mahmoudradwan.e_news V/FA: onActivityCreated
08-20 15:08:27.175 5140-5162/com.mahmoudradwan.e_news V/FA: Connection attempt already in progress
08-20 15:08:27.187 5140-5162/com.mahmoudradwan.e_news D/FA: Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_previous_class(_pc)=MainActivity, firebase_previous_id(_pi)=3366437205721944027, firebase_screen_class(_sc)=ArticlesExplore, firebase_screen_id(_si)=3366437205721944028}]
08-20 15:08:27.201 5140-5176/com.mahmoudradwan.e_news W/zygote: Unsupported class loader
08-20 15:08:27.224 5140-5176/com.mahmoudradwan.e_news W/zygote: Skipping duplicate class check due to unsupported classloader
08-20 15:08:27.236 5140-5176/com.mahmoudradwan.e_news I/DynamiteModule: Considering local module com.google.android.gms.firebase_database:4 and remote module com.google.android.gms.firebase_database:6
08-20 15:08:27.236 5140-5176/com.mahmoudradwan.e_news I/DynamiteModule: Selected remote version of com.google.android.gms.firebase_database, version >= 6
08-20 15:08:27.293 5140-5162/com.mahmoudradwan.e_news V/FA: Connection attempt already in progress
08-20 15:08:27.293 5140-5162/com.mahmoudradwan.e_news V/FA: Connection attempt already in progress
08-20 15:08:27.294 5140-5162/com.mahmoudradwan.e_news V/FA: Activity resumed, time: 5881552
08-20 15:08:27.300 5140-5167/com.mahmoudradwan.e_news D/EGL_emulation: eglMakeCurrent: 0xf19aff60: ver 2 0 (tinfo 0xf199b8a0)
08-20 15:08:27.331 5140-5176/com.mahmoudradwan.e_news W/zygote: Unsupported class loader
08-20 15:08:27.332 5140-5176/com.mahmoudradwan.e_news W/zygote: Skipping duplicate class check due to unsupported classloader
08-20 15:08:27.352 5140-5167/com.mahmoudradwan.e_news D/EGL_emulation: eglMakeCurrent: 0xf19aff60: ver 2 0 (tinfo 0xf199b8a0)
08-20 15:08:27.362 5140-5162/com.mahmoudradwan.e_news D/FA: Connected to remote service
08-20 15:08:27.365 5140-5162/com.mahmoudradwan.e_news V/FA: Processing queued up service tasks: 4
08-20 15:08:27.386 5140-5167/com.mahmoudradwan.e_news D/EGL_emulation: eglMakeCurrent: 0xf19aff60: ver 2 0 (tinfo 0xf199b8a0)
08-20 15:08:27.499 5140-5178/com.mahmoudradwan.e_news D/NetworkSecurityConfig: No Network Security Config specified, using platform default
08-20 15:08:28.848 5140-5145/com.mahmoudradwan.e_news I/zygote: Do partial code cache collection, code=26KB, data=30KB
08-20 15:08:28.849 5140-5145/com.mahmoudradwan.e_news I/zygote: After code cache collection, code=26KB, data=30KB
08-20 15:08:28.849 5140-5145/com.mahmoudradwan.e_news I/zygote: Increasing code cache capacity to 128KB
08-20 15:08:32.509 5140-5162/com.mahmoudradwan.e_news V/FA: Inactivity, disconnecting from the service
08-20 15:08:38.279 5140-5140/com.mahmoudradwan.e_news W/ClassMapper: No setter/field for mImageurl found on class com.mahmoudradwan.e_news.Blog
08-20 15:08:38.280 5140-5140/com.mahmoudradwan.e_news W/ClassMapper: No setter/field for mblogBegginer found on class com.mahmoudradwan.e_news.Blog
08-20 15:08:38.280 5140-5140/com.mahmoudradwan.e_news W/ClassMapper: No setter/field for mtitle found on class com.mahmoudradwan.e_news.Blog
08-20 15:08:38.318 5140-5140/com.mahmoudradwan.e_news W/Glide: Failed to find GeneratedAppGlideModule. You should include an annotationProcessor compile dependency on com.github.bumptech.glide:compiler in your application and a #GlideModule annotated AppGlideModule implementation or LibraryGlideModules will be silently ignored
08-20 15:08:38.402 5140-5140/com.mahmoudradwan.e_news W/Glide: Load failed for null with size [0x0]
class com.bumptech.glide.load.engine.GlideException: Received null model
08-20 15:08:38.420 5140-5140/com.mahmoudradwan.e_news W/Glide: Load failed for null with size [0x0]
class com.bumptech.glide.load.engine.GlideException: Received null model
Firebase dataBase Example
{
"-LKIJ4U5ymhgXyt7A4C2" : {
"mAudioAdvancedurl" : "com.google.android.gms.tasks.zzu#9f1c1e4",
"mAudioBegginersurl" : "com.google.android.gms.tasks.zzu#c28a776",
"mAudioIntermediateurl" : "com.google.android.gms.tasks.zzu#b997177",
"mImageurl" : "com.google.android.gms.tasks.zzu#2810a11",
"mblogAdvanced" : "null now",
"mblogBegginer" : "Hello we test desc yarb t4t8l rbna ystrha",
"mblogIntermediate" : "null now",
"mtitle" : "Hello it's a test version title Hi hi ."
}
}
Step 1 : Remove all the static keyword from Blog class( even before method names remove it). static info
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.....
//listView.setAdapter(adapter); remove this line from here
.......
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Blog blog = dataSnapshot.getValue(Blog.class);//also make sure this line is returning a valid result which can be cast to Blog Class
adapter.add(blog);
//listView.setAdapter(adapter); or you can call here but not good approach
}
.................
});
listView.setAdapter(adapter); // call it here
}
}
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";