Stack Exchange
Volley Request only working in LoginActivity
I have been trying to solve this problem for over 2 hours now.
My POST requests all seem to work in my LoginActivity, but for some reason they don't in my MainActivity.
My Webserver is handling requests fine.
The url is correct in my project, I just changed it here.
Here is the MainActivity:
package com.my.app;


import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;

public class MainActivity extends AppCompatActivity {

    String serverResponse;

    Boolean apiKeyValid = false;

    // User Data
    String status, userID, username, klasse, email, fullname, description, pb, classRep, schoolRep, mod, lastLogin, firstVisit, bugsFound, apiKey, userSummary;

    public void validateApiKey(){
        SharedPreferences sp =
                getSharedPreferences("Authentication",
                        Context.MODE_PRIVATE);
        if (sp.contains("apiKey")) {
            apiKey = sp.getString("apiKey", "false");

            RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
            String url = "http://mydomain/api/v1/apiKeyValid";
            StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        serverResponse = response;
                        JSONObject userData = new JSONObject(response);

                        status = userData.getString("status");
                        if (status.equals("valid")) {
                            apiKeyValid = true;
                        }
                    } catch (JSONException e) {
                        Log.e("App", "unexpected JSON exception", e);
                    }
                }
            }, new Response.ErrorListener() { 
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }) {
                protected Map<String, String> getParams() {
                    Map<String, String> MyData = new HashMap<String, String>();
                    MyData.put("apiKey", apiKey);
                    return MyData;
                }
            };
            MyRequestQueue.add(MyStringRequest);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        validateApiKey();
        if (apiKeyValid){
            TextView hello = (TextView) findViewById(R.id.hi);
            String msg = "Api Key is valid! :)\n" + "ApiKey: " + apiKey;
            hello.setText(msg);
        }
        else{
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
        }
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

If I should post anything else, just ask.
Hopefully someone recognizes my problem, thank you! :)

How does your LoginActivity look like?

I'm not sure but there's probably a fault here.
      validateApiKey();
      if (apiKeyValid){

Volley runs an asynchronous task and you don't have a response by the time that if statement is called.
Hope it helps.

Beat me to it by 5 minutes!

Oh thank you!, How would I fix that? Is there a better library or way to accomplish this using a synchronous task?

I just got it to work, by using the following:
`new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
                }
            }, 3000);`

But sometimes it still doesn't work, if android didn't get the response in time, so I still hope, that someone can give me a better solution.
But as this is another problem, I accepted your answer because it helped me find the cause of the problem :)

Timer may work, but you will face the same failture if you are on a slower connection that takes more than 3sec for the pending response.
I would suggest using a callback as a better approach.
public interface VolleyCallback{
    void onResult(Boolean result);
}

public void validateApiKey(final VolleyCallback callback){...

public void onResponse(String response) {... callback.onResult(true);

And finally when you call your StringRequest from onCreate use your anonymous inner class like this..
validateApiKey( new VolleyCallback() {
        @Override
        public void onResult(Boolean response) {
            if (apiKeyValid){....


Works perfectly, as far as I can tell! Thanks a lot :)
