Android Web服务无法连接

时间:2015-07-14 05:09:12

标签: android android-asynctask logcat

我正在开发一个Android应用程序,其中应用程序与Web服务连接..我能够成功连接Web服务,但有些时候应用程序崩溃了。如果有人可以提供帮助,我会在下面给出我的代码和logcat。

mainActivity


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

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Verifying the details... Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @SuppressWarnings("deprecation")
    @Override
    protected String doInBackground(String... args) {


        url = "https://xxx.xxx.com/appservice/appy_service.asmx/lLogi?";

        etUserName = (EditText)findViewById(R.id.editTextLogin);
        etPassword = (EditText)findViewById(R.id.editTextPassword);

        uname = etUserName.getText().toString();
        pswd  = etPassword.getText().toString();

         List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("uid", uname));       
            params.add(new BasicNameValuePair("pass", pswd));

            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += paramString;

        // TODO Auto-generated method stub
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL         
        JSONObject json = jParser.getJSONFromUrl(url);      

            try {

                final String stat  = json.getString(TAG_STATUS);
                final String cid   = json.getString(TAG_CID);
                final String cname = json.getString(TAG_CNAME);
                final String uid   = json.getString(TAG_UID);

                //Toast.makeText(MainActivity.this, stat + cid + cname + uid, Toast.LENGTH_LONG).show();

                if(stat.equals("111"))
                {
                runOnUiThread(new Runnable() {  
                    @Override
                    public void run() 
                    {
                        //webserviceResponse.setText("Success");

                        SharedPreferences login = MainActivity.this.getSharedPreferences(PREFS_NAME,0);
                        SharedPreferences.Editor loginedit = login.edit();
                        loginedit.putString("log", "log");           
                        loginedit.putString("cid", cid);
                        loginedit.putString("cname",cname);
                        loginedit.putString("uid",uid);
                        loginedit.commit();

                        Intent suc = new Intent(MainActivity.this, My_Account.class);
                        startActivity(suc);

                    }
                });

            }



            } catch (JSONException e) {
                // TODO Auto-generated catch block

                e.printStackTrace();



            }   


        return null;

    }
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once got all details
        pDialog.dismiss();
    }
    }

logcat的

07-14 10:30:03.157: E/AndroidRuntime(1325): FATAL EXCEPTION: AsyncTask #1
07-14 10:30:03.157: E/AndroidRuntime(1325): Process: com.example.sampleapplication, PID: 1325
07-14 10:30:03.157: E/AndroidRuntime(1325): java.lang.RuntimeException: An error occured while executing doInBackground()
07-14 10:30:03.157: E/AndroidRuntime(1325):     at android.os.AsyncTask$3.done(AsyncTask.java:304)
07-14 10:30:03.157: E/AndroidRuntime(1325):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
07-14 10:30:03.157: E/AndroidRuntime(1325):     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
07-14 10:30:03.157: E/AndroidRuntime(1325):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
07-14 10:30:03.157: E/AndroidRuntime(1325):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
07-14 10:30:03.157: E/AndroidRuntime(1325):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
07-14 10:30:03.157: E/AndroidRuntime(1325):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
07-14 10:30:03.157: E/AndroidRuntime(1325):     at java.lang.Thread.run(Thread.java:818)
07-14 10:30:03.157: E/AndroidRuntime(1325): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference
07-14 10:30:03.157: E/AndroidRuntime(1325):     at com.example.sampleapplication.MainActivity$ProgressTask.doInBackground(MainActivity.java:175)
07-14 10:30:03.157: E/AndroidRuntime(1325):     at com.example.sampleapplication.MainActivity$ProgressTask.doInBackground(MainActivity.java:1)
07-14 10:30:03.157: E/AndroidRuntime(1325):     at android.os.AsyncTask$2.call(AsyncTask.java:292)
07-14 10:30:03.157: E/AndroidRuntime(1325):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-14 10:30:03.157: E/AndroidRuntime(1325):     ... 4 more

3 个答案:

答案 0 :(得分:1)

公共类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 httpClients = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClients.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;

}

以下代码将起作用

class ProgressTask扩展了AsyncTask {

@Override
protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(MainActivity.this);
    pDialog.setMessage("Verifying the details... Please wait...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(true);
    pDialog.show();
}

@SuppressWarnings("deprecation")
@Override
protected String doInBackground(String... args) {


    url = "https://xxx.xxx.com/appservice/appy_service.asmx/lLogi?";

    etUserName = (EditText)findViewById(R.id.editTextLogin);
    etPassword = (EditText)findViewById(R.id.editTextPassword);

    uname = etUserName.getText().toString();
    pswd  = etPassword.getText().toString();

     List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("uid", uname));       
        params.add(new BasicNameValuePair("pass", pswd));

        String paramString = URLEncodedUtils.format(params, "utf-8");
        url += paramString;

    // TODO Auto-generated method stub
    JSONParser jParser = new JSONParser();

    // getting JSON string from URL         
 //   JSONObject json = jParser.getJSONFromUrl(url);      

JSONObject json = jParser.makeHttpRequest(url,&#34; POST&#34;,params);

        try {

            final String stat  = json.getString(TAG_STATUS);
            final String cid   = json.getString(TAG_CID);
            final String cname = json.getString(TAG_CNAME);
            final String uid   = json.getString(TAG_UID);

            //Toast.makeText(MainActivity.this, stat + cid + cname + uid, Toast.LENGTH_LONG).show();

            if(stat.equals("111"))
            {
            runOnUiThread(new Runnable() {  
                @Override
                public void run() 
                {
                    //webserviceResponse.setText("Success");

                    SharedPreferences login = MainActivity.this.getSharedPreferences(PREFS_NAME,0);
                    SharedPreferences.Editor loginedit = login.edit();
                    loginedit.putString("log", "log");           
                    loginedit.putString("cid", cid);
                    loginedit.putString("cname",cname);
                    loginedit.putString("uid",uid);
                    loginedit.commit();

                    Intent suc = new Intent(MainActivity.this, My_Account.class);
                    startActivity(suc);

                }
            });

        }



        } catch (JSONException e) {
            // TODO Auto-generated catch block

            e.printStackTrace();



        }   


    return null;

}
protected void onPostExecute(String file_url) {
    // dismiss the dialog once got all details
    pDialog.dismiss();
}
}

答案 1 :(得分:0)

首先检查您在getString(TAG_NAME)中提供的标签是否已正确初始化。

SechondCheck如果你得到的字符串不是null,那么执行try块;否则会向用户显示发送错误的祝酒词,请再试一次。

答案 2 :(得分:0)

检查您的许可互联网,显示希望这可以帮助您