Activity layout lagging behind until before next transition to another activity - java

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.

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.

Error while sending intent to other activity [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
Whats wrong in this code? It is not sending the intent to next page.I have done it many times.When i click on the button on the Mainactivity.java i get this log.It doesn't go to the next page.Intent is not working in this activity why?Hope to get answer soon.Thanks in advance.
package com.example.testing1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<String> hisnumber=new ArrayList<>();
ArrayList<Bitmap> hisimages=new ArrayList<>();
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=findViewById(R.id.button);
Intent intent = getIntent();
hisnumber = intent.getStringArrayListExtra("hisnumber");
hisimages = intent.getParcelableArrayListExtra("hisimages");
Log.d("num1", String.valueOf(hisnumber));
Log.d("img1", String.valueOf(hisimages));
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent = new Intent(MainActivity.this, Testing2.class);
myIntent.putExtra("hisnumber", hisnumber);
myIntent.putParcelableArrayListExtra("hisimages", hisimages);
Log.d("num", String.valueOf(hisnumber));
Log.d("img", String.valueOf(hisimages));
startActivity(myIntent);
}
});
}
}
Mainactivity.java
package com.example.testing1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
public class Testing2 extends AppCompatActivity {
ArrayList<String> hisnumber=new ArrayList<>();
ArrayList<Bitmap> hisimages=new ArrayList<>();
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testing2);
button=findViewById(R.id.button);
Intent intent = getIntent();
hisnumber = intent.getStringArrayListExtra("hisnumber");
hisimages = intent.getParcelableArrayListExtra("hisimages");
Log.d("num3", String.valueOf(hisnumber));
Log.d("img3", String.valueOf(hisimages));
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(hisnumber==null){
hisnumber=new ArrayList<>();
hisimages=new ArrayList<>();
}
hisnumber.add("ass");
Bitmap bp= BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_background);
hisimages.add(bp);
Intent myIntent = new Intent(Testing2.this, MainActivity.class);
myIntent.putExtra("hisnumber", hisnumber);
myIntent.putParcelableArrayListExtra("hisimages", hisimages);
Log.d("num2", String.valueOf(hisnumber));
Log.d("img2", String.valueOf(hisimages));
startActivity(myIntent);
}
});
}
}
Testing.java
07/28 11:07:11: Launching 'app' on Realme RMX1901.
$ adb shell am start -n "com.example.testing1/com.example.testing1.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 18360 on device 'realme-rmx1901-618cb732'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/Perf: Connecting to perf service.
E/Perf: Fail to get file list com.example.testing1
getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array
Fail to get file list com.example.testing1
getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array
W/xample.testing: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/xample.testing: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
D/num1: null
D/img1: null
D/WindowManager: Add to mViews: DecorView#5a6d981[MainActivity], this = android.view.WindowManagerGlobal#9161a26,pkg= com.example.testing1
I/AdrenoGLES: QUALCOMM build : e4029f9, I6b4cbc7431
Build Date : 10/01/19
OpenGL ES Shader Compiler Version: EV031.27.05.01
Local Branch :
Remote Branch :
Remote Branch :
Reconstruct Branch :
I/AdrenoGLES: Build Config : S P 8.0.11 AArch64
I/AdrenoGLES: PFP: 0x016ee187, ME: 0x00000000
W/AdrenoUtils: <ReadGpuID_from_sysfs:194>: Failed to open /sys/class/kgsl/kgsl-3d0/gpu_model
<ReadGpuID:218>: Failed to read chip ID from gpu_model. Fallback to use the GSL path
W/Gralloc3: mapper 3.x is not supported
I/Choreographer: Skipped 9 frames! The application may be doing too much work on its main thread.
I/Choreographer: Skipped 1 frames! The application may be doing too much work on its main thread.
D/ColorViewRootUtil: nav gesture mode swipeFromBottom ignore false downY 349 mScreenHeight 2340 mScreenWidth 1080 mStatusBarHeight 54 globalScale 1.125 nav mode 3 event MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=334.0, y[0]=349.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, classification=NONE, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=660935273, downTime=660935273, deviceId=7, source=0x1002, displayId=0 } rotation 0
D/num: null
D/img: null
I/Choreographer: Skipped 1 frames! The application may be doing too much work on its main thread.
I/Choreographer: Skipped 1 frames! The application may be doing too much work on its main thread.
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy#fa02c62
D/num3: null
D/img3: null
D/WindowManager: Add to mViews: DecorView#76b323c[Testing2], this = android.view.WindowManagerGlobal#9161a26,pkg= com.example.testing1
I/Choreographer: Skipped 6 frames! The application may be doing too much work on its main thread.
I/Choreographer: Skipped 3 frames! The application may be doing too much work on its main thread.
I/xample.testing: ProcessProfilingInfo new_methods=681 is saved saved_to_disk=1 resolve_classes_delay=5000
D/ColorViewRootUtil: nav gesture mode swipeFromBottom ignore false downY 327 mScreenHeight 2340 mScreenWidth 1080 mStatusBarHeight 54 globalScale 1.125 nav mode 3 event MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=81.0, y[0]=327.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, classification=NONE, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=660939314, downTime=660939314, deviceId=7, source=0x1002, displayId=0 } rotation 0
I/Choreographer: Skipped 1 frames! The application may be doing too much work on its main thread.
E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 3240640)
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.testing1, PID: 8832
java.lang.RuntimeException: Failure from system
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1720)
at android.app.Activity.startActivityForResult(Activity.java:5319)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
at android.app.Activity.startActivityForResult(Activity.java:5263)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663)
at android.app.Activity.startActivity(Activity.java:5648)
at android.app.Activity.startActivity(Activity.java:5616)
at com.example.testing1.Testing2$1.onClick(Testing2.java:50)
at android.view.View.performClick(View.java:7256)
at android.view.View.performClickInternal(View.java:7218)
at android.view.View.access$3800(View.java:824)
at android.view.View$PerformClick.run(View.java:27719)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:228)
at android.app.ActivityThread.main(ActivityThread.java:7782)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:981)
Caused by: android.os.TransactionTooLargeException: data parcel size 3240640 bytes
at android.os.BinderProxy.transactNative(Native Method)
at android.os.BinderProxy.transact(BinderProxy.java:523)
at android.app.IActivityTaskManager$Stub$Proxy.startActivity(IActivityTaskManager.java:3868)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1714)
at android.app.Activity.startActivityForResult(Activity.java:5319) 
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676) 
at android.app.Activity.startActivityForResult(Activity.java:5263) 
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663) 
at android.app.Activity.startActivity(Activity.java:5648) 
at android.app.Activity.startActivity(Activity.java:5616) 
at com.example.testing1.Testing2$1.onClick(Testing2.java:50) 
at android.view.View.performClick(View.java:7256) 
at android.view.View.performClickInternal(View.java:7218) 
at android.view.View.access$3800(View.java:824) 
at android.view.View$PerformClick.run(View.java:27719) 
at android.os.Handler.handleCallback(Handler.java:883) 
at android.os.Handler.dispatchMessage(Handler.java:100) 
at android.os.Looper.loop(Looper.java:228) 
at android.app.ActivityThread.main(ActivityThread.java:7782) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:981) 
I/Process: Sending signal. PID: 8832 SIG: 9
Log
Main reason behind NPE is this
hisnumber = intent.getStringArrayListExtra("hisnumber");
hisimages = intent.getParcelableArrayListExtra("hisimages");
You need to check why is this not working
Workaround for NPE
Arraylist seems to be null , so check if its null or not in onClick()
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent = new Intent(Testing2.this, MainActivity.class);
if(hisnumber!=null){
myIntent.putExtra("hisnumber", hisnumber);
}
if(hisimages!=null){
hisnumber.add("ass");
Bitmap bp= BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_background);
hisimages.add(bp);
myIntent.putParcelableArrayListExtra("hisimages", hisimages);
Log.d("num2", String.valueOf(hisnumber));
Log.d("img2", String.valueOf(hisimages));
}
startActivity(myIntent);
}
});
Your hisnumberand hisimages lists are NULL
Check their Nullability before adding somthing..
Testing.java
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (hisnumber != null) {
hisnumber.add("ass");
}
Bitmap bp= BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_background);
if (hisimages != null) {
hisimages.add(bp);
}
Intent myIntent = new Intent(Testing2.this, MainActivity.class);
myIntent.putExtra("hisnumber", hisnumber);
myIntent.putParcelableArrayListExtra("hisimages", hisimages);
Log.d("num2", String.valueOf(hisnumber));
Log.d("img2", String.valueOf(hisimages));
startActivity(myIntent);
}
});

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.

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.

AsyncTask task onPostExecute() not executing? Tried all answer already present on stackoverflow

Hi Developers and friends,
I am working on an android application, which required to read JSON url. I am using AsyncTask. But I dont know why the onPostExecute() is not executing. I successfully parse the json. The only thing left is to return the string (having parse json text).
Here is my code:
package com.vijay.jsonwizard.demo.activities;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.vijay.jsonwizard.demo.R;
import com.vijay.jsonwizard.activities.JsonFormActivity;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
private static final int REQUEST_CODE_GET_JSON = 1;
private static final String TAG = "MainActivity";
private static final String DATA_JSON_PATH = "http://jatinderbhola.in/phppractice/data.json";
String json;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button_start).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, JsonFormActivity.class);
BackgroundTask task = new BackgroundTask();
task.execute();
if (json != null) {
intent.putExtra("json", json);
startActivityForResult(intent, REQUEST_CODE_GET_JSON);
} else {
Toast.makeText(getApplicationContext(), "Error!!", Toast.LENGTH_LONG).show();
}
}
});
}
private class BackgroundTask extends AsyncTask < String, String, String > {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String...params) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(DATA_JSON_PATH)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
try {
//Log.d("Respose", response.body().string());
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String data) {
set_json(data);
}
}
private void set_json(String s) {
// json = s;
Toast.makeText(getApplicationContext(), "I'm in!!", Toast.LENGTH_LONG).show();
}
}
Thanks and advance.
no exception:
this is what android monitor displaying:
01-28 13:42:17.117 1450-1450/com.vijay.jsonwizard.demo I/art: Not late-enabling -Xcheck:jni (already on)
01-28 13:42:17.117 1450-1450/com.vijay.jsonwizard.demo I/art: Late-enabling JIT
01-28 13:42:17.119 1450-1450/com.vijay.jsonwizard.demo I/art: JIT created with code_cache_capacity=2MB compile_threshold=1000
01-28 13:42:17.147 1450-1450/com.vijay.jsonwizard.demo W/System: ClassLoader referenced unknown path: /data/app/com.vijay.jsonwizard.demo-1/lib/x86
01-28 13:42:17.309 1450-1477/com.vijay.jsonwizard.demo D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
01-28 13:42:17.411 1450-1477/com.vijay.jsonwizard.demo I/OpenGLRenderer: Initialized EGL, version 1.4
01-28 13:42:17.805 1450-1458/com.vijay.jsonwizard.demo W/art: Suspending all threads took: 31.806ms
01-28 13:42:17.935 1450-1477/com.vijay.jsonwizard.demo W/EGL_emulation: eglSurfaceAttrib not implemented
01-28 13:42:17.935 1450-1477/com.vijay.jsonwizard.demo W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad7600e0, error=EGL_SUCCESS
01-28 13:42:17.991 1450-1450/com.vijay.jsonwizard.demo I/Choreographer: Skipped 38 frames! The application may be doing too much work on its main thread.
01-28 13:43:25.890 1450-1458/com.vijay.jsonwizard.demo W/art: Suspending all threads took: 5.563ms
01-28 13:49:09.646 1450-1458/com.vijay.jsonwizard.demo W/art: Suspending all threads took: 6.337ms
01-28 13:56:08.565 1450-1477/com.vijay.jsonwizard.demo W/EGL_emulation: eglSurfaceAttrib not implemented
01-28 13:56:08.566 1450-1477/com.vijay.jsonwizard.demo W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad7603e0, error=EGL_SUCCESS
01-28 13:56:11.892 1450-1477/com.vijay.jsonwizard.demo E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb4053c00
move the next code to PostExecute stage:
Intent intent = new Intent(MainActivity.this, JsonFormActivity.class);
if (json != null) {
intent.putExtra("json", json);
startActivityForResult(intent, REQUEST_CODE_GET_JSON);
} else {
Toast.makeText(getApplicationContext(), "Error!!", Toast.LENGTH_LONG).show();
}
}

Categories