Solved

cannot resolve method getApplicationContext()

Posted on 2014-11-13
3
3,237 Views
Last Modified: 2014-11-30
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
0
Comment
Question by:Rohit Bajaj
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 20

Accepted Solution

by:
Sathish David  Kumar N earned 500 total points
ID: 40439482
0
 
LVL 36

Expert Comment

by:mccarl
ID: 40441920
Can you post the FULL code for ZuesService.java ?
0
 

Author Comment

by:Rohit Bajaj
ID: 40441980
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

0

Featured Post

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
You should read OS supplied guidelines before developing. I can't stress that enough. The guidelines will help you understand the reasons mobile app developers do what they do.  Apple is very particular when they review appstore submissions.
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

729 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question