Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.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 使用AsyncTask解析Json_Java_Android_Json_Android Asynctask - Fatal编程技术网

Java 使用AsyncTask解析Json

Java 使用AsyncTask解析Json,java,android,json,android-asynctask,Java,Android,Json,Android Asynctask,您好,我的注册表活动.java如下所示: public class RegisterActivity extends Activity{ private static final String TAG = "PostFetcher"; private static String URL = "http://api.example.com/"; @Override public void onCreate(Bundle sa

您好,我的注册表活动.java如下所示:

    public class RegisterActivity  extends Activity{
        private static final String TAG = "PostFetcher";
        private static String URL = "http://api.example.com/";
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.register);

            final EditText inputFname = (EditText) findViewById(R.id.registerFname);
            final EditText inputLname = (EditText) findViewById(R.id.registerLname);
            final EditText inputEmail = (EditText) findViewById(R.id.registerEmail);
            Button btnRegister = (Button) findViewById(R.id.btnRegister);
            Button btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLogin);
            final TextView loginErrorMsg = (TextView) findViewById(R.id.register_error);

            // Register Button Click event
            btnRegister.setOnClickListener(new View.OnClickListener() {  
                Login login2;
                RadioGroup radioSexGroup = (RadioGroup) findViewById(R.id.sex);
                public void onClick(View view) {
                    String fname = inputFname.getText().toString();
                    String lname = inputLname.getText().toString();
                    String email = inputEmail.getText().toString();

                    // get selected radio button from radioGroup
                    int selectedId = radioSexGroup.getCheckedRadioButtonId();
                    RadioButton radioSexButton = (RadioButton) findViewById(selectedId);
                    String gender = radioSexButton.getText().toString();
                    //System.out.println(fname);
                    //Toast.makeText(RegisterActivity.this, radioSexButton.getText(), Toast.LENGTH_SHORT).show();

                    String registerURL = URL +"&user_email="+ email /**+"&first_name="+ fname +"&last_name="+ lname*/ +"&gender="+ gender;
                    System.out.println(registerURL);

                    if( email.length() == 0) {
                        loginErrorMsg.setText(R.string.empty);
                        //Toast.makeText(view.getContext(), R.string.empty, Toast.LENGTH_SHORT).show();
                        return;
                    }else{

                        try {
                            //Create an HTTP client
                            DefaultHttpClient client = new DefaultHttpClient();
                            HttpPost post = new HttpPost(registerURL);

                            //Perform the request and check the status code
                            HttpResponse response = client.execute(post);
                            StatusLine statusLine = response.getStatusLine();
                            if(statusLine.getStatusCode() == 200) {
                                HttpEntity entity = response.getEntity();
                                InputStream content = entity.getContent();

                                try {
                                    //Read the server response and attempt to parse it as JSON
                                    Reader reader = new InputStreamReader(content);

                                    Gson gson = new Gson();
                                    this.login2 = gson.fromJson(reader, Login.class);
                                    //System.out.println(this.login2);
                                    //handlePostsList(posts);
                                } catch (Exception ex) {
                                    Log.e(TAG, "Failed to parse JSON due to: " + ex);
                                    failedLoading();
                                }
                            } else {
                                Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
                                failedLoading();
                            }
                        } catch(Exception ex) {
                            Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
                            failedLoading();
                        }

                        //To set register message
                        if(login2.getResult().equals("OK")){
                            loginErrorMsg.setText(login2.getMessage().toString());
                        }else if(login2.getResult().equals("KO")){
                            loginErrorMsg.setText(login2.getMessage().toString());
                        }
                    }

                }
            });


            // Link to Login
            btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View view) {
                        Intent i = new Intent(getApplicationContext(),LoginActivity.class);
                        startActivity(i);
                        finish();
                    }
            });

        }

        public void onRadioButtonClicked(View view) {
            // Is the button now checked?
            boolean checked = ((RadioButton) view).isChecked();

            // Check which radio button was clicked
            switch(view.getId()) {
                case R.id.male:
                    if (checked)
                        // Pirates are the best
                    break;
                case R.id.female:
                    if (checked)
                        // Ninjas rule
                    break;
            }
        }

        private void failedLoading() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(RegisterActivity.this, "Failed to Register. look at LogCat.", Toast.LENGTH_SHORT).show();
                }
            });
        }
}
但我得到如下错误:
未能发送HTTP POST请求,原因是:android.os.NetworkOnMainThreadException

Android开发者论坛建议我使用
AsyncTask
来解决这个问题。但我不知道如何改变这一点。有人能帮我解决这个问题吗?我花了几个小时,但找不到任何解决方案。

启动的最简单方法是创建一个匿名内部类,并在您的
onCreate中执行它:

// if email length != 0
new AsyncTask<Void, Void, Void> {
    protected void doInBackground() {
        //Create an HTTP client
        //Update login2
     }
}.execute();
//如果电子邮件长度!=0
新异步任务{
受保护的void doInBackground(){
//创建一个HTTP客户端
//更新登录2
}
}.execute();

然而,这里有很多细微的差别,我强烈建议您阅读这两个页面:

您希望将所有网络/解析代码放入
AsyncTask
doInBackground()
。将
AsyncTask
作为
活动的内部类。在获得结果后,您需要将其返回到
onPostExecute()
以执行任何
UI
操作,例如更新
视图

通过使
AsyncTask
成为一个内部类,您可以访问
活动的成员变量及其函数

将为您创建并调用
异步任务提供一个良好的起点

了解它所需要的规则


查看这些链接并尝试一下。然后在遇到问题时发布一个带有更具体问题的问题(如果遇到问题,请确保包含相关代码和logcat错误)。

我真诚地认为,您需要付出一些努力才能解决问题,但现在您可以:

public class RegisterActivity  extends Activity{
private static final String TAG = "PostFetcher";
private static String URL = "http://api.example.com/";
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.register);

    final EditText inputFname = (EditText) findViewById(R.id.registerFname);
    final EditText inputLname = (EditText) findViewById(R.id.registerLname);
    final EditText inputEmail = (EditText) findViewById(R.id.registerEmail);
    Button btnRegister = (Button) findViewById(R.id.btnRegister);
    Button btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLogin);
    final TextView loginErrorMsg = (TextView) findViewById(R.id.register_error);

    // Register Button Click event
    btnRegister.setOnClickListener(new View.OnClickListener() {  
        Login login2;
        RadioGroup radioSexGroup = (RadioGroup) findViewById(R.id.sex);
        public void onClick(View view) {
            String fname = inputFname.getText().toString();
            String lname = inputLname.getText().toString();
            String email = inputEmail.getText().toString();

            // get selected radio button from radioGroup
            int selectedId = radioSexGroup.getCheckedRadioButtonId();
            RadioButton radioSexButton = (RadioButton) findViewById(selectedId);
            String gender = radioSexButton.getText().toString();
            //System.out.println(fname);
            //Toast.makeText(RegisterActivity.this, radioSexButton.getText(), Toast.LENGTH_SHORT).show();

            String registerURL = URL +"&user_email="+ email /**+"&first_name="+ fname +"&last_name="+ lname*/ +"&gender="+ gender;
            System.out.println(registerURL);

            if( email.length() == 0) {
                loginErrorMsg.setText(R.string.empty);
                //Toast.makeText(view.getContext(), R.string.empty, Toast.LENGTH_SHORT).show();
                return;
            }else{
                new LoginTask.execute();
            }

        }
    });


    // Link to Login
    btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),LoginActivity.class);
                startActivity(i);
                finish();
            }
    });

}

public void onRadioButtonClicked(View view) {
    // Is the button now checked?
    boolean checked = ((RadioButton) view).isChecked();

    // Check which radio button was clicked
    switch(view.getId()) {
        case R.id.male:
            if (checked)
                // Pirates are the best
            break;
        case R.id.female:
            if (checked)
                // Ninjas rule
            break;
    }
}

private void failedLoading() {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(RegisterActivity.this, "Failed to Register. look at LogCat.", Toast.LENGTH_SHORT).show();
        }
    });

private class LoginTask extends
        AsyncTask<Void, Void, Void> {

            ProgressDialog progressDialog;

    // Before running code in separate thread
    @Override
    protected void onPreExecute() {
        // Create a new progress dialog.
        progressDialog = new ProgressDialog(context);
        // Set the progress dialog to display a horizontal bar .
        // progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        // Set the dialog title to 'Loading...'.
        // progressDialog.setTitle("Loading...");
        // Set the dialog message to 'Loading application View, please
        // wait...'.
        progressDialog.setMessage("Loading...");
        // This dialog can't be canceled by pressing the back key.
        progressDialog.setCancelable(false);
        // This dialog isn't indeterminate.
        progressDialog.setIndeterminate(true);
        // The maximum number of progress items is 100.
        // progressDialog.setMax(100);
        // Set the current progress to zero.
        // progressDialog.setProgress(0);
        // Display the progress dialog.
        progressDialog.show();

    }

    // The code to be executed in a background thread.
    @Override
    protected VoiddoInBackground(Void... arg) {
        try {
                    //Create an HTTP client
                    DefaultHttpClient client = new DefaultHttpClient();
                    HttpPost post = new HttpPost(registerURL);

                    //Perform the request and check the status code
                    HttpResponse response = client.execute(post);
                    StatusLine statusLine = response.getStatusLine();
                    if(statusLine.getStatusCode() == 200) {
                        HttpEntity entity = response.getEntity();
                        InputStream content = entity.getContent();

                        try {
                            //Read the server response and attempt to parse it as JSON
                            Reader reader = new InputStreamReader(content);

                            Gson gson = new Gson();
                            this.login2 = gson.fromJson(reader, Login.class);
                            //System.out.println(this.login2);
                            //handlePostsList(posts);
                        } catch (Exception ex) {
                            Log.e(TAG, "Failed to parse JSON due to: " + ex);
                            failedLoading();
                        }
                    } else {
                        Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
                        failedLoading();
                    }
                } catch(Exception ex) {
                    Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
                    failedLoading();
                }

    }


    // after executing the code in the thread
    @Override
    protected void onPostExecute() {
        // close the progress dialog
        progressDialog.dismiss();
                                   //To set register message
                if(login2.getResult().equals("OK")){
                    loginErrorMsg.setText(login2.getMessage().toString());
                }else if(login2.getResult().equals("KO")){
                    loginErrorMsg.setText(login2.getMessage().toString());
                }

    }
}

}
公共类注册表活动扩展活动{
私有静态最终字符串TAG=“PostFetcher”;
专用静态字符串URL=”http://api.example.com/";
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
最终EditText inputFname=(EditText)findViewById(R.id.RegisterName);
最终EditText inputLname=(EditText)findViewById(R.id.RegisterName);
final EditText inputEmail=(EditText)findViewById(R.id.registerEmail);
按钮btnRegister=(按钮)findViewById(R.id.btnRegister);
按钮btnLinkToLogin=(按钮)findViewById(R.id.btnLinkToLogin);
最终文本视图loginErrorMsg=(文本视图)findViewById(R.id.register\u错误);
//注册按钮点击事件
btnRegister.setOnClickListener(新视图.OnClickListener(){
登录2;
放射组RADIOEXGROUP=(放射组)findViewById(R.id.sex);
公共void onClick(视图){
字符串fname=inputFname.getText().toString();
字符串lname=inputLname.getText().toString();
字符串email=inputEmail.getText().toString();
//从radioGroup中获取所选单选按钮
int selectedId=RadioExGroup.getCheckedRadioButtonId();
RadioButton RadioExButton=(RadioButton)findViewById(selectedId);
字符串性别=RadioExButton.getText().toString();
//System.out.println(fname);
//Toast.makeText(RegisterActivity.this,radioexbutton.getText(),Toast.LENGTH\u SHORT.show();
字符串registerURL=URL+“&user_email=“+email/**+”&first_name=“+fname+”&last_name=“+lname*/+”&gender=“+gender;
System.out.println(registerURL);
如果(email.length()==0){
loginerrormg.setText(R.string.empty);
//Toast.makeText(view.getContext(),R.string.empty,Toast.LENGTH_SHORT).show();
回来
}否则{
新的LoginTask.execute();
}
}
});
//链接到登录
btnLinkToLogin.setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图){
Intent i=新Intent(getApplicationContext(),LoginActivity.class);
星触觉(i);
完成();
}
});
}
单击RadioButton上的公共无效(视图){
//按钮现在被选中了吗?
布尔选中=((RadioButton)视图).isChecked();
//检查单击了哪个单选按钮
开关(view.getId()){
病例R.id.男性:
如果(选中)
//海盗是最好的
打破
案例R.id.女性:
如果(选中)
//忍者法则
打破
}
}
私有void加载失败(){
runOnUiThread(新的Runnable(){
@凌驾
公开募捐{
Toast.makeText(RegisterActivity.this,“未能注册。查看LogCat.”,Toast.LENGTH_SHORT.show();
}
});
私有类登录任务扩展
异步任务{
进行对话进行对话;
//在单独的线程中运行代码之前
@凌驾
受保护的void onPreExecute(){
//创建一个新的进度对话框。
progressDialog=新建progressDialog(上下文);
//将“进度”对话框设置为显示水平条。
//progressDialog.setProgressStyle(progressDialog.STYLE_水平);
//将对话框标题设置为“正在加载…”。
//progressDialog.setTitle(“加载…”);
//请将对话框消息设置为“正在加载应用程序视图”
//等等……’。
progressDialog.setMessage(“加载…”);
//按后退键无法取消此对话框。
progressDialog.setCancelable(假);
//这个对话框不是不确定的。
progressDialog.setUndeterminate(true);
//最大进度项目数为100。
//progressDialog.setMax(100);
//将当前进度设置为零。
//progressDialog.setProgress(0);
//显示进度对话框。
progressDialog.show();
}
//要执行的代码