API请求捕获异常NULL响应

时间:2017-09-27 08:12:57

标签: api null response

我正在使用NYT的开发者电影评论API,我刚开始我只想看到回复。似乎我得到一个NULL响应,它捕获了我将在代码上查明的异常。 “CharSequence text =”发生错误。请再试一次”;”帮你找到它。有人可以告诉我是什么导致了这个问题。

NYT文档链接 http://developer.nytimes.com/movie_reviews_v2.json#/Documentation/GET/critics/%7Bresource-type%7D.json

public class MainActivity extends AppCompatActivity {

    private final String site = "https://api.nytimes.com/svc/movies/v2/reviews/search.json?query=";


    public int count;
    public int i;
    public int j;
    public int k;
    public int n;
    public int comas;
    public int ingadded;

    public String web2 = "";
    public String istos;
    public ArrayList<String> mylist = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Button next = (Button) findViewById(R.id.button);
        final EditText edit_text = (EditText) findViewById(R.id.ing);
        final TextView show_ing = (TextView) findViewById(R.id.show_ing);
        final Button done = (Button) findViewById(R.id.button3);
        final Button refresh = (Button) findViewById(R.id.refresh);
        final Button delete = (Button) findViewById(R.id.delete);
        final ProgressDialog Dialog = new ProgressDialog(MainActivity.this);

        //done move to next activity
        done.setOnClickListener(new View.OnClickListener() {

            @Override

//CHECK IF TEXT BOX IS EMPTY
            public void onClick(View view) {
                web2 = edit_text.getText().toString();
                //check if there are ingredients added
                if (web2 == "") {
                    Context context = getApplicationContext();
                    CharSequence text = "Search Bar is Empty!";
                    int duration = Toast.LENGTH_SHORT;

                    Toast toast = Toast.makeText(context, text, duration);
                    toast.show();
                    Dialog.dismiss();
                }
                else {
//IF NOT CREATE THE LINK AND SEND IT TO LongOperation
                   web2 = edit_text.getText().toString();
                    //create link - MAYBE THE WAY API KEY MUST BE CALLED?
                    istos = site + web2 + "?api-key=xxxxxxxxxxxx";
                    Log.v("Showme=", istos);
                    web2 = "";
                    // WebServer Request URL
                    String serverURL = istos;

                    // Use AsyncTask execute Method To Prevent ANR Problem
                    new LongOperation().execute(serverURL);
                }
                    }



        });

        edit_text.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus)
                    edit_text.setHint("");
                else
                    edit_text.setHint("Type the title of the movie");
            }
        });




    private class LongOperation extends AsyncTask<String, String, Void> {

        // Required initialization

        private final HttpClient Client = new DefaultHttpClient();
        private String Content;
        private String Error = null;
        private Integer count;
        private int add = 1;
        private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
        String data = "";


        TextView jsonParsedname = (TextView) findViewById(R.id.jsonParsedname1);

        ArrayList<ArrayList<Integer>> numArray = new ArrayList<ArrayList<Integer>>();



        int sizeData = 0;

        protected void onPreExecute() {


            //Start Progress Dialog (Message)

            Dialog.setMessage("Finding Movies..");
            Dialog.show();

            try {
                // Set Request parameter
                data = "&" + URLEncoder.encode("data", "UTF-8");

            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        // Call after onPreExecute method
        protected Void doInBackground(String... urls) {

            /************ Make Post Call To Web Server ***********/
            BufferedReader reader = null;

            // Send data
            try {

                // Defined URL  where to send data
                URL url = new URL(urls[0]);

                // Send POST data request

                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);
                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                wr.write(data);
                wr.flush();

                // Get the server response

                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line = "";

                // Read Server Response
                while ((line = reader.readLine()) != null) {
                    // Append server response in string
                    sb.append(line + "");
                }

                // Append Server Response To Content String
                Content = sb.toString();

            } catch (Exception ex) {
                Error = ex.getMessage();
            } finally {
                try {

                    reader.close();
                } catch (Exception ex) {
                }
            }

            /*****************************************************/
            return null;
        }

        protected void onPostExecute(Void unused) {
            // NOTE: You can call UI Element here.

            // Close progress dialog
            Dialog.dismiss();

            if (Error != null) {

                Context context = getApplicationContext();
                CharSequence text = "There was an error. Please try again";
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
                Dialog.dismiss();

            } else {


                JSONObject jsonResponse;

                try {

                    /****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
                    jsonResponse = new JSONObject(Content);

                    if (jsonResponse == null) {
                        jsonParsedname.setText("Wrong Input");
                    }

                    /***** Returns the value mapped by name if it exists and is a JSONArray. ***/
                    /*******  Returns null otherwise.  *******/
                    JSONArray jsonMainNode = jsonResponse.optJSONArray("results");

0 个答案:

没有答案