Я новичок в модернизации.У меня есть класс SmsListener, который расширяет класс Broadcast Receiver для этого класса для прослушивания сообщения, и когда он получает сообщение, он выполняет над ним некоторые операции.и я использую Retrofit для чтения некоторых данных JSON с локального URL хоста.Я хочу получить результат JSON из onResponse, чтобы использовать его в onReceive. Я определил список массивов, чтобы добавить значения json из метода onResponse.но когда я хочу использовать эти значения в onReceive, это дает мне tr_num: null, я не знаю, почему это происходит.но когда я пытаюсь Записать значения json внутри onResponse, он СОЗДАЕТСЯ УСПЕШНО.и я получаю то, что хочу.но когда я пытаюсь использовать эти значения в onReceive, это дает мне tr_num: null Это мой класс SmsListener
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
public class SmsListener extends BroadcastReceiver {
private SharedPreferences sp;
Context context;
String tr_number = "";
RequestQueue requestQueue;
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
this.context = context;
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Bundle bundle = intent.getExtras(); //---get the SMS message passed in---
SmsMessage[] msgs = null;
String msg_from;
if (bundle != null) {
//---retrieve the SMS message received---
try {
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
msg_from = msgs[i].getOriginatingAddress();
String msgBody = msgs[i].getMessageBody();
Intent intentCall = new Intent(context, MainActivity.class);
getTransactionNumber();
Log.d("ArrayList ", "ArrayList item 1 = " + tr_num.get(1)); // not Loged out
if (msg_from.contains("+249")) {
if (msgBody.contains("1435892")) {
if (msgBody.contains("50")) {
// send Notification to user with success msg
}
} else {
// send Notification to user with error msg
}
} else {
// send Notification to user with DO NOT CHEAT MSG
}
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intentCall, PendingIntent.FLAG_UPDATE_CURRENT);
pendingIntent.send();
}
} catch (Exception e) {
// Log.d("Exception caught",e.getMessage());
}
}
}
}
private String getAmount(String amount) {
return "";
}
ArrayList<String> tr_num;
private void getTransactionNumber() {
RegisterAPI2 registerAPI = ApiClient.getApiClient2().create(RegisterAPI2.class);
//registerAPI.insertUser(msg, amount, tr_number, phone);
Call<TrResponse> req = registerAPI.getTrNum();
req.enqueue(new Callback<TrResponse>() {
@Override
public void onResponse(Call<TrResponse> call, retrofit2.Response<TrResponse> response) {
TrResponse post = response.body();
tr_num = new ArrayList<String>();
tr_num.add(post.getComment().toString());
tr_num.add(post.getTotalCost().toString());
Log.d("CallBack", " response is " + post.getComment().toString()); // successfully Loged out
Log.d("CallBack", " response is " + tr_num.get(1).toString()); // successfully Loged out
//Log.d("CallBack", " response is " + response.toString());
}
@Override
public void onFailure(Call<TrResponse> call, Throwable t) {
Log.d("TTTT CallBack", " Throwable is " + t + " Call " + call.toString());
}
}
);
}
}
, и это мой интерфейс
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
public interface RegisterAPI2 {
// String msg, String phone, String tr_number, String amount
@GET("getTrNumber.php")
Call<TrResponse> getTrNum();
}
и это мой TrResponse POJOКласс
import com.google.gson.annotations.SerializedName;
public class TrResponse {
@SerializedName("Comment")
private String Comment;
@SerializedName("Number_of_people")
private String totalCost;
public String getTotalCost() {
return totalCost;
}
public void setTotalCost(String totalCost) {
this.totalCost = totalCost;
}
public TrResponse(String comment, String totalCost) {
Comment = comment;
this.totalCost = totalCost;
}
public String getComment() {
return Comment;
}
public void setComment(String comment) {
Comment = comment;
}
}
извините за мой английский.Пожалуйста, помогите мне.Заранее спасибо.