When merging PDF files using itext the result pdf show 0 bytes in android studio - pdf

My code is here; I was selecting PDF files from a SD card or internal phone memory using the showFileChooser() method then from onActivityResult(), the files go to mergePdfFiles(View view) method, and from there the files go to createPdf(String[] srcs).
Here is the complete code of my activity:
//Below is onCreate();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mergedpdf);
adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, locations);
// public void fileSelected(File file ) {
// locations.add(file.toString());
// adapter.notifyDataSetChanged();
// }
NewText = (TextView)findViewById(R.id.textView);
AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
listView = (ListView)findViewById(R.id.list_items);
btn = (ImageView) findViewById(R.id.imageView8);
btnconvert = (ImageView) findViewById(R.id.imageView11);
btnconvert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// btTag=((Button)v).getTag().toString();
try {
createPdf( locations);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Toast.makeText(Mergedpdf.this, "button clicked", Toast.LENGTH_SHORT).show();
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// btTag=((Button)v).getTag().toString();
showFileChooser();
NewText.setText("Below Files are Selected");
}
});
}
//this is mergedfiles();
public void mergePdfFiles(View view){
Toast.makeText(Mergedpdf.this, "merge function", Toast.LENGTH_SHORT).show();
try {String[] srcs= new String[locations.size()];
for(int i = 0;i<locations.size();i++) {
srcs[i] = locations.get(i);
}
// String[] srcs = {txt1.getText().toString(), txt2.getText().toString()};
createPdf(srcs);
}catch (Exception e){e.printStackTrace();}
}
//This method create merged pdf file
public void createPdf (String[] srcs) {
try {
// Create document object
File docsFolder = new File(Environment.getExternalStorageDirectory() + "/Merged-PDFFiles");
if (!docsFolder.exists()) {
docsFolder.mkdir();
Log.i(TAG, "Created a new directory for PDF");
}
Date date = new Date();
#SuppressLint("SimpleDateFormat") final String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date);
Document document = new Document();
// pdfCopy = new File(docsFolder.getAbsolutePath(),pdf+"Images.pdf");
// Document document = new Document();
//PdfWriter.getInstance(document, output);
// Create pdf copy object to copy current document to the output mergedresult file
PdfCopy copy = new PdfCopy(document, new FileOutputStream(docsFolder + "/" + timeStamp +"combine.pdf"));
Toast.makeText(Mergedpdf.this, "merged pdf saved", Toast.LENGTH_SHORT).show();
// Open the document
document.open();
PdfReader pr;
int n;
for (int i = 0; i < srcs.length; i++) {
// Create pdf reader object to read each input pdf file
pr = new PdfReader(srcs[i].toString());
// Get the number of pages of the pdf file
n = pr.getNumberOfPages();
for (int page = 1; page <= n; page++) {
// Import all pages from the file to PdfCopy
copy.addPage(copy.getImportedPage(pr, page));
}
}
document.close(); // close the document
} catch (Exception e) {
e.printStackTrace();
}
}
//below is showfilechooser(); method
private void showFileChooser () {
Log.e("AA", "bttag=" + btTag);
String folderPath = Environment.getExternalStorageDirectory() + "/";
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
Uri myUri = Uri.parse(folderPath);
intent.setDataAndType(myUri, "application/pdf");
Intent intentChooser = Intent.createChooser(intent, "Select a file");
startActivityForResult(intentChooser,PICKFILE_RESULT_CODE);
}
//below is onActivityResult(); method
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
if (requestCode == PICKFILE_RESULT_CODE) {
if (resultCode == RESULT_OK) {
String FilePath = data.getData().getPath();
locations.add(FilePath);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.listview,locations);
listView.setAdapter(adapter);
}
}
}
}
//And my declared variables before oncreate().
public com.itextpdf.text.Document Document;
public PdfCopy Copy;
public ByteArrayOutputStream ms;
TextView NewText;
private TextView txt1;
private Button bt1, bt2,bt3;
private Handler handler;
ListView listView;
ArrayList<String> locations = new ArrayList<>();
ArrayAdapter<String> adapter;
ImageView btn, btnconvert, btn3;
private static final String TAG = "PdfCreator";
private final int PICKFILE_RESULT_CODE=10;
private String btTag = "";

Related

Delete button stops working sporadically, only on Windows, when using our editor plugin

We are developing a markdown editor plugin for eclipse. My colleagues who are using Windows 10 encounter a bug that causes keys to stop working. The most common key is delete, other times it is ctrl + s.
Here is the code for the editor extension:
public class MarkdownEditor extends AbstractTextEditor {
private Activator activator;
private MarkdownRenderer markdownRenderer;
private IWebBrowser browser;
public MarkdownEditor() throws FileNotFoundException {
setSourceViewerConfiguration(new TextSourceViewerConfiguration());
setDocumentProvider(new TextFileDocumentProvider());
// Activator manages connections to the Workbench
activator = Activator.getDefault();
markdownRenderer = new MarkdownRenderer();
}
private IFile saveMarkdown(IEditorInput editorInput, IDocument document, IProgressMonitor progressMonitor) {
IProject project = getCurrentProject(editorInput);
String mdFileName = editorInput.getName();
String fileName = mdFileName.substring(0, mdFileName.lastIndexOf('.'));
String htmlFileName = fileName + ".html";
IFile file = project.getFile(htmlFileName);
String markdownString = "<!DOCTYPE html>\n" + "<html>" + "<head>\n" + "<meta charset=\"utf-8\">\n" + "<title>"
+ htmlFileName + "</title>\n" + "</head>" + "<body>" + markdownRenderer.render(document.get())
+ "</body>\n" + "</html>";
try {
if (!project.isOpen())
project.open(progressMonitor);
if (file.exists())
file.delete(true, progressMonitor);
if (!file.exists()) {
byte[] bytes = markdownString.getBytes();
InputStream source = new ByteArrayInputStream(bytes);
file.create(source, IResource.NONE, progressMonitor);
}
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return file;
}
private void loadFileInBrowser(IFile file) {
IWorkbench workbench = PlatformUI.getWorkbench();
try {
if (browser == null)
browser = workbench.getBrowserSupport().createBrowser(Activator.PLUGIN_ID);
URL htmlFile = FileLocator.toFileURL(file.getLocationURI().toURL());
browser.openURL(htmlFile);
IWorkbenchPartSite site = this.getSite();
IWorkbenchPart part = site.getPart();
site.getPage().activate(part);
} catch (IOException | PartInitException e) {
e.printStackTrace();
}
}
#Override
public void init(IEditorSite site, IEditorInput editorInput) throws PartInitException {
super.init(site, editorInput);
IDocumentProvider documentProvider = getDocumentProvider();
IDocument document = documentProvider.getDocument(editorInput);
IFile htmlFile = saveMarkdown(editorInput, document, null);
loadFileInBrowser(htmlFile);
}
#Override
public void doSave(IProgressMonitor progressMonitor) {
IDocumentProvider documentProvider = getDocumentProvider();
if (documentProvider == null)
return;
IEditorInput editorInput = getEditorInput();
IDocument document = documentProvider.getDocument(editorInput);
if (documentProvider.isDeleted(getEditorInput())) {
if (isSaveAsAllowed()) {
/*
* 1GEUSSR: ITPUI:ALL - User should never loose changes made in the editors.
* Changed Behavior to make sure that if called inside a regular save (because
* of deletion of input element) there is a way to report back to the caller.
*/
performSaveAs(progressMonitor);
} else {
}
} else {
// Convert document from string to string array with each instance a single line
// of the document
String[] stringArrayOfDocument = document.get().split("\n");
String[] formattedLines = PipeTableFormat.preprocess(stringArrayOfDocument);
StringBuilder builder = new StringBuilder();
for (String line : formattedLines) {
builder.append(line);
builder.append("\n");
}
String formattedDocument = builder.toString();
// Calculating the position of the cursor
ISelectionProvider selectionProvider = this.getSelectionProvider();
ISelection selection = selectionProvider.getSelection();
int cursorLength = 0;
if (selection instanceof ITextSelection) {
ITextSelection textSelection = (ITextSelection) selection;
cursorLength = textSelection.getOffset(); // etc.
activator.log(Integer.toString(cursorLength));
}
// This sets the cursor on at the start of the file
document.set(formattedDocument);
// Move the cursor
this.setHighlightRange(cursorLength, 0, true);
IFile htmlFile = saveMarkdown(editorInput, document, progressMonitor);
loadFileInBrowser(htmlFile);
performSave(false, progressMonitor);
}
}
private IProject getCurrentProject(IEditorInput editorInput) {
IProject project = editorInput.getAdapter(IProject.class);
if (project == null) {
IResource resource = editorInput.getAdapter(IResource.class);
if (resource != null) {
project = resource.getProject();
}
}
return project;
}
}
Here is the repository: https://github.com/borisv13/GitHub-Flavored-Markdown-Eclipse-Plugin
Any help is accepted

API request catches exception NULL response

I am using NYT's developers movie reviews API, and i am at the beginning where i just want to see a response. It appears that i get a NULL response which catches the exception that i will pinpoint on the code. " CharSequence text = "There was an error. Please try again";" to help you find it. Could someone please tell me what causes this problem.
NYT Documentation Link http://developer.nytimes.com/movie_reviews_v2.json#/Documentation/GET/critics/%7Bresource-type%7D.json
public class MainActivity extends AppCompatActivity {
private final String site = "https://api.nytimes.com/svc/movies/v2/reviews/search.json?query=";
public int count;
public int i;
public int j;
public int k;
public int n;
public int comas;
public int ingadded;
public String web2 = "";
public String istos;
public ArrayList<String> mylist = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button next = (Button) findViewById(R.id.button);
final EditText edit_text = (EditText) findViewById(R.id.ing);
final TextView show_ing = (TextView) findViewById(R.id.show_ing);
final Button done = (Button) findViewById(R.id.button3);
final Button refresh = (Button) findViewById(R.id.refresh);
final Button delete = (Button) findViewById(R.id.delete);
final ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
//done move to next activity
done.setOnClickListener(new View.OnClickListener() {
#Override
//CHECK IF TEXT BOX IS EMPTY
public void onClick(View view) {
web2 = edit_text.getText().toString();
//check if there are ingredients added
if (web2 == "") {
Context context = getApplicationContext();
CharSequence text = "Search Bar is Empty!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Dialog.dismiss();
}
else {
//IF NOT CREATE THE LINK AND SEND IT TO LongOperation
web2 = edit_text.getText().toString();
//create link - MAYBE THE WAY API KEY MUST BE CALLED?
istos = site + web2 + "?api-key=xxxxxxxxxxxx";
Log.v("Showme=", istos);
web2 = "";
// WebServer Request URL
String serverURL = istos;
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
}
}
});
edit_text.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus)
edit_text.setHint("");
else
edit_text.setHint("Type the title of the movie");
}
});
private class LongOperation extends AsyncTask<String, String, Void> {
// Required initialization
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private Integer count;
private int add = 1;
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
String data = "";
TextView jsonParsedname = (TextView) findViewById(R.id.jsonParsedname1);
ArrayList<ArrayList<Integer>> numArray = new ArrayList<ArrayList<Integer>>();
int sizeData = 0;
protected void onPreExecute() {
//Start Progress Dialog (Message)
Dialog.setMessage("Finding Movies..");
Dialog.show();
try {
// Set Request parameter
data = "&" + URLEncoder.encode("data", "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader = null;
// Send data
try {
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = "";
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (Exception ex) {
Error = ex.getMessage();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
/*****************************************************/
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if (Error != null) {
Context context = getApplicationContext();
CharSequence text = "There was an error. Please try again";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Dialog.dismiss();
} else {
JSONObject jsonResponse;
try {
/****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
jsonResponse = new JSONObject(Content);
if (jsonResponse == null) {
jsonParsedname.setText("Wrong Input");
}
/***** Returns the value mapped by name if it exists and is a JSONArray. ***/
/******* Returns null otherwise. *******/
JSONArray jsonMainNode = jsonResponse.optJSONArray("results");

How to implement a endless Recylerview?

How to implement a endless Recylerview?
This is Activity code:
public class ShopList extends AppCompatActivity {
RecyclerView rview;
RatingBar ratingbar;
private String `urlParameters`;
Recyclerviewshopl adapter;
String category;
JSONArray arr = null;
private Boolean Isinternetpresent = false;
ConnectionDetector cd;
String cat;
ProgressDialog dialog;
String lat,lon;
TextView nodata;
ImageView oops;
double latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shop_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ratingbar = (RatingBar) findViewById(R.id.ratingbar);
List<Itemshopl> rowListItem = getAllItemList();
rview=(RecyclerView)findViewById(R.id.recycleshop);
nodata=(TextView)findViewById(R.id.nodata);
oops=(ImageView)findViewById(R.id.oops);
nodata.setVisibility(View.GONE);
oops.setVisibility(View.GONE);
// LayerDrawable stars = (LayerDrawable) ratingbar.getProgressDrawable();
//stars.getDrawable(5).setColorFilter(Color.parseColor("#26ce61"),
// PorterDuff.Mode.SRC_ATOP);
// stars.getDrawable(1).setColorFilter(Color.YELLOW, PorterDuff.Mode.SRC_ATOP);
/* RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, //width
ViewGroup.LayoutParams.WRAP_CONTENT);//height
rview.setLayoutParams(lp);*/
Bundle extras = getIntent().getExtras();
cat = extras.getString("category");
lat=extras.getString("lat");
lon=extras.getString("lon");
System.out.println("gr++"+cat);
cd = new ConnectionDetector(getApplicationContext());
Isinternetpresent = cd.isConnectingToInternet();
// onBackPressed();
if(Isinternetpresent)
{
shoplist tasku=new shoplist();
tasku.execute(new String[]{"http://abc**.com/****/getshoplist"});
}else{
// Toast.makeText(UserProfileActivity.this,"No Internet connection",Toast.LENGTH_SHORT).show();
showAlertDialog(ShopList.this, "No Internet Connection", "You don't have internet connection.", false);
}
}
public void showAlertDialog(Context context, String title, String message, Boolean status)
{
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
// alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
alertDialog.setButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
}
});
alertDialog.show();
}
private List<Itemshopl> getAllItemList() {
List<Itemshopl> allItems = new ArrayList<Itemshopl>();
allItems.add(new Itemshopl());
allItems.add(new Itemshopl());
allItems.add(new Itemshopl());
allItems.add(new Itemshopl());
return allItems;
}
private class shoplist extends AsyncTask<String, String, List<Itemshopl>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(ShopList.this, "Loading", "Please Wait...", true);
dialog.show();
}
#Override
protected List<Itemshopl> doInBackground(String... urls) {
URL url;
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
urlParameters = "&cat=" + URLEncoder.encode(cat, "UTF-8")+
"&lat="+ URLEncoder.encode(lat, "UTF-8")+
"&lon="+ URLEncoder.encode(lon, "UTF-8");
url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
String finalJson = buffer.toString();
List<Itemshopl> itemshoplist = new ArrayList<>();
arr = new JSONArray(finalJson);
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
/// String state = obj.getString("status");
Itemshopl model = new Itemshopl();
model.setName(obj.getString("shopname"));
model.setcat1(obj.getString("subcat1"));
model.setcat2(","+obj.getString("subcat2"));
model.setcat3(","+obj.getString("subcat3"));
model.setcat4(","+obj.getString("subcat4"));
model.setThumbnailUrl(obj.getString("logo"));
model.setid(obj.getString("id"));
model.setrating(obj.getString("rating"));
model.setreview(obj.getString("reviews")+"Reviews");
model.setcat(obj.getString("category"));
itemshoplist.add(model);
}
// cacheThis.writeObject(ShopList.this, "name", "hai");
return itemshoplist;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<Itemshopl> detailsModels) {
super.onPostExecute(detailsModels);
dialog.dismiss();
if (detailsModels != null && detailsModels.size() > 0) {
nodata.setVisibility(View.GONE);
oops.setVisibility(View.GONE);
rview=(RecyclerView)findViewById(R.id.recycleshop);
rview.setHasFixedSize(true);
adapter = new Recyclerviewshopl(getApplicationContext(), detailsModels);
rview.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
rview.setAdapter(adapter);
}else
{
nodata.setVisibility(View.VISIBLE);
oops.setVisibility(View.VISIBLE);
}
}
}}
Adapter:
public class Recyclerviewshopl extends RecyclerView.Adapter<Recyclerviewshopl.ViewHolder> {
private List<Itemshopl> itemList;
private Context context;
public Recyclerviewshopl(Context context, List<Itemshopl> itemList) {
this.itemList = itemList;
this.context = context;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.name.setText(itemList.get(position).getName());
holder.icons.setImageResource(itemList.get(position).getPhoto());
holder.cat1.setText(itemList.get(position).getcat1());
holder.cat2.setText(itemList.get(position).getcat2());
holder.cat3.setText(itemList.get(position).getcat3());
holder.cat4.setText(itemList.get(position).getcat4());
holder.id.setText(itemList.get(position).getid());
// holder.review.setText(itemList.get(position).getreview());
holder.image.setText(itemList.get(position).getimg());
Glide.with(context).load(itemList.get(position).getThumbnailUrl()).into(holder.icons );
holder.phone.setText(itemList.get(position).getPhone());
holder.cat.setText(itemList.get(position).getcat());
if(itemList.get(position).getrating().equals(""))
{
itemList.get(position).getrating().equals("0");
} else {
//int value= Integer.parseInt(holder.rate.toString());
holder.rate.setRating(Float.parseFloat(itemList.get(position).getrating()));
}
holder.review.setText(itemList.get(position).getreview());
}
public ViewHolder onCreateViewHolder(ViewGroup parent, int i)
{
View layoutview = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardshoplist, null);
ViewHolder sg = new ViewHolder(layoutview);
return sg;
}
#Override
public int getItemCount() {
return this.itemList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView name, cat1,cat2,cat3,cat4,review,image,id,phone,cat;
ImageView photo;
ImageView icons;
RatingBar rate;
public ViewHolder(final View itemView) {
super(itemView);
icons = (ImageView) itemView.findViewById(R.id.img1);
name = (TextView) itemView.findViewById(R.id.shopname);
cat=(TextView)itemView.findViewById(R.id.cat);
cat1=(TextView)itemView.findViewById(R.id.cat1);
cat2=(TextView)itemView.findViewById(R.id.cat2);
cat3=(TextView)itemView.findViewById(R.id.cat3);
cat4=(TextView)itemView.findViewById(R.id.cat4);
review=(TextView)itemView.findViewById(R.id.review);
image=(TextView)itemView.findViewById(R.id.img);
id=(TextView)itemView.findViewById(R.id.idvalue);
phone=(TextView)itemView.findViewById(R.id.phone);
rate=(RatingBar)itemView.findViewById(R.id.ratingbar);
itemView.setOnClickListener(new View.OnClickListener() {
int pos = getAdapterPosition();
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
Intent in = new Intent(v.getContext(),ShopeProfile.class);
in.putExtra("id",id.getText().toString());
in.putExtra("shopname",name.getText().toString());
in.putExtra("phone",phone.getText().toString());
in.putExtra("rate",rate.getRating());
in.putExtra("cat",cat.getText().toString());
v.getContext().startActivity(in);
}
});
}
}
}

Add a Bitmap image in a PDF document in Android

please, how can i directly pass a bitmap image to a pdf file. I have made a graph with GraphView and at the end i convert it to Bitmap, inside an OnClickListener:
write.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0) {
Bitmap bitmap;
graph.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(graph.getDrawingCache());
graph.setDrawingCacheEnabled(false);
String filename = "imagen";
FileOperations fop = new FileOperations();
fop.write(filename, bitmap);
if (fop.write(filename,bitmap)) {
Toast.makeText(getApplicationContext(),
filename + ".pdf created", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(getApplicationContext(), "I/O error",
Toast.LENGTH_SHORT).show();
}
}
});
The problem is that in the class FileOperations:
public FileOperations() {
}
public Boolean write(String fname, Bitmap bm) {
try {
String fpath = "/sdcard/" + fname + ".pdf";
File file = new File(fpath);
if (!file.exists()) {
file.createNewFile();
}
Document document = new Document();
PdfWriter.getInstance(document,
new FileOutputStream(file.getAbsoluteFile()));
document.open();
String filename = bm.toString();
com.itextpdf.text.Image image =com.itextpdf.text.Image.getInstance(filename);
document.add(image);
document.add(new Paragraph("Hello World2!"));
// step 5
document.close();
Log.d("Suceess", "Sucess");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
}
I want to know how can i pass the bitmap Image to add it in the pdf document, i do this but i think this works only when i give it a path.
String filename = bm.toString();
com.itextpdf.text.Image image =com.itextpdf.text.Image.getInstance(filename);
I just solve it:
document.open();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.setAlignment(Image.MIDDLE);
document.add(myImg);
in the FileOperations class

How to send file with file name by use wifidirect?

I use wifidirect to send file,but I can't get the file name(include .jpg or .mp3),and sent it,it always null.
i'm using wifidirect demo provided Android Developers
I use
File f = new File(uri.getPath());
fileName = f.getName();
and
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ "Wifidirect" + "/" + fileName);
but fileName is alwas null
public class DeviceDetailFragment extends Fragment implements ConnectionInfoListener {
protected static final int CHOOSE_FILE_RESULT_CODE = 20;
private View mContentView = null;
private WifiP2pDevice device;
private WifiP2pInfo info;
//private static WiFiDirectBundle bundle = new WiFiDirectBundle();
ProgressDialog progressDialog = null;
private static String fileName;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mContentView = inflater.inflate(R.layout.device_detail, null);
mContentView.findViewById(R.id.btn_connect).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
config.wps.setup = WpsInfo.PBC;
config.groupOwnerIntent = 15;
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
progressDialog = ProgressDialog.show(getActivity(), "Press back to cancel",
"Connecting to :" + device.deviceAddress, true, true
// new DialogInterface.OnCancelListener() {
//
// #Override
// public void onCancel(DialogInterface dialog) {
// ((DeviceActionListener) getActivity()).cancelDisconnect();
// }
// }
);
((DeviceActionListener) getActivity()).connect(config);
}
});
mContentView.findViewById(R.id.btn_disconnect).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
((DeviceActionListener) getActivity()).disconnect();
}
});
mContentView.findViewById(R.id.btn_start_client).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// Allow user to pick an image from Gallery or other
// registered apps
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, CHOOSE_FILE_RESULT_CODE);
}
});
return mContentView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// User has picked an image. Transfer it to group owner i.e peer using
// FileTransferService.
Uri uri = data.getData();
File f = new File(uri.getPath());
fileName = f.getName();
TextView statusText = (TextView) mContentView.findViewById(R.id.status_text);
statusText.setText("Sending: " + uri);
Log.d(WiFiDirectActivity.TAG, "Intent----------- " + uri);
Intent serviceIntent = new Intent(getActivity(), FileTransferService.class);
serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE);
serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, uri.toString());
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS,
info.groupOwnerAddress.getHostAddress());
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, 8988);
getActivity().startService(serviceIntent);
}
#Override
public void onConnectionInfoAvailable(final WifiP2pInfo info) {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
this.info = info;
this.getView().setVisibility(View.VISIBLE);
// The owner IP is now known.
TextView view = (TextView) mContentView.findViewById(R.id.group_owner);
view.setText(getResources().getString(R.string.group_owner_text)
+ ((info.isGroupOwner == true) ? getResources().getString(R.string.yes)
: getResources().getString(R.string.no)));
// InetAddress from WifiP2pInfo struct.
view = (TextView) mContentView.findViewById(R.id.device_info);
view.setText("Group Owner IP - " + info.groupOwnerAddress.getHostAddress());
// After the group negotiation, we assign the group owner as the file
// server. The file server is single threaded, single connection server
// socket.
if (info.groupFormed && info.isGroupOwner) {
new FileServerAsyncTask(getActivity(), mContentView.findViewById(R.id.status_text))
.execute();
} else if (info.groupFormed) {
// The other device acts as the client. In this case, we enable the
// get file button.
mContentView.findViewById(R.id.btn_start_client).setVisibility(View.VISIBLE);
((TextView) mContentView.findViewById(R.id.status_text)).setText(getResources()
.getString(R.string.client_text));
}
// hide the connect button
mContentView.findViewById(R.id.btn_connect).setVisibility(View.GONE);
}
/**
* Updates the UI with device data
*
* #param device the device to be displayed
*/
public void showDetails(WifiP2pDevice device) {
this.device = device;
this.getView().setVisibility(View.VISIBLE);
TextView view = (TextView) mContentView.findViewById(R.id.device_address);
view.setText(device.deviceAddress);
view = (TextView) mContentView.findViewById(R.id.device_info);
view.setText(device.toString());
}
/**
* Clears the UI fields after a disconnect or direct mode disable operation.
*/
public void resetViews() {
mContentView.findViewById(R.id.btn_connect).setVisibility(View.VISIBLE);
TextView view = (TextView) mContentView.findViewById(R.id.device_address);
view.setText(R.string.empty);
view = (TextView) mContentView.findViewById(R.id.device_info);
view.setText(R.string.empty);
view = (TextView) mContentView.findViewById(R.id.group_owner);
view.setText(R.string.empty);
view = (TextView) mContentView.findViewById(R.id.status_text);
view.setText(R.string.empty);
mContentView.findViewById(R.id.btn_start_client).setVisibility(View.GONE);
this.getView().setVisibility(View.GONE);
}
/**
* A simple server socket that accepts connection and writes some data on
* the stream.
*/
public static class FileServerAsyncTask extends AsyncTask<Void, Void, String> {
private Context context;
private TextView statusText;
//String FileName = "bundle.fileName";
/**
* #param context
* #param statusText
*/
public FileServerAsyncTask(Context context, View statusText) {
this.context = context;
this.statusText = (TextView) statusText;
}
#Override
protected String doInBackground(Void... params) {
try {
ServerSocket serverSocket = new ServerSocket(8988);
Log.d(WiFiDirectActivity.TAG, "Server: Socket opened");
Socket client = serverSocket.accept();
Log.d(WiFiDirectActivity.TAG, "Server: connection done");
/*final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ "Wifidirect" + "/wifip2pshared-" + System.currentTimeMillis()
+ ".jpg");*/
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ "Wifidirect" + "/" + fileName);
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
Log.d(WiFiDirectActivity.TAG, "server: copying files " + f.toString());
InputStream inputstream = client.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
serverSocket.close();
return f.getAbsolutePath();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
return null;
}
}
/*
* (non-Javadoc)
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(String result) {
if (result != null) {
statusText.setText("File copied - " + result);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + result), "image/*");
context.startActivity(intent);
}
}
/*
* (non-Javadoc)
* #see android.os.AsyncTask#onPreExecute()
*/
#Override
protected void onPreExecute() {
statusText.setText("Opening a server socket");
}
}
public static boolean copyFile(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
} catch (IOException e) {
Log.d(WiFiDirectActivity.TAG, e.toString());
return false;
}
return true;
}
}
File f = new File(uri.getPath());
fileName = f.getName();
This part of code in your app will get executed - if device acts as client
and
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ "Wifidirect" + "/" + fileName);
this part of code in your app will get executed - if device acts as server (in this case GO) but fileName is always null
Since filename is initialized to "null" , on the server device this will be null.
FileServerAsyncTask is created only on GO( server ) as per the code.
In android sample code file transfer is working only from client to server. In this code user can do file sharing in both directions i.e client to server as well as server to client.
You can see this link.
How can I transfer files between Android devices using Wi-Fi Direct?