我不能在onReceive()中的onResponse()之外使用json结果 - Retrofit

时间:2018-06-07 17:49:34

标签: java android retrofit2

我是Retrofit的新手。 我有SmsListener类,它扩展了Broadcast Receiver类,这个类用于侦听消息,当它获取消息时,它将对它进行一些操作。 我正在使用Retrofit从本地主机URL读取一些json数据。 我想从onResponse获取JSON结果,以便在onReceive中使用它 我定义了一个数组列表来从onResponse方法添加json值。 但是当我想在onReceive中使用这个值时,它给了我tr_num:null 我不知道为什么会这样。但是当我试图在onResponse中记录json值时,它是LOGED SUCCESSFULLY。 我得到了我想要的东西。但是当我试图在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 Class

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;
}
}
抱歉我的英语。 请帮我。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

我在onResponse里面做了我的操作。 这在24小时搜索后解决了我的问题。