Android 显示JSON的上载进度
我有下面的一段代码,我想在这里添加一个特性,这样我就知道什么时候上传Android 显示JSON的上载进度,android,json,androidhttpclient,Android,Json,Androidhttpclient,我有下面的一段代码,我想在这里添加一个特性,这样我就知道什么时候上传JSON内容了我正在上传一个JSON内容 @Override protected String doInBackground(JSONObject... params) { // TODO Auto-generated method stub String state = ""; HttpPost httpPost = new HttpPost(commentURL); StringEntity
JSON
内容了我正在上传一个JSON
内容
@Override
protected String doInBackground(JSONObject... params) {
// TODO Auto-generated method stub
String state = "";
HttpPost httpPost = new HttpPost(commentURL);
StringEntity se = null;
HttpResponse response = null;
HttpEntity entity = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
InputStream is = null;
try {
se = new StringEntity(params[0].toString());
Log.i("SE", params[0].toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
httpPost.setEntity(se);
try {
response = httpClient.execute(httpPost);
Log.i("HTTP POST", httpPost.toString());
Log.i("RESPONSE", response.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
entity = response.getEntity();
try {
is = entity.getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
state = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return state;
}
我试着研究自己,在那里我偶然发现了
多个部分
,但由于我要通过POST
上传一个简单的JSON
内容,我觉得没有必要使用它。那么,我如何显示上传过程中取得了多少进展,以及JSON内容的总大小呢??我有点想我必须使用StringEntity
?我说的对吗?启动进度条
private ProgressDialog pDialog;
关于onPreExecute()
关于onPostExecute()
用于显示带有百分比的进度条,请尝试
public class AndroidDownloadFileByProgressBarActivity extends Activity {
// button to show progress dialog
Button btnShowProgress;
// Progress Dialog
private ProgressDialog pDialog;
ImageView my_image;
// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0;
// File url to download
private static String file_url = "your_url";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// show progress bar button
btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
// Image view to show image after downloading
my_image = (ImageView) findViewById(R.id.my_image);
/**
* Show Progress bar click event
* */
btnShowProgress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
}
});
}
/**
* Showing Dialog
* */
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
@Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
// setting downloaded into image view
my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}
}
}
公共类AndroidDownloadFileByProgressBarActivity扩展活动{
//显示进度对话框的按钮
按钮BTN显示进度;
//进度对话框
私人对话;
图像查看我的图像;
//进度对话框类型(0-用于水平进度条)
公共静态最终整数进度条类型=0;
//要下载的文件url
私有静态字符串文件\u url=“您的\u url”;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//显示进度条按钮
btnShowProgress=(按钮)findViewById(R.id.btnProgressBar);
//图像视图,用于在下载后显示图像
my_image=(ImageView)findViewById(R.id.my_image);
/**
*显示进度条单击事件
* */
btnShowProgress.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
//启动新的异步任务
新建DownloadFileFromURL().execute(文件url);
}
});
}
/**
*显示对话框
* */
@凌驾
受保护的对话框onCreateDialog(int id){
开关(id){
案例进度条类型:
pDialog=新建进度对话框(此对话框);
setMessage(“正在下载文件,请稍候…”);
pDialog.setUndeterminate(假);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_水平);
pDialog.setCancelable(真);
pDialog.show();
返回pDialog;
违约:
返回null;
}
}
/**
*要下载文件的后台异步任务
* */
类DownloadFileFromURL扩展异步任务{
/**
*在启动后台线程之前
*显示进度条对话框
* */
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
显示对话框(进度条类型);
}
/**
*在后台线程中下载文件
* */
@凌驾
受保护的字符串doInBackground(字符串…f_url){
整数计数;
试一试{
URL=新URL(f_URL[0]);
URLConnection conconnection=url.openConnection();
conconnect.connect();
//获取文件长度
int lenghtOfFile=conconnect.getContentLength();
//读取文件的输入流-带8k缓冲区
InputStream输入=新的BufferedInputStream(url.openStream(),8192);
//输出流以写入文件
OutputStream output=新文件OutputStream(“/sdcard/downloaddedfile.jpg”);
字节数据[]=新字节[1024];
长总计=0;
而((计数=输入。读取(数据))!=-1){
总数+=计数;
//发布进度。。。。
//在此之后,将调用onProgressUpdate
出版进度(“+(int)((总计*100)/长度文档));
//将数据写入文件
输出.写入(数据,0,计数);
}
//冲洗输出
output.flush();
//合流
output.close();
input.close();
}捕获(例外e){
Log.e(“错误:,e.getMessage());
}
返回null;
}
/**
*更新进度条
* */
受保护的void onProgressUpdate(字符串…进度){
//设置进度百分比
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
*完成后台任务后
*关闭进度对话框
* **/
@凌驾
受保护的void onPostExecute(字符串文件\u url){
//下载文件后关闭对话框
解雇对话框(进度条类型);
//在图像视图中显示下载的图像
//从SD卡读取图像路径
字符串imagePath=Environment.getExternalStorageDirectory().toString()+“/downloadedfile.jpg”;
//设置已下载到图像视图中
my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}
}
}
启动进度条作为
private ProgressDialog pDialog;
关于onPreExecute()
关于onPostExecute()
用于显示带有百分比的进度条,请尝试
public class AndroidDownloadFileByProgressBarActivity extends Activity {
// button to show progress dialog
Button btnShowProgress;
// Progress Dialog
private ProgressDialog pDialog;
ImageView my_image;
// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0;
// File url to download
private static String file_url = "your_url";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// show progress bar button
btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
// Image view to show image after downloading
my_image = (ImageView) findViewById(R.id.my_image);
/**
* Show Progress bar click event
* */
btnShowProgress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
}
});
}
/**
* Showing Dialog
* */
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
@Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
// setting downloaded into image view
my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}
}
}
公共类AndroidDownloadFileByProgressBarActivity扩展活动{
//显示进度对话框的按钮
按钮BTN显示进度;
//进度对话框
私人对话;
图像查看我的图像;
//进度对话框类型(0-用于水平进度条)
公共静态最终整数进度条类型=0;
//要下载的文件url
私有静态字符串文件\u url=“您的\u url”;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);