0

重複の可能性:
Android HttpClient : NetworkOnMainThreadException

私はリクエストを行っているアプリケーションに取り組んでおり、サーバーにリクエストを送信する必要があるまで、アプリは正常に動作します。同じアプリに対して以前に書かれたものと同じコードを使用していますが、これは改訂されています。

クリックを処理するフラグメント クラス:

import org.json.JSONException;
import org.json.JSONObject;
import org.myapp.app.utils.API;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class FragmentStudentLogin extends Fragment implements OnClickListener {
EditText uN, pW;
Button signin;

private API api;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    View v = inflater.inflate(R.layout.fragment_login, container, false);
    signin = (Button)v.findViewById(R.id.s_sign_in);
    signin.setOnClickListener(this);

    uN = (EditText)v.findViewById(R.id.f_t_s_username);
    pW = (EditText)v.findViewById(R.id.f_t_s_password);

    api = new API();

    return v;

    }

    public void onClick(View v){
    switch(v.getId())
    {
        case R.id.s_sign_in:
            String user = uN.getText().toString();
            String pass = pW.getText().toString();
            if(user.length()==0){
                PopIt("Please enter your username.");
            } else if(pass.length()==0){
                PopIt("Please enter your password.");
            } else {
                try {
            JSONObject json;
                    json = api.login(user, pass);
        if(json == null || json.isNull("status")){
            PopIt(getString(R.string.error_network));
        } else {
                        PopIt(json.getString("msg"));
                    }
                } catch (JSONException e){ }
            }
        break;
        }
    }

    public void PopIt(String msg){
        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
    }
}

Click が呼び出しを行うクラス:

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import org.myapp.app.utils.JSONParser;

public class API
{
    private JSONParser jsonParser;
    private static String serverURL = "http://mydomain.com/api/device/login";

    public API(){
        jsonParser = new JSONParser();
    }

    public JSONObject login(String uN, String pW)
    {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username", uN));
        params.add(new BasicNameValuePair("password", pW));
        JSONObject json = jsonParser.getJSONFromUrl(serverURL, params);
        return json;
    }

リクエストを処理するクラス:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

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

 // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

        // Making HTTP request
        try {
            // 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();

        } 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();
            Log.e("JSON", json);
        } 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;

    }
}

LogCat

10-02 19:40:23.734: E/AndroidRuntime(4401): FATAL EXCEPTION: main
10-02 19:40:23.734: E/AndroidRuntime(4401): android.os.NetworkOnMainThreadException
10-02 19:40:23.734: E/AndroidRuntime(4401):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at java.net.InetAddress.getAllByName(InetAddress.java:220)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.myapp.app.utils.JSONParser.getJSONFromUrl(JSONParser.java:42)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.myapp.app.utils.API.studentLogin(API.java:26)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.myapp.app.FragmentStudentLogin.onClick(FragmentStudentLogin.java:52)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at android.view.View.performClick(View.java:3511)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at android.view.View$PerformClick.run(View.java:14109)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at android.os.Handler.handleCallback(Handler.java:605)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at android.os.Handler.dispatchMessage(Handler.java:92)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at android.os.Looper.loop(Looper.java:137)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at android.app.ActivityThread.main(ActivityThread.java:4424)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at java.lang.reflect.Method.invokeNative(Native Method)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at java.lang.reflect.Method.invoke(Method.java:511)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at dalvik.system.NativeStart.main(Native Method)

私が言ったように、このコードは以前、「クリックが呼び出しを行うクラス:」および「リクエストを処理するクラス:」セクションで機能しましたが、以前は問題なく使用していました。Android API 16 は 7 インチ タブレットで使用されています。

4

1 に答える 1

1

例外メッセージは非常に明確です。Android 4.0 以降では、メイン (UI) スレッドでネットワーク呼び出しを行うことはできません。

于 2012-10-03T00:29:16.600 に答える