gpt4 book ai didi

java - android调用API后如何返回值(每次调用函数并返回值)?

转载 作者:行者123 更新时间:2023-12-01 19:41:08 25 4
gpt4 key购买 nike

下面是我在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

最佳答案

请尝试接口(interface)回调功能

第一步:创建一个界面

例如。

public interface Result {

public void success(String result);
}

第二步:创建接口(interface)对象

    Result result=new Result() {

@Override
public void success(String result) {
String token=result;
// it will return result here....

}
};

将接口(interface)对象传递给 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
}

关于java - android调用API后如何返回值(每次调用函数并返回值)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55371041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com