java - android调用API后如何返回值(每次调用函数并返回值)?
问题描述
下面是我在Util.java中的代码;
public static String getToken() {
JSONObject postdata = new JSONObject();
try {
AppUtill.getJsonWithHTTPPost(context, 1, new ServiceCallBack() {
@Override
public void serviceCallback(int id, JSONObject jsonResult) {
try {
if (jsonResult.getString("Status").equalsIgnoreCase("Success")) {
JSONObject jsonObject = jsonResult.getJSONObject("Data");
String apptime = jsonObject.optString("apptime");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
Date date1 = dateFormat.parse(apptime);
Date date2 = dateFormat.parse(currentDateandTime);
calendar1.setTime(date1);
calendar2.setTime(date2);
long diff = date1.getTime() - date2.getTime();
long seconds = diff / 1000;
calendar2.add(Calendar.SECOND, (int) seconds);
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
new_date = "FoodHIT" + sdf1.format(calendar2.getTime());
new_date = encryptStringmd5(new_date);
System.out.println("Compare Result : " + seconds);
System.out.println("AppTime: " + jsonObject.optString("apptime"));
System.out.println("token : " + new_date);
Prefs.putString("security_token",new_date);
Log.e("NNNNNNNNNNNNNNNN",""+new_date);
} else {
Toast.makeText(context, jsonResult.getString("Message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}, AppUtill.getapptime, postdata);
} catch (Exception e) {
e.printStackTrace();
}
Log.e("new_date........",""+new_date);
return new_date;
}
在Activity.java文件中,当我调用此函数时,它第一次给出 null;
String token= AppUtill.getToken() // gives null for first time
解决方案
请尝试接口回调功能
Step1: 创建接口
前任。
public interface Result {
public void success(String result);
}
Step2: 创建接口对象
Result result=new Result() {
@Override
public void success(String result) {
String token=result;
// it will return result here....
}
};
将接口对象传递给 getToken() 例如。
AppUtill.getToken(result);
你的方法
public static String getToken(Result result) {
// here your logic to call API
//after result call
result.success(result)//pass your result here
}
推荐阅读
- python - 尝试运行python脚本时出现ansible playbook错误
- swift - 如何与协议共享重用的 UIImageView?
- c++ - 如何在OpenGL中绘制圆点和方点
- git - 从未跟踪的文件和文件夹中清理工作树而不丢失它们
- r - 如何在R中将字符串转换为日期时间格式
- python - 如何本机附加到python进程?
- html - 使用 CSS 排列元素的困难
- laravel - 在 Laravel 中安排任务
- sql-server - 将 Kafka KTable 同步到 SQL 数据库的最简单方法是什么?
- git - Git - 无法拉新更改 - 如何在本地重置所有内容并强制拉当前远程分支?