如何在Class中全局声明方法

时间:2013-07-02 09:06:40

标签: java android

我想在startUpload(position);中调用loginbutton.setOnClickListener(new View.OnClickListener() {}方法,如下所示:

loginbutton.setOnClickListener(new View.OnClickListener() {

    @Override
public void onClick(View v) {
    SaveData();     
    alertDialog.dismiss();  
    startUpload(position);  
}

但始终获取位置无法解析为变量

所以我在做错的地方,我怎么能解决这个问题..?

//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
        strSDPath = ImageList.get(position).toString();

        // Upload to PHP Script
        String strUrlServer = "http://10.0.2.2/res/uploadFile.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 = "Unknow Status!";

    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"))
    {
        // When update Failed
        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 个答案:

答案 0 :(得分:0)

立场声明是关键。

确保它位于包含此loginButton.onClickListener代码的方法中,并确保将其声明为final

答案 1 :(得分:0)

如果它可以解析为变量,那不是因为你的方法, 这是因为position不是属性。

所以,把它当作:

int position = -1;

然后将其设置为使用您的方法。

答案 2 :(得分:0)

引用变量时,它们必须在方法范围内确定。

因此对于方法,请确保将其作为参数传递,或者将其定义为类中的全局变量。

答案 3 :(得分:0)

尝试一下 创建一个全局变量POSITION然后在你的startUpload()方法中指定POSITION = position,它会起作用。

相关问题