English 中文(简体)
显示在卸载时的方言和roid
原标题:Display loading dialog android while uploading file
  • 时间:2012-04-25 12:35:32
  •  标签:
  • android
  • url

我正在通过网站把一个文件上载到我的服务器上,即有一个简单的方法使工作得以完成,但装满......方言从没有显示如何确定这一点......这是我的法典。

public void send_data() throws IOException
{
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    String lineEnd = "
";
    String twoHyphens = "--";
    String boundary =  "*****";

    ProgressDialog dialog = ProgressDialog.show(CaptureTestActivity.this, "", 
        "Loading. Please wait...", true);
    dialog.show();

    String urlServer = "http://poi.gps.ro:80/postimg?lat=" + String.valueOf(mDraw.lat) + "&lon=" + String.valueOf(mDraw.lon)+"&comment=" + tmp;
    Log.w("DHA", urlServer);
    URL url = new URL(urlServer);
    if (url != null)
    {   
        Log.w("DHA", "Merge aici");
        connection = (HttpURLConnection) url.openConnection();
        if (connection != null)
        {
            Log.w("DHA", "Si aici mere!");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Host", "poi.gps.ro");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=*****");
            outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream.writeBytes("Content-Disposition: form-data; name="uploadedfile";filename="" + "PICT0000" +""" + lineEnd);
            outputStream.writeBytes(lineEnd);
            outputStream.write(btarr.toByteArray());
            outputStream.writeBytes(lineEnd);
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            Log.w("DHA", "Incep trimiterea pozei!");
            outputStream.flush();
            outputStream.close();
            int serverResponseCode = connection.getResponseCode();
            String conn = connection.getResponseMessage();
        //  InputStream in  = connection.getInputStream();
        //  StringWriter writer = new StringWriter();

            Log.w("DHA", conn);
            Log.w("DHA", "Serverul a raspuns cu " + String.valueOf(serverResponseCode));
            if (serverResponseCode == 200)
            {
                AlertDialog alertDialog;
                alertDialog = new AlertDialog.Builder(this).create();
                alertDialog.setTitle("Super :)");
                alertDialog.setMessage("Poza a fost trimisa cu success.");
                alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {

                      public void onClick(DialogInterface dialog, int id) {

                         finish();

                    } }); 
                alertDialog.show();

            }


}
    }
    dialog.dismiss();
}
最佳回答

As David said, you need an AsynTask, most practical option. You can do some clever things with the Void, Void, Void part, but unless you want to look into the documentation, this should work fine.

public class MyActivity extends Activity {

....

    private final class AsyncSender extends AsyncTask<Void, Void, Void> {

        ProgressDialog pd;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pd = new ProgressDialog(MyActivity.this);
            pd.setTitle("Sending Data");
            pd.setMessage("Please wait, data is sending");
            pd.setCancelable(false);
            pd.setIndeterminate(true);
            pd.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            send_data(); // You probably have to try/catch this
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            pd.dismiss();
        }
    }
}

那么,当你打电话时,最干净的方式就是呼吁。

new AsyncSender().execute();

此外,我还要提到,这应该是内部的阶层,也就是说,不会为它单独立案。 总的来说,我只是把他们放在Im的班底部。

问题回答

You are blocking the UI with your upload code. You need to use an AsyncTask / thread / service.

http://android-developers.blogspot.co.uk/2009/05/painless-threading.html” rel=“nofollow”>Painless Threading

First of all you call ProgressDialog.show() twice which is unnecessary. And perhaps one reason why it doesn t show is because it is dismissed right after it is shown. For instance if your file upload is really fast or fails or is done in another thread the call to dismiss() will be called so quickly that you won t be able to ever see the dialog.

When you want to do any task in background and want to show another thing on screen the you should use AsyncTask...

This is an example of login using AsyncTask now u can update it...

public class mytask extends AsyncTask<Object, Object, Object> {

    String METHOD_NAME = "Login";
    String NAMESPACE = "http://tempuri.org/";
    SoapObject request;
    String SOAP_ACTION = "http://tempuri.org/Login";
    @Override
    protected Object doInBackground(Object... params) {
        Log.d(TAG, "doInBackground(Void... params");
        Object flag = null;
        try {
            flag = TAGS.sendToServerAndGetResponse(request, SOAP_ACTION);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        }
        return flag;
    }

    @Override
    protected void onPostExecute(Object result) {
        if (result.toString().equalsIgnoreCase("true")) {

            mIntent = new Intent();
            mIntent.setClass(PresenTABActivity.this,
                    presentation_list.class);
            startActivity(mIntent);
            finish();
        } else {
            Toast.makeText(getApplicationContext(),
                    "Please Enter Valid Username or Password",
                    Toast.LENGTH_SHORT).show();
            edtPass.setVisibility(View.VISIBLE);
            edtUname.setVisibility(View.VISIBLE);
            chk_remeber_me.setVisibility(View.VISIBLE);
            btnSubmit.setVisibility(View.VISIBLE);
            mProgressBar.setVisibility(View.INVISIBLE);
            loading.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    protected void onPreExecute() {
        Log.d(TAG, "onPreExecute()");
        request = new SoapObject(NAMESPACE, METHOD_NAME);
        request.addProperty("Username", edtUname.getText().toString()
                .trim());
        request.addProperty("password", edtPass.getText().toString().trim());

        mProgressBar = (ProgressBar) findViewById(R.id.progress_login);
        loading = (TextView) findViewById(R.id.tv_loading);
        loading.setVisibility(View.VISIBLE);
        mProgressBar.setVisibility(View.VISIBLE);

        edtPass.setVisibility(View.INVISIBLE);
        edtUname.setVisibility(View.INVISIBLE);

        chk_remeber_me.setVisibility(View.INVISIBLE);
    }
}

查阅网页: rel=“nofollow” http://www.vogella.com/articles/AndroidPerformance/article.html

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

private ProgressDialog mProgressDialog;

    @Override
    protected void onPreExecute() {
        mProgressDialog = ProgressDialog.show(this, title, message, true);
    }

    @Override
    protected Void doInBackground(final Void... params) {
        // Do your work .. uploading
        return null;
    }

    @Override
    protected void onPostExecute(final Void result) {
        if (mProgressDialog != null) {
        mProgressDialog.dismiss();
        }
    }
}




相关问题
Android - ListView fling gesture triggers context menu

I m relatively new to Android development. I m developing an app with a ListView. I ve followed the info in #1338475 and have my app recognizing the fling gesture, but after the gesture is complete, ...

AsyncTask and error handling on Android

I m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What s unclear to me is how to handle ...

Android intent filter for a particular file extension?

I want to be able to download a file with a particular extension from the net, and have it passed to my application to deal with it, but I haven t been able to figure out the intent filter. The ...

Android & Web: What is the equivalent style for the web?

I am quite impressed by the workflow I follow when developing Android applications: Define a layout in an xml file and then write all the code in a code-behind style. Is there an equivalent style for ...

TiledLayer equivalent in Android [duplicate]

To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?

Using Repo with Msysgit

When following the Android Open Source Project instructions on installing repo for use with Git, after running the repo init command, I run into this error: /c/Users/Andrew Rabon/bin/repo: line ...

Android "single top" launch mode and onNewIntent method

I read in the Android documentation that by setting my Activity s launchMode property to singleTop OR by adding the FLAG_ACTIVITY_SINGLE_TOP flag to my Intent, that calling startActivity(intent) would ...

From Web Development to Android Development

I have pretty good skills in PHP , Mysql and Javascript for a junior developer. If I wanted to try my hand as Android Development do you think I might find it tough ? Also what new languages would I ...

热门标签