ProgressBar crash after orientation change [closed] - android

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am having a problem with a task that shows live content from a site.
I have been playing around with this code for a while and playing around with the status but I can't seem to get it to work correctly.
The only solution I have been able to come up with so far is completely disable orientation changes, but I would prefer not to do that if possible.
Here is the Stack Trace:
STACK_TRACE = java.lang.IllegalArgumentException: View not attached to window manager
at android.view.WindowManagerImpl.findViewLocked(WindowManagerImpl.java:653)
at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:349)
at android.view.WindowManagerImpl$CompatModeWrapper.removeView(WindowManagerImpl.java:160)
at android.app.Dialog.dismissDialog(Dialog.java:319)
at android.app.Dialog.dismiss(Dialog.java:302)
at cl.cromer.tronwell.concepcion.Progress.dismiss(Progress.java:72)
at cl.cromer.tronwell.concepcion.AdditionalMaterial.databaseLoaded(AdditionalMaterial.java:149)
at cl.cromer.tronwell.concepcion.AdditionalMaterial.access$13(AdditionalMaterial.java:122)
at cl.cromer.tronwell.concepcion.AdditionalMaterial$1$1.run(AdditionalMaterial.java:73)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5031)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
at dalvik.system.NativeStart.main(Native Method)
Here is my code for the class that is crashing:
package cl.cromer.tronwell.concepcion;
import java.util.Calendar;
import java.util.HashMap;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cl.cromer.tronwell.concepcion.DBSchema.DBAdditionalMaterial;
import cl.cromer.tronwell.concepcion.DBSchema.DBAdditionalMaterialGroups;
import cl.cromer.tronwell.concepcion.Files.Download;
public class AdditionalMaterial extends ActionBarActivity implements ListenerXML, ListenerDownload, ListenerAsync {
private final static String URL = "action=downloads";
private XMLParser xmlParser;
private Progress progress = null;
// Parsers
private SQLParser sqlParser;
private Handler threadHandler = new Handler();
// The database
private SQLiteDatabase tronDB;
private int downloadId = 0;
private boolean downloadAll = false;
private int downloadCount = 1;
private int firstDownloadAvailable = 0;
private String fileName;
private Files files = new Files();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("debug", "onCreate");
setContentView(R.layout.activity_additional_material);
//progress = new Progress();
//progress.show(this, this, false);
sqlParser = new SQLParser(this);
new Thread(new Runnable() {
public void run() {
tronDB = sqlParser.getWritableDatabase();
threadHandler.post(new Runnable() {
public void run() {
databaseLoaded();
}
});
}
}).start();
}
#Override
protected void onStart() {
super.onStart();
Log.d("debug", "onStart");
}
#Override
protected void onRestart() {
super.onRestart();
Log.d("debug", "onRestart");
}
#Override
protected void onResume() {
super.onResume();
progress = new Progress();
progress.show(this, this, false);
Log.d("debug", "onResume");
}
#Override
protected void onStop() {
super.onStop();
Log.d("debug", "onStop");
}
#Override
protected void onDestroy() {
super.onDestroy();
progress = null;
Log.d("debug", "onDestroy");
}
#Override
public void onPause() {
super.onPause();
Log.d("debug", "onDestroy");
}
private void databaseLoaded() {
SharedPreferences settings = getSharedPreferences(Settings.PREFERENCES, MODE_PRIVATE);
long materialDate = settings.getLong(Settings.MATERIAL_DATE, Settings.MATERIAL_DATE_DEFAULT);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 6);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
long currentDate = calendar.getTimeInMillis();
if (currentDate > materialDate ) {
// Update the database
String rut = settings.getString(Settings.RUT, Settings.RUT_DEFAULT);
String password = settings.getString(Settings.PASSWORD, Settings.PASSWORD_DEFAULT);
HashMap<String, String> postData = new HashMap<String, String>();
postData.put("rut", rut);
postData.put("pass", password);
xmlParser = new XMLParser(this, postData);
xmlParser.fetchListener = this; // Tell the XMLParser that this activity has the listener
xmlParser.execute(MainActivity.URL + URL);
}
else {
// Material does not need to be updated, just show what is in the database
if (progress != null && progress.isShowing()) {
progress.dismiss();
}
ShowContent showContent = new ShowContent(this);
showContent.asyncListener = this; // Tell the task that this class is listening
showContent.execute();
}
}
private void fetchFinished(HashMap<String, HashMap<String, String>> xmlData) {
// Let's put the groups in the database
HashMap<String, String> xmlHash = xmlData.get("1");
String groups = xmlHash.get("groups");
for (int i = 1; i <= Integer.valueOf(groups); i++) {
ContentValues values = new ContentValues();
values.put(DBAdditionalMaterialGroups.COLUMN_ID, String.valueOf(i));
values.put(DBAdditionalMaterialGroups.COLUMN_NAME, xmlHash.get("group" + String.valueOf(i)));
tronDB.replace(
DBAdditionalMaterialGroups.TABLE_NAME,
null,
values);
}
// Now the material
for (int i = 2; i <= xmlData.size() - 1; i++) {
xmlHash = xmlData.get(String.valueOf(i));
ContentValues values = new ContentValues();
values.put(DBAdditionalMaterial.COLUMN_ID, xmlHash.get("id"));
values.put(DBAdditionalMaterial.COLUMN_NAME, xmlHash.get("title"));
values.put(DBAdditionalMaterial.COLUMN_GROUP, xmlHash.get("group"));
values.put(DBAdditionalMaterial.COLUMN_TYPE, xmlHash.get("type"));
values.put(DBAdditionalMaterial.COLUMN_URL1, xmlHash.get("url1"));
values.put(DBAdditionalMaterial.COLUMN_URL2, xmlHash.get("url2"));
tronDB.replace(
DBAdditionalMaterial.TABLE_NAME,
null,
values);
}
SharedPreferences settings = getSharedPreferences(Settings.PREFERENCES, MODE_PRIVATE);
SharedPreferences.Editor settingsEditor = settings.edit();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 6);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
long currentDate = calendar.getTimeInMillis();
settingsEditor.putLong(Settings.MATERIAL_DATE, currentDate);
settingsEditor.commit();
progress.dismiss();
ShowContent showContent = new ShowContent(this);
showContent.asyncListener = this; // Tell the task that this class is listening
showContent.execute();
}
#TargetApi(Build.VERSION_CODES.FROYO)
protected class ShowContent extends AsyncTask<String, View, Void> {
private Context context;
private PowerManager.WakeLock wakeLock;
protected ListenerAsync asyncListener = null; // This needs to be set from the parent activity
private LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
protected ShowContent(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Let's make sure the CPU doesn't go to sleep
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
wakeLock.acquire();
}
#SuppressLint("InflateParams")
#Override
protected Void doInBackground(String... passedInfo) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View categoryView;
View downloadView;
View seperatorView;
TextView textView = new TextView(context);
ImageButton imageButton = new ImageButton(context);
Cursor cursorMaterialGroups = tronDB.query(
DBAdditionalMaterialGroups.TABLE_NAME,
DBAdditionalMaterialGroups.ALL_COLUMNS,
null,
null,
null,
null,
DBAdditionalMaterialGroups.COLUMN_ID + " ASC",
null);
while (cursorMaterialGroups.moveToNext()) {
// Create a group TextView by inflating a layout
categoryView = inflater.inflate(R.layout.additional_material_category, null);
textView = (TextView) categoryView;
textView.setText(cursorMaterialGroups.getString(cursorMaterialGroups.getColumnIndex(DBAdditionalMaterialGroups.COLUMN_NAME)));
publishProgress(textView);
// Now to get the downloads from the group
Cursor cursorMaterial = tronDB.query(DBAdditionalMaterial.TABLE_NAME,
DBAdditionalMaterial.ALL_COLUMNS,
DBAdditionalMaterial.COLUMN_GROUP + "=" + cursorMaterialGroups.getString(cursorMaterialGroups.getColumnIndex(DBAdditionalMaterialGroups.COLUMN_ID)),
null,
null,
null,
DBAdditionalMaterial.COLUMN_ID + " ASC",
null);
downloadCount += cursorMaterial.getCount();
while (cursorMaterial.moveToNext()) {
downloadView = inflater.inflate(R.layout.additional_material_download, null);
// Download title
textView = (TextView) downloadView.findViewById(R.id.download_title);
textView.setText(cursorMaterial.getString(cursorMaterial.getColumnIndex(DBAdditionalMaterial.COLUMN_NAME)));
// Download/play button
imageButton = (ImageButton) downloadView.findViewById(R.id.download_button);
imageButton.setId(Integer.valueOf(cursorMaterial.getString(cursorMaterial.getColumnIndex(DBAdditionalMaterial.COLUMN_ID))));
String fileName = null;
if (cursorMaterial.getString(cursorMaterial.getColumnIndex(DBAdditionalMaterial.COLUMN_TYPE)).equals("pdf")) {
fileName = cursorMaterial.getString(cursorMaterial.getColumnIndex(DBAdditionalMaterial.COLUMN_ID)) + ".pdf";
}
else {
fileName = cursorMaterial.getString(cursorMaterial.getColumnIndex(DBAdditionalMaterial.COLUMN_ID)) + ".mp3";
}
Drawable drawable = getResources().getDrawable(R.drawable.ic_action_play);
if (!files.fileExists(context, fileName)) {
if (firstDownloadAvailable == 0) {
firstDownloadAvailable = imageButton.getId();
}
drawable = getResources().getDrawable(R.drawable.ic_action_save);
imageButton.setImageDrawable(drawable);
imageButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
downloadId = view.getId();
download();
}
});
}
else {
imageButton.setImageDrawable(drawable);
imageButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String contentId = String.valueOf(view.getId());
openContent(contentId);
}
});
}
publishProgress(downloadView);
if (!cursorMaterial.isLast()) {
seperatorView = inflater.inflate(R.layout.additional_material_seperator, null);
publishProgress(seperatorView);
}
}
cursorMaterial.close();
}
// Other
categoryView = inflater.inflate(R.layout.additional_material_category, null);
textView = (TextView) categoryView;
textView.setText("OTHER");
publishProgress(textView);
// Download all
downloadView = inflater.inflate(R.layout.additional_material_download, null);
// Download title
textView = (TextView) downloadView.findViewById(R.id.download_title);
textView.setText("Download all material");
// Download/play button
imageButton = (ImageButton) downloadView.findViewById(R.id.download_button);
imageButton.setId(1);
Drawable drawable = getResources().getDrawable(R.drawable.ic_action_play);
drawable = getResources().getDrawable(R.drawable.ic_action_save);
imageButton.setImageDrawable(drawable);
imageButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
downloadId = firstDownloadAvailable;
downloadAll = true;
download();
}
});
publishProgress(downloadView);
cursorMaterialGroups.close();
return null;
}
#Override
protected void onProgressUpdate(View... view) {
linearLayout.addView(view[0]);
}
#Override
protected void onPostExecute(Void result) {
wakeLock.release();
if (asyncListener != null) {
// Call the listener if one is set
asyncListener.onAsyncComplete();
}
}
}
private void download() {
progress.show(this, this, true);
Files files = new Files();
// Check if the memory card can be written to
if (files.isWriteable()) {
Cursor cursorMaterial = tronDB.query(DBAdditionalMaterial.TABLE_NAME,
DBAdditionalMaterial.ALL_COLUMNS,
DBAdditionalMaterial.COLUMN_ID + "=" + String.valueOf(downloadId),
null,
null,
null,
null,
"1");
cursorMaterial.moveToFirst();
String title = cursorMaterial.getString(cursorMaterial.getColumnIndex(DBAdditionalMaterial.COLUMN_NAME));
String type = cursorMaterial.getString(cursorMaterial.getColumnIndex(DBAdditionalMaterial.COLUMN_TYPE));
String url1 = cursorMaterial.getString(cursorMaterial.getColumnIndex(DBAdditionalMaterial.COLUMN_URL1));
String url2 = cursorMaterial.getString(cursorMaterial.getColumnIndex(DBAdditionalMaterial.COLUMN_URL2));
cursorMaterial.close();
if (type.equals("pdf")) {
fileName = String.valueOf(downloadId) + ".pdf";
}
else {
fileName = String.valueOf(downloadId) + ".mp3";
}
// Change the message in the downloading prompt
progress.setMessage(getString(R.string.general_downloading) + " " + title);
SharedPreferences settings = getSharedPreferences(Settings.PREFERENCES, MODE_PRIVATE);
String rut = settings.getString(Settings.RUT, Settings.RUT_DEFAULT);
String url = url1 + rut + url2;
url = url.replace(" ", "%20");
final Download download = files.new Download(this, fileName, progress);
download.downloadListener = this;
download.execute(url);
progress.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
downloadAll = false;
download.cancel(true);
}
});
}
else {
progress.dismiss();
Toast.makeText(this, getString(R.string.general_no_memory), Toast.LENGTH_SHORT).show();
}
}
private void openContent(String contentId) {
Cursor cursorMaterial = tronDB.query(DBAdditionalMaterial.TABLE_NAME,
DBAdditionalMaterial.ALL_COLUMNS,
DBAdditionalMaterial.COLUMN_ID + "=" + contentId,
null,
null,
null,
null,
"1");
cursorMaterial.moveToFirst();
String type = cursorMaterial.getString(cursorMaterial.getColumnIndex(DBAdditionalMaterial.COLUMN_TYPE));
cursorMaterial.close();
String fileName = "";
String mimeType = "";
if (type.equals("pdf")) {
fileName = contentId + ".pdf";
mimeType = "application/pdf";
}
else {
fileName = contentId + ".mp3";
mimeType = "audio/mp3";
}
files.openFile(this, fileName, mimeType);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (intent.getBooleanExtra(ConnectionFailed.RETRY, false)) {
// Failed, let's try the connection again
SharedPreferences settings = getSharedPreferences(Settings.PREFERENCES, MODE_PRIVATE);
String rut = settings.getString(Settings.RUT, Settings.RUT_DEFAULT);
String password = settings.getString(Settings.PASSWORD, Settings.PASSWORD_DEFAULT);
HashMap<String, String> postData = new HashMap<String, String>();
postData.put("rut", rut);
postData.put("pass", password);
xmlParser = new XMLParser(this, postData);
xmlParser.fetchListener = this; // Tell the XMLParser that this activity has the listener
xmlParser.execute(MainActivity.URL + URL);
}
}
// This is the listener for the xml
public void onFetchComplete(String xml) {
if (xml == null) {
progress.dismiss();
// Failed to fetch xml, either a server error or an internet connection problem
Intent intent = new Intent(this, ConnectionFailed.class);
startActivityForResult(intent, 1);
}
else {
HashMap<String, HashMap<String, String>> xmlHash = xmlParser.parseXML(xml);
new User().checkUserValidation(xmlHash.get("0"));
fetchFinished(xmlHash);
}
}
// This is the listener for the download
public void onDownloadComplete(boolean result) {
progress.dismiss();
if (!result) {
Toast.makeText(this, getString(R.string.general_failed_download), Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(this, getString(R.string.general_download_complete), Toast.LENGTH_SHORT).show();
Drawable drawable = getResources().getDrawable(R.drawable.ic_action_play);
ImageButton buttonView = (ImageButton) findViewById(downloadId);
buttonView.setImageDrawable(drawable);
buttonView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String contentId = String.valueOf(view.getId());
openContent(contentId);
}
});
if (downloadAll) {
while (downloadCount >= downloadId) {
downloadId++;
Cursor cursorMaterial = tronDB.query(DBAdditionalMaterial.TABLE_NAME,
DBAdditionalMaterial.ALL_COLUMNS,
DBAdditionalMaterial.COLUMN_ID + "=" + String.valueOf(downloadId),
null,
null,
null,
null,
"1");
cursorMaterial.moveToFirst();
String type = cursorMaterial.getString(cursorMaterial.getColumnIndex(DBAdditionalMaterial.COLUMN_TYPE));
cursorMaterial.close();
if (type.equals("pdf")) {
fileName = String.valueOf(downloadId) + ".pdf";
}
else {
fileName = String.valueOf(downloadId) + ".mp3";
}
if (!files.fileExists(this, fileName)) {
download();
break;
}
}
if (downloadCount == downloadId) {
// The last one downloaded we can now stop the process
downloadAll = false;
}
}
}
}
// This is the listener for the Async
public void onAsyncComplete() {
progress.dismiss();
}
}
Here is the code for my progress bar:
package cl.cromer.tronwell.concepcion;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
public final class Progress {
protected ProgressDialog progressBar = null;
private int oldOrientation = -1; // Orientation not set
private Activity activity;
protected void show(Context context, Activity activity, boolean cancelable) {
this.activity = activity;
// Disable rotation while we are loading something
oldOrientation = activity.getRequestedOrientation();
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
if (progressBar != null && progressBar.isShowing()) {
activity.setRequestedOrientation(oldOrientation);
progressBar.dismiss();
}
progressBar = new ProgressDialog(context);
progressBar.setCancelable(cancelable);
if (!cancelable) {
progressBar.setMessage(context.getString(R.string.general_loading));
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
}
else {
progressBar.setIndeterminate(true);
progressBar.setCanceledOnTouchOutside(false);
progressBar.setMessage(context.getString(R.string.general_downloading));
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
}
protected void setMessage(String message) {
progressBar.setMessage(message);
}
protected void setIndeterminate(boolean indeterminate) {
progressBar.setIndeterminate(indeterminate);
}
protected void setProgress(int progress) {
progressBar.setProgress(progress);
}
protected void setOnCancelListener(DialogInterface.OnCancelListener listener) {
progressBar.setOnCancelListener(listener);
}
protected boolean isShowing() {
if (progressBar.isShowing()) {
return true;
}
return false;
}
protected void dismiss() {
// Turn rotation back to it's previous state
activity.setRequestedOrientation(oldOrientation);
if (progressBar != null && progressBar.isShowing()) {
progressBar.dismiss();
}
}
}

Check answer of this question Answer
I think you facing same issue
Check this one as well Answer 2

Related

How to wait for an activity to finish in asynctask

I know that the purpose of the AsyncTask is to run asynchronously with other tasks of the app and finish in the background, but apparently I need to do this, I need to start an activity from AsyncTask and since I cant extend an activity in this class I can not use startactivityforresult, so how can I wait till my activity finishes?
Here is my code:
public class ListSpdFiles extends AsyncTask<Void, Void, String[]> {
public AsyncResponse delegate = null;
private static final String TAG = "ListSpdFiles: ";
Context applicationContext;
ContentResolver spdappliationcontext;
public final CountDownLatch setSignal= new CountDownLatch(1);
private final ReentrantLock lock = new ReentrantLock();
String username = "";
/**
* Status code returned by the SPD on operation success.
*/
private static final int SUCCESS = 4;
private boolean createbutt;
private boolean deletebutt;
private String initiator;
private String path;
private String pass;
private String url;
private SecureApp pcas;
private boolean isConnected = false; // connected to PCAS service?
private String CurrentURL = null;
private PcasConnection pcasConnection = new PcasConnection() {
#Override
public void onPcasServiceConnected() {
Log.d(TAG, "pcasServiceConnected");
latch.countDown();
}
#Override
public void onPcasServiceDisconnected() {
Log.d(TAG, "pcasServiceDisconnected");
}
};
private CountDownLatch latch = new CountDownLatch(1);
public ListSpdFiles(boolean createbutt, boolean deletebutt, String url, String pass, Context context, String initiator, String path, AsyncResponse asyncResponse) {
this.initiator = initiator;
this.path = path;
this.pass= pass;
this.url= url;
this.createbutt= createbutt;
this.deletebutt=deletebutt;
applicationContext = context.getApplicationContext();
spdappliationcontext = context.getContentResolver();
delegate = asyncResponse;
}
private void init() {
Log.d(TAG, "starting task");
pcas = new AndroidNode(applicationContext, pcasConnection);
isConnected = pcas.connect();
}
private void term() {
Log.d(TAG, "terminating task");
if (pcas != null) {
pcas.disconnect();
pcas = null;
isConnected = false;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
init();
}
#Override
protected String[] doInBackground(Void... params) {
CurrentURL = getLastAccessedBrowserPage();
// check if connected to PCAS Service
if (!isConnected) {
Log.v(TAG, "not connected, terminating task");
return null;
}
// wait until connection with SPD is up
try {
if (!latch.await(20, TimeUnit.SECONDS)) {
Log.v(TAG, "unable to connected within allotted time, terminating task");
return null;
}
} catch (InterruptedException e) {
Log.v(TAG, "interrupted while waiting for connection in lsdir task");
return null;
}
// perform operation (this is where the actual operation is called)
try {
return lsdir();
} catch (DeadServiceException e) {
Log.i(TAG, "service boom", e);
return null;
} catch (DeadDeviceException e) {
Log.i(TAG, "device boom", e);
return null;
}
}
#Override
protected void onPostExecute(String[] listOfFiles) {
super.onPostExecute(listOfFiles);
if (listOfFiles == null) {
Log.i(TAG, "task concluded with null list of files");
} else {
Log.i(TAG, "task concluded with the following list of files: "
+ Arrays.toString(listOfFiles));
}
term();
delegate.processFinish(username);
}
#Override
protected void onCancelled(String[] listOfFiles) {
super.onCancelled(listOfFiles);
Log.i(TAG, "lsdir was canceled");
term();
}
/**
* Returns an array of strings containing the files available at the given path, or
* {#code null} on failure.
*/
private String[] lsdir() throws DeadDeviceException, DeadServiceException {
Result<List<String>> result = pcas.lsdir(initiator, path); // the lsdir call to the
boolean crtbut = createbutt;
boolean dlbut= deletebutt;
ArrayList<String> mylist = new ArrayList<String>();
final Global globalVariable = (Global) applicationContext;
if (crtbut==false && dlbut == false){
if ( globalVariable.getPasswordButt()==false ) {
final boolean isusername = globalVariable.getIsUsername();
if (isusername == true) {
Log.i(TAG, "current url: " + CurrentURL);
if (Arrays.toString(result.getValue().toArray(new String[0])).contains(CurrentURL)) {
String sharareh = Arrays.toString(result.getValue().toArray(new String[0]));
String[] items = sharareh.split(", ");
for (String item : items) {
String trimmed;
if (item.startsWith("[" + CurrentURL + ".")) {
trimmed = item.replace("[" + CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
} else if (item.startsWith(CurrentURL + ".")) {
trimmed = item.replace(CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
}
}
}
globalVariable.setPopupdone(false);
Intent i = new Intent(applicationContext, PopUp.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("EXTRA_SESSION_ID", mylist);
applicationContext.startActivity(i);
username = globalVariable.getUsername();
}
else if (isusername == false)
Log.i(TAG, "Wrong Input Type For Username.");
}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
//}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
public String getLastAccessedBrowserPage() {
String Domain = null;
Cursor webLinksCursor = spdappliationcontext.query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, null, null, Browser.BookmarkColumns.DATE + " DESC");
int row_count = webLinksCursor.getCount();
int title_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.TITLE);
int url_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.URL);
if ((title_column_index > -1) && (url_column_index > -1) && (row_count > 0)) {
webLinksCursor.moveToFirst();
while (webLinksCursor.isAfterLast() == false) {
if (webLinksCursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX) != 1) {
if (!webLinksCursor.isNull(url_column_index)) {
Log.i("History", "Last page browsed " + webLinksCursor.getString(url_column_index));
try {
Domain = getDomainName(webLinksCursor.getString(url_column_index));
Log.i("Domain", "Last page browsed " + Domain);
return Domain;
} catch (URISyntaxException e) {
e.printStackTrace();
}
break;
}
}
webLinksCursor.moveToNext();
}
}
webLinksCursor.close();
return null;
}
public String getDomainName(String url) throws URISyntaxException {
URI uri = new URI(url);
String domain = uri.getHost();
return domain.startsWith("www.") ? domain.substring(4) : domain;
}}
My Activity class:
public class PopUp extends Activity {
private static final String TAG = "PopUp";
ArrayList<String> value = null;
ArrayList<String> usernames;
#Override
protected void onCreate(Bundle savedInstanceState) {
final Global globalVariable = (Global) getApplicationContext();
globalVariable.setUsername("");
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getStringArrayList("EXTRA_SESSION_ID");
}
usernames = value;
super.onCreate(savedInstanceState);
setContentView(R.layout.popupactivity);
final Button btnOpenPopup = (Button) findViewById(R.id.openpopup);
btnOpenPopup.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button btnSelect = (Button) popupView.findViewById(R.id.select);
Spinner popupSpinner = (Spinner) popupView.findViewById(R.id.popupspinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(PopUp.this, android.R.layout.simple_spinner_item, usernames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
popupSpinner.setAdapter(adapter);
popupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
globalVariable.setUsername(usernames.get(arg2));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
btnSelect.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
globalVariable.setPopupdone(true);
popupWindow.dismiss();
finish();
}
}
);
popupWindow.showAsDropDown(btnOpenPopup, 50, -30);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.poupup_menu, menu);
return true;
}}

ProgressDialog remains open in android activity

I have made an activity in that I am making an api call by using AsyncTak,I have shown a progressDialog In DoBackground method ,and want to dismiss that progressDialog in postExecute i have done this way but its not working,My progressDialog remains, open after the operations too..My code is as below,can anybuddy help me to dissmiss it.
main.java
package com.epe.yehki.ui;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Paint.Join;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewDebug.FlagToString;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.backend.FavoriteAPI;
import com.epe.yehki.backend.ResponseListener;
import com.epe.yehki.uc.Menu;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Const.API_RESULT;
import com.epe.yehki.util.Pref;
import com.epe.yehki.util.Utils;
import com.example.yehki.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
public class WholesaleProductDetailActivity extends Activity {
public ImageView productImage;
private ImageLoader imageLoader;
private DisplayImageOptions options;
private ProgressDialog pDialog;
JSONArray proDetails = null;
private Menu menu;
Intent i1;
private FavoriteAPI favApi;
private int isFavourite;
private ProgressDialog progressDialog;
// CONTROLLS FOR WHOLESALE RETAILS.........!!!
TextView retailPrice;
TextView tv_moqW;
TextView tv_moqR;
TextView tv_shipping_cost;
TextView EscrowPayment;
TextView ProcessigPeriod;
LinearLayout llQuantity;
EditText quantity;
LinearLayout llbotm;
TextView tv_escrow_payment;
TextView tv_procesiing_period;
Button contactSuplier, addToCart, buyNOw;
LinearLayout ll_botom1;
// ************************
// strings.......!!!
String pro_id;
String name;
String retail_price;
String price_wholesale;
String keywords;
String supplier_id;
String supplier_name;
String listing_description;
String image;
String Specifications;
String date_added;
String status;
int flag = 0;
String port;
String customer_name;
String customer_id;
String cId;
String min_order_qty_retail;
String min_order_qty_wholesale;
String countyId;
String supply_amount;
String msg;
String supply_unit_id;
String supply_unit_name;
String supply_time;
String payment_terms;
String min_order_qty;
String min_order_qty_unit;
String min_order_qty_unit_name;
String delivery_time;
String company_name;
String country_id;
String state_id;
String procesPeriod;
// COMPANY DETAILS....
String companyDetail;
String companyDetailName;
String companyDetailAddress;
String companyDetailPhoto;
String companyDetailMainProduct;
String companyDetailotherProduct;
String cartNo;
// PRODUCT QUICK DETAILS...
// TextViews.............!!!
public TextView productName;
public TextView wholeSalePrice;
public TextView minOrder;
public TextView shippingCost;
public TextView escrowPayment;
public TextView processingPeriod;
public TextView compnyName;
public TextView countryName;
public TextView bussinessType;
public TextView mainProduct;
public TextView productDetails;
public String pid;
// Buttons of placeOrder and contact supplier..
private Button contactSupplier;
private ImageView iv_back;
private TextView cart;
private ImageView iv_fav;
public Intent i;
//
// Hashmap for ListView
ArrayList<HashMap<String, String>> ProductDetailList;
// URL to get contacts JSON
// API_PRODUCT?product_id=29
private static String productUrl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_detail);
initializeViews();
cId = Pref.getValue(WholesaleProductDetailActivity.this, Const.PREF_CUSTOMER_ID, "");
ll_botom1 = (LinearLayout) findViewById(R.id.ll_botom1);
ll_botom1.setVisibility(View.VISIBLE);
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(WholesaleProductDetailActivity.this));
options = new DisplayImageOptions.Builder().cacheOnDisc(true).showImageOnFail(R.drawable.logo).build();
new AddToCart().execute();
// get extras..............!!!!
i = getIntent();
i.getStringExtra(Const.TAG_PRODUCT_NAME);
i.getStringExtra(Const.TAG_PRODUCT_IMG);
pid = i.getStringExtra(Const.TAG_PRODUCT_ID);
favApi = new FavoriteAPI(WholesaleProductDetailActivity.this, responseListener, pid, Pref.getValue(WholesaleProductDetailActivity.this, Const.PREF_CUSTOMER_ID, ""));
favApi.callApi();
// bACK BUTTON.......!
iv_back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
finish();
}
});
// DO FAVOURITE YOUR PRODUCT..........!!!
iv_fav.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// CHECKING IS USER lOGIN...!
if (Pref.getValue(WholesaleProductDetailActivity.this, Const.PREF_CUSTOMER_ID, "") != null
&& !Pref.getValue(WholesaleProductDetailActivity.this, Const.PREF_CUSTOMER_ID, "").equals("")) {
// FAVOURITE API CALL..........!!!
if (iv_fav.isSelected()) {
isFavourite = 0;
iv_fav.setImageResource(R.drawable.star);
iv_fav.setSelected(false);
} else {
isFavourite = 1;
iv_fav.setImageResource(R.drawable.star_filled);
iv_fav.setSelected(true);
}
if (Utils.isOnline(WholesaleProductDetailActivity.this)) {
progressDialog = new ProgressDialog(WholesaleProductDetailActivity.this);
progressDialog.setMessage(getString(R.string.process_progress_msg));
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
favApi = new FavoriteAPI(WholesaleProductDetailActivity.this, responseListener, pid, Pref.getValue(WholesaleProductDetailActivity.this, Const.PREF_CUSTOMER_ID, ""));
favApi.callApi();
} else {
Toast.makeText(WholesaleProductDetailActivity.this, "Please check your interenet connection", Toast.LENGTH_SHORT).show();
}
} else {
i = new Intent(WholesaleProductDetailActivity.this, LoginActivity.class);
startActivity(i);
}
}
});
productUrl = Const.API_WHOLESALE_PRODUCT_DETAIL + "?" + Const.TAG_PRODUCT_ID + "=" + pid;
System.out.println(":::::::::::PRODUCT URL:::::::::::::::" + productUrl);
productName.setText(i.getStringExtra(Const.TAG_PRODUCT_NAME));
try {
imageLoader.displayImage(i.getStringExtra(Const.TAG_PRODUCT_IMG), productImage, options);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
productImage.setBackgroundResource(R.drawable.logo);
}
new GetProductDetails().execute();
buyNOw.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (quantity.getText().toString() != null && !quantity.getText().toString().equals("")) {
if (Double.parseDouble(quantity.getText().toString()) < (Double.parseDouble(min_order_qty_retail))) {
Utils.showCustomeAlertValidation(WholesaleProductDetailActivity.this, "Please Enter Quantity greater than min. retail quamtity", "Yehki", "Ok");
} else {
i1 = new Intent(WholesaleProductDetailActivity.this, WholesalePlaceOrderActivity.class);
i1.putExtra(Const.TAG_PRODUCT_NAME, name);
i1.putExtra(Const.TAG_PRODUCT_ID, pid);
i1.putExtra("QTY_RETAIL", min_order_qty_retail);
i1.putExtra("QTY_WHOLESALE", min_order_qty_wholesale);
i1.putExtra(Const.TAG_PRODUCT_SUPPLEY_UNIT_ID, supply_unit_id);
i1.putExtra(Const.TAG_PRODUCT_SUPPLY_UNIT_NAME, supply_unit_name);
i1.putExtra(Const.TAG_PRODUCT_MAX_PRICE, price_wholesale);
i1.putExtra(Const.TAG_PRODUCT_MIN_PRICE, retail_price);
i1.putExtra("takenQTY", quantity.getText().toString());
if (Double.parseDouble(quantity.getText().toString()) > (Double.parseDouble(min_order_qty_retail))
&& Double.parseDouble(quantity.getText().toString()) < (Double.parseDouble(min_order_qty_wholesale))) {
i1.putExtra("price", retail_price);
startActivity(i1);
} else if (Double.parseDouble(quantity.getText().toString()) > (Double.parseDouble(min_order_qty_wholesale))) {
i1.putExtra("price", price_wholesale);
startActivity(i1);
}
}
} else {
Utils.showCustomeAlertValidation(WholesaleProductDetailActivity.this, "Please Enter Quantity", "Yehki", "Ok");
}
}
});
contactSuplier.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(WholesaleProductDetailActivity.this, ContactSupplierActivity.class);
i.putExtra(Const.TAG_SUPPLIER_ID, supplier_id);
System.out.println("::::::::::::::::;my supplier id>>>>>>>>>>>>>>+++++++++++++++++" + supplier_id);
i.putExtra(Const.TAG_PRODUCT_ID, pid);
startActivity(i);
}
});
addToCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!quantity.getText().toString().equals("") && quantity.getText().toString() != null) {
new AddToCart().execute();
} else {
Utils.showCustomeAlertValidation(WholesaleProductDetailActivity.this, "Please enter quanitity", "Yehki", "Ok");
}
}
});
}
// ****INITIALIZING THE VIEWS.....!!!!!!!!!!!!!!!
private void initializeViews() {
productImage = (ImageView) findViewById(R.id.iv_product);
productName = (TextView) findViewById(R.id.tv_product_name);
buyNOw = (Button) findViewById(R.id.tv_place_order);
contactSupplier = (Button) findViewById(R.id.tv_contact_suplier);
wholeSalePrice = (TextView) findViewById(R.id.tv_price_range);
minOrder = (TextView) findViewById(R.id.tv_min_order);
shippingCost = (TextView) findViewById(R.id.tv_sply);
escrowPayment = (TextView) findViewById(R.id.tv_payment_terms);
processingPeriod = (TextView) findViewById(R.id.tv_port);
compnyName = (TextView) findViewById(R.id.tv_company_name);
countryName = (TextView) findViewById(R.id.tv_contry);
bussinessType = (TextView) findViewById(R.id.tv_bussiness_type);
mainProduct = (TextView) findViewById(R.id.tv_main_products);
productDetails = (TextView) findViewById(R.id.tv_pro_detail);
menu = (Menu) findViewById(R.id.menuProduct);
iv_back = (ImageView) findViewById(R.id.iv_back);
iv_fav = (ImageView) findViewById(R.id.iv_fvrt);
cart = (TextView) findViewById(R.id.tv_cart);
retailPrice = (TextView) findViewById(R.id.tv_retail_price);
tv_moqW = (TextView) findViewById(R.id.tv_moqw);
tv_moqR = (TextView) findViewById(R.id.tv_min_order);
tv_shipping_cost = (TextView) findViewById(R.id.tv_shipping_cost);
tv_escrow_payment = (TextView) findViewById(R.id.tv_escrow_payment);
tv_procesiing_period = (TextView) findViewById(R.id.tv_procesiing_period);
quantity = (EditText) findViewById(R.id.et_qty);
llQuantity = (LinearLayout) findViewById(R.id.ll_btm);
llQuantity.setVisibility(View.VISIBLE);
llbotm = (LinearLayout) findViewById(R.id.ll_botom1);
llbotm.setVisibility(View.VISIBLE);
tv_shipping_cost.setText("Shipping Cost:");
tv_escrow_payment.setText("Escrow Payment:");
tv_procesiing_period.setText("Processing Period:");
contactSuplier = (Button) findViewById(R.id.tv_contc_sup);
addToCart = (Button) findViewById(R.id.btn_add_cart);
buyNOw = (Button) findViewById(R.id.btn_buy);
retailPrice.setVisibility(View.VISIBLE);
menu.setSelectedTab(1);
}
private class GetProductDetails extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(WholesaleProductDetailActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
System.out.println("==========inside preexecute===================");
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(productUrl, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
System.out.println("=============MY RESPONSE==========" + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
if (jsonObj.has(Const.TAG_PRODUCT_DETAIL)) {
// yes
proDetails = jsonObj.getJSONArray(Const.TAG_PRODUCT_DETAIL);
System.out.println("==========inside doIn background===================");
// looping through All Contacts
for (int i = 0; i < proDetails.length(); i++) {
JSONObject c = proDetails.getJSONObject(i);
name = c.getString(Const.TAG_PRODUCT_NAME);
keywords = c.getString(Const.TAG_PRODUCT_KEYWORDS);
supplier_id = c.getString(Const.TAG_PRODUCT_SUPPLIER_ID);
supplier_name = c.getString(Const.TAG_PRODUCT_SUPPLIER_NAME);
listing_description = c.getString(Const.TAG_PRODUCT_LISTING_DESCRIPTION);
image = c.getString(Const.TAG_PRODUCT_IMG);
Specifications = c.getString(Const.TAG_PRODUCT_SPECIFICATION);
date_added = c.getString(Const.TAG_PRODUCT_DATE_ADDED);
customer_name = c.getString(Const.TAG_PRODUCT_CUSTMER_NAME);
customer_id = c.getString(Const.TAG_PRODUCT_CUSTOMER_ID);
retail_price = c.getString(Const.TAG_PRICE_RETAIL);
price_wholesale = c.getString(Const.TAG_PRICE_WHOLESALE);
System.out.println(":::::::::::::My wholesale price:::::::::>>>>>>>" + price_wholesale);
min_order_qty_retail = c.getString(Const.TAG_MIN_ORDER_QTY_RETAIL);
System.out.println(":::::::::::::My wholesale price:::::::::>>>>>>>" + min_order_qty_retail);
min_order_qty_wholesale = c.getString(Const.TAG_MIN_ORDER_QTY_WHOLESALE);
System.out.println(":::::::::::::My wholesale price:::::::::>>>>>>>" + min_order_qty_wholesale);
countyId = c.getString(Const.TAG_COUNTRY_ID);
state_id = c.getString(Const.TAG_STATE_WHOLESALE_ID);
supply_unit_id = c.getString(Const.TAG_PRODUCT_SUPPLEY_UNIT_ID);
supply_unit_name = c.getString(Const.TAG_PRODUCT_SUPPLY_UNIT_NAME);
System.out.println("::::::::::::::::mY supply unit name::::::::::::::");
supply_time = c.getString(Const.TAG_PRODUCT_SUPPLY_TIME);
delivery_time = c.getString(Const.TAG_DELIVERY_TIME_WHOLESALE);
System.out.println(":::::::::::::::supply unit name:::::::::::::::::::" + delivery_time);
company_name = c.getString(Const.TAG_PRODUCT_COMPANY_NAME);
System.out.println(":::::::::::::::supply unit name:::::::::::::::::::" + company_name);
// GETTING COMPANY DETAILS..........!!!
JSONObject companyDetails = c.getJSONObject(Const.TAG_PRODUCT_COMPANY_DETAILS);
companyDetailName = companyDetails.getString(Const.TAG_PRODUCTDETAIL_COMPANY_NAME);
companyDetailAddress = companyDetails.getString(Const.TAG_PRODUCTDETAIL_COMPANY_ADDRESS);
companyDetailMainProduct = companyDetails.getString(Const.TAG_PRODUCTDETAIL_COMPANY_MAIN_PRODUCT);
companyDetailotherProduct = companyDetails.getString(Const.TAG_PRODUCTDETAIL_COMPANY_OTHER_PRODUCT);
companyDetailPhoto = companyDetails.getString(Const.TAG_PRODUCTDETAIL_PHOTO);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog != null) {
pDialog.dismiss();
}
productName.setText(name);
wholeSalePrice.setText("WholeSale Price:" + " " + price_wholesale);
retailPrice.setText("Retail Price:" + " " + retail_price);
tv_moqW.setText("MoqW:" + min_order_qty_wholesale);
minOrder.setText("MoqR:" + min_order_qty_retail);
shippingCost.setText("");
escrowPayment.setText(payment_terms);
compnyName.setText(company_name);
countryName.setText(country_id);
mainProduct.setText(companyDetailMainProduct);
processingPeriod.setText(delivery_time);
}
}
// RESPONSE lISTENER FOR THE FAVOURITE......!!
ResponseListener responseListener = new ResponseListener() {
#Override
public void onResponce(String api, API_RESULT result, Object obj) {
if (progressDialog != null) {
progressDialog.dismiss();
}
if (api.equals(Const.API_DO_FAVOURITE)) {
if (result == Const.API_RESULT.SUCCESS) {
System.out.println("::::::::::::::::;INSIDE SUCCESS ACTIVITY OF FAVORITE:::::::::;");
}
}
}
};
// *********************ADD TO CART CALL...
// *******************
private class AddToCart extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(WholesaleProductDetailActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
System.out.println("==========inside preexecute===================");
}
#Override
protected Void doInBackground(Void... arg0) {
String addToCArt = Const.API_ADD_TO_CART + "?customer_id=" + cId + "&product_id=" + pid + "&quantity=" + quantity.getText().toString() + "&unit_id=" + supply_unit_id; // Creating
// service
// handler
// class
// instance
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::MY add to cart url:::::::::::;" + addToCArt);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(addToCArt, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
System.out.println("=============MY RESPONSE==========" + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
if (jsonObj.has(Const.TAG_STATUS)) {
status = jsonObj.getString(Const.TAG_STATUS);
if (status.equalsIgnoreCase("success")) {
flag = 1;
msg = jsonObj.getString(Const.TAG_MESSAGE);
cartNo = jsonObj.getString(Const.TAG_TOTAL_CART_PRODUCTS);
} else {
flag = 2;
msg = jsonObj.getString(Const.TAG_MESSAGE);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog != null) {
pDialog.dismiss();
}
if (flag == 1) {
Toast.makeText(WholesaleProductDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
quantity.setText("");
cart.setText(cartNo);
Pref.setValue(WholesaleProductDetailActivity.this, Const.PREF_CART_NO, cartNo);
} else {
Toast.makeText(WholesaleProductDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
}
}
}
}
replace your GetProductDetails AsyncTask code with this. and do same for other
// My AsyncTask start...
class GetProductDetails extends AsyncTask<Void, Void, Void> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(WholesaleProductDetailActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(productUrl, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
System.out.println("=============MY RESPONSE==========" + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
if (jsonObj.has(Const.TAG_PRODUCT_DETAIL)) {
// yes
proDetails = jsonObj.getJSONArray(Const.TAG_PRODUCT_DETAIL);
System.out.println("==========inside doIn background===================");
// looping through All Contacts
for (int i = 0; i < proDetails.length(); i++) {
JSONObject c = proDetails.getJSONObject(i);
name = c.getString(Const.TAG_PRODUCT_NAME);
keywords = c.getString(Const.TAG_PRODUCT_KEYWORDS);
supplier_id = c.getString(Const.TAG_PRODUCT_SUPPLIER_ID);
supplier_name = c.getString(Const.TAG_PRODUCT_SUPPLIER_NAME);
listing_description = c.getString(Const.TAG_PRODUCT_LISTING_DESCRIPTION);
image = c.getString(Const.TAG_PRODUCT_IMG);
Specifications = c.getString(Const.TAG_PRODUCT_SPECIFICATION);
date_added = c.getString(Const.TAG_PRODUCT_DATE_ADDED);
customer_name = c.getString(Const.TAG_PRODUCT_CUSTMER_NAME);
customer_id = c.getString(Const.TAG_PRODUCT_CUSTOMER_ID);
retail_price = c.getString(Const.TAG_PRICE_RETAIL);
price_wholesale = c.getString(Const.TAG_PRICE_WHOLESALE);
System.out.println(":::::::::::::My wholesale price:::::::::>>>>>>>" + price_wholesale);
min_order_qty_retail = c.getString(Const.TAG_MIN_ORDER_QTY_RETAIL);
System.out.println(":::::::::::::My wholesale price:::::::::>>>>>>>" + min_order_qty_retail);
min_order_qty_wholesale = c.getString(Const.TAG_MIN_ORDER_QTY_WHOLESALE);
System.out.println(":::::::::::::My wholesale price:::::::::>>>>>>>" + min_order_qty_wholesale);
countyId = c.getString(Const.TAG_COUNTRY_ID);
state_id = c.getString(Const.TAG_STATE_WHOLESALE_ID);
supply_unit_id = c.getString(Const.TAG_PRODUCT_SUPPLEY_UNIT_ID);
supply_unit_name = c.getString(Const.TAG_PRODUCT_SUPPLY_UNIT_NAME);
System.out.println("::::::::::::::::mY supply unit name::::::::::::::");
supply_time = c.getString(Const.TAG_PRODUCT_SUPPLY_TIME);
delivery_time = c.getString(Const.TAG_DELIVERY_TIME_WHOLESALE);
System.out.println(":::::::::::::::supply unit name:::::::::::::::::::" + delivery_time);
company_name = c.getString(Const.TAG_PRODUCT_COMPANY_NAME);
System.out.println(":::::::::::::::supply unit name:::::::::::::::::::" + company_name);
// GETTING COMPANY DETAILS..........!!!
JSONObject companyDetails = c.getJSONObject(Const.TAG_PRODUCT_COMPANY_DETAILS);
companyDetailName = companyDetails.getString(Const.TAG_PRODUCTDETAIL_COMPANY_NAME);
companyDetailAddress = companyDetails.getString(Const.TAG_PRODUCTDETAIL_COMPANY_ADDRESS);
companyDetailMainProduct = companyDetails.getString(Const.TAG_PRODUCTDETAIL_COMPANY_MAIN_PRODUCT);
companyDetailotherProduct = companyDetails.getString(Const.TAG_PRODUCTDETAIL_COMPANY_OTHER_PRODUCT);
companyDetailPhoto = companyDetails.getString(Const.TAG_PRODUCTDETAIL_PHOTO);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
productName.setText(name);
wholeSalePrice.setText("WholeSale Price:" + " " + price_wholesale);
retailPrice.setText("Retail Price:" + " " + retail_price);
tv_moqW.setText("MoqW:" + min_order_qty_wholesale);
minOrder.setText("MoqR:" + min_order_qty_retail);
shippingCost.setText("");
escrowPayment.setText(payment_terms);
compnyName.setText(company_name);
countryName.setText(country_id);
mainProduct.setText(companyDetailMainProduct);
processingPeriod.setText(delivery_time);
// Dismiss the progress dialog
pDialog.dismiss();
}
}
}
Remove
if (pDialog.isShowing())
and
use if (pDialog != null)
may this help you
You should remove super.onPostExecute(result); as you have your implementation of onPostExecute(), so you may not want framework to handle it.
Since you have definitely showed the Progress Dialog in onPreExecute(), then you can also omit check for isShowing(), but i will recommend you to keep this check as it causes no harm and adds little more security.
In your onPostExecute() block you are calling super.onPostExecute(result);
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Your code
}
However as you are overriding the onPostExecute() there is no need to call super.onPostExecute(result);
If you take a look at the AsyncTask source, you will see that the super class does nothing:
#SuppressWarnings({"UnusedDeclaration"})
protected void onPostExecute(Result result) {
}

Display PDF in fragments within app android

In my app, I have to display PDF file from sdcard in android. The app uses tab functionality so I have used fragments in my app. So how to display pdf file inside fragments?
I have used pdfviewer.jar, but I am not able to display inside fragments, it only works in activity.
And another question is I want to display pdf with multi-zoom and vertical page scrolling to see next/previous pages, not by manually clicking on zoom icon and arrow icon to see next page which is used in pdfviewer.jar.
I am giving the full code below of that changed fragment. I did it 3 years back and that time Sherlock library was used. I think now you have to replace that by appcompat library.
package net.sf.andpdf.pdfviewer;
import java.io.*;
import java.nio.channels.FileChannel;
import android.app.Activity;
import android.content.res.Configuration;
import android.graphics.*;
import android.widget.ImageView;
import android.widget.TextView;
import net.sf.andpdf.nio.ByteBuffer;
import net.sf.andpdf.pdfviewer.gui.TouchImageView;
import net.sf.andpdf.refs.HardReference;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFImage;
import com.sun.pdfview.PDFPage;
import com.sun.pdfview.PDFPaint;
import com.sun.pdfview.decrypt.PDFAuthenticationFailureException;
import com.sun.pdfview.decrypt.PDFPassword;
import com.sun.pdfview.font.PDFFont;
public class PdfViewerFragment extends SherlockFragment {
private static final int STARTPAGE = 1;
private static float STARTZOOM = 1f;
private static final String TAG = "PDFVIEWER";
private static final String FTAG = "PDFVIEWERFRG";
public static final String EXTRA_PDFFILENAME = "net.sf.andpdf.extra.PDFFILENAME";
public static final String EXTRA_SHOWIMAGES = "net.sf.andpdf.extra.SHOWIMAGES";
public static final String EXTRA_ANTIALIAS = "net.sf.andpdf.extra.ANTIALIAS";
public static final String EXTRA_USEFONTSUBSTITUTION = "net.sf.andpdf.extra.USEFONTSUBSTITUTION";
public static final String EXTRA_KEEPCACHES = "net.sf.andpdf.extra.KEEPCACHES";
public static final boolean DEFAULTSHOWIMAGES = true;
public static final boolean DEFAULTANTIALIAS = true;
public static final boolean DEFAULTUSEFONTSUBSTITUTION = false;
public static final boolean DEFAULTKEEPCACHES = true;
private String pdffilename;
private PDFFile mPdfFile;
private int mPage;
private float mZoom;
private File mTmpFile;
private ProgressDialog progress;
private TextView tv_page_no;
String imgFileName;
private ImageView rightArrow;
private ImageView leftArrow;
private PDFPage mPdfPage;
private Thread backgroundThread;
private Activity activity;
TouchImageView tiv;
#Override
public void onAttach(Activity activity) {
Log.i(FTAG, "PDFFragment.onAttatch");
this.activity = activity;
super.onAttach(activity);
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Display display = activity.getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
if(activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE )
{
STARTZOOM = (1f*width)/800.0f;
}
else
{
STARTZOOM = (1f*height)/800.0f;
}
Log.i(FTAG, "PDFFragment: onCreate");
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.i(FTAG, "PDFFragment: onCreateView");
View docView = inflater.inflate(R.layout.doc_viewer, container, false);
setRetainInstance(true);
boolean showImages = activity.getIntent().getBooleanExtra(PdfViewerFragment.EXTRA_SHOWIMAGES, PdfViewerFragment.DEFAULTSHOWIMAGES);
PDFImage.sShowImages = showImages;
boolean antiAlias = activity.getIntent().getBooleanExtra(PdfViewerFragment.EXTRA_ANTIALIAS, PdfViewerFragment.DEFAULTANTIALIAS);
PDFPaint.s_doAntiAlias = antiAlias;
boolean useFontSubstitution = activity.getIntent().getBooleanExtra(PdfViewerFragment.EXTRA_USEFONTSUBSTITUTION, PdfViewerFragment.DEFAULTUSEFONTSUBSTITUTION);
PDFFont.sUseFontSubstitution= useFontSubstitution;
boolean keepCaches = activity.getIntent().getBooleanExtra(PdfViewerFragment.EXTRA_KEEPCACHES, PdfViewerFragment.DEFAULTKEEPCACHES);
HardReference.sKeepCaches= keepCaches;
Bundle args = getArguments();
if (args != null) {
Log.i(FTAG, "Args Value: "+args.getString(EXTRA_PDFFILENAME));
pdffilename = args.getString(EXTRA_PDFFILENAME);;
} else {
// TODO: open a default document
pdffilename = "/mnt/sdcard/documents/3.pdf";
}
tiv = (TouchImageView) docView.findViewById(R.id.imageView);
leftArrow = (ImageView) docView.findViewById(R.id.leftArrow);
rightArrow = (ImageView) docView.findViewById(R.id.rightArrow);
leftArrow.setVisibility(View.GONE);
rightArrow.setVisibility(View.GONE);
if (pdffilename == null)
{
pdffilename = "No file selected";
}
else if(pdffilename.contains(".pdf"))
{
imgFileName= pdffilename.substring(0, pdffilename.lastIndexOf("."))+"_1.jpg";
mPage = STARTPAGE;
mZoom = STARTZOOM;
progress = ProgressDialog.show(activity, "Loading", "Loading PDF Page", true, true);
leftArrow.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
prevPage();
}
});
rightArrow.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
nextPage();
}
});
tv_page_no = (TextView) docView.findViewById(R.id.navigationText);
tiv.setParent(this);
setContent(null);
}
else if(pdffilename.contains(".jpg") || pdffilename.contains(".jpeg") || pdffilename.contains(".png") || pdffilename.contains(".gif") || pdffilename.contains(".bmp"))
{
imgFileName = pdffilename;
tiv.setImageLocation(imgFileName);
}
else
{
pdffilename = "Invalid file extension";
}
return docView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
Log.i(FTAG, "PDFFragment: onViewCreated");
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i(FTAG, "PDFFragment: onActivityCreated");
}
#Override
public void onStart() {
Log.i(FTAG, "PDFFragment.onStart");
super.onStart();
//Bundle args = getArguments();
}
#Override
public void onResume() {
Log.i(FTAG, "PDFFragment.onResume");
super.onResume();
}
#Override
public void onPause() {
Log.i(FTAG, "PDFFragment.onPause");
super.onPause();
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.i(FTAG, "PDFFragment.onSaveInstanceState");
super.onSaveInstanceState(outState);
}
#Override
public void onStop() {
Log.i(FTAG, "PDFFragment.onStop");
super.onStop();
}
#Override
public void onDestroyView() {
Log.i(FTAG, "PDFFragment.onDestroyView");
super.onDestroyView();
}
#Override
public void onDestroy() {
Log.i(FTAG, "PDFFragment.onDestroy");
super.onDestroy();
if (mTmpFile != null) {
mTmpFile.delete();
mTmpFile = null;
}
}
#Override
public void onDetach() {
Log.i(FTAG, "PDFFragment.onDetach");
super.onDetach();
}
private boolean setContent(String password) {
try {
parsePDF(pdffilename, password);
if(new File(imgFileName).exists())
{
tiv.setImageLocation(imgFileName);
updateTexts(1);
progress.dismiss();
}
else
startRenderThread(mPage, mZoom);
}
catch (PDFAuthenticationFailureException e) {
} catch (Exception e) {
}
return true;
}
public synchronized void startRenderThread(final int page, final float zoom) {
if (backgroundThread != null)
return;
backgroundThread = new Thread(new Runnable() {
public void run() {
try {
if (mPdfFile != null) {
generatePDFPage(page, zoom);
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
backgroundThread = null;
}
});
backgroundThread.start();
}
public void nextPage() {
if (mPdfFile != null) {
if (mPage < mPdfFile.getNumPages()) {
mPage += 1;
imgFileName= pdffilename.substring(0, pdffilename.lastIndexOf("."))+"_"+String.valueOf(mPage)+".jpg";
if(new File(imgFileName).exists())
{
tiv.setImageLocation(imgFileName);
updateTexts(mPage);
progress.dismiss();
}
else
{
progress = ProgressDialog.show(activity, "Loading", "Loading PDF Page " + mPage, true, true);
startRenderThread(mPage, STARTZOOM);
}
}
}
}
public void prevPage() {
if (mPdfFile != null) {
if (mPage > 1) {
mPage -= 1;
imgFileName= pdffilename.substring(0, pdffilename.lastIndexOf("."))+"_"+String.valueOf(mPage)+".jpg";
if(new File(imgFileName).exists())
{
tiv.setImageLocation(imgFileName);
updateTexts(mPage);
progress.dismiss();
}
else
{
progress = ProgressDialog.show(activity, "Loading", "Loading PDF Page " + mPage, true, true);
startRenderThread(mPage, STARTZOOM);
}
}
}
}
protected void updateTexts(int pageNo) {
if (mPdfFile != null) {
tv_page_no.setText("Page "+pageNo+"/"+mPdfFile.getNumPages());
if(mPdfFile.getNumPages() > 1)
{
if(pageNo==1)
leftArrow.setVisibility(View.GONE);
else
leftArrow.setVisibility(View.VISIBLE);
if(pageNo == mPdfFile.getNumPages())
rightArrow.setVisibility(View.GONE);
else
rightArrow.setVisibility(View.VISIBLE);
}
}
}
public void generatePDFPage(final int page, float zoom) throws Exception {
try {
// Only load the page if it's a different page (i.e. not just changing the zoom level)
if (mPdfPage == null || mPdfPage.getPageNumber() != page) {
mPdfPage = mPdfFile.getPage(page, true);
}
float width = mPdfPage.getWidth();
float height = mPdfPage.getHeight();
RectF clip = null;
Bitmap bmp = mPdfPage.getImage((int)(width*zoom), (int)(height*zoom), clip, true, true);
//imgFileName += String.valueOf(page)+".jpg";
FileOutputStream fo = null;
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 50, bytes);
File f = new File(imgFileName);
f.createNewFile();
fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (Exception ex) {
} finally {
if (fo != null) {
try {
fo.close();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
activity.runOnUiThread(new Runnable() {
public void run() {
tiv.setImageLocation(imgFileName);
//tiv.setImageBitmap(BitmapFactory.decodeFile(imgFileName));
updateTexts(page);
if (progress != null)
progress.dismiss();
}
});
} catch (Throwable e) {
Log.e(TAG, e.getMessage(), e);
}
}
public void parsePDF(String filename, String password) throws PDFAuthenticationFailureException {
pdffilename = filename;
try {
File f = new File(filename);
long len = f.length();
if (len == 0) {
}
else {
openFile(f, password);
}
}
catch (PDFAuthenticationFailureException e) {
throw e;
} catch (Throwable e) {
e.printStackTrace();
}
}
/**
* <p>Open a specific pdf file. Creates a DocumentInfo from the file,
* and opens that.</p>
*
* <p><b>Note:</b> Mapping the file locks the file until the PDFFile
* is closed.</p>
*
* #param file the file to open
* #throws IOException
*/
public void openFile(File file, String password) throws IOException {
// first open the file for random access
RandomAccessFile raf = null;
try
{
raf = new RandomAccessFile(file, "r");
// extract a file channel
FileChannel channel = raf.getChannel();
// now memory-map a byte-buffer
ByteBuffer bb = ByteBuffer.NEW(channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()));
// create a PDFFile from the data
if (password == null)
mPdfFile = new PDFFile(bb);
else
mPdfFile = new PDFFile(bb, new PDFPassword(password));
} catch (Exception ex)
{
} finally {
raf.close();
}
}
}
This is load PDF in fragment use PDFViewer
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_keluarga, container, false);
pdfView = (PDFView) v.findViewById(R.id.keluargaPdf);
pdfView.fromAsset("tiga.pdf").load();
// Inflate the layout for this fragment
return v;
}

how to set progress bar

package com.example.tabactivity;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ActivityGroup;
import android.app.ProgressDialog;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class circularlistparsing extends ActivityGroup {
public int currentPage = 1;
public ListView lisView1;
static final String KEY_ITEM = "docdetails";
static final String KEY_ITEM2 = "info";
static final String KEY_NAME1 = "";
static final String KEY_NAME = "heading";
static final String KEY_DATE = "date";
public Button btnNext;
public Button btnPre;
public static String url = "http://dev.taxmann.com/TaxmannService/TaxmannService.asmx/GetCircularList";
TextView txtreord;
TextView totalpage;
TextView pagenumber;
ProgressDialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtreord = (TextView) findViewById(R.id.recored);
totalpage = (TextView) findViewById(R.id.totalpage);
pagenumber = (TextView) findViewById(R.id.pagenumber);
// listView1
lisView1 = (ListView) findViewById(R.id.listView1);
// new YourTask().execute();
// Next
btnNext = (Button) findViewById(R.id.btnNext);
// Perform action on click
btnNext.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
currentPage = currentPage + 1;
// new YourTask().execute();
ShowData();
pagenumber.setText("Of" + currentPage+"]");
}
});
// Previous
btnPre = (Button) findViewById(R.id.btnPre);
// Perform action on click
btnPre.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
currentPage = currentPage - 1;
// new YourTask().execute();
ShowData();
pagenumber.setText("Of" + currentPage+"]");
}
});
// new YourTask().execute();
ShowData();
}
public void ShowData() {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(url); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
NodeList n2 = doc.getElementsByTagName(KEY_ITEM2);
int displayPerPage = 10; // Per Page
int TotalRows = nl.getLength();
txtreord.setText( TotalRows+"Records|"); // number of records
int indexRowStart = ((displayPerPage * currentPage) - displayPerPage);
int TotalPage = 0;
if (TotalRows <= displayPerPage) {
TotalPage = 1;
} else if ((TotalRows % displayPerPage) == 0) {
TotalPage = (TotalRows / displayPerPage);
} else {
TotalPage = (TotalRows / displayPerPage) + 1; // 7
TotalPage = (int) TotalPage; // 7
}
totalpage.setText("Page[" + TotalPage);
int indexRowEnd = displayPerPage * currentPage; // 5
if (indexRowEnd > TotalRows) {
indexRowEnd = TotalRows;
}
// Disabled Button Next
if (currentPage >= TotalPage) {
btnNext.setEnabled(false);
} else {
btnNext.setEnabled(true);
}
// Disabled Button Previos
if (currentPage <= 1) {
btnPre.setEnabled(false);
} else {
btnPre.setEnabled(true);
}
// Load Data from Index
int RowID = 1;
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
// RowID
if (currentPage > 1) {
RowID = (displayPerPage * (currentPage - 1)) + 1;
}
for (int i = indexRowStart; i < indexRowEnd; i++) {
Element e = (Element) nl.item(i);
Element e2 = (Element) n2.item(i);
String date = e2.getAttribute(KEY_DATE);
// adding each child node to HashMap key => value
map = new HashMap<String, String>();
map.put("RowID", String.valueOf(RowID));
map.put(KEY_DATE, date);
// String Heading = parser.getValue(e, KEY_NAME).replace("|", "|\n")
// .replace("|", "");
//
String mytime = date;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmdd");
Date myDate = null;
try {
myDate = dateFormat.parse(mytime);
} catch (ParseException t) {
t.printStackTrace();
} catch (java.text.ParseException t) {
// TODO Auto-generated catch block
t.printStackTrace();
}
SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd");
String finalDate = timeFormat.format(myDate);
// System.out.println("rrrrrrrrrrrrr"+finalDate);
String Heading = parser.getValue(e, KEY_NAME);
int a = Heading.indexOf("|");
String beforeSubString = Heading.substring(0, a);
String afterSubString = Heading.substring(a, Heading.length())
.replace("|", "") + "[" + finalDate + "]";
// String
// final1="<b>"+beforeSubString+"<b>"+"|"+afterSubString.replace("|",
// "|\n")
// .replace("|", "");
// String k=Html.fromHtml(final1).toString();
//
// Html.fromHtml(final1);
map.put(KEY_NAME, beforeSubString);
map.put(KEY_NAME1, afterSubString);
// adding HashList to ArrayList
menuItems.add(map);
RowID = RowID + 1;
}
SimpleAdapter sAdap;
sAdap = new SimpleAdapter(circularlistparsing.this, menuItems,
R.layout.list_item,
new String[] { "RowID", KEY_NAME1, KEY_NAME }, new int[] {
R.id.ColRowID, R.id.ColName, R.id.textView1 });
lisView1.setAdapter(sAdap);
lisView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Intent i = new Intent(circularlistparsing.this, detail.class);
// sending data to new activity
// i.putExtra("product", product);
startActivity(i);
}
});
}
class YourTask extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
dialog = ProgressDialog.show(circularlistparsing.this, "", "Please wait..");
}
protected Void doInBackground(Void... unused) {
try {
// doSomethingHeavy();
// publishProgress(...);
ShowData();
} catch(Exception e) {
//...
}
return null;
}
protected void onProgressUpdate(Void... unused) {
}
protected void onPostExecute(Void unused) {
dialog.dismiss();
}
}
}
Hii please this code show data function is for displaying data when i m using new YourTask().execute(); in place of show data then its showing Progress bar but not displaying data but able to read data while when we user showdata() function den it display data please tell me how to implement progress bar .
private class YourTask extends AsyncTask<Object, Integer, Object> {
ProgressDialog dialog = new ProgressDialog(Currentactivity.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.show();
this.dialog.setCancelable(false);
super.onPreExecute();
}
#Override
protected Object doInBackground(Object... params) {
//do hard work here
return params;
}
#Override
protected void onProgressUpdate(Integer... values) {
progress.getProgress();
}
#Override
protected void onPostExecute(Object result) {
progressBar.dismiss();
super.onPostExecute(result);
}
}
implement this code
private class YourTask extends AsyncTask<Object, Integer, Object> {
#Override
protected void onPreExecute() {
ProgressDialog dialog = ProgressDialog.show(Activity.this, "",
"Loading...");
super.onPreExecute();
}
#Override
protected Object doInBackground(Object... params) {
try {
// doSomethingHeavy();
// publishProgress(...);
ShowData();
} catch(Exception e) {
//...
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
dialog .getProgress();
}
#Override
protected void onPostExecute(Object result) {
dialog .dismiss();
super.onPostExecute(result);
}
}

How can i list google documents android?

Using Accountmanager i get the token now what?
m using the following class
package com.googleaccount;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;
public class GoogleAccountTestActivity extends Activity {
/** Called when the activity is first created. */
private static final int DIALOG_ACCOUNTS = 0;
private static final int REQUEST_AUTHENTICATE = 0;
protected static final String AUTH_TOKEN_TYPE = "";
private String authToken;
Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context=this;
gotAccount(false);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_ACCOUNTS:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select a Google account");
final AccountManager manager = AccountManager.get(this);
final Account[] accounts = manager.getAccountsByType("com.google");
final int size = accounts.length;
String[] names = new String[size];
for (int i = 0; i < size; i++) {
names[i] = accounts[i].name;
}
builder.setItems(names, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
gotAccount(manager, accounts[which]);
}
});
return builder.create();
}
return null;
}
private void gotAccount(boolean tokenExpired) {
SharedPreferences settings = getSharedPreferences("test", 0);
String accountName = settings.getString("accountName", null);
if (accountName != null) {
AccountManager manager = AccountManager.get(this);
Account[] accounts = manager.getAccountsByType("com.google");
int size = accounts.length;
for (int i = 0; i < size; i++) {
Account account = accounts[i];
if (accountName.equals(account.name)) {
Toast.makeText(this,"OLD accunt name"+account.name , Toast.LENGTH_SHORT).show();
if (tokenExpired) {
Toast.makeText(this,"Token EXpired", Toast.LENGTH_SHORT).show();
manager.invalidateAuthToken("com.google", this.authToken);
}
gotAccount(manager, account);
return;
}
}
}
showDialog(DIALOG_ACCOUNTS);
}
private void gotAccount(final AccountManager manager, final Account account) {
SharedPreferences settings = getSharedPreferences("test", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("accountName", account.name);
editor.commit();
new Thread() {
#Override
public void run() {
try {
final Bundle bundle =
manager.getAuthToken(account, AUTH_TOKEN_TYPE, true, null, null)
.getResult();
runOnUiThread(new Runnable() {
public void run() {
try {
if (bundle.containsKey(AccountManager.KEY_INTENT)) {
Intent intent =
bundle.getParcelable(AccountManager.KEY_INTENT);
int flags = intent.getFlags();
flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
intent.setFlags(flags);
startActivityForResult(intent, REQUEST_AUTHENTICATE);
} else if (bundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
authenticatedClientLogin(
bundle.getString(AccountManager.KEY_AUTHTOKEN));
}
} catch (Exception e) {
// handleException(e);
Toast.makeText(context,e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
} catch (Exception e) {
//handleException(e);
Toast.makeText(context,e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}.start();
}
#Override
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_AUTHENTICATE:
if (resultCode == RESULT_OK) {
Toast.makeText(this,"Result OK!!" , Toast.LENGTH_SHORT).show();
gotAccount(false);
} else {
Toast.makeText(this,"Result False!!" , Toast.LENGTH_SHORT).show();
showDialog(DIALOG_ACCOUNTS);
}
break;
}
}
private void authenticatedClientLogin(String authToken) {
this.authToken = authToken;
Toast.makeText(this,"Token "+authToken, Toast.LENGTH_LONG).show();
//((GoogleHeaders) transport.defaultHeaders).setGoogleLogin(authToken);
//authenticated();
}
}
Your best bet is to use the Google API Client library:
http://code.google.com/p/google-api-java-client/wiki/Setup
Download the core jars(link to be found in the wiki) and dependencies. In particular, you should be looking for these jars:
google-api-client-version-alpha.jar
google-api-client-googleapis-version-alpha.jar
guava-version.jar
jackson-core-asl-version.jar
Next. set up your model classes that describe your feed. For DocList, refer this sample:
Google API DocList Sample
DocUrl.java, DocumentListEntry.java, DocumentListFeed.java, Entry.java, Feed.java & Link.java are the model classes which should set you up.
Next, initialize your HTTPTransport by choosing the parser i.e. Atom/Json and fire your request.
public static final XmlNamespaceDictionary NAMESPACE_DICTIONARY = new XmlNamespaceDictionary();
static {
NAMESPACE_DICTIONARY.set("", "http://www.w3.org/2005/Atom");
NAMESPACE_DICTIONARY.set("app", "http://www.w3.org/2007/app");
NAMESPACE_DICTIONARY.set("batch", "http://schemas.google.com/gdata/batch");
NAMESPACE_DICTIONARY.set("docs", "http://schemas.google.com/docs/2007");
NAMESPACE_DICTIONARY.set("gs", "http://schemas.google.com/spreadsheets/2006");
NAMESPACE_DICTIONARY.set("gd", "http://schemas.google.com/g/2005");
NAMESPACE_DICTIONARY.set("gsx", "http://schemas.google.com/spreadsheets/2006/extended");
NAMESPACE_DICTIONARY.set("openSearch", "http://a9.com/-/spec/opensearch/1.1/");
NAMESPACE_DICTIONARY.set("xml", "http://www.w3.org/XML/1998/namespace");
}
private static HttpTransport transport;
private void setupTransport() {
transport = new NetHttpTransport();
GoogleHeaders headers = new GoogleHeaders();
transport.defaultHeaders = headers;
headers.setApplicationName("MyApp/1.0");
headers.gdataVersion = "3.0";
((GoogleHeaders) transport.defaultHeaders)
.setGoogleLogin(<yourtoken>);
AtomParser parser = new AtomParser();
parser.namespaceDictionary = Util.NAMESPACE_DICTIONARY;
transport.addParser(parser);
}
public processDocs() {
setupTransport();
DocUrl url = DocUrl.relativeToRoot(<URL suffix>);
DocListFeed feed = DocListFeed.executeGet(transport, url);
if (feed.entries != null) {
for (DocEntry entry : feed.entries) {
//<do whatever>
}
}

Categories

Resources