当前位置: 首页 > 知识库问答 >
问题:

我似乎无法通过我的android应用程序连接到远程服务器

胡天佑
2023-03-14

我在Android Studio做了一个登录和注册系统。每当我启动应用程序并登录或向数据库添加新用户时,都会出现以下错误:

runtimeException:执行doInBackground()时发生错误

private EditText user, pass;
private Button mSubmit, mRegister;

private ProgressDialog pDialog;


JSONParser jsonParser = new JSONParser();



private static final String LOGIN_URL = "http://10.0.2.2:1234/webservice/login.php";




private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);


    user = (EditText) findViewById(R.id.username);
    pass = (EditText) findViewById(R.id.password);


    mSubmit = (Button) findViewById(R.id.login);
    mRegister = (Button) findViewById(R.id.register);


    mSubmit.setOnClickListener(this);
    mRegister.setOnClickListener(this);

}

@Override
public void onClick(View v) {

    switch (v.getId()) {
    case R.id.login:
        new AttemptLogin().execute();
        break;
    case R.id.register:
        Intent i = new Intent(this, Register.class);
        startActivity(i);
        break;

    default:
        break;
    }
}

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

    @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) {

        int success;
        String username = user.getText().toString();
        String password = pass.getText().toString();
        try {

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("password", password));

            Log.d("request!", "starting");

            JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
                    params);

            Log.d("Login attempt", json.toString());


            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("Login Successful!", json.toString());

                SharedPreferences sp = PreferenceManager
                        .getDefaultSharedPreferences(Login.this);
                Editor edit = sp.edit();
                edit.putString("username", username);
                edit.commit();

                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;

    }

    protected void onPostExecute(String file_url) {

        pDialog.dismiss();
        if (file_url != null) {
            Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
        }

    }

}

在这里输入代码02-04 16:51:58.079 123 63-12496/com.example.app e/AndroidRuntime:致命异常:AsyncTask#1 java.lang.runtimeException:在Android.os.AsyncTask$3处执行doInBackground()时发生错误。在java.util.concurrent.futureTask$sync.innerSetException(FutureTask.java:273)处执行doInBackground,在java.util.concurrent.futureTask.java:124),在util.concurrent.futuretask.run(Futuretask.java:137)在Android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)在java.util.concurrent.threadPoolExecutor.runworker(threadPoolExecutor.java:1076)在java.util.concurrent.threadPoolExecutor.worker.run(threadPoolExecutor.javer.run(threadPoolExecutor.javer.569)在在Android.os.AsyncTask$2处的$AttabletLogin.doInBackground(login.java:93)中调用(Asynctask.java:287)在java.util.concurrent.futuretask$sync.innerrun(futuretask.java:305)              在java.util.concurrent.futuretask.run(futuretask.java:305)          在java.util.concurrent.futuretask.run(futuretask.concurrent.futuretask.run(futuretask.concurrent.futuretask.concurrent.threadpoolexecutor$worker.run(threadpoolexecutor.java:569) · · · · · · · · · · · 在java.lang.thread.run(thread.java:856)

private EditText user, pass;
private Button mSubmit, mRegister;

// Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();



// testing on Emulator:
private static final String LOGIN_URL = "http://www.skloink.com//ugur/login.php";


// JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);

    // 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().execute();
            break;
        case R.id.register:
            Intent i = new Intent(this, Register.class);
            startActivity(i);
            break;

        default:
            break;
    }
}

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

    @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;
        String username = user.getText().toString();
        String password = pass.getText().toString();
        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("password", password));

            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());
                // save user data
                SharedPreferences sp = PreferenceManager
                        .getDefaultSharedPreferences(Login.this);
                Editor edit = sp.edit();
                edit.putString("username", username);
                edit.commit();

                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;

    }

    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();
        }

    }

}

}

共有1个答案

鱼宜
2023-03-14

我尝试了这种方式,这里使用回调的原因是为了完成当前的活动。而函数startLogin(),在post execute中是一个可以做其他工作的函数,比如在数据库中保存或其他任务,不要忘记在startLogin函数中做一件事,就是取消进度条,比如progressdialog.disfiss();希望这有所帮助:)。

private void authenticate(String phoneNumber, String countryCode) {

        ServerVerify verify = new ServerVerify(this,new TaskCallback() {

            @Override
            public void done() {
                finish();

            }
        });
        verify.execute("");
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Registering.....");
        progressDialog.show();
    }
    public static class ServerVerify extends  AsyncTask<Object, Object, Object>{
        Context context;
        private TaskCallback mCallback;
        private ServerVerify(Context appContext , TaskCallback callback) {
            context = appContext.getApplicationContext();
            mCallback = callback;

        }
        @Override
        protected Object doInBackground(Object... param) {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
            nameValuePairs.add(new BasicNameValuePair(HTTPConstants.PHONE_NUMBER , phoneNo));

            nameValuePairs.add(new BasicNameValuePair(HTTPConstants.OS_VERSION, version));
            try {
                post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            }  catch (UnsupportedEncodingException e) {
                Log.e("UnsupportedEncodingException", "could not load url while registering user");
            }
            HttpResponse response = null;
            try {
                response =  client.execute(post);
            } catch (ClientProtocolException e) {
                Log.e("ClientProtocolException", "Error while registering user");
            } catch (IOException e) {   
                Log.e("IOException", "Error while registering user");
            }
            return response;
        }
        @Override
        protected void onProgressUpdate(Object... values) {
            super.onProgressUpdate(values);
        }
        @Override
        protected void onPostExecute(Object result) {
            responseJson = Utils.readResponse((HttpResponse)result);
            try {
                startLogin(context);
                mCallback.done();
            } catch (JSONException e) {
                Log.e("Json Exception", "Error in reading json response while registering User");
            }
        }


    }
 类似资料:
  • 我正在尝试使用js文件中的以下代码从我的机器上的meteor应用程序连接远程数据库: 将引发以下错误: 错误:EACCES,在object.future.wait处取消链接++os.linux.x86_64+web.browser+web.cordova/meteor-tool-os.linux.x86_64/tools/files.js:1124:24)在object.files.rm_recu

  • 我有一个运行在windows机器上的远程FileZilla ftp服务器。ftp服务器需要通过TLS显式ftp。协议是FTP而不是SFTP。我无法更改此服务器的设置。我可以使用filezilla gui客户端连接到此服务器。 现在,我需要通过使用org的java应用程序连接到FileZilla服务器。阿帕奇。平民净: 但是当我运行上面的代码时,我得到: 说到: 任何想法如何连接到Filezilla

  • 问题内容: 我已经在服务器上安装了Kibana 5.4和Elastic search 5.4,我可以通过使用本地计算机上的curl来访问Kibana和Elastic search 我得到以下回应 var hashRoute =’/ app / kibana’; var defaultRoute =’/ app / kibana’; var hash = window.location.hash;

  • 我已经在服务器上安装了Kibana 5.4和Elastic search 5.4,我可以使用 我得到以下回应 var hashRoute='/app/kibana'; var defaultRoute='/app/kibana'; var hash=window.location.hash; if(hash.length){window.location=hashRoute hash;}其他{wi

  • sudo ufw状态:活动状态 从---------22/TCP允许任意位置10000 允许任意位置Nginx完全 允许任意位置3333 允许任意位置27017 允许任意位置22/TCP(v6) 允许任意位置(v6)10000(v6) 允许任意位置(v6)Nginx完全(v6) 允许任意位置(v6)27017(v6) 允许任意位置(v6) 从我的mac连接到它会引发错误: mongo MongoD