I'm trying to make a simple webreader work in an AsyncTast,
main thread
public class main extends Activity implements CallBackListener{
...
WebReader wr = new WebReader();
wr.execute("http://www.google.com");
...
#Override
public void callback(String res)
{
Log.e("eee",res);
}
...
}
...
interface CallBackListener
{
void callback(String res);
}
and webreader
class WebReader extends AsyncTask<String, Void, String>{
CallBackListener mListener;
public void setListener(CallBackListener listener){
mListener = listener;
}
#Override
protected String doInBackground(String... urls) {
String response = "";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(urls[0]);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result) {
Log.e("s3","ss"+result);
mListener.callback(result); // null point here
}
}
yet it crashed with a nullpoint at mListener.callback ... any ideas what might be wrong?
Thanks!
You are not setting a listener. You should have something like this:
WebReader wr = new WebReader();
wr.setListener( new YourCallbackListener() );
wr.execute("http://www.google.com");
Related
I am trying to return an ArrayList from an AsyncTask. But in main activity i am not able to get the returned arraylist. I want to know the way to call the asynctask so that i can get the returned arraylist.
This is the AsyncTask -
public class GetBannerDB extends AsyncTask<Void, Void, ArrayList<String>> {
GetBannerDB() {
}
#Override
protected ArrayList<String> doInBackground(Void... params) {
InputStream is = null;
ArrayList<String> bannerList = new ArrayList<String>();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("data", "data"));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("url to fetch data");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
serverResult = sb.toString().trim();
try {
String sResult = serverResult.substring(0, 7);
if (sResult.equalsIgnoreCase("success")) {
// Creating user login session
// Use user real data
String[] temp = serverResult.split("\\^");
String banner_image = temp[1];
String banner_redirect = temp[2];
bannerList.add(banner_image);
bannerList.add(banner_redirect);
} else {
}
} catch (NullPointerException ex) {
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bannerList;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
super.onPostExecute(result);
mBannerTask = null;
}
}
In MainActivity, i am calling the output as --
ArrayList<String> adDetails = new ArrayList<>();
mBannerTask = new GetBannerDB();
adDetails = mBannerTask.execute();
But here i am getting error - Incompatible types.
Where m i going wrong pls guide.
Ashok as per your answer, i have done the following changes --
OnDataListener.java (As interface)
public interface OnDataListener {
void setData(ArrayList<String> result);
}
In MainActivity.java -
public class PushAds implements OnDataListener{
String serverResult = null;
private GetBannerDB mBannerTask = null;
ArrayList<String> adDetails = new ArrayList<>();
public void displayAds()
{
mBannerTask = new GetBannerDB(new OnDataListener {
public void setData(ArrayList<String> result){
adDetails = result;
}
});
mBannerTask.execute();
}
......
}
But its giving error.
public interface OnDataListner{
void setData(ArrayList<String> result);
}
and
public class GetBannerDB extends AsyncTask<Void, Void, ArrayList<String>> {
public OnDataListner dataListner;
GetBannerDB(OnDataListner dataListner) {
this.dataListner = dataListner;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
super.onPostExecute(result);
dataListner.setData(result);
}
}
finally
ArrayList<String> adDetails = new ArrayList<>();
mBannerTask = new GetBannerDB(new OnDataListner{
#Overrid
public void setData(ArrayList<String> result){
adDetails = result;
//do something
}
});
mBannerTask.execute();
I am trying to make a GET request on a URL, I created a class extending AsyncTask<Void, Void, Void> and I try to call new MyClass.execute() ... I have done this before and it worked, today it is not working. What am I doing wrong?
Here is my code:
public class SignUpActivity extends AppCompatActivity {
String TAG = SignUpActivity.class.getSimpleName();
String URL;
ArrayList<String> countries = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
new MyClass.execute();
}
private class MyClass extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//TODO
}
#Override
protected Void doInBackground(Void... params) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(URL, "GET");
//Handling response in jsonStr code
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//TODO
}
}
This is a syntax error. It should be
new MyClass().execute();
not as new MyClass.execute();
use this to get data use return to return value:
public class SignUpActivity extends AppCompatActivity {
String TAG = SignUpActivity.class.getSimpleName();
String URL;
ArrayList<String> countries = new ArrayList<>();
String jsonStr="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
String response = new MyClass.execute();
}
private class MyClass extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//TODP
}
#Override
protected String doInBackground(Void... params) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(URL, "GET");
//Handling response in jsonStr code
return jsonStr;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//TODO
jsonStr = result;
}
}
}
public class JsonHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public JsonHandler() {
}
public String makeServiceCall(String url,int method) {
return this.makeServiceCall(url, method, null);
}
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
if (params != null) {
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (Exception e) {
}
return response;
}
}
Add above class to your main package and do it as doInBackground
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
JsonHandler json = new JsonHandler();
String jsonStr = json.makeServiceCall(params[0], JsonHandler.GET);
// parse your json data here
}
I am currently trying to make an android app that basically downloads strings from a url. But I want to make it object oriented. My mainActivity gets string from webService which downloads string when button is clicked. But I am not good at interfaces and callbacks. What should I do to make this code run?
public class MainActivity extends Activity implements WebServiceInterface{
private TextView textView;
private Button readWebPage;
private WebService service;
private WebServiceInterface webServiceInterface;
private String response;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.TextView01);
readWebPage = (Button) findViewById(R.id.readWebpage);
service = new WebService();
readWebPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
service.execute(new String[]{"http://google.com/"});
onSuccess(response);
}
});
}
#Override
public void onSuccess(String response) {
textView.setText(Html.fromHtml(response));
}
#Override
public void onFail(Exception ex) {
textView.setText(ex.getLocalizedMessage());
}
}
public class WebService extends AsyncTask<String, Void, String> {
private WebServiceInterface webServiceInterface;
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
webServiceInterface.onSuccess(response);
} catch (Exception e) {
e.printStackTrace();
webServiceInterface.onFail(e);
}
}
return response;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
public interface WebServiceInterface {
void onSuccess(String response);
void onFail(Exception ex);
}
you need to create one public method for set webServiceInterface in WebService class like
public setWebServiceInterface (WebServiceInterface listener)
{
this.webServiceInterface =listener;
}
in MainActivity activity call this method and pass argument this
service.setWebServiceInterface (this);
in WebService class in onPostExecute Method call
webServiceInterface.onSuccess(s);
Add WebService (WebServiceInterface webServiceInterface) in your AsyncTask as a constructor.
service = new WebService(new WebServiceInterface (){
void onSuccess(String response){
//do your stuff
}
void onFail(Exception ex){
//do your stuff
}
});
and in your asynctask
public class WebService extends AsyncTask<String, Void, String> {
public WebService (WebServiceInterface webServiceInterface){
this.webinterface= webServiceInterface;
}
private WebServiceInterface webinterface;
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
webinterface.onSuccess(response);
} catch (Exception e) {
e.printStackTrace();
webinterface.onFail(e);
}
}
return response;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
I have found the problem, it is because of runOnUiThread is missing.
Pretty new in Android.
The problem here is simple.
My app needs to be waken up in some interval of time.
The problem is that I can`t call it properly.
There in the comment // HERE IS THE PROBLEM the code is breaking giving me error that cant find context and to declare it.
public class BackgroundService extends Service {
Integer background_connect = null;
String SERVER_IP;
String APP_ID;
private Context context;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
DB_Queries db = new DB_Queries(getApplicationContext());
Cursor c = db.getSettings();
StringBuilder app_id = new StringBuilder();
StringBuilder server_ip = new StringBuilder();
if (c.moveToFirst()) {
do {
server_ip.append(c.getString(c.getColumnIndex("server_ip")));
app_id.append(c.getString(c.getColumnIndex("app_id")));
} while (c.moveToNext());
}
db.close();
SERVER_IP = server_ip.toString();
APP_ID = app_id.toString();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
requestServerDelay delay = new requestServerDelay();
delay.execute("http://" + SERVER_IP + "/index.php/app/requestAppRecall");
return super.onStartCommand(intent, flags, startId);
}
private class requestServerDelay extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(params[0]);
post.addHeader("Content-type", "application/x-www-form-urlencoded");
List<NameValuePair> pair = new ArrayList<NameValuePair>();
pair.add(new BasicNameValuePair("app_id", APP_ID));
try {
post.setEntity(new UrlEncodedFormEntity(pair));
HttpResponse response = client.execute(post);
InputStream is = response.getEntity().getContent();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
StringBuilder str = new StringBuilder();
String chunk = null;
while ((chunk = br.readLine()) != null) {
str.append(chunk);
}
background_connect = Integer.parseInt(str.toString());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//HERE IS THE PROBLEM
Intent intent = new Intent(getApplication().getApplicationContext(), getApplication().getApplicationContext().getClass());
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().getApplicationContext().startActivity(intent);
}
}, background_connect * 60 * 1000);
}
}
}
If the requestServerDelay task is in the service, you can use getApplicationContext().startActivity(...) to start an activity.
No need for getApplication() before.
Alternatively You can keep a Context member in the Service class (mContext) and use it.
I am using this class to download txt file
class RetreiveFeedTask extends AsyncTask<String, Void,String> {
#Override
protected ArrayList<Item> doInBackground(String... params) {
try{
URL url = new URL("myurl");
InputStream is = url.openStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String str;
while ((str = in.readLine()) != null){
}
in.close();
return str;
}
catch (MalformedURLException e){}
catch (IOException e){}
return null;
}
protected void onPostExecute(Strin str) {
}
this is how i call this class from my activity:
new RetreiveFeedTask().execute();
And i want to know if there is a way to pass out this result to the activity that make the call.
You can create a listener which you'll pass in the constructor of your AsyncTask. In your onPostExecute you just call this listener.
Something like that:
public interface OnTaskCompleteListener {
void onTaskComplete(String result);
}
protected void onPostExecute(String str) {
onTaskCompleteListener.onTaskComplete(str);
}