2013-07-02 1 views
-1
이 같은 loginbutton.setOnClickListener(new View.OnClickListener() {}startUpload(position); 메소드를 호출 할

의 방법을 선언하는 방법 : 항상 점점세계적으로 클래스

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); 
    } 
} 
    } 
+3

위치 변수의 선언은 어디에 있습니까? –

답변

0

여기에 위치 선언이 중요합니다. position가 아니기 때문에

는이 loginButton.onClickListener 코드를 포함하고 그것은 그것 때문에 당신의 방법을 아닙니다 변수로 해결 될 수 있다면 그것의, 을가 final

+0

내 위의 코드를 확인하고 내게 어떻게 할 수 있습니까? 내 경우에는 이것을 할 수 있습니까? – Sun

+0

충분한 코드를 표시하지 않으면 어디에서나 선언되지 않은 posiiton이라는 변수를 참조하기 만하면됩니다. 위치를 얻으려는 위치를 설명해야합니다. – cowls

0

로 선언되어 있는지 확인하는 방법에 있는지 확인 속성.

그래서,로 delcare :

int position = -1; 

그리고 그것은 당신의 방법을 사용하도록 설정합니다.

+0

내 위의 코드를 확인하고 내게 어떻게 할 수 있습니까? 내 경우에 이것을 어떻게 할 수 있습니까? – Sun

0

변수를 참조 할 때 변수의 범위 내에서 결정적이어야합니다.

메소드의 경우 매개 변수로 전달되었거나 클래스 내의 전역 변수로 정의되어 있는지 확인하십시오.

0

TRY IT 글로벌 변수 POSITION을 만들고 startUpload() 메소드에서 POSITION = position을 할당하면 작동합니다.

+0

당신이 옳은 것 같아요.하지만 여러 번 시도해 보았습니다. 어떻게 코드를 써야할까요? – Sun

+0

글로벌 범위는 외부 메서드를 의미합니다 // 업로드 public void startUpload (final int position) {POSITION = position; Runnable runnable = new Runnable() { 공공 무효 실행() { – GOLDEE

관련 문제