cannot resolve method getApplicationContext()

Hi,
I have the following function in the file ZeusService.java -

  public ListenableFuture<String> getToken(String guid, String sessionId) {

    final ZeusService zeusService = this;
        zeusClient.setStagingUrl(stagingUrl);
        final ListenableFuture<HttpResponse> future = zeusClient.authenticate(guid, sessionId);
        final Function<HttpResponse, String> extractFunction =
                new Function<HttpResponse, String>() {
                    public String apply(HttpResponse httpresponse) {
                        HttpEntity entity = httpresponse.getEntity();
                        String responseString = null;
                        try {
                            responseString = EntityUtils.toString(entity, "UTF-8");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        JSONObject jsonResponse = null;
                        try {
                            jsonResponse = new JSONObject(responseString);
                            Log.d("Tring", "json response : " + jsonResponse);
                            String token = (String) jsonResponse.get("token");
                            Log.d("NumberActivity", "token : " + token);
                            Log.d("NumberActivity", "jsonResponse : " + responseString);
                            SharedPreferences settings = zeusService.getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
                            SharedPreferences.Editor editor = settings.edit();
                            editor.putString("token", token);
                            editor.commit();
                            return token;
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        return "";
                    }


                };
        return Futures.transform(future,extractFunction);
    }

Open in new window


But i am getting a red mark at the line -
                            SharedPreferences settings = zeusService.getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
It says : cannot resolve method getApplicationContext()


Why this error is coming . How do i resolve it.

Thanks
Rohit BajajAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
mccarlIT Business Systems Analyst / Software DeveloperCommented:
Can you post the FULL code for ZuesService.java ?
Rohit BajajAuthor Commented:
I made some changes to the code and it worked. The codes are below -

package com.example.robinsuri.tring;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.google.common.base.Function;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;

/**
 * Created by robinsuri on 10/29/14.
 */
public class ZeusService {


    String stagingUrl;

    public static final String PREFS_NAME = "MyPrefsFile";
    ZeusClient zeusClient = new ZeusClient();

    public void setSharePreferencesData(SharedPreferences sharePreferencesData) {
        this.sharePreferencesData = sharePreferencesData;
    }

    SharedPreferences sharePreferencesData;
    Context context;

    public void setContext(Context context) {
        this.context = context;
    }


    public ListenableFuture<HttpResponse> createAccount(String firstName, String lastName, String number, String emailId) {

        zeusClient.setStagingUrl(stagingUrl);
        ListenableFuture<HttpResponse> future = zeusClient.createAccount(firstName, lastName, number, emailId);
        return future;
    }

    public ListenableFuture<HttpResponse> createSession(String guid) {

        ListenableFuture<HttpResponse> future = zeusClient.getSessionMappingFromGuid(guid);
        return future;

    }

    public void setStagingUrl(String stagingUrl) {
        this.stagingUrl = stagingUrl;
    }

    public ListenableFuture<String> getmapping(final String firstName, final String lastName, final String number, final String emailId) {
        final ListenableFuture<HttpResponse> future = createAccount(firstName, lastName, number, emailId);

        final ListenableFuture<String> future1 = Futures.transform(future, new AsyncFunction<HttpResponse, String>() {
            @Override
            public ListenableFuture<String> apply(HttpResponse httpResponse) {
                ListenableFuture<String> future2 = null;
                try {
                    Log.d("Tring", httpResponse.toString());
                    HttpEntity entity = httpResponse.getEntity();
                    String responseString = EntityUtils.toString(entity, "UTF-8");

                    JSONObject jsonResponse = new JSONObject(responseString);
                    Log.d("Tring", "json response : " + jsonResponse);
                    String guid = (String) jsonResponse.get("guid");

                    persist(guid);


                    ListenableFuture<HttpResponse> future = createSession(guid);
                    future2 = Futures.transform(future, new Function<HttpResponse, String>() {
                        @Override
                        public String apply(HttpResponse httpResponse) {
                            HttpEntity entity = httpResponse.getEntity();
                            String responseString = null;
                            String mapping = null;
                            try {
                                responseString = EntityUtils.toString(entity, "UTF-8");

                                JSONObject jsonResponse = null;

                                jsonResponse = new JSONObject(responseString);

                                Log.d("Tring", "json response : " + jsonResponse);

                                mapping = (String) jsonResponse.get("mapping");

                                String sessionId = null;

                                sessionId = (String) jsonResponse.get("sessionId");

                                persist(mapping, sessionId);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            return mapping;
                        }
                    });


                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return future2;
            }
        });

        return future1;
    }


    private void persist(String mapping, String sessionId) {
        SharedPreferences.Editor editor = Tring.settings.edit();
        editor.putString("number", mapping);
        editor.putString("sessionId", sessionId);
        editor.commit();
        Log.d("Tring", "Number from file : " + Tring.settings.getString("number", ""));
    }


    private void persist(String guid) {

        SharedPreferences.Editor editor = sharePreferencesData.edit();
        editor.putString("guid", guid);
        editor.commit();
        Log.d("ZeusService", "Guid from sharedPreferences : " + sharePreferencesData.getString("guid", ""));
    }

    public ListenableFuture<String> getToken(String guid, String sessionId) {

        final ZeusService zeusService = this;
        zeusClient.setStagingUrl(stagingUrl);
        final ListenableFuture<HttpResponse> future = zeusClient.authenticate(guid, sessionId);
        final Function<HttpResponse, String> extractFunction =
                new Function<HttpResponse, String>() {
                    public String apply(HttpResponse httpresponse) {
                        HttpEntity entity = httpresponse.getEntity();
                        String responseString = null;
                        try {
                            responseString = EntityUtils.toString(entity, "UTF-8");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        JSONObject jsonResponse = null;
                        String token = null;
                        try {
                            jsonResponse = new JSONObject(responseString);
                            Log.d("Tring", "json response : " + jsonResponse);
                            token = (String) jsonResponse.get("token");
                            Log.d("NumberActivity", "token : " + token);
                            Log.d("NumberActivity", "jsonResponse : " + responseString);
                            SharedPreferences.Editor editor = NumberActivity.settings.edit();
                            editor.putString("token", token);
                            editor.commit();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        return token;
                    }


                };
        return Futures.transform(future, extractFunction);
    }


}

Open in new window


Above is the code for ZeusService.java

Following is for NumberActivity.java :

package com.example.robinsuri.tring;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class NumberActivity extends Activity {
    public static final String PREFS_NAME = "MyPrefsFile";
    String stagingUrl = "https://proxy-staging-external.handler.talk.to/";
    boolean isClicked = false;
    public static SharedPreferences settings = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        settings = this.getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
        Log.d("NumberActivity", "Inside onCreate of NumberActivity");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_number);
        EditText t = (EditText) findViewById(R.id.calltext);
        Intent intent = getIntent();
        String message = intent.getStringExtra("message");
        t.setText("Call the number for verification : " + message);

        SharedPreferences settings = this.getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean("isBackButtonPressed", false);
        editor.commit();

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.number, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d("NumberActivity", "Inside onRestart()");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d("NumberActivity", "Inside onStart()");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Executor executor = Executors.newSingleThreadExecutor();
        executor.execute(new Runnable() {
            @Override
            public void run() {
                Log.d("NumberActivity", "Inside onResume");
           //     final NumberActivity numberActivity = this;

                SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
                boolean isPaused = settings.getBoolean("isPaused", false);
                Log.d("NumberActivity", "Value of isClicked = " + isClicked);
                if (isClicked) {
                    final ZeusService zeusservice = new ZeusService();
                    Log.d("NumberActivity", "After call");
                    zeusservice.setStagingUrl(stagingUrl);
                    SharedPreferences.Editor editor = settings.edit();
                    String sessionId = settings.getString("sessionId", "");
                    String guid = settings.getString("guid", "");
                    Log.d("NumberActivity", "Calling getToken of zeusService");
                    ListenableFuture<String> future = zeusservice.getToken(guid, sessionId);
                    Futures.addCallback(future, new FutureCallback<String>() {
                        @Override
                        public void onSuccess(String token) {
                            Log.d("NumberActivity", "After REfactoring Token is : " + token);

                            runOnUiThread(new Runnable() {


                                @Override
                                public void run() {
                                    Intent intent = new Intent(numberActivity, MainScreen.class);
                                    startActivity(intent);
                                    Log.d("NumberActivity", "SetResult called");
                                    setResult(RESULT_OK, new Intent());
                                    finish();
                                    Log.d("NumberActivity", "Finish Called");
                                }
                            });

                        }

                        @Override
                        public void onFailure(Throwable throwable) {

                        }
                    });

                    Log.d("NumberActivity", "Before addCallback current Thread Name : " + Thread.currentThread().getName());
                    editor.putBoolean("isPaused", false);
                }
            }
        });


    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d("NumberActivity", "Inside onStop()");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("NumberActivity", "Inside onPause()");
        SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean("isPaused", true);
        editor.commit();

    }

    public void onClickCall(View v) {
        isClicked = true;
        Intent intent = getIntent();
        String message = intent.getStringExtra("message");
        Log.d("NumberActivity", "Mobile number : " + message);

        Intent phoneIntent = new Intent(Intent.ACTION_CALL);
        phoneIntent.setData(Uri.parse("tel:" + message));
        try {
            startActivity(phoneIntent);

            Log.i("Finished making a call...", "");

        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(NumberActivity.this,
                    "Call faild, please try again later.", Toast.LENGTH_SHORT).show();
        }

    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Log.d("NumberActivity", "Inside onBackPressed");
        SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean("isBackButtonPressed", true);
        editor.commit();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("NumberActivity", "Inside onDestroy");
    }


}

Open in new window

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.