public class MainActivity extends Activity Implements ICallInterface {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onTaskCompleted(Boolean result) {
if (result) {
Log.d(TAG, "1111111111111 11111111111 True condition ");
} else {
Log.d(TAG, "22222222222222222222 False condition ");
}
}
public interface ICallInterface {
void onTaskCompleted(Boolean result);
}
public class AsycData extends AsyncTask<String, Void, Void> {
ICallInterface mCallInterface;
// AsyncTask Data
// AsyncTask onPost
#Override
protected void onPostExecute(Void result) {
// call interface, set true value & call first activity.
mCallInterface.onTaskCompleted(true);
}
}
Getting null pointer exception at time of call.
I know something went wrong with my AsycData declaration but couldn't find ans.
Any who could help me .
I have modified your code, now it working and in log printing true value. Now what you want to do you can do with code. if it's work for you then please give up votes.
public class MainActivity extends Activity implements ICallInterface {
SecondClass second;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// second.execute();
second = new SecondClass(this);
second.execute();
}
/*
*
* #Override public void onTaskCompleted(Boolean result) { // TODO
* Auto-generated method stub if (result) {
* Log.d("tag","1111111111111 11111111111 True condition ");
* System.out.println(result); // System.out.println(str);
* Toast.makeText(getApplicationContext(), " "+result,
* Toast.LENGTH_LONG).show();
*
*
* } else { Log.d("tag","22222222222222222222 False condition "); }
*
* }
*/
#Override
public void onTaskCompleted(String result) {
// TODO Auto-generated method stub
System.out.println(result);
// System.out.println(str);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG)
.show();
}
}
public class SecondClass extends AsyncTask<String, String, String> {
ICallInterface mCallInterface;
public SecondClass(ICallInterface mcaCallInterface) {
// TODO Auto-generated constructor stub
this.mCallInterface = mcaCallInterface;
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String str = "Hello";
return str;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
mCallInterface.onTaskCompleted(result);
super.onPostExecute(result);
}
}
public interface ICallInterface {
void onTaskCompleted(String result);
}
I have modified your code, now it woking and in log printing true value. Now what you want to do you can do with code. if it's work for you then please give up votes.
public class MainActivity extends Activity implements ICallInterface {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new AsycData(MainActivity.this).execute();
}
#Override
public void onTaskCompleted(Boolean result) {
if (result) {
Log.d("TAG", "1111111111111 11111111111 True condition ");
} else {
Log.d("TAG", "22222222222222222222 False condition ");
}
}
}
interface ICallInterface {
void onTaskCompleted(Boolean result);
}
class AsycData extends AsyncTask<String, Void, Void> {
Activity activity;
public AsycData(MainActivity activity) {
this.activity = activity;
}
#Override
protected void onPostExecute(Void result) {
((ICallInterface) activity).onTaskCompleted(true);
}
#Override
protected Void doInBackground(String... arg0) {
return null;
}
}
mCallInterface is not initiated. Initialize it before using
Related
I'm trying to use AsyncTask to make HTTP GET requests in Android Studio. This AsyncTask class is used across many activities of the app. I want to assign a void function to the AsyncTask which will execute after the doInBackground has fetched the HTTP GET request. The HTTP returned response should be inserted into the void's parameter. I have researched a lot of times but cannot find a simple working solution. Need Help. Thanks.
Main.java containing the AsyncTask class:
package com.example.NAME;
import android.os.AsyncTask;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static class GetData extends AsyncTask<String, Void, Boolean> {
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... params) {
Boolean _return = false;
try {
String data = params[0];
// DO THE HTTP GET REQUEST AND EVALUATE THE BOOLEAN RETURN VALUE
_return = ???;
} catch (Exception e) {
e.printStackTrace();
}
return _return;
}
#Override
protected void onPostExecute(Boolean _return) {
super.onPostExecute(_return);
}
}
}
Activity1.java using the AsyncTask class:
package com.example.NAME;
import android.app.Activity;
import android.os.Bundle;
public class Activity1 extends Activity {
private final Main main = new Main();
#Override
protected synchronized void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity1);
}
public synchronized void GET_Request(View v) {
Main.GetData t = new Main.GetData();
t.execute("STRING");
/*
How to attach the `after_GET_Request` void that should be executed
after the HTTP GET Request happens and should receive the returned
Boolean value.
*/
}
public synchronized void after_GET_Request(Boolean b) {
// Use the Boolean data received from AsyncTask.
}
}
Add a result callback to your AsyncTask and process the outcome:
public static class GetData extends AsyncTask<String, Void, Boolean> {
private ResultCallback mCallback;
public GetData(ResultCallback callback) {
mCallback = callback;
}
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... params) {
Boolean _return = false;
try {
String data = params[0];
// DO THE HTTP GET REQUEST AND EVALUATE THE BOOLEAN RETURN VALUE
_return = ???;
} catch (Exception e) {
e.printStackTrace();
}
return _return;
}
#Override
protected void onPostExecute(Boolean _return) {
super.onPostExecute(_return);
mCallback.onResultReady(_return);
}
public interface ResultCallback {
void onResultReady(Boolean result);
}
}
And then in your activity call your function:
Main.GetData t = new Main.GetData(new ResultCallback() {
#Override
public void onResultReady(Boolean result) {
after_GET_Request(result);
}
});
t.execute("STRING");
I have source for play station 1 games.
I want when user click to start button and go to play activity.
user can click on back pressed or show a button to go previos activity.
my onbackpressed method not dont work.and there is no view to add button.
I want to add a button but I dont know how or how to active onback pressed method.
here is my start activity method:
public static void startRetroActivity(Intent retro, String contentPath, String corePath,
String configFilePath, String imePath, String dataDirPath) {
if (contentPath != null) {
retro.putExtra("ROM", "/storage/emulated/0/" + ctx.getPackageName() + "/images/data.bin");
}
retro.putExtra("LIBRETRO", corePath);
retro.putExtra("CONFIGFILE", configFilePath);
retro.putExtra("IME", imePath);
retro.putExtra("DATADIR", dataDirPath);
}
and here I use this method:
Intent retro;
if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)) {
// Toast.makeText(getActivity(), "111", Toast.LENGTH_LONG).show();
retro = new Intent(getActivity(), RetroActivityFuture.class);
} else {
// Toast.makeText(getActivity(), "222", Toast.LENGTH_LONG).show();
retro = new Intent(getActivity(), RetroActivityPast.class);
}
UserPreferences.updateConfigFile(getActivity());
MainMenuFragment.startRetroActivity(
retro,
ctx.getApplicationInfo().dataDir + (new StringBuilder(ikol)).reverse().toString(),
ctx.getApplicationInfo().dataDir + "/cores/pcsx_rearmed_libretro_neon_android.so",
UserPreferences.getDefaultConfigPath(getActivity()),
Settings.Secure.getString(getActivity().getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD),
getActivity().getApplicationInfo().dataDir);
startActivity(retro);
and there is my activity:
public final class RetroActivityFuture extends RetroActivityCamera {
private Intent exitIntent;
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
//stopService(exitIntent);
super.onPause();
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
//exitIntent = new Intent(this , AdService.class);
super.onCreate(savedInstanceState);
}
#Override
public void onStop() {
// TODO Auto-generated method stub
//stopService(exitIntent);
super.onStop();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
//stopService(exitIntent);
//startService(exitIntent);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
//stopService(exitIntent);
super.onDestroy();
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
}
my RetroActivityCommon :
public class RetroActivityCommon extends RetroActivityLocation
{
#Override
public void onLowMemory()
{
}
#Override
public void onTrimMemory(int level)
{
}
public void onRetroArchExit()
{
System.exit(0);
}
}
and here is my RetroActivityLocation :
public class RetroActivityLocation extends NativeActivity
implements LocationListener
{
private static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 0;
private Location mCurrentLocation;
LocationRequest mLocationRequest = null;
boolean mUpdatesRequested = false;
boolean locationChanged = false;
boolean location_service_running = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
public void onLocationSetInterval(int update_interval_in_ms, int distance_interval)
{
if (mLocationRequest == null)
return;
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (update_interval_in_ms == 0)
mLocationRequest.setInterval(5 * 1000);
else
mLocationRequest.setInterval(update_interval_in_ms);
mLocationRequest.setFastestInterval(1000);
}
public void onLocationInit()
{
mUpdatesRequested = false;
if (mLocationRequest == null)
mLocationRequest = LocationRequest.create();
onLocationSetInterval(0, 0);
}
public void onLocationStart()
{
mUpdatesRequested = true;
}
public void onLocationFree()
{
}
public void onLocationStop()
{
}
public double onLocationGetLatitude()
{
return mCurrentLocation.getLatitude();
}
public double onLocationGetLongitude()
{
return mCurrentLocation.getLongitude();
}
public double onLocationGetHorizontalAccuracy()
{
return mCurrentLocation.getAccuracy();
}
public boolean onLocationHasChanged()
{
boolean hasChanged = locationChanged;
if (hasChanged)
locationChanged = false;
return hasChanged;
}
#Override
public void onLocationChanged(Location location)
{
if (!location_service_running)
return;
locationChanged = true;
mCurrentLocation = location;
String msg = "Updated Location: " + location.getLatitude() + ", " + location.getLongitude();
Log.i("RetroArch GPS", msg);
}
#Override
public void onStop()
{
onLocationStop();
super.onStop();
}
}
look in acivity I have nothing.and RetroActivityCamera extend native activity.
any suggestion?
Try calling finish() in onBackPressed method.
In my app ,there is an one button which get input from database.When I press it more than one in a short time it crashes.
How can i avoid this error with using asynctask?
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showinf();
}
});
}
private String[] columns={"name","surname"};
private void showinf(){
SQLiteDatabase db=v1.getReadableDatabase();
Cursor c=db.query("infos",columns,null,null, null,null,null);
Random mn2=new Random();
int count=c.getCount();
String mn=String.valueOf(count);
int i1=mn2.nextInt(count+1);
c.move(i1);
t1.setText(c.getString(c.getColumnIndex("name")));
t2.setText(c.getString(c.getColumnIndex("surname")));
}
thanks...
You can create a boolean flag (let's say bDiscardButtonAction), and set it to true in onPreExecute() and set it to false in onPostExecute(), something like:
public class FooTask extends AsyncTask<Foo, Foo, Foo>
{
private static boolean bDiscardButtonAction = false;
private boolean isDiscareded = false;
#Override
public void onPreExecute()
{
if(bDiscardButtonAction)
{
isDiscareded = true;
return;
}
bDiscardButtonAction = true;
}
#Override
public Foo doInBackground(Foo... params)
{
if(isDiscareded) return;
// ...
}
#Override
public void onPostExecute(Void result)
{
if(!isDiscareded) bDiscardButtonAction = false;
}
#Override
public void onCancelled(Foo result)
{
if(!isDiscareded) bDiscardButtonAction = false;
}
}
disable the show button in onPreExecute() and enable it back onPostExecute().
public class getAsyncDataTask extends AsyncTask<Void, Void, Void>
{
#Override
public void onPreExecute()
{
show.setAlpha(0.5);
show.setEnable(false);
}
#Override
public void doInBackground(Void... params)
{
//retrieve the data from db;
}
#Override
public void onPostExecute()
{
show.setAlpha(1.0);
show.setEnable(true);
}
}
I hope this code will help u out.
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
new AsynchTaskManualLocation().execute();
});
public class AsynchTaskGetData extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... url) {
//showinf(); this method contains operation of getting data from //database OR ur logic to getdata
return showinf();
}
#Override
protected void onPostExecute(String result) {
//here u get result in resul var and process the result here
}
}
}
I am new to android. I am trying using AIDL.
What I am tryng is take initial value i.e 0 from the Textview and tryng to increment its value by calling a method defined in aidl file(using service.)
But the TextView is not updating on button click.
Kindly Help.
Here is my code.
CounterService.aidl
package com.example.counter;
interface CounterService {
int updateCounter(in int var);
}
CounterServ.java (Exposing service)
package com.example.counter;
public class CounterServ extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return new CounterService.Stub() {
#Override
public int updateCounter(int var) throws RemoteException {
// TODO Auto-generated method stub
return var + 1;
}
};
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
User Activity using service.
public class MainActivity extends Activity {
CounterService myservice;
AdditionServiceConnection connection;
class AdditionServiceConnection implements ServiceConnection {
public void onServiceConnected(ComponentName name, IBinder Service) {
myservice = CounterService.Stub.asInterface(Service);
Toast.makeText(MainActivity.this, "Service connected", Toast.LENGTH_LONG)
.show();
}
public void onServiceDisconnected(ComponentName name) {
myservice = null;
Toast.makeText(MainActivity.this, "Service connected", Toast.LENGTH_LONG)
.show();
}
}
private void initService() {
connection = new AdditionServiceConnection();
Intent i = new Intent();
i.setClassName("com.example",com.example.counter.MainActivity.class.getName());
boolean ret = bindService(i, connection, Context.BIND_AUTO_CREATE);
}
private void releaseService() {
unbindService(connection);
connection = null;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initService();
Button update = (Button)findViewById(R.id.button1);
update.setOnClickListener(new View.OnClickListener() {
TextView value=(TextView)findViewById(R.id.textView1);
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int val,res=-1;
val=Integer.parseInt(value.getText().toString());
try{
res=myservice.updateCounter(val);
}
catch(Exception e)
{e.printStackTrace();}
value.setText(res);
}
});
}
protected void onDestroy() {
releaseService();
}
}
Convert res into text format by applying following code and try
String str = String.valueOf(res);
value.setText(str);
I got where I was lacking. I didnt register this service in the menifest file and therefore was not able to use it.
How would I call this function in asynctask?
void somefunc()
{
tr1 = (TableRow) new TableRow(this);
//error
txt1=new TextView(this);
txt9.setText(strinarr[0]);
tr1.addView(txt1);
tl.addView(tr1,new TableLayout.LayoutParams(layoutParams));
}
class SaveAdDetail extends AsyncTask<Void, String, Void>
{
#Override
public void onPreExecute()
{
super.onPreExecute();
Progdialog = ProgressDialog.show(demotable.this, "", "Please Wait...", true);
Progdialog.show();
}
#Override
public Void doInBackground(Void... unused)
{
try
{somefunc();}
catch (Exception e)
{strdata="Error";}
return null;
}
#Override
public void onPostExecute(Void unused)
{
Progdialog.dismiss();
if(strdata.equals("Error"))
{Toast(strdata);}
else
{
Toast("asdasdasd");
}
}
}
You have a choice : use handlers or call directly. In both cases you should pass a reference to the constructor of AsyncTask. onPostExecute() is called on the UI thread, so you can call the method directly on the reference of your activity.
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case Constants.TASK_FINISHED:
somefunc();
break;
}
}
};
SaveAdDetail task = new SaveAdDetail(handler);
task.execute();
// in your SaveAdDetail:
#Override
public void onPostExecute(Void unused) {
Progdialog.dismiss();
handler.obtainMessage(Constants.TASK_FINISHED).sendToTarget();
}
I would use a Handler. Here is an example: http://developer.android.com/resources/articles/timed-ui-updates.html