how can i create progress bar UI that appear during PDF creation and that stop when PDF creation is finished?
TwoFragment.java
public class TwoFragment extends Fragment{
private View v;
Intent chooser=null;
String myInt="";
public TwoFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_two, container, false);
Button mButton = (Button) rootView.findViewById(R.id.newbutton);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//sendemail();
createPDF();
viewPDF();
}
});
TextView titolo3 = (TextView)rootView.findViewById(R.id.result);
TextView titolo2 = (TextView)rootView.findViewById(R.id.result2);
TextView titolo4 = (TextView)rootView.findViewById(R.id.resultpizze);
//TextView titolo = (TextView)rootView.findViewById(R.id.quantità3);
/* Bundle bundle2=getArguments();
if(bundle2 != null){
String string = bundle2.getString("scelta2", null);
titolo3.setText(string);
}*/
Bundle bundle2=getArguments();
if(bundle2 != null){
myInt = bundle2.getString("scelta2", null);
titolo3.setText(myInt);
}
Bundle bundle3=getArguments();
if(bundle3 != null){
// String myInt3 = bundle3.getString("totalebirre", null);
// cazzo2=Integer.parseInt(myInt3);
int cazzo2=bundle3.getInt("totalebirre");
titolo2.setText(String.valueOf(cazzo2));
}
Bundle bundle=getArguments();
if(bundle != null){
// String myInt2 = bundle2.getString("totalepizze", null);
// cazzo=Integer.parseInt(myInt2);
//titolo2.setText(myInt2);
String string=bundle.getString("scelta3", null);
titolo4.setText(string);
}
return rootView;
}
/* public void sendemail(){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setData(Uri.parse("mailto:"));
String[] to={"marco_marcoletto#hotmail.it"};
intent.putExtra(Intent.EXTRA_EMAIL,to);
intent.putExtra(Intent.EXTRA_SUBJECT, "ciao");
intent.putExtra(Intent.EXTRA_TEXT, "zao");
intent.setType("message/rfc822");
chooser=intent.createChooser(intent,"manda email");
startActivity(chooser);
}*/
public void createPDF() {
Document doc = new Document();
try {
String path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/droidText";
File dir = new File(path);
if (!dir.exists())
dir.mkdirs();
Log.d("PDFCreator", "PDF Path: " + path);
File file = new File(dir, "sample.pdf");
FileOutputStream fOut = new FileOutputStream(file);
PdfWriter.getInstance(doc, fOut);
// open the document
doc.open();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getContext()
.getResources(), R.drawable.androtuto);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.setAlignment(Image.MIDDLE);
// add image to document
doc.add(myImg);
Paragraph p1 = new Paragraph(myInt);
Log.d("ciao",myInt);
Font paraFont = new Font(Font.COURIER);
p1.setAlignment(Paragraph.ALIGN_CENTER);
p1.setFont(paraFont);
// add paragraph to document
doc.add(p1);
Paragraph p2 = new Paragraph("Ciao");
Font paraFont2 = new Font(Font.COURIER, 14.0f, Color.GREEN);
p2.setAlignment(Paragraph.ALIGN_CENTER);
p2.setFont(paraFont2);
doc.add(p2);
stream = new ByteArrayOutputStream();
bitmap = BitmapFactory.decodeResource(getContext()
.getResources(), R.drawable.android);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
myImg = Image.getInstance(stream.toByteArray());
myImg.setAlignment(Image.MIDDLE);
// add image to document
doc.add(myImg);
// set footer
Phrase footerText = new Phrase("Pied de page ");
HeaderFooter pdfFooter = new HeaderFooter(footerText, false);
doc.setFooter(pdfFooter);
} catch (DocumentException de) {
Log.e("PDFCreator", "DocumentException:" + de);
} catch (IOException e) {
Log.e("PDFCreator", "ioException:" + e);
} finally {
doc.close();
}
}
public void viewPDF(){
String path = "/sdcard/droidText/sample.pdf";
File targetFile = new File(path);
Uri targetUri = Uri.fromFile(targetFile);
Intent intent;
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(targetUri, "application/pdf");
startActivity(intent);
}
}
ThreeFragment.java
FRAGMENT FROM WHERE I PASS VARIABLES:
public class ThreeFragment extends Fragment implements
android.widget.CompoundButton.OnCheckedChangeListener {
ListView lv2;
ArrayList<Planet> planetList;
ListView lv;
ArrayList<Birra> birraList;
BirraAdapter biAdapter;
PlanetAdapter plAdapter;
Planet p;
String myInt="";
PlanetAdapter.PlanetHolder holder;
public ThreeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_three, container, false);
Button mButton = (Button) rootView.findViewById(R.id.button2);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MyListFragment mlf=new MyListFragment();
mlf.showResult(v);
// MyListFragment.showResult(v);
showResult2(v);
}
});
//return inflater.inflate(R.layout.fragment_list2, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
lv2 = (ListView) getView().findViewById(R.id.listview2);
displayBirraList();
}
private void displayBirraList() {
birraList = new ArrayList<Birra>();
birraList.add(new Birra("Paulaner", 6, "€"));
birraList.add(new Birra("Forst", 7, "€"));
birraList.add(new Birra("Peroni", 5, "€"));
birraList.add(new Birra("Corona", 5, "€"));
birraList.add(new Birra("Nastro Azzurro", 4, "€"));
biAdapter = new BirraAdapter(birraList, getContext()) {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int pos = lv2.getPositionForView(buttonView);
if (pos != ListView.INVALID_POSITION) {
Birra b = birraList.get(pos);
b.setSelected(isChecked);
/*Toast.makeText(
getActivity(),
"Clicked on Pizza: " + p.getName() + ". State: is "
+ isChecked, Toast.LENGTH_SHORT).show();*/
}
}
};
lv2.setAdapter(biAdapter);
}
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
/*int pos = lv.getPositionForView(buttonView);
if (pos != ListView.INVALID_POSITION) {
Planet p = planetList.get(pos);
p.setSelected(isChecked);
*//**//**//**//*Toast.makeText(
getActivity(),
"Clicked on Planet: " + p.getName() + ". State: is "
+ isChecked, Toast.LENGTH_SHORT).show();*//**//**//**//*
}
*/
}
public void showResult2(View v) {
String result = "Selected Product are :";
int totalAmount = 0;
// String a = "";
for (Birra b : biAdapter.getBox()) {
if (b.selected) {
result += "\n" + b.name + " " + b.distance + "€" + "q.tà :" + b.getQuantità();
int quantitaInt = Integer.parseInt(b.getQuantità());
totalAmount += b.distance * quantitaInt;
// a=String.valueOf(totalAmount);
}
}
/* for (Planet p : plAdapter.getBox()) {
if (p.isSelected()) {
result += "\n" + p.getName() + " " + p.getDistance() + "€" + "q.tà :" + p.getQuantità();
int quantitaInt = Integer.parseInt(p.getQuantità());
//totalAmount2+=p.distance * quantitaInt;
//z=String.valueOf(totalAmount2);
}
}*/
Toast.makeText(getActivity(), result + "\n" +myInt + "\n" + "Total Amount:=" + totalAmount + "€", Toast.LENGTH_LONG).show();
Bundle bun2 = new Bundle();
bun2.putString("scelta2", result);
TwoFragment fgsearch2 = new TwoFragment();
fgsearch2.setArguments(bun2);
android.support.v4.app.FragmentTransaction transaction2 = getActivity().getSupportFragmentManager().beginTransaction();
transaction2.replace(R.id.content_main, fgsearch2);
transaction2.commit();
Bundle bun = new Bundle();
// bun.putString("totalebirre", a);
bun.putInt("totalebirre", totalAmount);
TwoFragment fgsearch = new TwoFragment();
fgsearch.setArguments(bun);
android.support.v4.app.FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_main2, fgsearch);
transaction.commit();
}
}
Step 1 - Declare a global variable - private ProgressBar pdfProgress;
Step 2 - Create a progress bar widget in your respective layour.xml(fragment_two) and give it an id.
Step 3 - In onCreate() method of TwoFragment, write this code just after defining the rootView.
pdfProgress = (ProgressBar)rootView.findViewById(R.id."your progress bar id");
Step 4 - just above createPDF(); write this -
pdfProgress.setVisibility(View.VISIBLE);
Step 5 - just below createPDF(); write this -
pdfProgress.setVisibility(View.GONE);
**
Updated Answer
**
Try this code in your TwoFragment - onClick()-
Button mButton = (Button) rootView.findViewById(R.id.newbutton);
ProgressBar pdfProgress = (ProgressBar) rootView.findViewById(R.id.progressBar);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//sendemail();
pdfProgress.setVisibility(View.VISIBLE);
createPDF();
pdfProgress.setVisibility(View.GONE);
viewPDF();
}
});
The fragment_two.xml (your fragment layout xml) must contain a progress bar that looks like this - (you can add drawables too, might wanna look at a tutorial for that)
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/progressBar"/>
Related
I want to show list item name in fragment textview.
How can I do this?
Here is my code:
Title.java
public class Title extends AppCompatActivity implements OnVersionNameSelectionChangeListener{
private static final String TAG = Title.class.getSimpleName();
String str, arr[];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_title);
str = getIntent().getExtras().getString("string","defaultValue");
//Toast.makeText(getApplicationContext(), str , Toast.LENGTH_SHORT).show();
// Check whether the Activity is using the layout verison with the fragment_container
// FrameLayout and if so we must add the first fragment
if (findViewById(R.id.fragment_container) != null){
// However if we are being restored from a previous state, then we don't
// need to do anything and should return or we could end up with overlapping Fragments
if (savedInstanceState != null){
return;
}
// Create an Instance of Fragment
VersionsFragment versionsFragment = new VersionsFragment();
Bundle bundle = new Bundle();
bundle.putString("key", str);
//versionsFragment.setArguments(getIntent().getExtras());
versionsFragment.setArguments(bundle);
getFragmentManager().beginTransaction().add(R.id.fragment_container, versionsFragment).commit();
}
}
#Override
public void OnSelectionChanged(int versionNameIndex, String[] answer) {
DescriptionFragment descriptionFragment = (DescriptionFragment) getFragmentManager()
.findFragmentById(R.id.version_description);
if (descriptionFragment != null){
// If description is available, we are in two pane layout
// so we call the method in DescriptionFragment to update its content
// Bundle args = new Bundle();
// args.putString("key", str);
// args.putStringArray("answer", answer );
//args.putInt(DescriptionFragment.KEY_POSITION,versionNameIndex);
//descriptionFragment.setArguments(args);
setArray(answer);
//setStr(str);
descriptionFragment.setDescription(versionNameIndex);
} else {
DescriptionFragment newDescriptionFragment = new DescriptionFragment();
Bundle args = new Bundle();
//args.putString("key", str);
//args.putStringArray("answer", answer );
setArray(answer);
args.putInt(DescriptionFragment.KEY_POSITION,versionNameIndex);
newDescriptionFragment.setArguments(args);
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the backStack so the User can navigate back
fragmentTransaction.replace(R.id.fragment_container,newDescriptionFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
public String getStr(){
return str;
}
public void setArray(String[] s)
{
arr = s;
//Log.d(TAG, "setArray: " + arr[0]);
}
public String[] getArray(){
return arr;
}
}
DescriptionFragment.java
public class DescriptionFragment extends Fragment {
private static final String TAG = DescriptionFragment.class.getSimpleName();
final static String KEY_POSITION = "position";
int mCurrentPosition = -1;
String[] mVersionTitle;
String[] mVersionDescriptions;
TextView mVersionTitleTextView;
TextView mVersionDescriptionTextView;
public DescriptionFragment() {
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Title t = (Title) getActivity();
mVersionDescriptions = t.getArray();
//Log.d(TAG , "onActivityCreated: " + mVersionDescriptions.length);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// If the Activity is recreated, the savedInstanceStare Bundle isn't empty
// we restore the previous version name selection set by the Bundle.
// This is necessary when in two pane layout
String strtext = getArguments().getString("title");
if (savedInstanceState != null) {
mCurrentPosition = savedInstanceState.getInt(KEY_POSITION);
//Log.d(TAG, "Show last click position: "+ KEY_POSITION);
}
View view = inflater.inflate(R.layout.fragment_description, container, false);
mVersionTitleTextView = (TextView) view.findViewById(R.id.textView_Title);
mVersionTitleTextView.setText(strtext);
mVersionDescriptionTextView = (TextView) view.findViewById(R.id.version_description);
return view;
}
#Override
public void onStart() {
super.onStart();
Bundle args = new Bundle();
args = getArguments();
if (args != null) {
// Set description based on argument passed in
// setTitle(args.getInt(KEY_POSITION));
setDescription(args.getInt(KEY_POSITION));
} else if (mCurrentPosition != -1) {
// Set description based on savedInstanceState defined during onCreateView()
// setTitle(mCurrentPosition);
setDescription(mCurrentPosition);
}
}
public void setDescription(int descriptionIndex) {
Title t = (Title) getActivity();
// mVersionTitle = t.getArray();
mVersionDescriptions = t.getArray();
//mVersionTitleTextView.setText(mVersionTitle[descriptionIndex]);
mVersionDescriptionTextView.setText(mVersionDescriptions[descriptionIndex]);
mCurrentPosition = descriptionIndex;
Log.d(TAG, "onSaveInstanceState: " + mCurrentPosition);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save the current description selection in case we need to recreate the fragment
outState.putInt(KEY_POSITION, mCurrentPosition);
//Log.d(TAG, "onSaveInstanceState: " + mCurrentPosition);
}
}
versionFragment.java
public class VersionsFragment extends ListFragment {
private static final String TAG = VersionsFragment.class.getSimpleName();
String[] title = new String[0];
String[] description = new String[0];
String table=new String();
public VersionsFragment() {
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String myValue = this.getArguments().getString("key");
Title q = (Title) getActivity();
table = q.getStr();
//Log.d(TAG, "onActivityCreated: " + table);
if(table.equals("Paragraph Writing"))
table="paragraph";
else if(table.equals("Story Writing"))
table="story";
table = table.toLowerCase();
new MyTask().execute();
}
class MyTask extends AsyncTask<String, Integer, String[]> {
#Override
protected String[] doInBackground(String... params) {
String[] versionName = new String[0];
ArrayList<String> scripts = new ArrayList<String>();
ArrayList<String> scripts2 = new ArrayList<String>();
try {
//Log.d(VersionsFragment.class.getSimpleName(),"http://192.168.1.105/android/phpcall.php?table="+table );
URL url = new URL("http://192.168.1.6/ps/phpcall.php?table="+table);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String strJson = "";
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
strJson += line;
}
//Log.d(VersionsFragment.class.getSimpleName(), "JSON string =" + strJson);
JSONArray jArray = new JSONArray(strJson);
//JSONObject jsonObj = new JSONObject(strJson);
// Getting JSON Array node
//JSONArray jArray = jsonObj.getJSONArray(strJson);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
String name = jObject.getInt("id") + ". " + jObject.getString("title");
scripts.add(name);
Bundle bundle = new Bundle();
bundle.putString("title", name);
// set Fragmentclass Arguments
DescriptionFragment fragobj = new DescriptionFragment();
fragobj.setArguments(bundle);
String name2 = jObject.getString("description");
scripts2.add(name2);
}
versionName = scripts.toArray(new String[scripts.size()]);
// title = scripts.toArray(new String[scripts.size()]);
description = scripts2.toArray(new String[scripts.size()]);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return versionName;
}
protected void onPostExecute(String[] result){
//for(int i=0;i<result.length;i++)
//Log.d(VersionsFragment.class.getSimpleName(), result[i]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, result);
setListAdapter(adapter);
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
OnVersionNameSelectionChangeListener listener = (OnVersionNameSelectionChangeListener) getActivity();
listener.OnSelectionChanged(position,description);
}
}
How can I show a progress bar when I click a button during the creation of a PDF file and hide it when I finished creating the file?
public class TwoFragment extends android.support.v4.app.Fragment {
private View v;
Intent chooser=null;
String myInt="";
String ciao="";
private String string="";
private ProgressBar pdfProgress;
ProgressTask task;
public TwoFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_two, container, false);
Button mButton = (Button) rootView.findViewById(R.id.newbutton);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//sendemail();
// pdfProgress.setVisibility(View.GONE);
/* pdfProgress.setVisibility(View.VISIBLE);
createPDF();
pdfProgress.setVisibility(View.GONE);
viewPDF();*/
/*MyAsyncTask myTask = new MyAsyncTask();
myTask.execute();
*/
showProgress();
}
});
TextView titolo3 = (TextView)rootView.findViewById(R.id.result);
TextView titolo2 = (TextView)rootView.findViewById(R.id.result2);
TextView titolo4 = (TextView)rootView.findViewById(R.id.resultpizze);
pdfProgress = (ProgressBar)rootView.findViewById(R.id.progressbar);
pdfProgress.setVisibility(View.GONE);
//pdfProgress.setVisibility(View.INVISIBLE);
//TextView titolo = (TextView)rootView.findViewById(R.id.quantità3);
/* class MyAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// This runs in new thread!!!
// Always run long operations in another thread, so GUI will never be blocked
createPDF();
return null;
}
#Override
protected void onPostExecute(Void v) {
// This runs in MAIN thread, after the job's done.
// You always have to update gui from main thread
pdfProgress.setVisibility(View.GONE);
viewPDF();
}
}
*/
Bundle bundle2=getArguments();
if(bundle2 != null){
string = bundle2.getString("scelta2");
titolo3.setText(string);
}
/* Bundle bundle2=getArguments();
if(bundle2 != null){
// myInt = bundle2.getString("scelta2",myInt);
cacca=bundle2.getString("result",null);
//cacca=myInt;
// Log.d("ciao",cacca);
titolo3.setText(cacca);
}*/
//titolo3.setText(myInt);
/* Bundle bundle3=getArguments();
if(bundle3 != null){
// String myInt3 = bundle3.getString("totalebirre", null);
// cazzo2=Integer.parseInt(myInt3);
int cazzo2=bundle3.getInt("totalebirre");
titolo2.setText(String.valueOf(cazzo2));
}
Bundle bundle=getArguments();
if(bundle != null){
// String myInt2 = bundle2.getString("totalepizze", null);
// cazzo=Integer.parseInt(myInt2);
//titolo2.setText(myInt2);
String string=bundle.getString("scelta3", null);
titolo4.setText(string);
}
*/
return rootView;
}
/* public void sendemail(){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setData(Uri.parse("mailto:"));
String[] to={"marco_marcoletto#hotmail.it"};
intent.putExtra(Intent.EXTRA_EMAIL,to);
intent.putExtra(Intent.EXTRA_SUBJECT, "ciao");
intent.putExtra(Intent.EXTRA_TEXT, "zao");
intent.setType("message/rfc822");
chooser=intent.createChooser(intent,"manda email");
startActivity(chooser);
}*/
//#TargetApi(Build.VERSION_CODES.M)
public void createPDF() {
Document doc = new Document();
try {
String path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/droidText";
File dir = new File(path);
if (!dir.exists())
dir.mkdirs();
Log.d("PDFCreator", "PDF Path: " + path);
//File file = new File(dir, "sample.pdf");
File file = new File(dir, "salve.pdf");
FileOutputStream fOut = new FileOutputStream(file);
PdfWriter.getInstance(doc, fOut);
// open the document
doc.open();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getContext()
.getResources(), R.drawable.androtuto);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.setAlignment(Image.MIDDLE);
// add image to document
doc.add(myImg);
Paragraph p1 = new Paragraph(string);
Font paraFont = new Font(Font.COURIER);
p1.setAlignment(Paragraph.ALIGN_CENTER);
p1.setFont(paraFont);
// add paragraph to document
doc.add(p1);
Paragraph p2 = new Paragraph("Bonjour Android Tuto");
Font paraFont2 = new Font(Font.COURIER, 14.0f, Color.GREEN);
p2.setAlignment(Paragraph.ALIGN_CENTER);
p2.setFont(paraFont2);
doc.add(p2);
stream = new ByteArrayOutputStream();
bitmap = BitmapFactory.decodeResource(getContext()
.getResources(), R.drawable.android);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
myImg = Image.getInstance(stream.toByteArray());
myImg.setAlignment(Image.MIDDLE);
// add image to document
doc.add(myImg);
// set footer
Phrase footerText = new Phrase("Pied de page ");
HeaderFooter pdfFooter = new HeaderFooter(footerText, false);
doc.setFooter(pdfFooter);
} catch (DocumentException de) {
// Log.e("PDFCreator", "DocumentException:" + de);
Log.e("PDFCreator", "DocumentException:" + de.getMessage());
} catch (IOException e) {
// Log.e("PDFCreator", "ioException:" + e);
Log.e("PDFCreator", "DocumentException:" + e.getMessage());
} finally {
doc.close();
}
}
public void viewPDF(){
String path = "/sdcard/droidText/salve.pdf";
File targetFile = new File(path);
Uri targetUri = Uri.fromFile(targetFile);
Intent intent;
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(targetUri, "application/pdf");
startActivity(intent);
}
private class ProgressTask extends AsyncTask<Integer,Integer,Void> {
protected void onPreExecute() {
pdfProgress.setMax(100); // set maximum progress to 100.
}
protected void onCancelled() {
pdfProgress.setMax(0); // stop the progress
}
protected Void doInBackground(Integer... params) {
int start=params[0];
for(int i=start;i<=100;i+=5){
try {
boolean cancelled=isCancelled();
if(!cancelled) {
publishProgress(i);
Log.v("Progress","increment " + i);
//onProgressUpdate(i);
SystemClock.sleep(1000);
}
createPDF();
} catch (Exception e) {
Log.e("Error", e.toString());
}
}
return null;
}
protected void onProgressUpdate(Integer... values) {
// increment progress bar by progress value
//setProgress(10);
}
protected void onPostExecute(Void result) {
// async task finished
Log.v("Progress", "Finished");
viewPDF();
}
}
public void showProgress() {
task = new ProgressTask();
// start progress bar with initial progress 10
///////////////////task.execute(10,10,null);
task.execute(10);
}
}
Define a ProgressDialog in your Fragment as follows. The following code will add a ProgessDialog; to update it to show a Progress Bar too, read this.
private ProgressDialog processingDialog;
Now, in your onClick()
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
processingDialog = ProgressDialog.show(this, "Creating PDF", "Please wait ...", true, false);
createPDF();
processingDialog.dismiss();
viewPDF();
}
});
This should do the task, however, I have some more recommendations for you. As creating a PDF (I assume) will be time consuming, it might not be a good idea to do it on the UI Thread. Instead, use an AsyncTask to generate your PDF in doInBackground(), show the ProgressDialog, and finally dismiss() it in onPostExecute().
This code will do what you want using AsyncTask which is reccomended way of doing this!
private class MakePDF extends AsyncTask<Void, Void, Void> {
private ProgressDialog processingDialog;
Context cnt = null;
MakePDF(Context cnt)
{
this.cnt = cnt;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
processingDialog = ProgressDialog.show( this.cnt, "Creating PDF", "Please wait ...", true, false);
}
#Override
protected Void doInBackground(Void... arg0) {
createPDF();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
processingDialog.dismiss();
viewPDF();
}
}
Now call above AsyncTask using
new MakePDF(ActivityName.this).execute(); //here in constructor pass context of an calling activity.
from your activity class
I have a table layout where rows are dynamically added. I want 30 data to be shown in one page.pages should be automatically added with increasing data. This is my code.
int increment = 0;
public int TOTAL_LIST_ITEMS;
public int NUM_ITEMS_PAGE = 50;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.frag_tab1, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tableLayout = (TableLayout) view.findViewById(R.id.tableLay);
buttonNext = (Button) view.findViewById(R.id.next);
listView = (ListView) view.findViewById(R.id.list);
title = (TextView) view.findViewById(R.id.text);
buttonPrev = (Button) view.findViewById(R.id.prev);
buttonPrev.setEnabled(false);
// data = new ArrayList<String>();
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
increment++;
loadList(increment);
Toast.makeText(getActivity(),"the page is"+increment,Toast.LENGTH_LONG).show();
checkEnable();
}
});
buttonPrev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
increment--;
loadList(increment);
Toast.makeText(getActivity(),"the page is"+increment,Toast.LENGTH_LONG).show();
checkEnable();
}
});
db = getActivity().openOrCreateDatabase("hitechData.db", Context.MODE_PRIVATE, null);
DBHelper dh = new DBHelper(getActivity(), "hitechData.db", null, 1);
tableLayout.setColumnStretchable(0, true);
tableLayout.setColumnStretchable(2, true);
tableLayout.setStretchAllColumns(true);
tableLayout.bringToFront();
db = getActivity().openOrCreateDatabase("hitechData.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
db.setVersion(1);
db.setLocale(Locale.getDefault());
dh.onCreate(db);
db.setLockingEnabled(true);
String query = "SELECT * FROM leadData3 Order by id DESC";
Cursor cur;
cur = db.rawQuery(query, null);
TOTAL_LIST_ITEMS = cur.getCount();
data=TOTAL_LIST_ITEMS;
int val = TOTAL_LIST_ITEMS % NUM_ITEMS_PAGE;
val = val == 0?0:1;
pageCount = TOTAL_LIST_ITEMS / NUM_ITEMS_PAGE;
if (cur != null && cur.getCount() > 0) {
if (cur.moveToFirst()) {
try {
while (cur.isAfterLast() == false ){
TableRow tr = new TableRow(getActivity().getBaseContext());
final TextView compName = new TextView(getActivity().getBaseContext());
compName.setBackgroundResource(R.drawable.borderr);
final TextView firstName = new TextView(getActivity().getBaseContext());
firstName.setBackgroundResource(R.drawable.borderr);
final TextView midName = new TextView(getActivity().getBaseContext());
midName.setBackgroundResource(R.drawable.borderr);
final TextView lastName = new TextView(getActivity().getBaseContext());
lastName.setBackgroundResource(R.drawable.borderr);
compName.append(cur.getString(1));
compName.setTextColor(this.getResources().getColor(R.color.colorPrimary));
compName.setPadding(30, 0, 0, 0);
firstName.append(cur.getString(21));
firstName.setTextColor(this.getResources().getColor(R.color.colorPrimary));
firstName.setPadding(30, 0, 0, 0);
midName.append(cur.getString(22));
midName.setTextColor(this.getResources().getColor(R.color.colorPrimary));
midName.setPadding(30, 0, 0, 0);
lastName.append(cur.getString(23));
lastName.setTextColor(this.getResources().getColor(R.color.colorPrimary));
lastName.setPadding(30, 0, 0, 0);
// String name =firstName.getText().toString()+midName.getText().toString()+lastName.getText().toString();
firstName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String nameValue = firstName.getText().toString();
String companyValue = compName.getText().toString();
Intent intent = new Intent(getActivity().getApplicationContext(), ShowDetailData.class);
intent.putExtra("name", nameValue);
intent.putExtra("accNo", companyValue);
Toast.makeText(getActivity().getApplicationContext(), nameValue, Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
tr.addView(firstName);
tr.addView(compName);
tableLayout.addView(tr);
cur.moveToNext();
/* count++;
nextPage++;
Toast.makeText(getActivity().getApplicationContext(), "count is : " + count, Toast.LENGTH_LONG).show();*/
//cur.close();
}
} finally {
cur.close();
db.close();
}
} else {
Toast.makeText(getActivity().getApplicationContext(), "no Data", Toast.LENGTH_LONG).show();
}
}
}
/*
*/
/*
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nextPage++;
Toast.makeText(getActivity(), "next page is"+nextPage, Toast.LENGTH_SHORT).show();
}
});*/
private void loadList(int number){
ArrayList<String> sort = new ArrayList<String >();
title.setText("Page "+(number+1+" of " +pageCount));
int start = number * NUM_ITEMS_PAGE;
for (int i=start; i<(start)+NUM_ITEMS_PAGE; i++)
{
if(i<data)
{
sort.add(String.valueOf(data));
}
else {
break;
}
// adapter = new ArrayAdapter<String>(getActivity(), //android.R.layout.simple_list_item_1,sort);
// tablerow.setAdapter(adapter);
//implement table row in adapter
}}
private void checkEnable(){
if(increment+1 == pageCount)
{
buttonNext.setEnabled(false);
}
else if(increment == 0){
buttonPrev.setEnabled(false);
}
else {
buttonPrev.setEnabled(true);
buttonNext.setEnabled(true);
}
}
}
I want to know how can i change the page after no. of rows exceeds 30. I am unable to do pagination.
Currently i am using Sqlite and all the filled data is appearing on the first page.
I want to divide the data and want it appear in set of 30 after click of previous and next.
I want to send email with an attachment from my app (attachment is csv file), but Gmail says, that attachment couldn't be added. Is mistake in converting text into csv or in Adding attachment to gmail?
My code:
public class EmailInput extends DialogFragment {
View mainView;
TextView email;
Button submitSend;
ArrayList<String> resultsEmail;
ArrayList<String> valuesMail;
TextView soucetVysledkuMail;
String subject = "Kubírovací kalkulačka";
MainActivity MA;
String attachmentFile;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
MA = (MainActivity) getActivity();
mainView = inflater.inflate(R.layout.fragment_email_input, container, false);
email = (TextView) mainView.findViewById(R.id.email);
submitSend = (Button) mainView.findViewById(R.id.submitSend);
resultsEmail = ((MainActivity) getActivity()).getVysledky();
valuesMail = ((MainActivity) getActivity()).getValues();
soucetVysledkuMail = ((MainActivity) getActivity()).getSoucetVysledku();
getDialog().setTitle("Odeslat výsledky");
submitSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String FILENAME = "email-attachment.csv";
String string = "";
try {
FileOutputStream fOut = ((MainActivity) getActivity()).getContext().openFileOutput(FILENAME, Context.MODE_PRIVATE);
for (int i = 0; i < resultsEmail.size(); i++) {
string += resultsEmail.get(i) + "," + valuesMail.get(i);
}
string += "Součet výsledků:," + MA.getsoucetVsechVysledkuMA();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
attachmentFile = "mail-attachment.csv";
Uri URI = Uri.parse("file://" + attachmentFile);
String content = results();
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{email.getText().toString()});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, content);
emailIntent.putExtra(Intent.EXTRA_STREAM, URI);
emailIntent.setType("text/plain");
startActivity(Intent.createChooser(emailIntent, "Vyberte aplikaci:"));
}
});
return mainView;
}
public String results() {
String content = "";
for (int i = 0; i < resultsEmail.size(); i++) {
int cislovka = i+1;
content += cislovka + ". " + resultsEmail.get(i) + " (" + valuesMail.get(i) + ") \n";
}
content += "Součet výsledků: " + MA.getsoucetVsechVysledkuMA();
return content;
}
}
There is a problem with permissions. If you want to attach file to your mail, it has to be saved in a public folder like Documents.
I am writing a simple application to scan and record WiFi Access Points, there are three options; a single scan, 10 scans, or scan for a period of time.
When I enter my nWiFiScans activity it preforms the scans, records the file and STARTS THE ACTIVITY AGAIN!!!
WHY WOULD IT DO THIS???
nWiFiScans.java
public class nWiFiScans extends Activity
{
//declarations
public static String pntNameStr;
public static int numScans;
public static int scansMin;
LinearLayout layout1;
ScrollView scrollLayout;
TextView label1;
EditText n1Text;
EditText n2Text;
LayoutParams params_layout1;
WifiManager mainWifi = null;
WifiReceiver receiverWifi;
List<ScanResult> wifiList;
StringBuilder sb = new StringBuilder();
Intent intent;
SimpleDateFormat time;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
scrollLayout = new ScrollView(this);
scrollLayout.setBackgroundColor(Color.BLUE);
//Create new layout in "this" activity
params_layout1 = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT, 1);
layout1 = new LinearLayout(this);
layout1.setBackgroundColor(Color.RED);
layout1.setLayoutParams(params_layout1);
//Create TextView in "this" activity
label1 = new TextView(this);
label1.setBackgroundColor(Color.YELLOW);
//Put some text in the TextView
// Get the message from the intent
intent = getIntent();
pntNameStr = intent.getStringExtra(MainActivity.EXTRA_pntNameStr);
numScans = intent.getIntExtra(MainActivity.EXTRA_numScans, 1);
label1.setText(pntNameStr);
//Place the TextView inside the Layout
layout1.addView(label1);
layout1.setOrientation(LinearLayout.VERTICAL);
//scrollLayout.addView(label1);
//layout1.addView(n1Text);
//layout1.addView(n2Text);
//By default the layout is set to HOR, so we change it to VERT orientation:
// Display layout1 when the activity is created:
setContentView(layout1);
mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
checkIfWifiIsOn(mainWifi);
receiverWifi = new WifiReceiver();
registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
mainWifi.startScan();
label1.setText("Starting Scan..."+String.valueOf(numScans));
}
public void checkIfWifiIsOn(WifiManager mainWifi)
{
if (mainWifi.isWifiEnabled() == false)
{
// If wifi disabled then enable it
Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled",
Toast.LENGTH_LONG).show();
mainWifi.setWifiEnabled(true);
}
else {Toast.makeText(getApplicationContext(), "wifi is enabled... thats good...",
Toast.LENGTH_SHORT).show();}
}
public void generateNoteOnSD(String sFileName, String sBody)
{
File root = null;
try
{
root = new File(Environment.getExternalStoragePublicDirectory("SurveyAppData"), "ScanResults");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(this, "Saved" + "/n" +root.toURI(), Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "IM MOTHERFUCKING DONE" ,
Toast.LENGTH_SHORT).show();
//Log.d("Scan Results",sb.toString());
Intent i=new Intent(nWiFiScans.this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
catch(IOException e)
{
e.printStackTrace();
Toast.makeText(this, "!!! - Could NOT Saved" + "/n" +root.toURI(), Toast.LENGTH_LONG).show();
}
}
public class WifiReceiver extends BroadcastReceiver
{
// This method call when number of wifi connections changed
long fisrtScanTS;
private String FILENAME = pntNameStr;
public FileOutputStream outputStream;
#SuppressLint("NewApi")
public void onReceive(Context c, Intent intent)
{
time = new SimpleDateFormat("ddMMyyyyhhmmss");
int ScanTime = numScans;
if(ScanTime==1 | ScanTime==10)
{
for (int scanNum = 1; scanNum<ScanTime+1; scanNum++)
{
wifiList = mainWifi.getScanResults();
for(int i = 0; i < wifiList.size(); i++)
{
sb.append(((wifiList.get(i)).BSSID + " " + (wifiList.get(i)).level + " " + (wifiList.get(i)).frequency + " "+ (wifiList.get(i)).timestamp + " "+ (wifiList.get(i)).SSID +" "+ time.format(new Date()) + "\n" ) );
fisrtScanTS = (wifiList.get(1)).timestamp;
}
do
{
mainWifi.startScan();
wifiList = mainWifi.getScanResults();
try{Thread.currentThread().sleep(200);}
catch(InterruptedException ie){
//If this thread was intrrupted by nother thread
}
} while(fisrtScanTS == (wifiList.get(1)).timestamp);
Toast.makeText(getApplicationContext(), "Scan number " + scanNum ,
Toast.LENGTH_SHORT).show();
}
}else if (ScanTime!=0)
{
Calendar timeNow = Calendar.getInstance();
Calendar timeEnd = Calendar.getInstance();
timeEnd.set(timeNow.YEAR, timeNow.MONTH, timeNow.DAY_OF_MONTH, timeNow.HOUR, timeNow.MINUTE+numScans, timeNow.SECOND);
while(!(timeNow.after(timeEnd))){
wifiList = mainWifi.getScanResults();
for(int i = 0; i < wifiList.size(); i++){
sb.append(((wifiList.get(i)).BSSID + " " + (wifiList.get(i)).level + " " + (wifiList.get(i)).frequency + " "+ (wifiList.get(i)).timestamp + " "+ (wifiList.get(i)).SSID +" "+ time.format(new Date()) + "\n" ) );
fisrtScanTS = (wifiList.get(1)).timestamp;
}
do {
mainWifi.startScan();
wifiList = mainWifi.getScanResults();
try{Thread.currentThread().sleep(200);}
catch(InterruptedException ie){
//If this thread was intrrupted by nother thread
}} while(fisrtScanTS == (wifiList.get(1)).timestamp);
timeNow = Calendar.getInstance();
Toast.makeText(getApplicationContext(), timeNow.getTime().toString() + " :: " + timeEnd.getTime().toString() ,
Toast.LENGTH_SHORT).show();
}
}
generateNoteOnSD(FILENAME, sb.toString());
FILENAME="x";
ScanTime=0;
}
}
}
MainActivity.java
public class MainActivity extends Activity
{
LinearLayout mainLayout,leftLayout,rightLayout;
EditText pointName;
EditText scanTime;
Button scan10, scan1, timedScan;
TextView msg;
LayoutParams paramsL,paramsR;
static final String EXTRA_pntNameStr = "com.example.surveyappv2.pntNameStr";
static final String EXTRA_scanTimeMin = "com.example.surveyappv2.scanTimeMin";
static final String EXTRA_numScans = "com.example.surveyappv2.numScans";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mainLayout = new LinearLayout(this);
mainLayout.setOrientation(LinearLayout.HORIZONTAL);
paramsL = new LayoutParams(500,LayoutParams.MATCH_PARENT, 1);
paramsR = new LayoutParams(500,LayoutParams.MATCH_PARENT, 1);
leftLayout = new LinearLayout(this);
leftLayout.setOrientation(LinearLayout.VERTICAL);
leftLayout.setLayoutParams(paramsL);
leftLayout.setGravity(Gravity.CENTER_HORIZONTAL);
leftLayout.setBackgroundColor(Color.YELLOW);
rightLayout = new LinearLayout(this);
rightLayout.setOrientation(LinearLayout.VERTICAL);
rightLayout.setLayoutParams(paramsR);
rightLayout.setGravity(Gravity.CENTER_HORIZONTAL);
rightLayout.setBackgroundColor(Color.BLUE);
scanTime = new EditText(this);
scanTime.setHint("Scan Duration (min)");
scanTime.setInputType(InputType.TYPE_CLASS_NUMBER);
pointName = new EditText(this);
pointName.setHint("Enter Point Name");
scan10 = new Button(this);
scan1 = new Button(this);
timedScan = new Button(this);
msg = new TextView(this);
scan10.setText("Do 10 Scans");
scan1.setText("Do a Single Scan");
timedScan.setText("Timed Scan");
msg.setText("Alec Sucks");
leftLayout.addView(pointName);
leftLayout.addView(scanTime);
rightLayout.addView(msg);
rightLayout.addView(scan10);
rightLayout.addView(scan1);
rightLayout.addView(timedScan);
mainLayout.addView(leftLayout);
mainLayout.addView(rightLayout);
mainLayout.setBackgroundColor(Color.RED);
setContentView(mainLayout);
setButtonClickListener();
}
private void setButtonClickListener()
{
scan10.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String message2 = "Button: \n" + scan10.getText();
msg.setText(message2);
startScan(mainLayout,10);
}
});
scan1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String message2 = "Button: \n" + scan1.toString();
msg.setText(message2);
startScan(mainLayout,1);
}
});
timedScan.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String message2 = "Button: \n" + timedScan.toString();
msg.setText(message2);
startScan(mainLayout,Integer.parseInt(scanTime.getText().toString()));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void startScan(View view, int numScans)
{
Intent intent = new Intent(this, nWiFiScans.class);
String pntNameStr = pointName.getText().toString();
intent.putExtra(EXTRA_pntNameStr, pntNameStr);
intent.putExtra(EXTRA_numScans, numScans);
startActivity(intent);
}
}
I ran it, removed the file creation and the Intent(You only need to call finish();) and then it worked. Have you checked that it actually goes through File creation for you? Because mine got stuck there and then it jumps out of try so it can't reach the finish(); call, I also called unregisterReceiver(receiverWifi); before finish();
EDIT, File creation:
File sdCard = Environment.getExternalStorageDirectory(); //returns sdcard directory
File dir = new File (sdCard.getAbsolutePath() + "/mydirectory");
dir.mkdirs();
File file = new File(dir, "filename");