List of usage examples for android.app Dialog findViewById
@Nullable public <T extends View> T findViewById(@IdRes int id)
From source file:com.ibm.hellotodo.MainActivity.java
/** * Launches a dialog for updating the TodoItem name. Called when the list item is tapped. * * @param view The TodoItem that is tapped. *//*from www . ja va2 s .c o m*/ public void editTodoName(View view) { // Gets position in list view of tapped item final Integer pos = mListView.getPositionForView(view); final Dialog addDialog = new Dialog(this); addDialog.setContentView(R.layout.add_edit_dialog); addDialog.setTitle("Edit Todo"); TextView textView = (TextView) addDialog.findViewById(android.R.id.title); if (textView != null) { textView.setGravity(Gravity.CENTER); } addDialog.setCancelable(true); EditText et = (EditText) addDialog.findViewById(R.id.todo); final String name = mTodoItemList.get(pos).text; final boolean isDone = mTodoItemList.get(pos).isDone; final int id = mTodoItemList.get(pos).idNumber; et.setText(name); Button addDone = (Button) addDialog.findViewById(R.id.Add); addDialog.show(); // When done is pressed, send PUT request to update TodoItem on Bluemix addDone.setOnClickListener(new View.OnClickListener() { // Save text inputted when done is tapped @Override public void onClick(View view) { EditText editedText = (EditText) addDialog.findViewById(R.id.todo); String newName = editedText.getText().toString(); // If new text is not empty, create JSON with updated info and send PUT request if (!newName.isEmpty()) { String json = "{\"text\":\"" + newName + "\",\"isDone\":" + isDone + ",\"id\":" + id + "}"; // Create PUT REST request using the IBM Mobile First SDK and set HTTP headers so Bluemix knows what to expect in the request Request request = new Request(client.getBluemixAppRoute() + "/api/Items", Request.PUT); HashMap headers = new HashMap(); List<String> cType = new ArrayList<>(); cType.add("application/json"); List<String> accept = new ArrayList<>(); accept.add("Application/json"); headers.put("Content-Type", cType); headers.put("Accept", accept); request.setHeaders(headers); request.send(getApplicationContext(), json, new ResponseListener() { // On success, update local list with updated TodoItem @Override public void onSuccess(Response response) { Log.i(TAG, "Item updated successfully"); loadList(); } // On failure, log errors @Override public void onFailure(Response response, Throwable t, JSONObject extendedInfo) { String errorMessage = ""; if (response != null) { errorMessage += response.toString() + "\n"; } if (t != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); errorMessage += "THROWN" + sw.toString() + "\n"; } if (extendedInfo != null) { errorMessage += "EXTENDED_INFO" + extendedInfo.toString() + "\n"; } if (errorMessage.isEmpty()) errorMessage = "Request Failed With Unknown Error."; Log.e(TAG, "editTodoName failed with error: " + errorMessage); } }); } addDialog.dismiss(); } }); }
From source file:the.joevlc.MainActivity.java
private void showInfoDialog() { final Dialog infoDialog = new Dialog(this, R.style.info_dialog); infoDialog.setContentView(R.layout.info_dialog); Button okButton = (Button) infoDialog.findViewById(R.id.ok); okButton.setOnClickListener(new OnClickListener() { @Override/*from ww w . j ava2s . c om*/ public void onClick(View view) { CheckBox notShowAgain = (CheckBox) infoDialog.findViewById(R.id.not_show_again); if (notShowAgain.isChecked() && mSettings != null) { Editor editor = mSettings.edit(); editor.putInt(PREF_SHOW_INFO, mVersionNumber); editor.commit(); } /* Close the dialog */ infoDialog.dismiss(); /* and finally open the sliding menu if first run */ if (mFirstRun) mMenu.showBehind(); } }); infoDialog.show(); }
From source file:com.adithya321.sharesanalysis.fragments.SalesShareFragment.java
private void setRecyclerViewAdapter() { sharesList = databaseHandler.getShares(); final List<Purchase> salesList = databaseHandler.getSales(); PurchaseShareAdapter purchaseAdapter = new PurchaseShareAdapter(getContext(), salesList); purchaseAdapter.setOnItemClickListener(new PurchaseShareAdapter.OnItemClickListener() { @Override/*from w w w . j a v a 2 s . c om*/ public void onItemClick(View itemView, int position) { final Purchase purchase = salesList.get(position); final Dialog dialog = new Dialog(getActivity()); dialog.setTitle("Edit Share Sale"); dialog.setContentView(R.layout.dialog_sell_share_holdings); dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT); dialog.show(); final Spinner spinner = (Spinner) dialog.findViewById(R.id.existing_spinner); ArrayList<String> shares = new ArrayList<>(); int pos = 0; for (int i = 0; i < sharesList.size(); i++) { shares.add(sharesList.get(i).getName()); if (sharesList.get(i).getName().equals(purchase.getName())) pos = i; } ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, shares); spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(spinnerAdapter); spinner.setSelection(pos); spinner.setVisibility(View.VISIBLE); final EditText quantity = (EditText) dialog.findViewById(R.id.no_of_shares); final EditText price = (EditText) dialog.findViewById(R.id.selling_price); quantity.setText(String.valueOf(purchase.getQuantity())); price.setText(String.valueOf(purchase.getPrice())); Calendar calendar = Calendar.getInstance(); calendar.setTime(purchase.getDate()); year_start = calendar.get(Calendar.YEAR); month_start = calendar.get(Calendar.MONTH) + 1; day_start = calendar.get(Calendar.DAY_OF_MONTH); final Button selectDate = (Button) dialog.findViewById(R.id.select_date); selectDate.setText(new StringBuilder().append(day_start).append("/").append(month_start).append("/") .append(year_start)); selectDate.setOnClickListener(SalesShareFragment.this); Button sellShareBtn = (Button) dialog.findViewById(R.id.sell_share_btn); sellShareBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Purchase p = new Purchase(); p.setId(purchase.getId()); String stringStartDate = year_start + " " + month_start + " " + day_start; DateFormat format = new SimpleDateFormat("yyyy MM dd", Locale.ENGLISH); try { Date date = format.parse(stringStartDate); p.setDate(date); } catch (Exception e) { Toast.makeText(getActivity(), "Invalid Date", Toast.LENGTH_SHORT).show(); return; } try { p.setQuantity(Integer.parseInt(quantity.getText().toString())); } catch (Exception e) { Toast.makeText(getActivity(), "Invalid Number of Shares", Toast.LENGTH_SHORT).show(); return; } try { p.setPrice(Double.parseDouble(price.getText().toString())); } catch (Exception e) { Toast.makeText(getActivity(), "Invalid Buying Price", Toast.LENGTH_SHORT).show(); return; } p.setType("sell"); p.setName(spinner.getSelectedItem().toString()); databaseHandler.updatePurchase(p); setRecyclerViewAdapter(); dialog.dismiss(); } }); } }); salesRecyclerView.setHasFixedSize(true); salesRecyclerView.setAdapter(purchaseAdapter); salesRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); }
From source file:com.untie.daywal.activity.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); thisMonthTv = (TextView) findViewById(R.id.this_month_tv); Calendar now = Calendar.getInstance(); Intent intent = getIntent();//from w w w . j a v a 2s . c om year = intent.getIntExtra("year", now.get(Calendar.YEAR)); month = intent.getIntExtra("month", now.get(Calendar.MONTH)); order = intent.getIntExtra("order", 0); if (order == 0) { mf = MonthlyFragment.newInstance(year, month); getSupportFragmentManager().beginTransaction().add(R.id.monthly, mf).commit(); } else if (order == 1) { mf = MonthlyFragment.newInstance(year, month - 1); getSupportFragmentManager().beginTransaction().replace(R.id.monthly, mf).commit(); } mf.setOnMonthChangeListener(new MonthlyFragment.OnMonthChangeListener() { @Override public void onChange(int year, int month) { HLog.d(TAG, CLASS, "onChange " + year + "." + month); thisMonthTv.setText(year + " " + (month + 1) + ""); } @Override public void onDayClick(OneDayView dayView) { int year = dayView.get(Calendar.YEAR); int month = dayView.get(Calendar.MONTH); int day = dayView.get(Calendar.DAY_OF_MONTH); int week = dayView.get(Calendar.DAY_OF_WEEK); Intent intent = new Intent(MainActivity.this, PopupActivity.class); intent.putExtra("year", year); intent.putExtra("month", month); intent.putExtra("day", day); intent.putExtra("week", week); intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); startActivity(intent); //overridePendingTransition(0, 0); } @Override public void onDayLongClick(OneDayView dayView) { if (dayView.getImage() != null) { final Dialog dayPickerDialog = new Dialog(MainActivity.this); dayPickerDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dayPickerDialog.setContentView(R.layout.dialog_image); dayPickerDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); dayPickerDialog.getWindow().setBackgroundDrawable((new ColorDrawable(0x7000000))); ImageView imageView = (ImageView) dayPickerDialog.findViewById(R.id.image_popup); Uri uri = dayView.getImage(); Glide.with(MainActivity.this).load(uri).centerCrop().into(imageView); dayPickerDialog.show(); //dayPickerDialog.dismiss(); } } }); thisMonthTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showDayPicker(); } }); }
From source file:edu.berkeley.boinc.BOINCActivity.java
/** * React to selection of nav bar item// w w w. j a v a 2 s .c om * @param item * @param position * @param init */ private void dispatchNavBarOnClick(NavDrawerItem item, boolean init) { // update the main content by replacing fragments if (item == null) { if (Logging.WARNING) Log.w(Logging.TAG, "dispatchNavBarOnClick returns, item null."); return; } if (Logging.DEBUG) Log.d(Logging.TAG, "dispatchNavBarOnClick for item with id: " + item.getId() + " title: " + item.getTitle() + " is project? " + item.isProjectItem()); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); Boolean fragmentChanges = false; if (init) { // if init, setup status fragment ft.replace(R.id.status_container, new StatusFragment()); } if (!item.isProjectItem()) { switch (item.getId()) { case R.string.tab_tasks: ft.replace(R.id.frame_container, new TasksFragment()); fragmentChanges = true; break; case R.string.tab_notices: ft.replace(R.id.frame_container, new NoticesFragment()); fragmentChanges = true; break; case R.string.tab_projects: ft.replace(R.id.frame_container, new ProjectsFragment()); fragmentChanges = true; break; case R.string.menu_help: Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://boinc.berkeley.edu/wiki/BOINC_Help")); startActivity(i); break; case R.string.menu_about: final Dialog dialog = new Dialog(this); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.dialog_about); Button returnB = (Button) dialog.findViewById(R.id.returnB); TextView tvVersion = (TextView) dialog.findViewById(R.id.version); try { tvVersion.setText(getString(R.string.about_version) + " " + getPackageManager().getPackageInfo(getPackageName(), 0).versionName); } catch (NameNotFoundException e) { if (Logging.WARNING) Log.w(Logging.TAG, "version name not found."); } returnB.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.show(); break; case R.string.menu_eventlog: startActivity(new Intent(this, EventLogActivity.class)); break; case R.string.projects_add: startActivity(new Intent(this, SelectionListActivity.class)); break; case R.string.tab_preferences: ft.replace(R.id.frame_container, new PrefsFragment()); fragmentChanges = true; break; default: if (Logging.ERROR) Log.d(Logging.TAG, "dispatchNavBarOnClick() could not find corresponding fragment for " + item.getTitle()); break; } } else { // ProjectDetailsFragment. Data shown based on given master URL Bundle args = new Bundle(); args.putString("url", item.getProjectMasterUrl()); Fragment frag = new ProjectDetailsFragment(); frag.setArguments(args); ft.replace(R.id.frame_container, frag); fragmentChanges = true; } mDrawerLayout.closeDrawer(mDrawerList); if (fragmentChanges) { ft.commit(); setTitle(item.getTitle()); mDrawerListAdapter.selectedMenuId = item.getId(); //highlight item persistently mDrawerListAdapter.notifyDataSetChanged(); // force redraw } if (Logging.DEBUG) Log.d(Logging.TAG, "displayFragmentForNavDrawer() " + item.getTitle()); }
From source file:com.entertailion.android.launcher.Dialogs.java
/** * Display about dialog to user when invoked from menu option. * //from w w w . j a v a 2 s . co m * @param context */ public static void displayAbout(final Launcher context) { final Dialog dialog = new Dialog(context); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.about); Typeface lightTypeface = ((LauncherApplication) context.getApplicationContext()).getLightTypeface(context); TextView aboutTextView = (TextView) dialog.findViewById(R.id.about_text1); aboutTextView.setTypeface(lightTypeface); aboutTextView.setText(context.getString(R.string.about_version_title, Utils.getVersion(context))); aboutTextView.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { context.showCover(false); dialog.dismiss(); Intent intent = new Intent(context, EasterEggActivity.class); context.startActivity(intent); Analytics.logEvent(Analytics.EASTER_EGG); return true; } }); TextView copyrightTextView = (TextView) dialog.findViewById(R.id.copyright_text); copyrightTextView.setTypeface(lightTypeface); TextView feedbackTextView = (TextView) dialog.findViewById(R.id.feedback_text); feedbackTextView.setTypeface(lightTypeface); ((Button) dialog.findViewById(R.id.button_web)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(context.getString(R.string.about_button_web_url))); context.startActivity(intent); Analytics.logEvent(Analytics.ABOUT_WEB_SITE); context.showCover(false); dialog.dismiss(); } }); ((Button) dialog.findViewById(R.id.button_privacy_policy)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(context.getString(R.string.about_button_privacy_policy_url))); context.startActivity(intent); Analytics.logEvent(Analytics.ABOUT_PRIVACY_POLICY); context.showCover(false); dialog.dismiss(); } }); ((Button) dialog.findViewById(R.id.button_more_apps)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(context.getString(R.string.about_button_more_apps_url))); context.startActivity(intent); Analytics.logEvent(Analytics.ABOUT_MORE_APPS); context.showCover(false); dialog.dismiss(); } }); dialog.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { context.showCover(false); } }); context.showCover(true); dialog.show(); Analytics.logEvent(Analytics.DIALOG_ABOUT); }
From source file:co.edu.uniajc.vtf.content.MapSitesFragment.java
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_search: Dialog loDialog = this.createDialog(); loDialog.setCanceledOnTouchOutside(false); loDialog.show();//from w ww . jav a 2 s .c o m OptionsManager loOptions = new OptionsManager(this.getActivity()); OptionsEntity loOptionsData = loOptions.getOptions(); EditText loSearchControl = (EditText) loDialog.findViewById(R.id.txtSearch); loSearchControl.setText(loOptionsData.getSearch()); break; case R.id.action_refresh: MapSitesFragment.this.cboForceUpdate = true; this.loadList(LoadActions.LOAD_DATA); break; } return super.onOptionsItemSelected(item); }
From source file:org.tigase.mobile.muc.JoinMucDialog.java
@Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Dialog dialog = new Dialog(getActivity()); dialog.setCancelable(true);//from w w w.j a v a2 s . c o m dialog.setCanceledOnTouchOutside(true); dialog.setContentView(R.layout.join_room_dialog); dialog.setTitle(getString(R.string.aboutButton)); ArrayList<String> accounts = new ArrayList<String>(); for (Account account : AccountManager.get(getActivity()).getAccountsByType(Constants.ACCOUNT_TYPE)) { accounts.add(account.name); } final Spinner accountSelector = (Spinner) dialog.findViewById(R.id.muc_accountSelector); final Button joinButton = (Button) dialog.findViewById(R.id.muc_joinButton); final Button cancelButton = (Button) dialog.findViewById(R.id.muc_cancelButton); final TextView name = (TextView) dialog.findViewById(R.id.muc_name); final TextView roomName = (TextView) dialog.findViewById(R.id.muc_roomName); final TextView mucServer = (TextView) dialog.findViewById(R.id.muc_server); final TextView nickname = (TextView) dialog.findViewById(R.id.muc_nickname); final TextView password = (TextView) dialog.findViewById(R.id.muc_password); final CheckBox autojoin = (CheckBox) dialog.findViewById(R.id.muc_autojoin); ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, accounts.toArray(new String[] {})); accountSelector.setAdapter(adapter); Bundle data = getArguments(); final boolean editMode = data != null && data.containsKey("editMode") && data.getBoolean("editMode"); final String id = data != null ? data.getString("id") : null; if (data != null) { accountSelector.setSelection(adapter.getPosition(data.getString("account"))); name.setText(data.getString("name")); roomName.setText(data.getString("room")); mucServer.setText(data.getString("server")); nickname.setText(data.getString("nick")); password.setText(data.getString("password")); autojoin.setChecked(data.getBoolean("autojoin")); } if (!editMode) { name.setVisibility(View.GONE); autojoin.setVisibility(View.GONE); } else { joinButton.setText("Save"); } cancelButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); joinButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (editMode) { BareJID account = BareJID.bareJIDInstance(accountSelector.getSelectedItem().toString()); final Jaxmpp jaxmpp = ((MessengerApplication) getActivity().getApplicationContext()) .getMultiJaxmpp().get(account); Bundle data = new Bundle(); data.putString("id", id); data.putString("account", account.toString()); data.putString("name", name.getText().toString()); data.putString("room", roomName.getText().toString()); data.putString("server", mucServer.getText().toString()); data.putString("nick", nickname.getText().toString()); data.putString("password", password.getText().toString()); data.putBoolean("autojoin", autojoin.isChecked()); ((BookmarksActivity) getActivity()).saveItem(data); dialog.dismiss(); return; } BareJID account = BareJID.bareJIDInstance(accountSelector.getSelectedItem().toString()); final Jaxmpp jaxmpp = ((MessengerApplication) getActivity().getApplicationContext()) .getMultiJaxmpp().get(account); Runnable r = new Runnable() { @Override public void run() { try { Room room = jaxmpp.getModule(MucModule.class).join( roomName.getEditableText().toString(), mucServer.getEditableText().toString(), nickname.getEditableText().toString(), password.getEditableText().toString()); if (task != null) task.execute(room); } catch (Exception e) { Log.w("MUC", "", e); // TODO Auto-generated catch block e.printStackTrace(); } } }; (new Thread(r)).start(); dialog.dismiss(); } }); return dialog; }
From source file:com.adithya321.sharesanalysis.fragments.SalesShareFragment.java
@Nullable @Override/*from ww w . ja v a 2s . c o m*/ public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_share_sales, container, false); databaseHandler = new DatabaseHandler(getContext()); salesRecyclerView = (RecyclerView) root.findViewById(R.id.sales_recycler_view); setRecyclerViewAdapter(); FloatingActionButton sellShareFab = (FloatingActionButton) root.findViewById(R.id.sell_share_fab); sellShareFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final Dialog dialog = new Dialog(getContext()); dialog.setTitle("Sell Share Holdings"); dialog.setContentView(R.layout.dialog_sell_share_holdings); dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT); dialog.show(); final Spinner spinner = (Spinner) dialog.findViewById(R.id.existing_spinner); ArrayList<String> shares = new ArrayList<>(); for (Share share : sharesList) { shares.add(share.getName()); } ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, shares); spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(spinnerAdapter); Calendar calendar = Calendar.getInstance(); year_start = calendar.get(Calendar.YEAR); month_start = calendar.get(Calendar.MONTH) + 1; day_start = calendar.get(Calendar.DAY_OF_MONTH); final Button selectDate = (Button) dialog.findViewById(R.id.select_date); selectDate.setText(new StringBuilder().append(day_start).append("/").append(month_start).append("/") .append(year_start)); selectDate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Dialog dialog = new DatePickerDialog(getActivity(), onDateSetListener, year_start, month_start - 1, day_start); dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { selectDate.setText(new StringBuilder().append(day_start).append("/") .append(month_start).append("/").append(year_start)); } }); dialog.show(); } }); Button sellShareBtn = (Button) dialog.findViewById(R.id.sell_share_btn); sellShareBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Purchase purchase = new Purchase(); purchase.setId(databaseHandler.getNextKey("purchase")); purchase.setName(spinner.getSelectedItem().toString()); String stringStartDate = year_start + " " + month_start + " " + day_start; DateFormat format = new SimpleDateFormat("yyyy MM dd", Locale.ENGLISH); try { Date date = format.parse(stringStartDate); purchase.setDate(date); } catch (Exception e) { Toast.makeText(getActivity(), "Invalid Date", Toast.LENGTH_SHORT).show(); return; } EditText quantity = (EditText) dialog.findViewById(R.id.no_of_shares); try { purchase.setQuantity(Integer.parseInt(quantity.getText().toString())); } catch (Exception e) { Toast.makeText(getActivity(), "Invalid Number of Shares", Toast.LENGTH_SHORT).show(); return; } EditText price = (EditText) dialog.findViewById(R.id.selling_price); try { purchase.setPrice(Double.parseDouble(price.getText().toString())); } catch (Exception e) { Toast.makeText(getActivity(), "Invalid Selling Price", Toast.LENGTH_SHORT).show(); return; } purchase.setType("sell"); databaseHandler.addPurchase(spinner.getSelectedItem().toString(), purchase); setRecyclerViewAdapter(); dialog.dismiss(); } }); } }); return root; }
From source file:org.anurag.compress.ExtractTarFile.java
public ExtractTarFile(final Context ctx, final Item zFile, final int width, String extractDir, final File file, final int mode) { // TODO Auto-generated constructor stub running = false;//from ww w. ja va 2 s . co m errors = false; prog = 0; read = 0; final Dialog dialog = new Dialog(ctx, Constants.DIALOG_STYLE); dialog.setCancelable(true); dialog.setContentView(R.layout.extract_file); dialog.getWindow().getAttributes().width = width; DEST = extractDir; final ProgressBar progress = (ProgressBar) dialog.findViewById(R.id.zipProgressBar); final TextView to = (TextView) dialog.findViewById(R.id.zipFileName); final TextView from = (TextView) dialog.findViewById(R.id.zipLoc); final TextView cfile = (TextView) dialog.findViewById(R.id.zipSize); final TextView zsize = (TextView) dialog.findViewById(R.id.zipNoOfFiles); final TextView status = (TextView) dialog.findViewById(R.id.zipFileLocation); if (extractDir == null) to.setText(ctx.getString(R.string.extractingto) + " Cache directory"); else to.setText(ctx.getString(R.string.extractingto) + " " + DEST); from.setText(ctx.getString(R.string.extractingfrom) + " " + file.getName()); if (mode == 2) { //TAR ENTRY HAS TO BE SHARED VIA BLUETOOTH,ETC... TextView t = null;//= (TextView)dialog.findViewById(R.id.preparing); t.setText(ctx.getString(R.string.preparingtoshare)); } try { if (file.getName().endsWith(".tar.gz")) tar = new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(file))); else tar = new TarArchiveInputStream(new BufferedInputStream(new FileInputStream(file))); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); tar = null; } final Handler handle = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: progress.setProgress(0); cfile.setText(ctx.getString(R.string.extractingfile) + " " + name); break; case 1: status.setText(name); progress.setProgress((int) prog); break; case 2: try { tar.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (running) { dialog.dismiss(); if (mode == 0) { //after extracting file ,it has to be opened.... new OpenFileDialog(ctx, Uri.parse(dest)); } else if (mode == 2) { //FILE HAS TO BE SHARED.... new BluetoothChooser(ctx, new File(dest).getAbsolutePath(), null); } else { if (errors) Toast.makeText(ctx, ctx.getString(R.string.errorinext), Toast.LENGTH_SHORT).show(); Toast.makeText(ctx, ctx.getString(R.string.fileextracted), Toast.LENGTH_SHORT).show(); } } break; case 3: zsize.setText(size); progress.setMax((int) max); break; case 4: status.setText(ctx.getString(R.string.preparing)); break; case 5: running = false; Toast.makeText(ctx, ctx.getString(R.string.extaborted), Toast.LENGTH_SHORT).show(); } } }; final Thread thread = new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub if (running) { if (DEST == null) { DEST = Environment.getExternalStorageDirectory() + "/Android/data/org.anurag.file.quest"; new File(DEST).mkdirs(); } TarArchiveEntry ze; try { while ((ze = tar.getNextTarEntry()) != null) { if (ze.isDirectory()) continue; handle.sendEmptyMessage(4); if (!zFile.isDirectory()) { //EXTRACTING A SINGLE FILE FROM AN ARCHIVE.... if (ze.getName().equalsIgnoreCase(zFile.t_getEntryName())) { try { //SENDING CURRENT FILE NAME.... try { name = zFile.getName(); } catch (Exception e) { name = zFile.t_getEntryName(); } handle.sendEmptyMessage(0); dest = DEST; dest = dest + "/" + name; FileOutputStream out = new FileOutputStream((dest)); max = ze.getSize(); size = AppBackup.size(max, ctx); handle.sendEmptyMessage(3); InputStream fin = tar; while ((read = fin.read(data)) != -1 && running) { out.write(data, 0, read); prog += read; name = AppBackup.status(prog, ctx); handle.sendEmptyMessage(1); } out.flush(); out.close(); fin.close(); break; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); //errors = true; } catch (IOException e) { errors = true; } } } else { //EXTRACTING A DIRECTORY FROM TAR ARCHIVE.... String p = zFile.getPath(); if (p.startsWith("/")) p = p.substring(1, p.length()); if (ze.getName().startsWith(p)) { prog = 0; dest = DEST; name = ze.getName(); String path = name; name = name.substring(name.lastIndexOf("/") + 1, name.length()); handle.sendEmptyMessage(0); String foname = zFile.getPath(); if (!foname.startsWith("/")) foname = "/" + foname; if (!path.startsWith("/")) path = "/" + path; path = path.substring(foname.lastIndexOf("/"), path.lastIndexOf("/")); if (!path.startsWith("/")) path = "/" + path; dest = dest + path; new File(dest).mkdirs(); dest = dest + "/" + name; FileOutputStream out; try { max = ze.getSize(); out = new FileOutputStream((dest)); size = AppBackup.size(max, ctx); handle.sendEmptyMessage(3); // InputStream fin = tar; while ((read = tar.read(data)) != -1 && running) { out.write(data, 0, read); prog += read; name = AppBackup.status(prog, ctx); handle.sendEmptyMessage(1); } out.flush(); out.close(); //fin.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); // errors = true; } catch (IOException e) { errors = true; } catch (Exception e) { //errors = true; } } } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); errors = true; } handle.sendEmptyMessage(2); } } }); /* Button cancel = (Button)dialog.findViewById(R.id.calcelButton); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub dialog.dismiss(); handle.sendEmptyMessage(5); } }); Button st = (Button)dialog.findViewById(R.id.extractButton); st.setVisibility(View.GONE);*/ dialog.show(); running = true; thread.start(); dialog.setCancelable(false); progress.setVisibility(View.VISIBLE); }