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