Solved

cannot resolve method getApplicationContext()

Posted on 2014-11-13
3
2,833 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
3 Comments
 
LVL 20

Accepted Solution

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

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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Protect jar file - windows app 2 53
Problem to App 4 82
Measure data usage per hotspot, on computer 3 52
how to root nextbook 10 running marshmallow 1 8
Often, people trade privacy and security for convenience. However in today's concrete jungle, this is an extremely foolish decision considering the vast amount of technologies being used against consumer interest. First off, I won't waste any time e…
If your app took Google’s lash recently, here are the 5 most likely reasons.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
This video is in connection to the article "The case of a missing mobile phone (https://www.experts-exchange.com/articles/28474/The-Case-of-a-Missing-Mobile-Phone.html)". It will help one to understand clearly the steps to track a lost android phone.

773 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