试图从服务器获得响应,但它只显示" Toast Server没有响应"

时间:2017-01-06 05:26:44

标签: java android

我正在尝试从服务器获得响应,但它只显示我不支持的吐司服务器。我不明白这里发生了什么。我已经将api分配给我在另一个类中声明的静态变量。

代码:

    public class SpeakersFrag extends Fragment {
    private List<SpeakersBean> dataset;
   // private Context context;
    private ProgressDialog progressDialog;
    SessionContoller sessionContoller;
    RecyclerView recyclerView;
    public  SpeakerAdapter speakerAdapter;
    Context context;
    @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,      Bundle savedInstanceState) {
            super.onCreateView(inflater, container, savedInstanceState);
            View myview=inflater.inflate(R.layout.speakers,null);

            this.context=getActivity();      //cmt ctx
            this.sessionContoller=new SessionContoller(this.context);

            RecyclerView recyclerView = (RecyclerView) myview.findViewById(R.id.Recycler_viewrest);
        // List<String> dataSet=new ArrayList<>();
            recyclerView.setHasFixedSize(true);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this.context);
            recyclerView.setLayoutManager(linearLayoutManager);
            //linearLayoutManager.setOrientation;
            recyclerView.setLayoutManager(linearLayoutManager);
        if (AppStatus.getInstance(this.context).isOnline(this.context)) {
            new GetSpeakerList().execute(new Void[0]);
        } else if (this.sessionContoller.getSpeakerData() != null) {
            setData(this.sessionContoller.getSpeakerData());
        } else {


            Dialog.noInternetAlertBox(this.context);
        }
           // new GetSpeakerList().execute(new Void[0]);
            recyclerView.addOnItemTouchListener(new    RecyclerItemClickListener(this.context,new Listener()));
            return myview;
        }


    class Listener implements RecyclerItemClickListener.ClickListener{
    @Override
    public void onItemClick(View view, int i) {

        SpeakersBean   speakersBean=SpeakersFrag.this.getSpeakerAdapter().getItem(i);
        Intent in=new Intent(SpeakersFrag.this.context,SpeakerDetail.class);
        in.putExtra("speaker", speakersBean);
        startActivity(in);
    }
}


    class GetSpeakerList extends AsyncTask<Void, Void,String> {
        ProgressDialog pd;
        @Override
        protected void onPreExecute() {
           // pd = new ProgressDialog(getActivity()).show(getActivity(), "", "Loading...");
            SpeakersFrag.this.progressDialog = new ProgressDialog(SpeakersFrag.this.context);
            SpeakersFrag.this.progressDialog.setMessage("Loading...");
            SpeakersFrag.this.progressDialog.setCancelable(false);
            SpeakersFrag.this.progressDialog.show();
        }

        @Override
        protected String doInBackground(Void... params) {

            return  SpeakersFrag.this.performPostCallback(Constants.Webservice.SPEAKER_API);
        }

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

            if (!result.equals(BuildConfig.FLAVOR))
            {

                try
                {
                    JSONObject jsonObject = new JSONObject(result);  // set  `  *emphasized text*`status code to continue the webservice as define in constants
                    if (jsonObject.getString("status_code").equals("100") && jsonObject.getString("message").equalsIgnoreCase("Success"))
                    {
                        System.out.println("Speaker data with Json and gson Parsing");
                        sessionContoller = new SessionContoller(getContext());
                        JSONArray jsonArray = jsonObject.getJSONArray("items");  //items
                        SpeakersFrag.this.dataset = (List) new Gson().fromJson(jsonArray.toString()
                                , new TypeToken<List<SpeakersBean>>() {}.getType());
                        SpeakersFrag.this.speakerAdapter = new SpeakerAdapter(SpeakersFrag.this.context, SpeakersFrag.this.dataset);
                        SpeakersFrag.this.recyclerView.setAdapter(SpeakersFrag.this.speakerAdapter);
                        SpeakersFrag.this.sessionContoller.setSpeakerData(jsonArray.toString());
                    }
                } catch (JSONException e)
                    {
                        Log.e("SpeakerFragment", e.toString(), e);
                        // e.printStackTrace();
                    }
            }
            else if (SpeakersFrag.this.sessionContoller.getSpeakerData() != null) {

                SpeakersFrag.this.setData(SpeakersFrag.this.sessionContoller.getSpeakerData());
            }else{
                Toast.makeText(getActivity(),Constants.SERVER_ERROR,Toast.LENGTH_LONG).show();
            }
            SpeakersFrag.dismissDialog(SpeakersFrag.this.progressDialog);
        }
    }
    private void setData(String speakerData){
    JSONException e;
          try {
            JSONArray jsonSpeaker = new JSONArray(speakerData);
            JSONArray jarray;
            {
                try {
                    this.dataset = (List) new Gson().fromJson(jsonSpeaker.toString(), new TypeToken<TypeToken<List<SpeakersBean>>>(){}.getType());
                    this.speakerAdapter = new SpeakerAdapter(SpeakersFrag.this.context, SpeakersFrag.this.dataset);
                    this.recyclerView.setAdapter(this.speakerAdapter);  //add speakerfrag
                    jarray=jsonSpeaker;
                    // ().getType());
                } catch (Exception e1) {

                    jarray = jsonSpeaker;
                    e1.printStackTrace();
                }
            }
        }catch (JSONException e3) {
                e=e3;
            e.printStackTrace();
        }
    }
    public String performPostCallback(String requestURL)
    {
        String response=BuildConfig.FLAVOR;
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        try {
            //send post data request
            HttpURLConnection connection=(HttpURLConnection) new URL(requestURL).openConnection();
            connection.setReadTimeout(15000);
            connection.setConnectTimeout(15000);
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setReadTimeout(15000);
            OutputStream outputStream=connection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new    OutputStreamWriter(outputStream, "UTF-8"));   //UTF-8 encode the string into utf  format
            outputStream.flush();  //flushes the output stream and forces to any buffered device to be written out
            outputStream.close();  //close pd

            if (connection.getResponseCode() != ItemTouchHelper.Callback.DEFAULT_DRAG_ANIMATION_DURATION) {
                return BuildConfig.FLAVOR;
            }
            //Read the server response
            BufferedReader br = new BufferedReader(new     InputStreamReader(connection.getInputStream()));
            while (true) {
                String line = br.readLine();   //read server response
                if (line == null) {
                    return response;
                }

                response = response + line;  //Append response
                System.out.println("Response request====>>>>>"+response);   //response from server
            }
        } catch (Exception e) {
            Log.e("SpeakerFragment", e.toString(), e);
            return response;
        }
    }


        public  SpeakerAdapter getSpeakerAdapter(){
        return  this.speakerAdapter;

    }
       public static void dismissDialog(ProgressDialog pd) {
        if (pd != null) {
            try {
                if (pd.isShowing()) {
                    pd.dismiss();
                }
            } catch (Exception e)
            {
                e.printStackTrace();
            } catch (Throwable th){
                th.printStackTrace();

             }
         }
     }


    ----------


    }

    Blockquote

1 个答案:

答案 0 :(得分:0)

我认为它从服务器端错误....

 Toast.makeText(getActivity(),Constants.SERVER_ERROR,Toast.LENGTH_LONG).show();

此代码正常运行,这就是为什么它显示错误