Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

java - Async task which is trigger in different class and callback function is implemented in different class

I am new to android and java. i have been doing a project in android studio in which i am using Asynctask to extract Location of user and there is a Call back interface to get Location data.

I have looked in to other post regarding asyntask but there the asynctask is triggered in MainActivity and interface is also implemented in that same class. But mine project have 4 different class

1)data_extractor: in this Asynctask is triggered.

2)Async_task : The asynctask is done here.

3)ICallBack : Call back interface.

4)DataCollector : This class has Implemented the ICallBback interface and it will store data in DB.

I am not able to get loc_data in my datacollector class.and also ICallBack i.e is an Interface is returing null.

data_extractor.java

static Context _context = null;
static ICallBackInterface iCallBackInterface;
new IPAsyncTask(iCallBackInterface,_context).execute(struct_data); //fpstruc is class to structure my data


Async_Task.java

public class Async_Task extends AsyncTask<Struct_Data, Void, String> {
private ICallBackInterface iCallBackInterface;
Context context = null;
String data;
Struct_data data_struct= null;
public Async_Task(ICallBackInterface iCallBackInterface,Context context){
    this.iCallBackInterface=iCallBackInterface;
    this.context=context;
}

@Override
protected String doInBackground(Struct_Data... data_struct1) {
    String res = "GPS Data";
   return res;
}

@Override
protected void onPostExecute(String result) {

    try {
String loc=LocationExtractor.addLocation(context, data_struct); //LocationExtractor is returning value.

iCallBackInterface.OnApiCallBAckReceived(loc);

}
catch(Exception e)
Log.e("Error",e);
}

}


ICallBackInterface

public interface ICallBackInterface {
void OnApiCallBAckReceived(String loc_data);
}


DataCollector.java

public class DataCollector implements ICallBackInterface{

Context context;
String data;

@Override
public void OnApiCallBAckReceived(String loc_data) {
 Log.d("CallBackData","Location=>"+loc_data)
}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What is this LocationExtractor class ?
For getting device current location and updates in location, have a look at https://developer.android.com/reference/android/location/LocationListener.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...