0

我正在编写一个应用程序,其中我正在显示列表视图项目的状态,这里:我正在显示 SD 卡图像,并允许用户单击上传按钮将图像上传到服务器,并显示结果,例如:如果上传完成到服务器然后显示上传完成,如果用户已经上传到服务器然后显示已经上传但是每当用户点击上传按钮时,但现在我想显示图像的状态,每当列表加载时,请参见下面的屏幕截图:

在此处输入图像描述

上传活动.java:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);       
        setContentView(R.layout.activity_uploads);

         // Permission StrictMode
        if (android.os.Build.VERSION.SDK_INT > 9) 
        {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }           

        // click to create new event
        btn_previous_activity = (Button) findViewById(R.id.btn_previous_activity);
        btn_previous_activity.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // using Intent to call EventListActivity               
                Intent intentNewEvent = new Intent(UploadActivity.this, EventListActivity.class);
                startActivity(intentNewEvent);
            }
        });

        /*** Get Images from SDCard ***/
        ImageList = getSD();
        Log.d(UploadActivity.LOG_TAG, "getSD() :::--- " + ImageList);

        // ListView and imageAdapter
        lstView = (ListView) findViewById(R.id.listView1);
        lstView.setAdapter(new ImageAdapter(this));

    }


    private List <String> getSD()
    {
        List <String> it = new ArrayList <String>();

        String string = "/mnt/sdcard/Pictures/MyNewImages/";
        File f = new File (string+ SingleAngelActivity.customFolder+ "/");

        Log.d(UploadActivity.LOG_TAG, "KEY_TITLE :::--- " + f);
        File[] files = f.listFiles ();
        Log.d(UploadActivity.LOG_TAG, "getListImages() :::--- " + files);

        for (int i = 0; i <files.length; i++)           
        {
            File  file = files[i];
            Log.d(UploadActivity.LOG_TAG, "i<files.length() :::--- " + i);
            Log.d("Count",file.getPath());
            it.add (file.getPath());
        }
        Log.d(UploadActivity.LOG_TAG, "List <String> it :::--- " + it);
        return it;
    }

//Upload
    public void startUpload(final int position) {      
        Runnable runnable = new Runnable() {

            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                        View v = lstView.getChildAt(position - lstView.getFirstVisiblePosition());
                        // Show ProgressBar
                        ProgressBar progress = (ProgressBar)v.findViewById(R.id.progressBar);
                        progress.setVisibility(View.VISIBLE);

                        //  Status  
                        TextView status = (TextView)v.findViewById(R.id.ColStatus);
                        status.setText("Uploading..");

                        new UploadFileAsync().execute(String.valueOf(position));   
                    }
                }); 
            }
        };
        new Thread(runnable).start();
    }


    // Async Upload
    public class UploadFileAsync extends AsyncTask<String, Void, Void> {

        String resServer;
        int position;

        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(String... params) {
            //  TODO Auto-generated method stub
            position = Integer.parseInt(params[0]);

            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024 * 1024;
            int resCode = 0;
            String resMessage = "";

            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary =  "*****";

            //  File Path
            String strSDPath = ImageList.get(position).toString();

            // Upload to PHP Script
            String strUrlServer = "http://10.0.2.2/res/files.php";              

            try {
                /** Check file on SD Card ***/
                File file = new File(strSDPath);
                if(!file.exists())
                {
                    resServer = "{\"StatusID\":\"0\",\"Error\":\"Please check path on SD Card\"}";
                    return null;
                }

                FileInputStream fileInputStream = new FileInputStream(new File(strSDPath));

                URL url = new URL(strUrlServer);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true);  
                conn.setDoOutput(true);
                conn.setUseCaches(false);
                conn.setRequestMethod("POST");

                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("Content-Type",
                        "multipart/form-data;boundary=" + boundary);

                DataOutputStream outputStream = new DataOutputStream(conn
                        .getOutputStream());
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream
                .writeBytes("Content-Disposition: form-data; name=\"filUpload\";filename=\""
                        + strSDPath + "\"" + lineEnd);
                outputStream.writeBytes(lineEnd);

                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];

                // Read file
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                while (bytesRead > 0) {
                    outputStream.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                }

                outputStream.writeBytes(lineEnd);
                outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                // Response Code and  Message
                resCode = conn.getResponseCode();
                if(resCode == HttpURLConnection.HTTP_OK)
                {
                    InputStream is = conn.getInputStream();
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();

                    int read = 0;
                    while ((read = is.read()) != -1) {
                        bos.write(read);
                    }
                    byte[] result = bos.toByteArray();
                    bos.close();

                    resMessage = new String(result);
                }

                Log.d("resCode=",Integer.toString(resCode));
                Log.d("resMessage=",resMessage.toString());

                fileInputStream.close();
                outputStream.flush();
                outputStream.close();

                resServer = resMessage.toString();

            } catch (Exception ex) {
                // Exception handling
                return null;
            }
            return null;
        }

        protected void onPostExecute(Void unused) {
            statusWhenFinish(position,resServer);
        }       
    }

    // when upload finish
    protected void statusWhenFinish(int position, String resServer) {

        View v = lstView.getChildAt(position - lstView.getFirstVisiblePosition());

        // Show ProgressBar
        ProgressBar progress = (ProgressBar)v.findViewById(R.id.progressBar);
        progress.setVisibility(View.GONE);


        // Status
        TextView status = (TextView)v.findViewById(R.id.ColStatus);
        /*** Default Value ***/
        String strStatusID = "0";
        String strMessage = "File Exists!";

        try {      

            JSONObject c = new JSONObject(resServer);
            strStatusID = c.getString("StatusID");
            strMessage = c.getString("Message");
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // Prepare Status       
        if(strStatusID.equals("0"))
        {               
            status.setText( strMessage );
            status.setTextColor(Color.RED);

            // Enabled Button again
            Button btnUpload = (Button) v.findViewById(R.id.btnUpload);
            btnUpload.setText("Already Uploaded");
            btnUpload.setTextColor(Color.RED);
            btnUpload.setEnabled(true);
        }
        else
        {
            status.setText("Upload Completed.");
            status.setTextColor(Color.GREEN);
        }
    }
4

1 回答 1

0

在适配器中添加新值并调用 notifyDataSetChanged 。

按照步骤更新列表视图。

1) First Add new values to your CountriesList .
2) Before Assign EfficientAdapter to listiew, make one object of it and then assign that object.
3) Create one function in your  EfficientAdapter class called notifyDataSetChanged().
4) Call notifyDataSetChanged() function using EfficientAdapter object.

例子

EfficientAdapter objectAdapter = new EfficientAdapter(this);
listView.setAdapter(objectAdapter);

@Override
public void notifyDataSetChanged() // Create this function in your adapter class
{
    super.notifyDataSetChanged();
}

现在在刷新按钮的 onClick 事件上调用 objectAdapter.notifyDataSetChanged()。

于 2013-07-16T11:22:54.467 回答