Android progress Dialog only updating Message , not the bar and the lines - android

I am going to implement the FTP download function. It works but when it comes to reporting the progress, I have only found that only the message changes but not the numbers and the bar changing
I have screen captured as below
The below is my code:
public void buttonExit(View v) {
System.exit(1);
}
public void doClick(View v){
//ftp
filename = null;
filename = "giant.mp4";
pd = new ProgressDialog(this);
pd.setTitle("EOrder");
pd.setMessage("Downloading file. Please wait...");
pd.setIndeterminate(true);
pd.setMax(100);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setProgress(0);
pd.setCancelable(false);
pd.show();
ad = new AlertDialog.Builder(this);
ad.setTitle("EOrder");
ad.setMessage("Download Finish");
ad.setNeutralButton("OK", null);
new FTPDownload().execute(filename);
}
class FTPDownload extends AsyncTask<String , String , Void>{
boolean running = true;
Date today = Calendar.getInstance().getTime();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
String reportDate = formatter.format(today);
String fileAndroid = reportDate + "_" + filename;
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
Log.d("******", "Background thread starting......");
FTPClient client = new FTPClient();
try {
Log.d("tag" , "arrived");
client.connect("newaswrissssing.win5.siteonlinetest.com");
boolean successLogin = client.login("newaswrissssing", "newaswrissssing2014cap!");
if(successLogin){
client.changeWorkingDirectory("dummy");
Log.d("tag" , "success");
long fileSize = getFileSize(client , params[0]);
client.setFileType(FTP.BINARY_FILE_TYPE);
client.enterLocalPassiveMode();
File instanceRecordDirectory = new File(Environment.getExternalStorageDirectory() + File.separator + "TVB_Movie");
if(!instanceRecordDirectory.exists()){
instanceRecordDirectory.mkdirs();
}
File instanceRecord = new File(instanceRecordDirectory.getAbsolutePath() + File.separator + fileAndroid);
if(!instanceRecord.exists()){
instanceRecord.createNewFile();
}
BufferedOutputStream desFileStream = new BufferedOutputStream(new FileOutputStream(instanceRecord.getAbsolutePath()),8*1024);
InputStream in = client.retrieveFileStream(params[0]);
Log.d("as" , String.valueOf(in));
byte[] buffer = new byte[1024];
int len1 = 0;
long total = 0;
while ((len1 = in.read(buffer)) > 0) {
total += len1; //total = total + len1
Log.d("aDDs" , String.valueOf(in));
publishProgress("" + (int)((total*100)/fileSize));
desFileStream.write(buffer, 0, len1);
}
desFileStream.flush();
desFileStream.close();
client.completePendingCommand();
in.close();
}else{
Log.d("tag" , "sosad");
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
client.logout();
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
protected void onProgressUpdate(String... progress) {
super.onProgressUpdate(progress);
Log.d("progress","values: "+progress[0]);
pd.incrementProgressBy(Integer.parseInt(progress[0]));
pd.setMessage("Downloading file... Progress at " + progress[0] + "%");
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pd.dismiss();
ad.show();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
Would you please tell me what other steps to do besides using pd.incrementProgressBy(Integer.parseInt(progress[0])); or setProgress?

your ProgressDialog should not be intederminate. You should call setIndeterminate with false instead of true
pd.setIndeterminate(false);
and you should use setProgress instead of incrementProgressBy

Related

Populate Android SQLite Dat Records into Excel

I create my Project . but I sucked in final mode.. My Table has been generated but for attaching Purpose, I have to create that Table into EXCEL.. PLease give me link. I also tried for pdf but API is not free for commercial use. so give me guide lines , links or GitHub...
Solution is to convert the sqlite database into csv then convert the csv file to xls.You will need 2 libraries (opencsv-1.7.jar poi-3.8-20120326.jar)
public class ExportDatabaseCSVTask extends AsyncTask<String, Void, Boolean>
{
private final ProgressDialog dialog = new ProgressDialog(DatabaseExampleActivity.this);
#Override
protected void onPreExecute()
{
this.dialog.setMessage("Exporting database...");
this.dialog.show();
}
protected Boolean doInBackground(final String... args)
{
File dbFile=getDatabasePath("database_name");
//AABDatabaseManager dbhelper = new AABDatabaseManager(getApplicationContext());
AABDatabaseManager dbhelper = new AABDatabaseManager(DatabaseExampleActivity.this) ;
System.out.println(dbFile); // displays the data base path in your logcat
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists())
{
exportDir.mkdirs();
}
File file = new File(exportDir, "excerDB.csv");
try
{
if (file.createNewFile()){
System.out.println("File is created!");
System.out.println("myfile.csv "+file.getAbsolutePath());
}else{
System.out.println("File already exists.");
}
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
//SQLiteDatabase db = dbhelper.getWritableDatabase();
Cursor curCSV=db.getdb().rawQuery("select * from " + db.TABLE_NAME,null);
csvWrite.writeNext(curCSV.getColumnNames());
while(curCSV.moveToNext())
{
String arrStr[] ={curCSV.getString(0),curCSV.getString(1),curCSV.getString(2)};
/*curCSV.getString(3),curCSV.getString(4)};*/
csvWrite.writeNext(arrStr);
}
csvWrite.close();
curCSV.close();
/*String data="";
data=readSavedData();
data= data.replace(",", ";");
writeData(data);*/
return true;
}
catch(SQLException sqlEx)
{
Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
return false;
}
catch (IOException e)
{
Log.e("MainActivity", e.getMessage(), e);
return false;
}
}
protected void onPostExecute(final Boolean success)
{
if (this.dialog.isShowing())
{
this.dialog.dismiss();
}
if (success)
{
Toast.makeText(DatabaseExampleActivity.this, "Export succeed", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(DatabaseExampleActivity.this, "Export failed", Toast.LENGTH_SHORT).show();
}
}}
Export CSV to XLS part
public class CSVToExcelConverter extends AsyncTask<String, Void, Boolean> {
private final ProgressDialog dialog = new ProgressDialog(DatabaseExampleActivity.this);
#Override
protected void onPreExecute()
{this.dialog.setMessage("Exporting to excel...");
this.dialog.show();}
#Override
protected Boolean doInBackground(String... params) {
ArrayList arList=null;
ArrayList al=null;
//File dbFile= new File(getDatabasePath("database_name").toString());
File dbFile=getDatabasePath("database_name");
String yes= dbFile.getAbsolutePath();
String inFilePath = Environment.getExternalStorageDirectory().toString()+"/excerDB.csv";
outFilePath = Environment.getExternalStorageDirectory().toString()+"/test.xls";
String thisLine;
int count=0;
try {
FileInputStream fis = new FileInputStream(inFilePath);
DataInputStream myInput = new DataInputStream(fis);
int i=0;
arList = new ArrayList();
while ((thisLine = myInput.readLine()) != null)
{
al = new ArrayList();
String strar[] = thisLine.split(",");
for(int j=0;j<strar.length;j++)
{
al.add(strar[j]);
}
arList.add(al);
System.out.println();
i++;
}} catch (Exception e) {
System.out.println("shit");
}
try
{
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");
for(int k=0;k<arList.size();k++)
{
ArrayList ardata = (ArrayList)arList.get(k);
HSSFRow row = sheet.createRow((short) 0+k);
for(int p=0;p<ardata.size();p++)
{
HSSFCell cell = row.createCell((short) p);
String data = ardata.get(p).toString();
if(data.startsWith("=")){
cell.setCellType(Cell.CELL_TYPE_STRING);
data=data.replaceAll("\"", "");
data=data.replaceAll("=", "");
cell.setCellValue(data);
}else if(data.startsWith("\"")){
data=data.replaceAll("\"", "");
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(data);
}else{
data=data.replaceAll("\"", "");
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(data);
}
//*/
// cell.setCellValue(ardata.get(p).toString());
}
System.out.println();
}
FileOutputStream fileOut = new FileOutputStream(outFilePath);
hwb.write(fileOut);
fileOut.close();
System.out.println("Your excel file has been generated");
} catch ( Exception ex ) {
ex.printStackTrace();
} //main method ends
return true;
}
protected void onPostExecute(final Boolean success)
{
if (this.dialog.isShowing())
{
this.dialog.dismiss();
}
if (success)
{
Toast.makeText(DatabaseExampleActivity.this, "file is built!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(DatabaseExampleActivity.this, "file fail to build", Toast.LENGTH_SHORT).show();
}
}
}

Maintain progress of progressbar on orientation change in android

I am trying to download multiple videos from server using AsyncTask, I have list of progress bar for videos but I am unable to maintain the progress for each progress bar on orientation change of my phone.
I am calling downlodThreadVideos() in adapter of listview
public UserVideoDTO downlodThreadVideos(final ProgressBar _progress, ImageView _imgLaunch, ImageView _imgDownload, UserVideoDTO vpideoDTO)
{
DownloadVideoFileAsyncTask mDownloadFileAsync = new DownloadVideoFileAsyncTask(videoDTO,_progress,_imgLaunch,_imgDownload);
mDownloadFileAsync.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,videoDTO);
return mDownloadFileAsync._videoDTO;
}
private class DownloadVideoFileAsyncTask extends AsyncTask<UserVideoDTO, Integer, UserVideoDTO> {
ProgressBar _progress;
ImageView _imgLaunch;
ImageView _imgDownload;
public UserVideoDTO _videoDTO;
String OfflinePath=null;
public DownloadVideoFileAsyncTask(UserVideoDTO videoDTO,ProgressBar progress, ImageView imgLaunch, ImageView imgDownload) {
// TODO Auto-generated constructor stub
_videoDTO=videoDTO;
_progress = progress;
_imgLaunch=imgLaunch;
_imgDownload=imgDownload;
}
protected UserVideoDTO doInBackground(UserVideoDTO... params) {
UserVideoDTO videoDTO = _videoDTO;
try {
String _videoURL="http://mylinkforvideodownload/videoDTO.onlinepath";
if (cancelThread)
return null;
String Path = new String(_videoURL);
Path = Path.replaceAll(" ", "%20");
URL url = new URL(Path);
long startTime = System.currentTimeMillis();
HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
ucon.setConnectTimeout(60000);
File folder = new File(getExternalFilesDir(null).getAbsolutePath()+"/Download");
folder.mkdir();
String fileName = getExternalFilesDir(null).getAbsolutePath()+ "/Download/videos_";
File file = new File(fileName);
String offlineFileName = videoDTO.lmsvideoid;
String offlineFilePath = file + offlineFileName + ".mp4";
BufferedInputStream inStream = new BufferedInputStream(ucon.getInputStream());
FileOutputStream outStream = new FileOutputStream(offlineFilePath);
byte[] buff = new byte[1024];
int lengthOfFile = ucon.getContentLength();
int len;
long total = 0;
try {
while (!cancelThread && ((len = inStream.read(buff)) != -1)) {
total += len;
publishProgress((int) ((total * 100) / lengthOfFile));
outStream.write(buff, 0, len);
}
} catch (Exception e) {
cancelThread = true;
}
outStream.flush();
outStream.close();
inStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
return videoDTO;
}
protected void onProgressUpdate(Integer... progress) {
Log.d("ANDRO_ASYNC", progress[0].toString());
_progress.setProgress(progress[0]);
}
protected void onPreExecute() {
super.onPreExecute();
_progress.setMax(100);
}
protected void onPostExecute(UserVideoDTO result) {
super.onPostExecute(result);
_progress.setProgress(100);
}
protected void onCancelled() {
super.onCancelled();
}
}

How to implement "downloader files" in a method?

I have created a code to download multiple files showing a progressbar progress. This works perfectly, but now I want to deploy it to an external project (library itself) and I have problems.
My intention is to call "download" and when the download completes or returns 0 or 1. But being asynchronous the method returns the value before finishing., I tried to control it without success with "CountdownLatch" ...
Any idea?
The following code works, the problem is that the method "download" returns the value without waiting for it to finish the rest of code.
Main.java
if(MyLib.download(Main.this, url, nameFiles, "internal", "folderExtra") == 1){
System.out.println("SUCCESS DOWNLOAD!");
}else{
System.out.println("error download");
}
MyLib.java
/** DOWNLOADER WITH PROCESSDIALOG **/
ProgressDialog pDialog;
Context context;
String urlName;
String[] filesToDownload;
int downloadOK = -1;
int currentFile = -1;
int totalFiles = 0;
String typeStorage = "internal";
String folder = "";
CountDownLatch controlLatch;
public int download(Context ctx, String urlName, String[] filesToDownload, String typeStorage, String extraFolder ){
System.out.println("estoy en download");
this.context = ctx;
this.urlName = urlName;
this.filesToDownload = filesToDownload;
this.totalFiles = filesToDownload.length;
this.typeStorage = typeStorage;
/** Almacenamiento de la descarga - Interno o externo **/
if (typeStorage.equalsIgnoreCase("internal")) {
System.out.println("internal");
this.folder = context.getFilesDir().toString() + "/";
} else if (typeStorage.equalsIgnoreCase("external")) {
System.out.println("external");
}
/** COMPLETEMENTO DIRECTORIO/S OPCIONAL **/
if (extraFolder != null && extraFolder != "") {
folder += extraFolder;
}
System.out.println("FOLDER: " + folder);
File directoryFile = new File(folder);
if (!directoryFile.isDirectory()) {
if (!directoryFile.mkdir()) {
Toast.makeText(context, "No se puede crear el directorio o no existe", Toast.LENGTH_LONG).show();
}
}
pDialog = new ProgressDialog(context);
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setTitle("Descargando recursos...");
// controlLatch = new CountDownLatch(1);
startDownload();
/*
try {
System.out.println("STOP");
controlLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
*/
return downloadOK;
}
private void startDownload() {
currentFile++;
System.out.println("startDownload!");
if (currentFile < totalFiles) {
pDialog.setMessage("Descargando " + (currentFile + 1) + " de " + totalFiles + "\n\n(..." + filesToDownload[currentFile] + ")");
System.out.println("startDownload currentFile +[" + currentFile + "] totalFiles [" + totalFiles + "]");
System.out.println("file: " + filesToDownload[currentFile].toString());
new DownloaderFile().execute(filesToDownload[currentFile]);
}
}
private class DownloaderFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
try {
File checkFile = new File(folder + params[0]);
if(!checkFile.exists()){
URL urlFinal = new URL(urlName+params[0]);
URLConnection connection = urlFinal.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
InputStream input = new BufferedInputStream(urlFinal.openStream());
OutputStream output = new FileOutputStream(folder + params[0]);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} else {
System.out.println("The file " + filesToDownload[currentFile] + " is downloaded" );
}
} catch (Exception e) {
e.printStackTrace();
return "error";
}
return "ok";
}
#Override
protected void onPreExecute() {
super.onPreExecute();
System.out.println("-1");
File checkFile = new File(folder + filesToDownload[currentFile]);
if(!checkFile.exists()){
System.out.println("pDialogShow");
pDialog.show();
}
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
pDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String res) {
System.out.println("10");
if (currentFile == (totalFiles - 1)) {
System.out.println("FINISH!!!!!!!!!!!!!!");
currentFile = 0;
pDialog.dismiss();
downloadOK = 1;
//controlLatch.countDown();
} else {
if (res.equals("ok")) {
startDownload();
} else {
System.out.println("error download");
downloadOK = 0;
}
}
}
}
It sounds like you want callback.
Your DownloaderFile class can take a listener interface which is implemented by whatever contains the DownloaderFile object. Call that listener inside onPostExecute().
It might look like this:
public class MyActivity extends Activity implements OnDownloadCompleteListener {
private void startDownload() {
//inside whatever method
Downloader downloader = new Downloader(this); //'this' implements OnDownloadCompleteListener
downloader.go();
}
#Override
public void onDownloadFinished(boolean success) {
//implementation
}
}
Inside Downloader:
//...
#Override
protected void onPostExecute(String res) {
onDownloadCompleteListener.onDownloadComplete(true);
}
The OnDownloadCompleteListener interface:
public interface OnDownloadCompleteListener {
public void onDownloadComplete(boolean success);
}

How to prevent a method returns a default value before finishing its function?

I have 2 projects: App Project and own library.
My project have this code:
main.java (MyProject)
...
// call method Lib.download()
String nameFiles[] = {"do.mp3","re.mp3","mi.mp3","billiejean.mp3"};
String url = "http://myweb.net/getfiles/";
if( Lib.download(Main.this, url, nameFiles, "internal", "folderExtra" ) == 1){
System.out.println("finish");
} else {
System.out.println("error download");
}
The problem is that Lib.download return the default value without waiting for it to finish the rest of code.
I'm trying controller this with Semaphore / CountDownLatch / whiles but it doesn't work and also i'm trying implement a callback but without success because classes for "download" must be out of my project. Any help?
The downloads are done correctly but the download method returns the value before completing the downloads ...
My intention is to call a method "download" from any activity, this launch the dialog process and the rest of my activity code does not run until this method "download" returns a value.
Lib.java (MyLib)
/** DOWNLOADER WITH PROCESSDIALOG **/
ProgressDialog pDialog;
Context context;
String urlName;
String[] filesToDownload;
int downloadOK = -1;
int currentFile = -1;
int totalFiles = 0;
String typeStorage = "internal";
String folder = "";
CountDownLatch controlLatch;
public int download(Context ctx, String urlName, String[] filesToDownload, String typeStorage, String extraFolder ){
this.context = ctx;
this.urlName = urlName;
this.filesToDownload = filesToDownload;
this.totalFiles = filesToDownload.length;
this.typeStorage = typeStorage;
/** Almacenamiento de la descarga - Interno o externo **/
if (typeStorage.equalsIgnoreCase("internal")) {
System.out.println("internal");
this.folder = context.getFilesDir().toString() + "/";
} else if (typeStorage.equalsIgnoreCase("external")) {
}
/** EXTRA OPTIONALL **/
if (extraFolder != null && extraFolder != "") {
folder += extraFolder;
}
File directoryFile = new File(folder);
if (!directoryFile.isDirectory()) {
if (!directoryFile.mkdir()) {
Toast.makeText(context, "problems create directory", Toast.LENGTH_LONG).show();
}
}
pDialog = new ProgressDialog(context);
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setTitle("Descargando recursos...");
// controlLatch = new CountDownLatch(1);
startDownload();
/*
try {
System.out.println("STOP");
controlLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
*/
return downloadOK;
}
private void startDownload() {
currentFile++;
System.out.println("startDownload!");
if (currentFile < totalFiles) {
pDialog.setMessage("Descargando " + (currentFile + 1) + " de " + totalFiles + "\n\n(..." + filesToDownload[currentFile] + ")");
System.out.println("startDownload currentFile +[" + currentFile + "] totalFiles [" + totalFiles + "]");
System.out.println("file: " + filesToDownload[currentFile].toString());
new DownloaderFile().execute(filesToDownload[currentFile]);
}
}
private class DownloaderFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
try {
File checkFile = new File(folder + params[0]);
if(!checkFile.exists()){
URL urlFinal = new URL(urlName+params[0]);
URLConnection connection = urlFinal.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
InputStream input = new BufferedInputStream(urlFinal.openStream());
OutputStream output = new FileOutputStream(folder + params[0]);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} else {
System.out.println("The file " + filesToDownload[currentFile] + " is downloaded" );
}
} catch (Exception e) {
e.printStackTrace();
return "error";
}
return "ok";
}
#Override
protected void onPreExecute() {
super.onPreExecute();
System.out.println("-1");
File checkFile = new File(folder + filesToDownload[currentFile]);
if(!checkFile.exists()){
System.out.println("pDialogShow");
pDialog.show();
}
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
pDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String res) {
System.out.println("10");
if (currentFile == (totalFiles - 1)) {
System.out.println("FINISH!!!!!!!!!!!!!!");
currentFile = 0;
pDialog.dismiss();
downloadOK = 1;
//controlLatch.countDown();
} else {
if (res.equals("ok")) {
startDownload();
} else {
System.out.println("error download");
downloadOK = 0;
}
}
}
}
AsyncTasks would run at separate thread once your .execute() is called. Your calling line startDownload() will never wait for AsyncTask to return any value, what you can do is:
Implement some callback interface on your main activity, so that your onPostExecute method would be able to notify your main activity once the operation is finished.
As you're the one developing this library, consider moving the AsyncTask to your main activity, and leave very plain download functions (what in your doInBackground method) in the library.
Use LocalBroadcastManager to send a broadcast from your library, listen and react to it on your main.java

android problem with progress dialog

I have an application where I fetch data from http server & set data to activity.
for fetching data from server it takes time. so i want to give an progress dialog there.
I did that but problem is that progressdialog is coming but its not rotating(only constant).
Plz anybody tell me how it came like this!
Below is my code,
private void setupViews()
{
imgRestro = (ImageView) findViewById(R.id.imageResturant);
tvRestroName = (TextView) findViewById(R.id.tvRestroName);
tvRestroAddr = (TextView) findViewById(R.id.tvRestroAddr);
tvRestroArea = (TextView) findViewById(R.id.tvRestroArea);
tvRestroCity = (TextView) findViewById(R.id.tvRestroCity);
tvRestroPhone = (TextView) findViewById(R.id.tvRestroPhone);
tvRestroRating = (TextView) findViewById(R.id.tvRestroRating);
tvRestroCuisines = (TextView) findViewById(R.id.tvRestroCuisines);
tvRestroAttr = (TextView) findViewById(R.id.tvRestroAttributes);
}
//to execute url
private String executeHttpGet(String URL) throws Exception {
URL url = null;
StringBuffer strBuf = null;
BufferedReader read = null;
HttpURLConnection httprequest = null;
try {
url = new URL(URL);
httprequest = (HttpURLConnection) url.openConnection();
httprequest.setRequestMethod("GET");
httprequest.setDoInput(true);
httprequest.setDoOutput(true);
httprequest.setConnectTimeout(5000); //time for before connect
httprequest.setRequestProperty("Content-Type",
"text/plain; charset=utf-8");
//httprequest.setReadTimeout(15000); //time for after connect
read = new BufferedReader(new InputStreamReader(
httprequest.getInputStream()));
strBuf = new StringBuffer();
String line = "";
while ((line = read.readLine()) != null) {
strBuf.append(line).append("\n");
}
} catch (IOException ex) {
} finally {
try {
httprequest.disconnect();
read.close();
} catch (Exception ex) {
}
}
return strBuf.toString();
}
//to assign all the info from json to activity textview or imageview
private void examineJSONFile() {
try {
String str = "";
page = executeHttpGet(url);
Log.i("hello", str.toString());
JSONObject topobj = new JSONObject(page);
JSONObject innerobj = topobj.getJSONObject("restarutant");
tvRestroName.setText("Restaurant "+innerobj.getString("name"));
String photoURL = innerobj.getString("photo");
URI uri = new URI(photoURL);
Bitmap bmp = loadBitmap(photoURL);
System.out.println("str ;" + photoURL + " uri " + uri);
imgRestro.setImageBitmap(Bitmap.createScaledBitmap(bmp, 300, 300,true));
tvRestroAddr.setText("Address: " + innerobj.getString("address"));
tvRestroArea.setText("Area: " + innerobj.getString("area"));
tvRestroCity.setText("City: " + innerobj.getString("city"));
JSONArray location = innerobj.getJSONArray("location");
String lat = location.get(0).toString();
String lng = location.get(1).toString();
latitude = Double.valueOf(lat.trim()).doubleValue();
longitude = Double.valueOf(lng.trim()).doubleValue();
System.out.println("Lat :" + latitude + " Long :" + longitude);
JSONArray phone = innerobj.getJSONArray("phone");
tvRestroPhone.setText("Phone: " + phone.get(0).toString() + " ,"
+ phone.get(1).toString());
tvRestroRating.setText("Rating: " + innerobj.getString("rating"));
JSONArray cuisines = innerobj.getJSONArray("cuisines");
tvRestroCuisines.setText("Cuisines: " + cuisines.get(0).toString()
+ " ," + cuisines.get(1).toString());
JSONArray attributes = innerobj.getJSONArray("attributes");
tvRestroAttr.setText("Attributes: " + attributes.get(0).toString()
+ " ," + attributes.get(1).toString() + " ,"
+ attributes.get(2).toString());
Log.i("hello", str.toString());
} catch (Exception je) {
tvRestroAddr.setText("Error w/file: " + je.getMessage());
}
}
// to get image from url in form of bitmap
private static Bitmap loadBitmap(String url) {
URL myFileUrl = null;
InputStream is = null;
try {
myFileUrl = new URL(url);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
Log.i("im connected", "Download");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return BitmapFactory.decodeStream(is);
}
//for progressdialog
private class DownloadTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog = new ProgressDialog(InfoActivity.this);
protected void onPreExecute() {
System.out.println("In onPreExecute ");
dialog.setTitle("Loading..");
dialog.setMessage("Downloading source..");
dialog.setProgress(100);
dialog.setMax(5000);
dialog.show();
}
protected Void doInBackground(Void... unused) {
//examineJSONFile();
System.out.println("In doInBackground ");
return null;
}
protected void onPostExecute(Void unused) {
System.out.println("In onPostExecute ");
dialog.dismiss();
examineJSONFile();
}
Plz have a look and give the answer.
Thank you
You should override onProgressUpdate() method in AsyncTask and change your dialog's value there. You can send your progress value to the dialog via publishProgress() method from doInBackground(). Hope this helps.
Try using Async task as shown below:
try{
class test extends AsyncTask{
TextView tv_per;
int mprogress;
Dialog UpdateDialog = new Dialog(ClassContext);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
mprogress = 0;
UpdateDialog.setTitle(getResources().getString(R.string.app_name));
UpdateDialog.setContentView(R.layout.horizontalprogressdialog);
TextView dialog_message = (TextView)UpdateDialog.findViewById(R.id.titleTvLeft);
tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
dialog_message.setText(getResources().getString(R.string.dialog_retrieving_data));
dialog_message.setGravity(Gravity.RIGHT);
UpdateDialog.setCancelable(false);
UpdateDialog.show();
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Object... values) {
// TODO Auto-generated method stub
ProgressBar update = (ProgressBar)UpdateDialog.findViewById(R.id.horizontalProgressBar);
update.setProgress((Integer) values[0]);
int percent = (Integer) values[0];
if(percent>=100)
{
percent=100;
}
tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
tv_per.setText(""+percent);
}
#Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
//your code
}
super.onPostExecute(result);
UpdateDialog.dismiss();
}
}
new test().execute(null);
}
catch(Exception e)
{
e.printStackTrace();
}

Categories

Resources