getContext () , getApplicationContext(), getBaseContext are not working in Android - android

I want to show a toast message but getContext() in Toast.makeText((getContext()," Message" , Toat.LENGTH_LONG.show())) is giving error
Cannot resolve Method.
The problem is that in which class I want to show the Toast message is not MainActivity class. This is AsyncTask class. Can i show Toast message in other classes (other than MainActivity class) as the above mentioned problem?
import android.os.AsyncTask;
import android.widget.Toast;
public class myClass extends AsyncTask<String, String, String> {
public myClass(double a, double b,Context context ) {
this.a = a;
this.b=b;
this.context = context;
}
protected String doInBackground(String... params) {
return null;
}
protected void onPostExecute(String result) {
Toast.makeText((getApplicationContext(), "Message", Toast.LENGTH_LONG).show();
}
}
Edit
I made the constructor (See above code) but in the MainActivity class I am calling in this way myClassObj = new myClass(a, b,this); but is giving error
myClas() in myClass cannot be applied to:
Expected Actual
Parameters Arguments
a: double a
b: double b
context: android.content.Context this(anonymous...view.View.OnClickListener)
Edit3
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
myClass Object;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
double age = 16;
double number = 33;
Object = new myClass(age,number,this);
}
});
}
}
SecondClass.
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
public class myClass extends AsyncTask<String, String, String> {
Context context;
double a;
double b;
public myClass(double a, double b,Context context ) {
this.a = a;
this.b=b;
this.context = context;
}
protected String doInBackground(String... params) {
return null;
}
protected void onPostExecute(String result) {
Toast.makeText((context), "Message", Toast.LENGTH_LONG).show();
}
}

When you are using this it refers to the enclosing class. In your case this is View.OnClickListener. But you need to pass the context of your Activity.
So you need to call it this way,
Object = new myClass(age,number, MainActivity.this);

You can use the ApplicationClass.getinstance().getApplicationContext();

Edit 3
Do this in your MainActivity:
Object = new myClass(age,number,MainActivity.this);
And do this in your myClass
Toast.makeText(context, "Message", Toast.LENGTH_LONG).show();
Edit 2
class MyClass extends AsyncTask<Void, Void, Void> {
int SPLASH_SHOW_TIME=3000;
Context context;
public MyClass(Context context ) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
Thread.sleep(SPLASH_SHOW_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Toast.makeText(context, "Created a server socket",Toast.LENGTH_LONG).show();
}
}

Related

Where should implement the methods of AsyncTask class if have multiple classes in Android?

I have four classes:
MainActivity extends AppCompactActivity
MainAsyncTask extends AsyncTask<String, String, List>
Intermediate extends MainAsyncTask and have two functions. (FuncA, FuncB)
Leaf extends Intermediate and implementation of doInBackground() and onPostExecute().
When I run the application it prompts:
Unable to instantiate activity ComponentInfo{}: android.os.NetworkonMainThreadException.
How can I get rid off the Error. As far as My understanding is concerned, doInBackground() and onPostExecute()should be implemented in MainAsyncTask class?
Classes are :
MianActivity.java
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Leaf object = new Leaf();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button fab = (Button) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
object.execute();
}
});
}
}
MainAsyncTask.java
import android.os.AsyncTask;
public class MainAsync extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
return null;
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(String... text) {
}
}
Intermediate.java
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
public class Intermediate extends MainAsync{
public Document FunA(){
System.out.println("Printed FunA()");
String url = "http://blogs.tribune.com.pk/story/37034/zakir-naik-has-a-large-following-in-pakistan-should-we-be-alarmed/";
Document doc = null;
try {
doc = Jsoup.connect(url).timeout(10 * 1000).get();
} catch (IOException e) {
e.printStackTrace();
}
return doc;
}
public void FunB(){ System.out.println("Printed FunB()");}
}
}
Leaf.java
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Leaf extends Intermediate{
Document HTM = FunA();
public void FunC() {
String heading = "";
System.out.println("Printed FunC()");
Elements seep = HTM.select("h1");
for (Element foo : seep) {
heading = foo.text();
System.out.println(heading);
break;
}
}
public void FunD() {
System.out.println("Printed FunD()");
}
public void FunE() {
System.out.println("Printed FunE()");
}
#Override
protected String doInBackground(String... params) {
FunB();FunC();FunD();FunE();
return null;
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(String... text) {
}
}
The purpose of doing in this way is to add FuncA and FuncB along with AsyncTask methods in one class that is Leaf class.
In the absence of a stack trace I would say:
Initiating your Leaf class causes the HTM variable to be initiated.
The HTM variable is initiated by calling the FunA method.
The FunA method runs network accessing code and is not running inside DoInBackground (and therefore running on the main thread).
Your network code can only be run inside DoInBackground if you wish to not get a NetworkOnMainThread Exception.
The exception is thrown before you even start the AsyncTask as just the act of creating it causes the FunA code to run.
Move this line inside DoInBackground so it runs when the AsyncTask is executed and not when it is created.
Document HTM = FunA();
On a separate note, your class hierarchy is very convoluted. You do not need Intermediate or Leaf classes. All that code could be easily moved to the MainAsync class and so would be much easier to understand.

Accessing TextView from other class in android

Hello i am new to android.i was creating a simple google cloud appengine app with endpoint.i was using using this tutorial https://github.com/GoogleCloudPlatform/gradle-appengine-templates/tree/master/HelloEndpoints .but the thing is i want to show the result in a textview not in a toast.
Layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/lay1">
<EditText
android:id="#+id/edt1"
android:layout_width="match_parent"
android:layout_height="100dp"
android:hint="Enter Number"
android:inputType="number"
android:textSize="24sp" />
<EditText
android:id="#+id/edt2"
android:layout_width="match_parent"
android:layout_height="100dp"
android:hint="Enter Number"
android:inputType="number"
android:textSize="24sp" />
<TextView
android:id="#+id/tv1"
android:layout_width="match_parent"
android:layout_height="100dp"
android:hint="Result Will be Here"
android:textSize="24sp" />
<Button
android:id="#+id/btnAdd"
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="Add" />
</LinearLayout>
GoogleAppEngActivity.java (main activity)
package com.ontech.googleappengine;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Pair;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class GoogleAppEngActivity extends AppCompatActivity {
Button btnAdd;
TextView tv1;
//String val1,val2;
EditText edt1,edt2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_app_eng);
edt1=(EditText)findViewById(R.id.edt1);
edt2=(EditText)findViewById(R.id.edt2);
tv1=(TextView)findViewById(R.id.tv1);
btnAdd =(Button)findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String temp = "";
temp = edt1.getText().toString();
temp += "+";
temp += edt2.getText().toString();
new EndpointsAsyncTask().execute(new Pair<Context, String>(GoogleAppEngActivity.this, temp));
// tv1.setText( new EndpointsAsyncTask().);
}
});
// new EndpointsAsyncTask().execute(new Pair<Context, String>(this, "Manfred"));
}
public TextView getTextView(){
TextView txtView=(TextView)findViewById(R.id.tv1);
return txtView;
}
}
EndpointsAsyncTask.java
package com.ontech.googleappengine;
//package com.ontech.googleappengine;
import android.content.Context;
import android.os.AsyncTask;
import android.text.Layout;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import com.ontech.myapplication.backend.myApi.MyApi;
import java.io.IOException;
/**
* Created by on 05-11-2015.
*/
public class EndpointsAsyncTask extends AsyncTask<Pair<Context, String>, Void, String> {
private static MyApi myApiService = null;
private Context context;
#Override
protected String doInBackground(Pair<Context, String>... params) {
if (myApiService == null) { // Only do this once
/* MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});*/
MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
.setRootUrl("https://leafy-display-112017.appspot.com/_ah/api/");
// end options for devappserver
myApiService = builder.build();
}
context = params[0].first;
String name = params[0].second;
try {
return myApiService.sayHi(name).execute().getData();
} catch (IOException e) {
return e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
}
My endpoint.java
package com.ontech.myapplication.backend;
import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiNamespace;
import javax.inject.Named;
/**
* An endpoint class we are exposing
*/
#Api(
name = "myApi",
version = "v1",
namespace = #ApiNamespace(
ownerDomain = "backend.myapplication.ontech.com",
ownerName = "backend.myapplication.ontech.com",
packagePath = ""
)
)
public class MyEndpoint {
/**
* A simple endpoint method that takes a name and says Hi back
*/
#ApiMethod(name = "sayHi")
public MyBean sayHi(#Named("name") String name) {
MyBean response = new MyBean();
String val1, val2;
val1 = name.substring(0, name.indexOf("+"));
val2 = name.substring(name.indexOf("+") + 1);
int res = Integer.parseInt(val1) + Integer.parseInt(val2);
// response.setData("Hi, " + name);
response.setData(Integer.toString(res));
return response;
}
}
MyBean.java
package com.ontech.myapplication.backend;
/**
* The object model for the data we are sending through endpoints
*/
public class MyBean {
private String myData;
public String getData() {
return myData;
}
public void setData(String data) {
myData = data;
}
}
Pass TextView as parameter to Constructor of EndpointsAsyncTask in which you want to show result as done below.
public class EndpointsAsyncTask extends AsyncTask<Pair<Context, String>, Void, String> {
private static MyApi myApiService = null;
private Context context;
private TextView textView
public EndpointsAsyncTask(Context context,TextView mtextView) {
// TODO Auto-generated constructor stub
this.context=context;
this.textView=mtextView;
}
#Override
protected String doInBackground(Pair<Context, String>... params) {
if (myApiService == null) { // Only do this once
/* MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});*/
MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
.setRootUrl("https://leafy-display-112017.appspot.com/_ah/api/");
// end options for devappserver
myApiService = builder.build();
}
context = params[0].first;
String name = params[0].second;
try {
return myApiService.sayHi(name).execute().getData();
} catch (IOException e) {
return e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
textView.setText(result);
}
}
call AsyncTask from you Activity or Fragment
new EndpointsAsyncTask(context,yourTextView).execute(yourParams);
In EndpointsAsyncTask.java replace
#Override
protected void onPostExecute(String result) {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
With
#Override
protected void onPostExecute(String result) {
GoogleAppEngActivity.getTextView().setText(result);
}
change to:new EndpointsAsyncTask(tv1) in GoogleAppEngActivity class
and add next code to EndpointsAsyncTask class
TextView view;
public EndpointsAsyncTask(TextView tv) {
view = tv;
}
and replace Toast.makeText(context, result, Toast.LENGTH_LONG).show();
to view.setText(result);
I'll suggest making EndpointsAsyncTask an inner class of your activity. Get a reference to textView in postExecute and update it there. Something like this
Ideally, the UI elements belonging to an activity should be changed in the activity itself, and no where else. Try following the presentation pattern.
A small example:
1. Create an interface - ActivityPresenter with methods signifying events with parameters as the input data required for the views to change. An example would be:
void onServerResponse(ServerResponse resp);
Make the activity implement this interface. That is, you define what UI changes to make in the activity when the server response arrives.
When you call a service / asynctask from the activity to do some task asynchronously for you, send the activity presenter reference. Call the presenter.onServerResponse(response) from your service / asynctask.
For this purpose you can use callback interface:
Create a public interface:
public interface AsyncTaskResponse {
void asyncTaskFinish(String output);
}
Now override the method of callback interface and define the action need to do i.e set the TextView value. After that pass it to async task class:
package com.ontech.googleappengine;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Pair;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class GoogleAppEngActivity extends AppCompatActivity {
Button btnAdd;
final TextView tv1;
//String val1,val2;
EditText edt1,edt2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_app_eng);
edt1=(EditText)findViewById(R.id.edt1);
edt2=(EditText)findViewById(R.id.edt2);
tv1=(TextView)findViewById(R.id.tv1);
btnAdd =(Button)findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String temp = "";
temp = edt1.getText().toString();
temp += "+";
temp += edt2.getText().toString();
new EndpointsAsyncTask(new AsyncTaskResponse() {
#Override
public void asyncTaskFinish(String response) {
tv1.setText(response);
}
};).execute(new Pair<Context, String>(GoogleAppEngActivity.this, temp));
// tv1.setText( new EndpointsAsyncTask().);
}
});
// new EndpointsAsyncTask(new AsyncTaskResponse().execute(new Pair<Context, String>(this, "Manfred"));
}
public TextView getTextView(){
TextView txtView=(TextView)findViewById(R.id.tv1);
return txtView;
}
}
Now in async task class call the Callback interface method and pass response String to set edit text value:
package com.ontech.googleappengine;
//package com.ontech.googleappengine;
import android.content.Context;
import android.os.AsyncTask;
import android.text.Layout;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import com.ontech.myapplication.backend.myApi.MyApi;
import java.io.IOException;
/**
* Created by on 05-11-2015.
*/
public class EndpointsAsyncTask extends AsyncTask<Pair<Context, String>, Void, String> {
private static MyApi myApiService = null;
private Context context;
private AsyncTaskResponse asyncCallback;
public EndpointsAsyncTask(AsyncTaskResponse asyncTaskResponse){
asyncCallback = asyncTaskResponse;
}
#Override
protected String doInBackground(Pair<Context, String>... params) {
if (myApiService == null) { // Only do this once
/* MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});*/
MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
.setRootUrl("https://leafy-display-112017.appspot.com/_ah/api/");
// end options for devappserver
myApiService = builder.build();
}
context = params[0].first;
String name = params[0].second;
try {
return myApiService.sayHi(name).execute().getData();
} catch (IOException e) {
return e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
//Toast.makeText(context, result, Toast.LENGTH_LONG).show();
asyncCallback.asyncTaskFinish(result); // call the method of callback interface
}
}

can't return data from inner asynctask class to outer class

Hi friends I know there is a bunch of questions about this topic but I can not get any result from them. i am parsing xml data with my ClassIsInternalParser extends default handler. I use this class in my activity in an inner class PostAsync extends AsyncTask
but the reason is i can not return the data that ı collected in PostAsync class to main activity. it sets only null
here is my codes
package com.example.uiexercisesplash;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ClassIsInternalListViewActivity extends Activity implements OnClickListener{
TextView tv, tv2;
Button back;
String[][] array = new String[10][3];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.classisinternal_listview);
new PostAsync().execute();
tv=(TextView) findViewById(R.id.tatar);
tv2= (TextView) findViewById(R.id.tatar2);
tv2.setText(array[0][0]); //Why this sets null!!
back= (Button) findViewById(R.id.back);
back.setOnClickListener(this);
}
class PostAsync extends AsyncTask<Void, Void,String[][]>{
ProgressDialog pd;
ClassIsInternalParser parser;
#Override
protected void onPreExecute() {
//we can set up variables here
pd = ProgressDialog.show(ClassIsInternalListViewActivity.this,
"Classisinternal","Loading last post...",true,false);
}
protected void onPostExecute(String[][] result) {
//in this way it sets correctly
tv.setText(result[0][0]);
array=result;
pd.dismiss();
pd.cancel();
}
protected String[][] doInBackground(Void... params) {
parser = new ClassIsInternalParser();
parser.get();
return parser.dataArray;
}
}
#Override
public void onClick(View v) {
finish();
}
}
Try to create PostAsync object and call execute() from that object. After that call get() method to retrieve your return array like this:
PostAsync obj=new PostAsync(this);
obj.execute();
String[][] array=obj.get();
tv2.setText(array[0][0]);
tv2.setText(array[0][0]); is null because you are getting array value before setting values in it,i.e. tv2.setText(array[0][0]); is execute before completing Asynctask.
So do this step in onPostExecute method as
protected void onPostExecute(String[][] result) {
//in this way it sets correctly
tv.setText(result[0][0]);
tv2.setText(result[0][2]);
array=result;
tv2.setText(array[0][0]);// add here
pd.dismiss();
pd.cancel();
}

Can't cast library class to fragment

I added Yahoo weather library to m project. Then I tried to implement YahooWeatherInfoListener to the main fragment.
There is a problem.
Inside AsyncTask I can't cast YahooWeatherInfoListener to the fragment.
I think there is sth I'm doin wrong inside AsncTask. Please take a look:
import zh.wang.android.apis.yweathergetter4a.WeatherInfo;
import zh.wang.android.apis.yweathergetter4a.YahooWeather;
import zh.wang.android.apis.yweathergetter4a.YahooWeather.SEARCH_MODE;
import zh.wang.android.apis.yweathergetter4a.YahooWeatherInfoListener;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class HomeFragment extends Fragment implements YahooWeatherInfoListener {
public HomeFragment(){}
private TextView Temperature;
private YahooWeather mYahooWeather = YahooWeather.getInstance(5000, 5000, true);
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
Temperature = (TextView) rootView.findViewById(R.id.txtLabel);
new searchByGPS().execute();
return rootView;
}
private class searchByGPS extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... unused) {
mYahooWeather.setNeedDownloadIcons(true);
mYahooWeather.setSearchMode(SEARCH_MODE.GPS);
mYahooWeather.queryYahooWeatherByGPS(getActivity().getApplicationContext(), (YahooWeatherInfoListener) this);
return null;
}
protected void onPostExecute(Void unused) {
}
}
#Override
public void gotWeatherInfo(WeatherInfo weatherInfo) {
// TODO Auto-generated method stub
Temperature.setText(weatherInfo.getCurrentTempC());
}
}
That's because in
(YahooWeatherInfoListener) this
this refers to the AsyncTask. Instead, you need to use:
(YahooWeatherInfoListener) HomeFragment.this
The cleaner way to implement this would be:
private class SearchByGPSTask extends AsyncTask<Void, Void, Void>{
private YahooWeatherInfoListener mListener;
public SearchByGPSTask( YahooWeatherInfoListener listener ) {
super();
mListener = listener;
}
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... unused) {
mYahooWeather.setNeedDownloadIcons(true);
mYahooWeather.setSearchMode(SEARCH_MODE.GPS);
mYahooWeather.queryYahooWeatherByGPS(getActivity().getApplicationContext(), mListener );
return null;
}
protected void onPostExecute(Void unused) {
}
}
(note: Classes are generally uppercase, and better nouns -- "searchByGPS" sounds like a method, while "SearchByGPSTask" indicates that it's a class meant to do something.)
protected Void doInBackground(Void... unused) {
mYahooWeather.setNeedDownloadIcons(true);
mYahooWeather.setSearchMode(SEARCH_MODE.GPS);
mYahooWeather.queryYahooWeatherByGPS(getActivity().getApplicationContext(), (YahooWeatherInfoListener) HomeFragment.this);
return null;
}
You have to change your this to HomeFragment.this because this is directly connected to your AsyncTask.
With this line mYahooWeather.queryYahooWeatherByGPS(getActivity().getApplicationContext(), (YahooWeatherInfoListener) this);, you are trying to cast the AsyncTask to a YahooWeatherInfoListener. Use HomeFragment.this instead

call onListItemClick() after execution of onPostExecute(Void result) android

I am having problem to call onListItemClick() function after execution of onPostExecute(Void result)
Below is my code snippet .
package com.myapp.checkoutnhangout;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.util.List;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class CheckoutNearestPlaces extends ListActivity {
private String[] placeName;
private String[] imageUrl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new GetPlaces(this,getListView()).execute();
}
class GetPlaces extends AsyncTask<Void, Void, Void> {
Context context;
private ListView listView;
private ProgressDialog progressDialog;
public GetPlaces(Context context , ListView listView) {
this.context = context;
this.listView = listView;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setIndeterminate(true);
progressDialog.setTitle("Loading");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
findNearLocation();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
progressDialog.dismiss();
setListAdapter(new ArrayAdapter<String>(context,android.R.layout.simple_list_item_1,placeName));
// this.listView.setAdapter(new ArrayAdapter<String>(context,android.R.layout.simple_list_item_1,placeName));
}
public void onListItemClick(ListView listView , View v , int position , long id){
System.out.println("position------------"+placeName[position]);
}
public void findNearLocation() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
PlacesService placesService = new PlacesService("AIzaSyC3y3fOMTqTkCjNNETQTCKustG7BRk_eVc");
List<Place> findPlaces = placesService.findPlaces(28.6752, 77.4362, "");
int findPlacesSize = findPlaces.size();
placeName = new String[findPlacesSize];
imageUrl = new String[findPlacesSize];
for(int index = 0 ; index < findPlacesSize ; index ++) {
Place placeDetail = findPlaces.get(index);
// System.out.println("name of place : "+placeDetail.getName());
placeName[index] = placeDetail.getName();
// System.out.println("url of place : "+placeDetail.getIcon());
imageUrl[index] = placeDetail.getIcon();
}
}
}
}
Above code use google palce api and display list of locations on the basis of user's interest .
After that , I want to call onListItemClick() function , so that I can call another activity on each item click.
Any help will be appreciable.
remove
public void onListItemClick(ListView listView , View v , int position , long id){
System.out.println("position------------"+placeName[position]);
}
from class GetPlaces
and put in CheckoutNearestPlaces

Categories

Resources