如何在全球范围类的方法声明 [英] How to declare method globally in Class
本文介绍了如何在全球范围类的方法声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要打电话 startUpload(位置);
方法 loginbutton.setOnClickListener(新View.OnClickListener(){}
是这样的:
loginbutton.setOnClickListener(新View.OnClickListener(){ @覆盖
公共无效的onClick(视图v){
保存数据();
alertDialog.dismiss();
startUpload(位置);
}
但总是得到的位置不能被解析到一个变量
所以我在哪里做的错,我怎么能解决这个问题..?
//上传
公共无效startUpload(最终诠释位置){
可运行可运行=新的Runnable(){ 公共无效的run(){
handler.post(新的Runnable(){
公共无效的run(){
视图V = lstView.getChildAt(位置 - lstView.getFirstVisiblePosition());
//显示进度
进度进度=(进度)v.findViewById(R.id.progressBar);
progress.setVisibility(View.VISIBLE); // 状态
TextView的状态=(TextView中)v.findViewById(R.id.ColStatus);
status.setText(上传..); 新UploadFileAsync()执行(将String.valueOf(位置));
}
});
}
};
新的线程(可运行)。开始();
}
//异步上传
公共类UploadFileAsync扩展的AsyncTask<弦乐,太虚,太虚> { 串resServer;
INT位置; 在preExecute保护无效(){
super.on preExecute();
} @覆盖
保护无效doInBackground(字符串... PARAMS){
// TODO自动生成方法存根
位置=的Integer.parseInt(PARAMS [0]); INT读取动作,方bytesAvailable,缓冲区大小;
字节[]缓冲区;
INT MAXBUFFERSIZE = 1 * 1024 * 1024;
中期业绩code = 0;
串resMessage =; 字符串lineEnd =\\ r \\ n;
串twoHyphens = - ;
字符串边界=*****; // 文件路径
strSDPath = ImageList.get(位置)的ToString(); //上传到PHP脚本
字符串strUrlServer =http://10.0.2.2/res/uploadFile.php; 尝试{
/ **检查SD卡文件*** /
档案文件=新的文件(strSDPath);
如果(!file.exists())
{
resServer ={\\StatusID \\:\\0 \\,\\错误\\:\\请检查SD卡\\路径};
返回null;
} 的FileInputStream的FileInputStream =新的FileInputStream(新文件(strSDPath)); 网址URL =新的URL(strUrlServer);
HttpURLConnection的康恩=(HttpURLConnection类)url.openConnection();
conn.setDoInput(真);
conn.setDoOutput(真);
conn.setUseCaches(假);
conn.setRequestMethod(POST); conn.setRequestProperty(连接,保持活动);
conn.setRequestProperty(内容类型,
的multipart / form-data的;边界=+边界); DataOutputStream类的OutputStream =新的DataOutputStream类(康恩
.getOutputStream());
outputStream.writeBytes(twoHyphens +边界+ lineEnd);
的OutputStream
.writeBytes(内容处置:表格数据;名称= \\filUpload \\;文件名= \\
+ strSDPath +\\+ lineEnd);
outputStream.writeBytes(lineEnd); 参考bytesAvailable = fileInputStream.available();
BUFFERSIZE = Math.min(方bytesAvailable,MAXBUFFERSIZE);
缓冲区=新的字节[缓冲区大小] //读取文件
读取动作= fileInputStream.read(缓冲液,0,缓冲区大小); 而(读取动作大于0){
outputStream.write(缓冲液,0,缓冲区大小);
参考bytesAvailable = fileInputStream.available();
BUFFERSIZE = Math.min(方bytesAvailable,MAXBUFFERSIZE);
读取动作= fileInputStream.read(缓冲液,0,缓冲区大小);
} outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens +边界+ twoHyphens + lineEnd); //响应code和留言
RES code = conn.getResponse code();
如果(RES code == HttpURLConnection.HTTP_OK)
{
InputStream为= conn.getInputStream();
ByteArrayOutputStream BOS =新ByteArrayOutputStream(); INT读= 0;
而((读= is.read())!= -1){
bos.write(读);
}
字节[]结果= bos.toByteArray();
bos.close(); resMessage =新的字符串(结果);
} Log.d(RES code =,Integer.toString(RES code));
Log.d(resMessage =,resMessage.toString()); fileInputStream.close();
outputStream.flush();
outputStream.close(); resServer = resMessage.toString(); }赶上(例外前){
// 异常处理
返回null;
}
返回null;
} 保护无效onPostExecute(虚空未使用){
statusWhenFinish(位置,resServer);
}
}//当上传完成
保护无效statusWhenFinish(INT位置,弦乐resServer){ 视图V = lstView.getChildAt(位置 - lstView.getFirstVisiblePosition()); //显示进度
进度进度=(进度)v.findViewById(R.id.progressBar);
progress.setVisibility(View.GONE);
// 状态
TextView的状态=(TextView中)v.findViewById(R.id.ColStatus);
/*** 默认值 ***/
串strStatusID =0;
字符串strMessage =未知状态!; 尝试{ JSONObject的C =新的JSONObject(resServer);
strStatusID = c.getString(StatusID);
strMessage = c.getString(信息);
}赶上(JSONException E){
// TODO自动生成catch块
e.printStackTrace();
} // prepare状态
如果(strStatusID.equals(0))
{
//当更新失败
status.setText(strMessage);
status.setTextColor(Color.RED); 再次启用//按钮
按钮btnUpload =(按钮)v.findViewById(R.id.btnUpload);
btnUpload.setText(已上传);
btnUpload.setTextColor(Color.RED);
btnUpload.setEnabled(真);
}
其他
{
status.setText(上传已完成。);
status.setTextColor(Color.GREEN);
}
}
}
解决方案
在引用变量,它们必须是方法的范围内确定的。
因此,对于方法,确保它作为参数传递两种,或者它被定义为类中的一个全局变量。
I want to call startUpload(position);
method in loginbutton.setOnClickListener(new View.OnClickListener() {}
like this:
loginbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SaveData();
alertDialog.dismiss();
startUpload(position);
}
but always getting : position cannot be resolved to a variable
so where i am doing mistake, how can i resolve this issue..?
//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);
}
}
}
解决方案
When referencing variables, they must be definitive within the scope of the method.
So for methods, make sure it is either passed as a parameter, or it is defined as a global variable within the class.
这篇关于如何在全球范围类的方法声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文