1

次のコードを使用しましたが、Asyntask の実行時にエラーが発生し、JsonParser クラスも投稿しました。このエラーを削除する方法を教えてください。

        public class Login extends Activity implements OnClickListener {

            private EditText user, pass;
            private Button mSubmit, mRegister;
            private ProgressDialog pDialog;
            // JSON parser class
            JSONParser jsonParser = new JSONParser();
             private static final String LOGIN_URL = "http://******/web_service/index.php";
           //www.itsoft-solutions.net
            //JSON element ids from repsonse of php script:
            private static final String TAG_SUCCESS = "success";
            private static final String TAG_MESSAGE = "message";
            public static String uname;
            public static String password;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                // TODO Auto-generated method stub
                super.onCreate(savedInstanceState);
                setContentView(R.layout.login);
                String uName, pwd;
                //setup input fields
                user = (EditText) findViewById(R.id.username);
                pass = (EditText) findViewById(R.id.password);
                //setup buttons
                mSubmit = (Button) findViewById(R.id.login);
                mRegister = (Button) findViewById(R.id.register);
                //register listeners
                mSubmit.setOnClickListener(this);
                mRegister.setOnClickListener(this);

            }

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                switch (v.getId()) {
                    case R.id.login:
                         new AttemptLogin(user.getText().toString(), pass.getText().toString()).execute();
                        break;
                    case R.id.register:
                        Intent i = new Intent(this, Register.class);
                        startActivity(i);
                        break;

                    default:
                        break;
                }
            }

Asyntask クラスも投稿しました

            class AttemptLogin extends AsyncTask<String, String, String> {

                boolean failure = false;
                String uName, pwd;
                public AttemptLogin(String userName, String password) {
                    uName = userName;
                    pwd = password;
                }

                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    pDialog = new ProgressDialog(Login.this);
                    pDialog.setMessage("Attempting login...");
                    pDialog.setIndeterminate(false);
                    pDialog.setCancelable(true);
                    pDialog.show();
                }

                @Override
                protected String doInBackground(String... args) {
                    // TODO Auto-generated method stub
                    // Check for success tag
                    int success;

                    try {
                        // Building Parameters
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair("username", uName));
                        params.add(new BasicNameValuePair("password", pwd));

                        Log.d("request!", "starting");
                        // getting product details by making HTTP request
                        JSONObject json = jsonParser.makeHttpRequest(
                                LOGIN_URL, "POST", params);

                        // check your log for json response
                        Log.d("Login attempt", json.toString());

                        // json success tag
                        success = json.getInt(TAG_SUCCESS);
                        if (success == 1) {
                            Log.d("Login Successful!", json.toString());
                            Intent i = new Intent(Login.this, ReadComments.class);
                            finish();
                            startActivity(i);
                            return json.getString(TAG_MESSAGE);
                        } else {
                            Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                            return json.getString(TAG_MESSAGE);

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

                    return null;

                }

                /**
                 * After completing background task Dismiss the progress dialog
                 **/
                protected void onPostExecute(String file_url) {
                    // dismiss the dialog once product deleted
                    pDialog.dismiss();
                    if (file_url != null) {
                        Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
                    }

                }

            }

        }

JSONParser.java 内の次のコード

        package com.example.mysqltest;

        public class JSONParser {

            static InputStream is = null;
            static JSONObject jObj = null;
            static String json = "";

            // constructor
            public JSONParser() {

            }

            // function get json from url
            // by making HTTP POST or GET mehtod
            public JSONObject makeHttpRequest(String url, String method,
                    List<NameValuePair> params) {

                // Making HTTP request
                try {

                    // check for request method
                    if(method == "POST"){
                        // request method is POST
                        // defaultHttpClient
                        DefaultHttpClient httpClient = new DefaultHttpClient();
                        HttpPost httpPost = new HttpPost(url);
                        httpPost.setEntity(new UrlEncodedFormEntity(params));

                        HttpResponse httpResponse = httpClient.execute(httpPost);
                        HttpEntity httpEntity = httpResponse.getEntity();
                        is = httpEntity.getContent();

                    }else if(method == "GET"){
                        // request method is GET
                        DefaultHttpClient httpClient = new DefaultHttpClient();
                        String paramString = URLEncodedUtils.format(params, "utf-8");
                        url += "?" + paramString;
                        HttpGet httpGet = new HttpGet(url);

                        HttpResponse httpResponse = httpClient.execute(httpGet);
                        HttpEntity httpEntity = httpResponse.getEntity();
                        is = httpEntity.getContent();
                    }           

                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(
                            is, "iso-8859-1"), 8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    is.close();
                    json = sb.toString();
                } catch (Exception e) {
                    Log.e("Buffer Error", "Error converting result " + e.toString());
                }

                // try parse the string to a JSON object
                try {
                    jObj = new JSONObject(json);
                } catch (JSONException e) {
                    Log.e("JSON Parser", "Error parsing data " + e.toString());
                }

                // return JSON String
                return jObj;

            }
        }

次のライブラリをプロジェクトに含めました。

    1. httpclient-4.5.jar
    2. httpcore-4.4.1.jar

以下はエラースタックです。

        09-01 14:22:44.365  16257-16869/com.example.mysqltest E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #3
            Process: com.example.mysqltest, PID: 16257
            java.lang.RuntimeException: An error occured while executing doInBackground()
                    at android.os.AsyncTask$3.done(AsyncTask.java:300)
                    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
                    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
                    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
                    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                    at java.lang.Thread.run(Thread.java:818)
             Caused by: java.lang.NoSuchMethodError: No virtual method execute(Lorg/apache/http/client/methods/HttpUriRequest;)Lorg/apache/http/client/methods/CloseableHttpResponse; in class Lorg/apache/http/impl/client/DefaultHttpClient; or its super classes (declaration of 'org.apache.http.impl.client.DefaultHttpClient' appears in /system/framework/ext.jar)
                    at com.example.mysqltest.JSONParser.makeHttpRequest(JSONParser.java:52)
                    at com.example.mysqltest.Login$AttemptLogin.doInBackground(Login.java:136)
                    at com.example.mysqltest.Login$AttemptLogin.doInBackground(Login.java:96)
                    at android.os.AsyncTask$2.call(AsyncTask.java:288)
                    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
                    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                    at java.lang.Thread.run(Thread.java:818)
4

2 に答える 2

6

build.gradle android セクションに、このコードを
配置 useLibrary 'org.apache.http.legacy'

次に、アプリケーションは Android/Sdk/platforms/android-23/optional にある org.apache.http.legacy.jar を使用します。クラッシュの理由は、Google が Apache HTTP クライアントのサポートを削除し、代わりに HttpURLConnection クラスを使用することを提案したためです。

HttpURLConnection を使用して特定の URL のコンテンツを取得する方法のサンプルを次に示します (たとえば、http://google.com?hacked=trueにすることができます)。

public static String file_get_contents(String fileURL)
        throws Exception {

    Log.d("file_get_contents", "getting url " + fileURL);
    String result = "";
    URL url = new URL(fileURL);
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    int responseCode = httpConn.getResponseCode();

    // always check HTTP response code first
    if (responseCode == HttpURLConnection.HTTP_OK) {
        String fileName = "";
        String disposition = httpConn.getHeaderField("Content-Disposition");
        String contentType = httpConn.getContentType();
        int contentLength = httpConn.getContentLength();

        if (disposition != null) {
            // extracts file name from header field
            int index = disposition.indexOf("filename=");
            if (index > 0) {
                fileName = disposition.substring(index + 10,
                        disposition.length() - 1);
            }
        } else {
            // extracts file name from URL
            fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
                    fileURL.length());
        }

        Log.d("file_get_contents", "Content-Type = " + contentType);
        Log.d("file_get_contents", "Content-Disposition = " + disposition);
        Log.d("file_get_contents", "Content-Length = " + contentLength);
        Log.d("file_get_contents", "fileName = " + fileName);

        // opens input stream from the HTTP connection
        InputStream inputStream = httpConn.getInputStream();

        int bytesRead = -1;
        byte[] buffer = new byte[BUFFER_SIZE];
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            Log.d("file_get_contents", "bytes read: " + bytesRead);
            String bufferString = new String(buffer, 0, bytesRead, "UTF-8");
            Log.d("file_get_contents", "buffer string: " + bufferString);
            result = result.concat(bufferString);
            //outputStream.write(buffer, 0, bytesRead);
        }

        //outputStream.close();
        inputStream.close();

        Log.d("file_get_contents", "File downloaded");
    } else {
        Log.d("file_get_contents", "No file to download. Server replied HTTP code: " + responseCode);
    }
    httpConn.disconnect();

    Log.d("file_get_contents", "returning " + result);
    return result;
}
于 2015-12-01T15:27:27.973 に答える
1

次のバージョンを使用してみてください

HttpClient : httpclient-4.0-beta2.jar HttpCore : httpcore-4.1.jar

于 2015-10-29T12:07:19.803 に答える