Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The method getActivity() is undefined for the type MainActivity

Tags:

android

I'm trying to use the demo how ever when I have pulled it in to my MainActivity I am getting the error "The method getActivity() is undefined for the type MainActivity"

createRequestSuccessListener() and createRequestErrorListener() also got the same problem

package com.example.testgetanik;

    import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import com.android.volley.Response.ErrorListener;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Map<String, String> params = new HashMap<String, String>();
        params.put("id","1");
        params.put("name", "myname");

        String url = "http://api.rottentomatoes.com/api/public/v1.0/movies/770672123/cast.json?apikey=3p9ehnhzbxwpbd6mk8fncf67";
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        CustomRequest jsObjRequest = new CustomRequest(Method.POST,url,params,this.createRequestSuccessListener(),this.createRequestErrorListener());

        requestQueue.add(jsObjRequest);
        try{
            URL urlToRequest = new URL(url);
            WebServiceAsyncTask asyncTask = new WebServiceAsyncTask();
            asyncTask.execute(urlToRequest);
        }catch(MalformedURLException e){
            e.printStackTrace();
        }
    }

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

}
like image 444
user3660001 Avatar asked May 21 '14 10:05

user3660001


2 Answers

Try below code:-

getActivity()

change to

MainActivity.this

You have to pass activity instance.

like image 165
duggu Avatar answered Nov 04 '22 19:11

duggu


Activity is a Context, so when you need a Context inside Activity, just use this. If you need a Context inside a Fragment, use getActivity().

like image 32
David Corsalini Avatar answered Nov 04 '22 20:11

David Corsalini