Android asynctask doinbackground返回null

时间:2018-12-11 04:56:44

标签: java android android-asynctask

我正在使用 Google Search Console API 从服务器获取数据,在调试时我知道,尽管我从服务器获取响应,但未反映在onPostExecute();中,然后我还在onDoInBackground()中创建了一个随机字符串,该字符串也没有传递,并且onPostExecute()在控制台中显示了“ 未找到”。

请帮助解决此错误,谢谢。

代码:

public class FragmentStatistics extends Fragment implements AdapterView.OnItemSelectedListener {

View view;
Spinner statsSpinner;
String duration;
static String jsonclick, jsonposition,jsonimpressions, jsonctra;
static TextView clk;
static TextView imp;
static TextView ctr;
static TextView pos;
private static String yesterday,starDay ,dayBefore;
private static Double ctrpercent,posDouble, clicksDouble, impDouble;
//static CardView card1,card2,card3,card4;
static CardView errorCard;
static TextView errorText, siteNameText;
static ImageView prevResultImage, prevImpImage,prevCtrImage,prevPosImage;
static TextView prevResult, prevImp, prevPos, prevCtr;
static LinearLayout liClicks,liImp,liPos,liCtr;
ProgressBar FragProgressBar;

public FragmentStatistics() {
    // Required empty public constructor
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    //Yesterday {END POINT}
    Calendar yester = Calendar.getInstance();
    yester.add(Calendar.DATE, -3);
    yesterday = dateFormat.format(yester.getTime());

    //StartDate
    Calendar start = Calendar.getInstance();
    start.add(Calendar.DATE,-3);
    starDay = dateFormat.format(start.getTime());

    //Day before {END POINT}
    Calendar dayBF = Calendar.getInstance();
    dayBF.add(Calendar.DATE, -4);
    dayBefore = dateFormat.format(dayBF.getTime());

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    view = inflater.inflate(R.layout.fragment_fragment_statistics, container, false);

    statsSpinner = view.findViewById(R.id.statsSpinner);
    clk = view.findViewById(R.id.clicks);
    imp = view.findViewById(R.id.impressions);
    ctr = view.findViewById(R.id.ctr);
    pos = view.findViewById(R.id.position);
    prevResult = view.findViewById(R.id.prev_result);
    prevResultImage = view.findViewById(R.id.prev_result_image);
    prevImp = view.findViewById(R.id.prev_imp);
    prevImpImage = view.findViewById(R.id.imp_image);
    prevCtr = view.findViewById(R.id.prev_ctr);
    prevCtrImage = view.findViewById(R.id.ctr_image);
    prevPos = view.findViewById(R.id.prev_pos);
    prevPosImage = view.findViewById(R.id.pos_image);
    liClicks=view.findViewById(R.id.LinearClicksYes);
    liCtr=view.findViewById(R.id.LinearCtrYes);
    liImp=view.findViewById(R.id.LinearImpYes);
    liPos=view.findViewById(R.id.LinearPosYes);
    errorCard = view.findViewById(R.id.error_card);
    errorText = view.findViewById(R.id.error_text);
    FragProgressBar = view.findViewById(R.id.FragProgressBar);
    FragProgressBar.setVisibility(View.INVISIBLE);
    siteNameText = view.findViewById(R.id.site_name);

    statsSpinner.setOnItemSelectedListener(this);
    statsSpinner.setSelection(0);
    duration = statsSpinner.getSelectedItem().toString();


    //Calling AsyncTask postRequest
    if(MainActivity.ExpiryTime == null || System.currentTimeMillis() > MainActivity.ExpiryTime){
        Intent intent = new Intent(view.getContext(),MainActivity.class);
        startActivity(intent);
    } else {

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                new postRequest().execute();
               // callforpost();

            }
        },100);

        new android.os.Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                new DayBeforeRequest().execute();
            }
        },1000);
    }



    return view;


}

@Override
public void onItemSelected(AdapterView<?> parent, View mView, int position, long id) {


    duration = parent.getItemAtPosition(position).toString();
    //Date Formatting
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    //Yesterday {END POINT}
    Calendar yester = Calendar.getInstance();
    yester.add(Calendar.DATE, -3);
    yesterday = dateFormat.format(yester.getTime());

    if(duration.equals("Recent Date")) {
        //StartDate
        Calendar start = Calendar.getInstance();
        start.add(Calendar.DATE,-3);
        starDay = dateFormat.format(start.getTime());

        //Day before {END POINT}
        Calendar dayBF = Calendar.getInstance();
        dayBF.add(Calendar.DATE, -4);
        dayBefore = dateFormat.format(dayBF.getTime());

    } else if(duration.equals("Last Week vs Previous Week")){

        //StartDate
        Calendar start = Calendar.getInstance();
        start.add(Calendar.DATE,-9);
        starDay = dateFormat.format(start.getTime());

        //PrevDate
        Calendar prevStart = Calendar.getInstance();
        prevStart.add(Calendar.DATE,-15);
        dayBefore = dateFormat.format(prevStart.getTime());

    }

    if(MainActivity.ExpiryTime == null || System.currentTimeMillis() > MainActivity.ExpiryTime){
        Intent intent = new Intent(view.getContext(),MainActivity.class);
        startActivity(intent);
    } else {
    new postRequest().execute();
   // callforpost();
    }

}

@Override
public void onNothingSelected(AdapterView<?> parent) {

}

//AsyncTask to get Data

public class postRequest extends AsyncTask<String,Void,String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        FragProgressBar.setVisibility(View.VISIBLE);

        if(clk != null){
            clk.setText(getString(R.string.fetching_data));
            imp.setText(getString(R.string.fetching_data));
            ctr.setText(getString(R.string.fetching_data));
            pos.setText(getString(R.string.fetching_data));
        }
        //fragPB.setProgress(25);
    }

    @Override
    protected String doInBackground(String... strings) {

       // String responseString = "Blaah";
        final MediaType mediaType = MediaType.parse("application/json");
        String jsonStr = "{ \"startDate\": \"" + starDay +"\", \"endDate\": \"" + yesterday + "\"}";
        OkHttpClient OKHttpClient = new OkHttpClient();
        Request OKpostReq = new Request.Builder()
                .url("https://www.googleapis.com/webmasters/v3/sites/" + MainData.siteName + "searchAnalytics/query" + "?access_token=" + MainActivity.Authcode)
                .post(RequestBody.create(mediaType, jsonStr))
                .build();

        try {
            Response response=OKHttpClient.newCall(OKpostReq).execute();
            assert response.body() != null;
            //data is returned to onPostExecute over here
           // This is not getting captured though, response from server is OK.            
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String postDatareceived) {
        super.onPostExecute(postDatareceived);

        Toast.makeText(view.getContext(),postDatareceived,Toast.LENGTH_LONG).show();

        DecimalFormat formatter = new DecimalFormat("###,###,###,###,###");
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(postDatareceived);
            if(jsonObject.has("rows")){
                errorCard.setVisibility(View.GONE);
                JSONArray jsonArray = jsonObject.getJSONArray("rows");
                for(int i = 0; i < jsonArray.length(); i++ ) {
                    JSONObject rows = jsonArray.getJSONObject(i);
                    jsonclick = rows.getString("clicks");
                    clicksDouble = Double.parseDouble(jsonclick);
                    String formatClick = formatter.format(clicksDouble);
                    jsonclick = formatClick;


                    jsonimpressions = rows.getString("impressions");
                    impDouble = Double.parseDouble(jsonimpressions);
                    String formatimpression = formatter.format(impDouble);
                    jsonimpressions = formatimpression;


                    jsonctra = rows.getString("ctr");
                    ctrpercent = Double.parseDouble(jsonctra) * 100;
                    jsonctra = String.format("%.2f", ctrpercent);
                    jsonctra = jsonctra + "%";

                    jsonposition = rows.getString("position");
                    posDouble = Double.parseDouble(jsonposition);
                    jsonposition = String.format("%.2f", posDouble);


                    clk.setText(jsonclick);
                    imp.setText(jsonimpressions);
                    ctr.setText(jsonctra);
                    pos.setText(jsonposition);


                    FragProgressBar.setVisibility(View.INVISIBLE);

                }} else  if(jsonObject.has("error") && clk != null){
                JSONObject errorcodes = jsonObject.getJSONObject("error");
                String msg = errorcodes.getString("message");
                String errCoode = errorcodes.getString("code");
                errorCard.setVisibility(View.VISIBLE);
                String ErrorMessage = "ERROR " + errCoode + ": " + msg;
                errorText.setText(ErrorMessage);
                clk.setText("No Data");
                imp.setText("No Data");
                ctr.setText("No Data");
                pos.setText("No Data");

                Toast.makeText(view.getContext(), errCoode + " " + msg, Toast.LENGTH_LONG).show();
                FragProgressBar.setVisibility(View.INVISIBLE);

            } else if ((!(jsonObject.has("error")) && clk != null && (!jsonObject.has("rows")))){

                clk.setText("Data currently unavailable.");
                imp.setText("Data currently unavailable.");
                ctr.setText("Data currently unavailable.");
                pos.setText("Data currently unavailable.");
                FragProgressBar.setVisibility(View.INVISIBLE);

            } else if (jsonObject == null){
                Toast.makeText(view.getContext(), getString(R.string.no_sm), Toast.LENGTH_LONG).show();
            }


        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

}

public class DayBeforeRequest extends AsyncTask<String,Void,String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        if(prevResult != null){

            prevResult.setText(getString(R.string.fetching_data));
            prevResult.setTextColor(Color.parseColor("#fc9b00"));
            prevResultImage.setBackgroundResource(R.drawable.noc);
            prevImp.setText(getString(R.string.fetching_data));
            prevImp.setTextColor(Color.parseColor("#fc9b00"));
            prevImpImage.setBackgroundResource(R.drawable.noc);
            prevCtr.setText(getString(R.string.fetching_data));
            prevCtr.setTextColor(Color.parseColor("#fc9b00"));
            prevCtrImage.setBackgroundResource(R.drawable.noc);
            prevPos.setText(getString(R.string.fetching_data));
            prevPos.setTextColor(Color.parseColor("#fc9b00"));
            prevPosImage.setBackgroundResource(R.drawable.noc);

        }
    }

    @Override
    protected String doInBackground(String... strings) {

        final MediaType mediaType = MediaType.parse("application/json");
        String jsonStr = "{ \"startDate\": \"" + dayBefore +"\", \"endDate\": \"" + starDay + "\"}";
        OkHttpClient dayBefore = new OkHttpClient();
        Request beforeRequest = new Request.Builder()
                .url("https://www.googleapis.com/webmasters/v3/sites/" + MainData.siteName + "/searchAnalytics/query" + "?access_token=" + MainActivity.Authcode)
                .post(RequestBody.create(mediaType, jsonStr))
                .build();

        try {
            Response response=dayBefore.newCall(beforeRequest).execute();
            assert response.body() != null;
            //data is returned to onPostExecute over here
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String postDatareceived) {
        super.onPostExecute(postDatareceived);


        DecimalFormat formatter = new DecimalFormat("###,###,###,###,###");
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(postDatareceived);
            if(jsonObject.has("rows") && clicksDouble != null){
                JSONArray jsonArray = jsonObject.getJSONArray("rows");
                for(int i = 0; i < jsonArray.length(); i++ ){
                    JSONObject rows = jsonArray.getJSONObject(i);

                    String oldClick = rows.getString("clicks");
                    Double prev_clicks = Double.parseDouble(oldClick);
                    //String formatClick = formatter.format(clicks);
                    //Double curr_clicks = Double.parseDouble(jsonclick);
                    Double resultClicks = clicksDouble - prev_clicks;
                    String formatresult = formatter.format(resultClicks);
                    Double percentClicks = ((resultClicks/prev_clicks) * 100);
                    String formatClicksCent = String.format("%.2f",percentClicks) + " %";

                    if(resultClicks > 0 ){
                        String ClicksResultPost = formatresult +  getString(R.string.more_aka) + " "+ formatClicksCent + " " + getString(R.string.inc);
                        prevResultImage.setBackgroundResource(R.drawable.inc);
                        prevResult.setTextColor(Color.parseColor("#00d683"));
                        prevResult.setText(ClicksResultPost);
                    } else if(resultClicks < 0){
                        String ClicksResultPost = formatresult  + getString(R.string.less_aka) + " "+  formatClicksCent + " " + getString(R.string.dec);
                        prevResultImage.setBackgroundResource(R.drawable.dec);
                        prevResult.setTextColor(Color.parseColor("#e30024"));
                        prevResult.setText(ClicksResultPost);
                    } else {
                        String ClicksResultPost = formatresult + " " + getString(R.string.nc);
                        prevResultImage.setBackgroundResource(R.drawable.noc);
                        prevResult.setTextColor(Color.parseColor("#ffbc00"));
                        prevResult.setText(ClicksResultPost);
                    }

                    String oldImpression = rows.getString("impressions");
                    Double impressionss = Double.parseDouble(oldImpression);
                    //Double currImpressions = Double.parseDouble(jsonimpressions);
                    Double resultImpressions = impDouble - impressionss;
                    String formatImp = formatter.format(resultImpressions);
                    Double percentImp = ((resultImpressions/impressionss) * 100);
                    String formatImpCent = String.format("%.2f",percentImp) + " %";

                    if(resultImpressions > 0){
                        String ImpResultPost = formatImp +  getString(R.string.more_aka) + " "+ formatImpCent + " " + getString(R.string.inc);
                        prevImp.setText(ImpResultPost);
                        prevImp.setTextColor(Color.parseColor("#00d683"));
                        prevImpImage.setBackgroundResource(R.drawable.inc);
                    } else if (resultImpressions < 0){
                        String ImpResultPost = formatImp  + getString(R.string.less_aka) + " "+  formatImpCent + " " + getString(R.string.dec);
                        prevImp.setText(ImpResultPost);
                        prevImp.setTextColor(Color.parseColor("#e30024"));
                        prevImpImage.setBackgroundResource(R.drawable.dec);
                    } else{
                        String ImpResultPost = formatImp + " " + getString(R.string.nc);
                        prevImpImage.setBackgroundResource(R.drawable.noc);
                        prevImp.setTextColor(Color.parseColor("#ffbc00"));
                        prevImp.setText(ImpResultPost);
                    }

                    String oldCtra = rows.getString("ctr");
                    Double oldctrpercent = Double.parseDouble(oldCtra)*100;
                    Double resultCTR = ctrpercent - oldctrpercent;
                    String resultCTRStr = String.format("%.2f",resultCTR);
                    Double percentCTR = ((resultCTR / oldctrpercent)*100);
                    String formatPercentCTR = String.format("%.2f",percentCTR) + " %";

                    if(resultCTR > 0){
                        String ctrResultPost = resultCTRStr + getString(R.string.more_aka) + " "+ formatPercentCTR + " " + getString(R.string.inc);
                        prevCtr.setText(ctrResultPost);
                        prevCtr.setTextColor(Color.parseColor("#00d683"));
                        prevCtrImage.setBackgroundResource(R.drawable.inc);
                    } else if (resultCTR < 0){
                        String ctrResultPost = resultCTRStr + getString(R.string.less_aka) + " "+ formatPercentCTR + " " + getString(R.string.dec);
                        prevCtr.setText(ctrResultPost);
                        prevCtr.setTextColor(Color.parseColor("#e30024"));
                        prevCtrImage.setBackgroundResource(R.drawable.dec);
                    } else{
                        String ctrResultPost = resultCTRStr + " " + getString(R.string.nc);
                        prevCtrImage.setBackgroundResource(R.drawable.noc);
                        prevCtr.setTextColor(Color.parseColor("#ffbc00"));
                        prevCtr.setText(ctrResultPost);
                    }

                    String oldPos = rows.getString("position");
                    Double OldposDouble = Double.parseDouble(oldPos );
                    Double resultPos = posDouble - OldposDouble;
                    String resultPosStr = String.format("%.2f",resultPos);
                    Double posPercent = ((resultPos / OldposDouble)*100);
                    String FormatPosPercent = String.format("%.2f",posPercent) + " %";

                    if(resultPos > 0){
                        String posResultPost = resultPosStr + getString(R.string.more_aka) + " "+ FormatPosPercent + " " + getString(R.string.inc);
                        prevPos.setText(posResultPost);
                        prevPos.setTextColor(Color.parseColor("#00d683"));
                        prevPosImage.setBackgroundResource(R.drawable.inc);
                    } else if (resultPos < 0){
                        String posResultPost = resultPosStr +  getString(R.string.less_aka) + " "+ formatPercentCTR + " " + FormatPosPercent + " " + getString(R.string.dec);
                        prevPos.setText(posResultPost);
                        prevPos.setTextColor(Color.parseColor("#e30024"));
                        prevPosImage.setBackgroundResource(R.drawable.dec);
                    } else{
                        String posResultPost = resultPosStr + getString(R.string.nc);
                        prevPosImage.setBackgroundResource(R.drawable.noc);
                        prevPos.setTextColor(Color.parseColor("#ffbc00"));
                        prevPos.setText(posResultPost);
                    }


                }} else if(jsonObject.has("error") && prevResult != null){

                prevResult.setText(getString(R.string.data_insuff));
                prevResult.setTextColor(Color.parseColor("#e30024"));
                prevImp.setText(getString(R.string.data_insuff));
                prevImp.setTextColor(Color.parseColor("#e30024"));
                prevCtr.setText(getString(R.string.data_insuff));
                prevCtr.setTextColor(Color.parseColor("#e30024"));
                prevPos.setText(getString(R.string.data_insuff));
                prevPos.setTextColor(Color.parseColor("#e30024"));




            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
}

0 个答案:

没有答案
相关问题