我正在根据我在互联网上找到的示例,使用android创建多上传屏幕。我进行了一些简单的修改,使每个文件发送给谁的文件传递到列表的下一个文件。 我使用了以下简单的行:
int n = ImageList.size()-1;
if (position<n) {
startUpload(position + 1);
}
这是链接上的完整代码。
例如:http://www.thaicreate.com/mobile/android-upload-file-show-items-progressbar-listview.html
更多遇到了麻烦。问题是当它自动进入列表视图的问题字段时,它在屏幕上不可见,系统停止并且它吸收了消息和错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById (int)' on a null object reference.
我已经搜索了论坛,但没有找到解决方案。
此行中发生错误:
View v = lstView.getChildAt(position - lstView.getFirstVisiblePosition());
完整代码:
public class MainActivity extends Activity {
private ListView lstView;
private Handler handler = new Handler();
private int counter = 0;
List <String> ImageList;
private ProgressBar progress;
private TextView status;
private Button btnUpload;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*** Get Images from SDCard ***/
ImageList = getSD();
// ListView and imageAdapter
lstView = (ListView) findViewById(R.id.listView1);
lstView.setAdapter(new ImageAdapter(this));
}
private List <String> getSD()
{
List <String> it = new ArrayList <String>();
File f = new File ("/mnt/sdcard/RAIOTOI/photo/");
File[] files = f.listFiles ();
for (int i = 0; i <files.length; i++)
{
File file = files[i];
Log.d("Count",file.getPath());
it.add (file.getPath());
}
return it;
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageAdapter(Context c)
{
// TODO Auto-generated method stub
context = c;
}
public int getCount() {
// TODO Auto-generated method stub
return ImageList.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.activity_column, null);
}
status = (TextView) convertView.findViewById(R.id.ColStatus);
btnUpload = (Button) convertView.findViewById(R.id.btnUpload);
// ColImgName
TextView txtName = (TextView) convertView.findViewById(R.id.ColImgName);
String strPath = ImageList.get(position).toString();
// Get File Name
String fileName = strPath.substring( strPath.lastIndexOf('/')+1, strPath.length() );
File file = new File(strPath);
long length = file.length();
txtName.setPadding(3, 0, 0, 0);
txtName.setText(fileName + " ("+length/1024+" KB.)");
// Image Resource
ImageView imageView = (ImageView) convertView.findViewById(R.id.ColImgPath);
imageView.getLayoutParams().height = 110;
imageView.getLayoutParams().width = 110;
imageView.setPadding(10, 10, 2, 10);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
Bitmap bm = BitmapFactory.decodeFile(strPath);
imageView.setImageBitmap(bm);
// ColStatus
final TextView txtStatus = (TextView) convertView.findViewById(R.id.ColStatus);
txtStatus.setPadding(3, 0, 0, 0);
txtStatus.setText("...");
// progressBar
progress = (ProgressBar) convertView.findViewById(R.id.progressBar);
progress.setVisibility(View.GONE);
progress.setPadding(0, 0, 0, 0);
//btnUpload
final Button btnUpload = (Button) convertView.findViewById(R.id.btnUpload);
btnUpload.setTextColor(Color.BLACK);
btnUpload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Upload
btnUpload.setEnabled(false);
btnUpload.setTextColor(Color.GRAY);
startUpload(position);
}
});
return convertView;
}
}
//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
status = (TextView) v.findViewById(R.id.ColStatus);
status.setText("Enviando...");
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://192.168.1.134:8080/up.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());
progress = (ProgressBar) v.findViewById(R.id.progressBar);
// Show ProgressBar
progress.setVisibility(View.GONE);
// Status
status = (TextView) v.findViewById(R.id.ColStatus);
/** Get result from Server (Return the JSON Code)
* StatusID = ? [0=Failed,1=Complete]
* Error = ? [On case error return custom error message]
*
* Eg Upload Failed = {"StatusID":"0","Error":"Cannot Upload file!"}
* Eg Upload Complete = {"StatusID":"1","Error":""}
*/
/*** Default Value ***/
String strStatusID = "0";
String strError = "Unknow Status!";
try {
JSONObject c = new JSONObject(resServer);
strStatusID = c.getString("StatusID");
strError = c.getString("Error");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Prepare Status
if(strStatusID.equals("0"))
{
// When update Failed
status.setText("FALHOU ("+ strError +")");
status.setTextColor(Color.RED);
// Enabled Button again
btnUpload = (Button) v.findViewById(R.id.btnUpload);
btnUpload.setText("Repetir");
btnUpload.setTextColor(Color.RED);
btnUpload.setEnabled(true);
}
else
{
status.setText("Envio completo.");
status.setTextColor(Color.GREEN);
btnUpload.setEnabled(false);
btnUpload.setTextColor(Color.GRAY);
int n = ImageList.size()-1;
Log.i("IDID", " "+position+" "+n);
if (position<n) {
startUpload(position + 1);
}
}
}
}
答案 0 :(得分:0)
您的 lstView 是null
,请确保先findViewById()
。