如何制作响应方法并在主类中调用它

时间:2016-03-23 11:08:49

标签: java android android-activity

我想使用API​​从服务器访问html,我想在响应中创建一个方法,该方法我想在主类中使用它。我使用webview在webview中显示输出结果。以下代码我在用。

public class Dashboard_Description__page extends AppCompatActivity {
    ImageButton reader_back;
    ArrayList<Reader_Model> actorsList;
    String addCat;
    ActorAdapter adapter;


    WebView webView;
    String alternate_id;
    String bookmarkid;
    String bookmarkfile;
    private String webData;


    String mimeType = "text/html";
    String encoding = "utf-8";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard__description__page);
        WebView webView = (WebView) findViewById(R.id.webview);

        // String summary = "<html><body>You scored <b>192</b> points.</body></html>";
        webView.loadData(getWebData(), "text/html", null);



        if (savedInstanceState == null) {
            Bundle extras = getIntent().getExtras();

            if(extras == null) {
                alternate_id= null;
                bookmarkid= null;
                bookmarkfile = null;
            } else {
                alternate_id= extras.getString("alternateid");
                bookmarkid= extras.getString("bookmarkid");
                bookmarkfile = extras.getString("bookmarkfile");

            }
        } else {
            alternate_id= (String) savedInstanceState.getSerializable("alternateid");
            bookmarkid= (String) savedInstanceState.getSerializable("bookmarkid");
            bookmarkfile= (String) savedInstanceState.getSerializable("bookmarkfile");

        }
        webView.setWebViewClient(new WebViewClient() {
            @Override


            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);


                return true;
            }

        });
            // System.out.println(stringCameFromFirstAcvitity);

      //  actorsList = new ArrayList<Actors>();
        new JSONReaderAsyncTask().execute("https://www.webo.com/secure-mobile/get_article_detail?", " access_token","bookmark_file","alternate_id","bookmarkId");

    reader_back=(ImageButton)

    findViewById(R.id.reader_back_btn);

    reader_back.setOnClickListener(new View.OnClickListener()

    {
        @Override
        public void onClick (View v) {
                Intent dash_back = new Intent(getApplicationContext(),Dashboard.class);
                startActivity(dash_back);

            }
        });


    }

    public String getWebData() {


        return webData;
    }

    public void setWebData(String data) {
        this.webData = data;
    }

    class JSONReaderAsyncTask extends AsyncTask<String, Void, Boolean> {

        ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(Dashboard_Description__page.this);
            dialog.setMessage("Loading, please wait");
            dialog.setTitle("Connecting server");
            dialog.show();
            dialog.setCancelable(false);


        }

        @Override
        protected Boolean doInBackground(String... params)
        {
            HttpParams httpParameters = new BasicHttpParams();

            HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);

            HttpConnectionParams.setSoTimeout(httpParameters, 5000);
            HttpClient httpClient = new DefaultHttpClient(httpParameters);

            HttpPost httpPost = new HttpPost(params[0]);
            String jsonResult = "";
            try {

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);

                nameValuePairs.add(new BasicNameValuePair("access_token", "94529e5dbc6234fc3bbfce7406b8dde9"));
                nameValuePairs.add(new BasicNameValuePair("bookmark_file", bookmarkfile));
                nameValuePairs.add(new BasicNameValuePair("alternate_id", alternate_id));
                nameValuePairs.add(new BasicNameValuePair("bookmarkId", bookmarkid));

               // System.out.println(alternate_id);
                //System.out.println(bookmarkfile);
               // System.out.println(bookmarkid);
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpClient.execute(httpPost);
                // System.out.println("hello Hitu");

                //  jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
                // System.out.println(jsonResult);
                // StatusLine stat = response.getStatusLine();
                int status = 200;

                if (status == 200) {
                    HttpEntity entity = response.getEntity();
                    String data = EntityUtils.toString(entity);
                  //  ArrayList<String> mylist = new ArrayList<String>();
                   // mylist.add(data);
                   // System.out.println(first);


                    System.out.println(data);
                    System.out.println("fffff");

                    //here result is coming from the server. I want here a method which can be used in main class.I want to view this result in html form using webview. 


                   // JSONObject jsono = new JSONObject(data);
                   // JSONArray jarray = jsono.getJSONArray("content");

                    }
                    return true;


                //------------------>>

            } catch (ParseException e1) {
                e1.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return false;
        }

        protected void onPostExecute(Boolean result) {
            dialog.cancel();
           // adapter.notifyDataSetChanged();
            if(result == false)
                Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();

        }

    }

}

2 个答案:

答案 0 :(得分:0)

public class HttpClientWrapper {

public static String  post(String requestUrl,String postValues) {

    URL url;
    String response = "";

    try {
        url = new URL(requestUrl);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);// Specifies whether this URLConnection allows receiving data.
        conn.setDoOutput(true);// Specifies whether this URLConnection allows sending data.
        conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        conn.setRequestProperty("Accept", "application/json; charset=utf-8");



        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        writer.write(postValues);

        writer.flush();
        writer.close();
        os.close();
        int responseCode=conn.getResponseCode();

        if (responseCode == HttpsURLConnection.HTTP_OK) {
            String line="";
            BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            StringBuilder sb = new StringBuilder();
            while ((line=br.readLine()) != null) {

                sb.append(line+"\n");
                response = sb.toString().substring(0, sb.toString().length() - 1);
            }
        }
        else {
            response="";
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return response;
}




public static String getResponseGET(String url) {

    String response = "";
    HttpURLConnection c = null;

    try {
        URL u = new URL(url);
        c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setConnectTimeout(15000);
        c.setReadTimeout(15000);

        c.connect();
        int status = c.getResponseCode();

        switch (status) {
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                    response = sb.toString().substring(0, sb.toString().length() - 1);
                }
                br.close();
                return response;
        }

    } catch (IOException ex) {
        if (c != null) {
            c.disconnect();
        }
    } finally {
        if (c != null) {
            try {
                c.disconnect();
            } catch (Exception ex) {

            }
        }
    }
    return null;
}

}

答案 1 :(得分:0)

private class RegistrationAsyncTask extends AsyncTask<Void, Void, String> {
    ProgressDialog dialog;
    Context mContext;
    String error;
    String response;
    String mData;

    public RegistrationAsyncTask(Context context,String data) {
        this.mContext = context;
        this.error = "";
        this.mData = data;
    }

    @Override
    protected void onPreExecute() {
        dialog = new ProgressDialog(mContext);
        dialog.setTitle("Registration");
        dialog.setMessage("Registration in process...");
        dialog.setCancelable(false);
        dialog.show();
    }

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

            response = HttpClientWrapper.post(URL.URL_REGISTRATION, mData);
            Log.e(TAG, "Response: " + response);
        } catch (Exception e) {
            e.printStackTrace();
            this.error = e.getMessage();
        }
        return response;
    }

    @Override
    protected void onPostExecute(String result) {
        Log.e(TAG, "result: " + response);

        if (dialog.isShowing()) {
            dialog.dismiss();
        }

        if (response.isEmpty()){

            Utils.message(getActivity(), getResources().getString(R.string.error_server));
            return;
        }

        try {
            JSONObject jsonObject = new JSONObject(result);
            if (jsonObject.has("error")) {
                String error = jsonObject.getString("error");
                JSONObject jsonObject1 = new JSONObject(error);
                String message = jsonObject1.getString("message");

                Utils.showDialog(mContext, alert, alertDialog, getResources().getString(R.string.text_title_reg),message);

                return;
            } else {

                String error = jsonObject.getString("success");
                JSONObject jsonObject1 = new JSONObject(error);
                String message = jsonObject1.getString("message");

                alert = new AlertDialog.Builder(getActivity());
                alert.setTitle(R.string.text_title_reg);
                alert.setMessage(message);
                alert.setCancelable(false);

                alert.setPositiveButton("OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(
                                    DialogInterface dialog,
                                    int whichButton) {
                                clearForm();
                                dialog.dismiss();
                            }
                        });

                alertDialog = alert.create();
                alertDialog.show();
            }

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