Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/390.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何生成响应方法并在主类中调用它_Java_Android_Android Activity - Fatal编程技术网

Java 如何生成响应方法并在主类中调用它

Java 如何生成响应方法并在主类中调用它,java,android,android-activity,Java,Android,Android Activity,我想使用API从服务器访问html,我想在响应中创建一个方法,我想在主类中使用该方法。我正在使用webview在webview中显示输出结果。我正在使用以下代码 public class Dashboard_Description__page extends AppCompatActivity { ImageButton reader_back; ArrayList<Reader_Model> actorsList; String addCat; Ac

我想使用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();

        }

    }

}
public class Dashboard\u Description\u\u页面扩展了AppCompative活动{
图像按钮读取器返回;
ArrayList ActorList;
字符串addCat;
ActorAdapter适配器;
网络视图;
字符串替换id;
字符串书签ID;
字符串书签文件;
私有字符串webData;
字符串mimeType=“text/html”;
字符串编码=“utf-8”;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\仪表板\说明\页面);
WebView WebView=(WebView)findViewById(R.id.WebView);
//String summary=“您得了192分。”;
loadData(getWebData(),“text/html”,null);
如果(savedInstanceState==null){
Bundle extras=getIntent().getExtras();
如果(附加==null){
备用_id=null;
bookmarkid=null;
bookmarkfile=null;
}否则{
alternate_id=extras.getString(“alternateid”);
bookmarkid=extras.getString(“bookmarkid”);
bookmarkfile=extras.getString(“bookmarkfile”);
}
}否则{
alternate_id=(字符串)savedInstanceState.getSerializable(“alternateid”);
bookmarkid=(字符串)savedInstanceState.getSerializable(“bookmarkid”);
bookmarkfile=(字符串)savedInstanceState.getSerializable(“bookmarkfile”);
}
setWebViewClient(新的WebViewClient(){
@凌驾
公共布尔值shouldOverrideUrlLoading(WebView视图,字符串url){
view.loadUrl(url);
返回true;
}
});
//System.out.println(StringCamefromFirstAcvity);
//actorsList=newarraylist();
新建JSONReaderAsyncTask()。执行(“https://www.webo.com/secure-mobile/get_article_detail?“,”访问令牌“,”书签文件“,”备用标识“,”书签标识“;
读卡器返回=(图像按钮)
findViewById(R.id.reader\u back\u btn);
reader\u back.setOnClickListener(新视图.OnClickListener()
{
@凌驾
公共void onClick(视图v){
Intent dash_back=新Intent(getApplicationContext(),Dashboard.class);
起始触觉(后破折号);
}
});
}
公共字符串getWebData(){
返回网络数据;
}
public void setWebData(字符串数据){
this.webData=数据;
}
类JSONReaderAsyncTask扩展了AsyncTask{
进程对话;
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
dialog=新建进度对话框(仪表板描述页面。此页面);
setMessage(“正在加载,请稍候”);
setTitle(“连接服务器”);
dialog.show();
对话框。可设置可取消(false);
}
@凌驾
受保护的布尔doInBackground(字符串…参数)
{
HttpParams httpParameters=新的BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,5000);
HttpConnectionParams.setSoTimeout(httpParameters,5000);
HttpClient HttpClient=新的默认HttpClient(httpParameters);
HttpPost HttpPost=新的HttpPost(参数[0]);
字符串jsonResult=“”;
试一试{
List nameValuePairs=新的ArrayList(4);
添加(新的基本名称对(“访问令牌”,“94529e5dbc6234fc3bbfce7406b8dde9”);
添加(新的BasicNameValuePair(“书签文件”,bookmarkfile));
添加(新的BasicNameValuePair(“备用id”,备用id));
添加(新的BasicNameValuePair(“bookmarkId”,bookmarkId));
//系统输出打印LN(备用标识);
//System.out.println(书签文件);
//System.out.println(书签ID);
setEntity(新的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状态=200;
如果(状态==200){
HttpEntity=response.getEntity();
字符串数据=EntityUtils.toString(实体);
//ArrayList mylist=新的ArrayList();
//添加(数据);
//System.out.println(第一);
系统输出打印项次(数据);
System.out.println(“fffff”);
//这里的结果来自服务器。我想要一个可以在主类中使用的方法。我想要使用webview以html形式查看此结果。
//JSONObject jsono=新的JSONObject(数据);
//JSONArray jarray=jsono.getJSONArray(“内容”);
}
返回true;
//------------------>>
}捕获(解析异常e1){
e1.printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}捕获(JSONException e){
e、 printStackTrace();
}
返回false;
}
受保护的void onPostExecute(布尔结果){
dialog.cancel();
//adapter.notifyDataSetChanged();
如果(结果==false)
Toast.makeText(getAp
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;
}
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();
        }
    }
}