i want to Convert My Activity To fragment can any One help to Convert Activity to Fragment..i have created Pdf
reader (Click On Button It Will Open Pdf File In Another Activty using pdfviwer.jar library..and I want When I click On Button Pdf Open On Same Screen on Right Side )
i need Help please Solve My Problem
i m posting my Activity
maiinActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn =(Button)findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "ABC.pdf");
try
{
in = assetManager.open("ABC.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e)
{
Log.e("tag", e.getMessage());
}
Intent intent = new Intent(getApplicationContext(), MyPdfViewerActivity.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, getFilesDir()+"/ABC.pdf");
startActivity(intent);
/*
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" + getFilesDir() + "/ABC.pdf"),
"application/pdf");
startActivity(intent);*/
}
});
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
}
PdfviwerActivty.java
public class MyPdfViewerActivity extends PdfViewerActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO Auto-generated method stub
}
public int getPreviousPageImageResource() { return R.drawable.left_arrow; }
public int getNextPageImageResource() { return R.drawable.right_arrow; }
public int getZoomInImageResource() { return R.drawable.zoom_in; }
public int getZoomOutImageResource() { return R.drawable.zoom_out; }
public int getPdfPasswordLayoutResource() { return R.layout.pdf_file_password; }
public int getPdfPageNumberResource() { return R.layout.dialog_pagenumber; }
public int getPdfPasswordEditField() { return R.id.etPassword; }
public int getPdfPasswordOkButton() { return R.id.btOK; }
public int getPdfPasswordExitButton() { return R.id.btExit; }
public int getPdfPageNumberEditField() { return R.id.pagenum_edit; }
}
Try "extends FragmentActivity" instead of "extends Activity"..
You should use FragementActivity instead of Activity and paste your ui-components into the fragment's onCreateView()-Method. For further information look at this tutorial: http://www.vogella.com/tutorials/AndroidFragments/article.html
Related
I am working on an app where the user creates an form in the MainActivity. By clicking on the add button a listview appears (QuestionActivity). In this activity some questions appear. By clicking on, let's say question 1 (Question1 activity), an edittext appears where users can set the name for this form which appears in the MainActivity, also in a listview.
The one thing I am struggling with is the fact that when I open an already saved form, I arrive at the questionlist in QuestionActivity. But when I click on Question 1, the data I already saved here is gone. So I want the users to be able to view and change the data they already saved. But I am not sure how to do this.
I should probably be using an onResume method in the QuestionActivity but I hope someone can help me to do this in a proper way.
Here are my codes:
public class MainActivity extends AppCompatActivity {
private ListView mListViewNotes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListViewNotes = findViewById(R.id.main_listview_notes);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_main_new_note:
Intent newActivity = new Intent(this, QuestionsActivity.class);
startActivity(newActivity);
break;
}
return true;
}
#Override
protected void onResume() {
super.onResume();
mListViewNotes.setAdapter(null);
ArrayList<Note> notes = Utilities.getAllSavedNotes(this);
if (notes ==null || notes.size() == 0) {
Toast.makeText(this, "no saved notes", Toast.LENGTH_SHORT).show();
return;
}else {
NoteAdapter na = new NoteAdapter(this, R.layout.item_note, notes);
mListViewNotes.setAdapter(na);
mListViewNotes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String fileName = ((Note)mListViewNotes.getItemAtPosition(position)).getDateTime()
+ Utilities.FILE_EXTENSION;
Intent viewNoteIntent = new Intent(getApplicationContext(),QuestionsActivity.class);
viewNoteIntent.putExtra("NOTE_FILE", fileName);
startActivity(viewNoteIntent);
}
});
}
}
}
public class QuestionsActivity extends AppCompatActivity {
ListView lv;
String[] charactersDC = {"Question 1", "Question 2", "Question 3", "Question 4", "Question 5"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_questions);
lv = (ListView) findViewById(R.id.idListView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, charactersDC);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if(position == 0)
{
String stringFromQuestion1Result = ((Note)lv.getItemAtPosition(position)).getDateTime()
+ Utilities.FILE_EXTENSION;
Intent myIntent = new Intent(QuestionsActivity.this, Question1.class);
myIntent.putExtra("SAVED_FILE", stringFromQuestion1Result);
startActivityForResult(myIntent,0);
}
if(position == 1)
{
Intent myIntent = new Intent(QuestionsActivity.this, Question2.class);
startActivityForResult(myIntent, 0);
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == request_Code) {
if (resultCode == RESULT_OK) {
String stringFromQuestion1Result = data.getData().toString();
}
}
}
}
public class Question1 extends AppCompatActivity {
private EditText mEtTitle;
private String mNoteFileName;
private Note mLoadedNote;
private String mShowSavedData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question1);
mEtTitle = (EditText) findViewById(R.id.note_et_title);
mNoteFileName = getIntent().getStringExtra("NOTE_FILE");
if(mNoteFileName !=null && !mNoteFileName.isEmpty()) {
mLoadedNote = Utilities.getNoteByName(this, mNoteFileName);
if(mLoadedNote !=null) {
mEtTitle.setText(mLoadedNote.getTitle());
}
}
mShowSavedData = getIntent().getStringExtra("SAVED_FILE");
if(mShowSavedData !=null && !mShowSavedData.isEmpty()) {
mLoadedNote = Utilities.getNoteByName(this, mShowSavedData);
if (mLoadedNote !=null) {
mEtTitle.setText(mLoadedNote.getTitle());
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_note_new, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_note_save:
saveNote();
break;
}
return true;
}
private void saveNote() {
Note note;
if(mLoadedNote ==null) {
note = new Note(System.currentTimeMillis(), mEtTitle.getText().toString());
}else {
note = new Note(mLoadedNote.getDateTime(), mEtTitle.getText().toString());
}
if (Utilities.saveNote(this, note)){
Toast.makeText(this, "saved", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "not enough space", Toast.LENGTH_SHORT).show();
}
setResult (Activity.RESULT_OK, mEtTitle.getText().toString());
finish();
}
}
public class Utilities {
public static final String FILE_EXTENSION = ".bin";
public static boolean saveNote(Context context, Note note) {
// DELETED -> String fileName = String.valueOf(note.getDateTime()) + FILE_EXTENSION;
String stringFromQuestion1Result = String.valueOf(note.getDateTime()) + FILE_EXTENSION;
FileOutputStream fos;
ObjectOutputStream oos;
try {
fos = context.openFileOutput(stringFromQuestion1Result, context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
oos.writeObject(note);
oos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
return false; //tell user something went wrong
}
return true;
}
public static ArrayList<Note> getAllSavedNotes(Context context){
ArrayList<Note> notes = new ArrayList<>();
File filesDir = context.getFilesDir();
ArrayList<String> noteFiles = new ArrayList<>();
for(String file : filesDir.list()) {
if(file.endsWith(FILE_EXTENSION)) {
noteFiles.add(file);
}
}
FileInputStream fis;
ObjectInputStream ois;
for(int i = 0; i < noteFiles.size(); i++) {
try{
fis = context.openFileInput(noteFiles.get(i));
ois = new ObjectInputStream(fis);
notes.add((Note) ois.readObject());
fis.close();
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
return notes;
}
public static Note getNoteByName(Context context, String fileName) {
File file = new File(context.getFilesDir(), fileName);
Note note;
if(file.exists()) {
FileInputStream fis;
ObjectInputStream ois;
try{
fis = context.openFileInput(fileName);
ois = new ObjectInputStream(fis);
note = (Note) ois.readObject();
fis.close();
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
return note;
}
return null;
}
}
Capture the result value of the startActivityForResult for the Question activity. Ie., add the onActivityResult to your QuestionActivity, as described here:
Android: how to make an activity return results to the activity which calls it?
In your Question1 activity, before you call finish(), set the result value:
setResult(Activity.RESULT_OK, mEtTitle.getText().toString());
finish();
In your QuestionActivity, add the method
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == request_Code) {
if (resultCode == RESULT_OK) {
String stringFromQuestion1Result = data.getData().toString();
}
}
}
Store the result in your QuestionActivity and pass it back using the activity Intent. Similar to how you passed the "NOTE_FILE" data to your QuestionActivity you need to pass the data you want to show up in each Question1 activity to it and load the values if provided.
Intent myIntent = new Intent(QuestionsActivity.this, Question1.class);
myIntent.putExtra("Question1String", stringFromQuestion1Result);
startActivityForResult(myIntent, 0);
I am developing multiple file download app. in which, if switch is on then downloading is start and if switch is off then downloading is cancel. I am updating item value using timertask with handler. below is my code of adapter. everything is working fine but when I am scrolling listview, item value (percentage count) are conflict with other values which are other file downloaded progress.
Code:
public class DownloadAdapter extends ArrayAdapter<AudioSubModel> {
private static final String PDF_MIME_TYPE = "application/pdf";
private LayoutInflater lf;
Context mContext;
private List<ListContent> lstHolders;
private Handler mHandler = new Handler();
private Runnable updateRemainingTimeRunnable = new Runnable() {
#Override
public void run() {
synchronized (lstHolders) {
for (ListContent holder : lstHolders) {
holder.updateTimeRemaining();
}
}
}
};
AudioSubModel getAlarm(int position){
return ((AudioSubModel) getItem(position));
}
public DownloadAdapter(Context context, int resource, List<AudioSubModel> objects) {
super(context, resource, objects);
lf = LayoutInflater.from(context);
lstHolders = new ArrayList<ListContent>();
mContext = context;
Log.e("ADAPTER", "CONSTR");
startUpdateTimer();
}
private void startUpdateTimer() {
Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(updateRemainingTimeRunnable);
}
}, 1000, 1000);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
ListContent holder = null;
if (view == null) {
view = lf.inflate(R.layout.row_audio_desc_layout, null);
holder = new ListContent();
holder.ivImg = (CircleImageView)view.findViewById(R.id.row_audio_desc_ivImg);
holder.tvTitle = (TextView) view
.findViewById(R.id.row_audio_desc_tvTitle);
holder.tvDesc = (TextView) view
.findViewById(R.id.row_audio_desc_tvDesc);
holder.llDownload = (LinearLayout)view.findViewById(R.id.row_audio_desc_llDownload);
holder.PBDownload = (RoundCornerProgressBar)view.findViewById(R.id.row_audio_desc_PBDownload);
holder.tvReadPdf = (TextView)view.findViewById(R.id.row_audio_desc_tvReadPdf);
holder.tvMakeOffline = (TextView)view.findViewById(R.id.row_audio_desc_tvMakeOffline);
holder.swtchDownload = (Switch)view.findViewById(R.id.row_audio_desc_swtchDownloadOn);
holder.tvDownload = (TextView)view.findViewById(R.id.row_audio_desc_tvDownload);
holder.tvDownloadPercent = (TextView)view.findViewById(R.id.row_audio_desc_tvDownloadPercent);
holder.ivCancel = (ImageView)view.findViewById(R.id.row_audio_desc_ivCancel);
holder.ivPlay = (ImageView)view.findViewById(R.id.row_audio_desc_ivPlay);
holder.tvTitle.setTypeface(MyApplication.app_bold);
holder.tvDesc.setTypeface(MyApplication.app_light);
holder.tvReadPdf.setTypeface(MyApplication.app_bold);
holder.tvMakeOffline.setTypeface(MyApplication.app_bold);
holder.swtchDownload.setTypeface(MyApplication.app_bold);
holder.tvDownload.setTypeface(MyApplication.app_bold);
holder.tvDownloadPercent.setTypeface(MyApplication.app_bold);
view.setTag(holder);
synchronized (lstHolders) {
lstHolders.add(holder);
}
} else {
holder = (ListContent) view.getTag();
}
holder.setData(getAlarm(position));
// convertView.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// ((MainActivity)mContext).ItemClickFetch(getItem(position).getId());
// }
// });
return view;
}
class ListContent {
LinearLayout llDownload;
RoundCornerProgressBar PBDownload;
CircleImageView ivImg;
ImageView ivCancel, ivPlay;
TextView tvTitle, tvDesc, tvReadPdf, tvMakeOffline, tvDownload, tvDownloadPercent;
Switch swtchDownload;
private AudioSubModel aItem;
DownloadFileFromURL dwnldFileUrl;
public void setData(AudioSubModel item) {
aItem = item;
dwnldFileUrl = new DownloadFileFromURL();
if(item.isPlaying()){
ivPlay.setImageResource(R.drawable.pausebtn);
}else{
ivPlay.setImageResource(R.drawable.playbtn);
}
if(aItem.isDownloading()){
swtchDownload.setOnCheckedChangeListener(null);
swtchDownload.setChecked(true);
tvDownloadPercent.setText(aItem.getPercent() + "");
}else{
swtchDownload.setOnCheckedChangeListener(null);
swtchDownload.setChecked(false);
tvDownloadPercent.setText("0");
}
// holder.tvDownloadPercent.setText(data.get(position).getPercent()+" %");
tvDownload.setText(aItem.getDwnLbl());
tvTitle.setText(aItem.getTitle());
tvDesc.setText(aItem.getDesc());
Bitmap bmp = BitmapFactory.decodeFile(aItem.getImage());
ivImg.setImageBitmap(bmp);
// Log.e("MAIN", "IS DONE: " + aItem.isOn());
tvReadPdf.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(isPDFSupported(mContext)){
Uri path = Uri.fromFile(new File(aItem.getPdf()));
Intent objIntent = new Intent(Intent.ACTION_VIEW);
objIntent.setDataAndType(path, "application/pdf");
objIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mContext.startActivity(objIntent);
}else{
if(GeneralClass.getConnectivityStatusString(mContext)){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://docs.google.com/gview?embedded=true&url="+aItem.getPdfurl()));
mContext.startActivity(browserIntent);
}else{
GeneralClass.showToast("Check internet connection to view pdf file", mContext);
}
}
}
});
ivPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(aItem.isPlaying()){
aItem.setPlaying(false);
((MainActivity)mContext).stopAudioFile();
}else{
aItem.setPlaying(true);
((MainActivity)mContext).playAudioFile(aItem);
}
}
});
swtchDownload.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
// updateView(position, arg1);
Log.e("Audio ADAPTER", "file: " + arg1);
if(arg1){
aItem.setDownloading(true);
aItem.setDwnLbl("Downloading");
dwnldFileUrl.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, aItem.getAudiourl());
}else if(!arg1){
aItem.setDownloading(false);
aItem.setDwnLbl("Download");
dwnldFileUrl.cancel(true);
}
}
});
ivCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
aItem.setDownloading(false);
aItem.setDwnLbl("Download");
dwnldFileUrl.cancel(true);
// updateView(position, false);
// new DownloadFileFromURL(holder, position).execute(data.get(position).getAudiourl());
}
});
updateTimeRemaining();
}
public void updateTimeRemaining() {
// Log.e("MAIN", "GET TIME: " + aItem.getTimeStamp());
if(aItem.isDownloading()){
llDownload.setVisibility(View.VISIBLE);
tvDownloadPercent.setVisibility(View.VISIBLE);
tvDownloadPercent.setText(aItem.getPercent()+"");
// PBDownload.setProgress(aItem.getPercent());
tvDownload.setText(aItem.getDwnLbl());
}else{
llDownload.setVisibility(View.INVISIBLE);
tvDownloadPercent.setVisibility(View.INVISIBLE);
tvDownloadPercent.setText("0");
// PBDownload.setProgress(0);
tvDownload.setText(aItem.getDwnLbl());
}
// if(aItem.isOn()){
// tvTitle.setText(aItem.getPercent()+"");
// }else{
// tvTitle.setText("0");
// }
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
private volatile boolean running = true;
String finalFilePath="";
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
// URL url = new URL(f_url[0]);
URL url = new URL("http://www.robtowns.com/music/blind_willie.mp3");
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
String outputFile = extStorageDirectory+"/"+GeneralClass.FILE_PATH;
finalFilePath = outputFile+"/audio"+aItem.getId()+".mp3";
OutputStream output = new FileOutputStream(finalFilePath);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1 && running) {
if(isCancelled()){
Log.e("ADAPTER", "Async break");
break;
}
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
#Override
protected void onCancelled() {
running = false;
Log.e("ADAPTER", "Async cancelled");
}
/**
* Updating progress bar
* */
#Override
protected void onProgressUpdate(String... progress) {
// setting progress percentage
aItem.setPercent(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
// dismissDialog(progress_bar_type);
Log.e("ADAPTER", "DONE ID: " + aItem.getId());
((MainActivity)mContext).updateAudioFileDownload(aItem.getId(), finalFilePath);
ivCancel.setVisibility(View.INVISIBLE);
}
}
}
public static boolean isPDFSupported(Context context) {
Intent i = new Intent( Intent.ACTION_VIEW );
final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), "test.pdf" );
i.setDataAndType( Uri.fromFile( tempFile ), PDF_MIME_TYPE );
return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
}
}
Help me with this major issue.
I have Text can someone please tell me how do i convert text to pdf and how do i show it in my android application. i saw there are many libraries which do the same can some one give me the sample code for that. thanks
i have used pdfviewer lib but still didnt get the pdf.
hear is my code -
File images = Environment.getExternalStorageDirectory();
imagelist = images.listFiles(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return ((name.endsWith(".pdf")));
}
});
pdflist = new String[imagelist.length];
for(int i = 0;i<imagelist.length;i++)
{
pdflist[i] = imagelist[i].getName();
}
this.setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, pdflist));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
String path = imagelist[(int)id].getAbsolutePath();
openPdfIntent(path);
}
private void openPdfIntent(String path)
{
try
{
final Intent intent = new Intent(this, Second.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
startActivity(intent);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
add PDFViewer as library in your project, copy its resources in your as guided in Here. This is working code for me. I am reading pdf from assets folder. Do customization as your requirement.
Download pdf reader project from above link.
copy all resources in your project.
extend your activity (in which you want to display pdf) from PdfViewerActivity.
copy all methods from pdfreader project in yourpdfview activity.
Run.
Happy Coding
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "ABC.pdf");
try {
in = assetManager.open("ABC.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
Intent intent = new Intent(this, YourNextActivityName.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, getFilesDir() + "/ABC.pdf");
startActivity(intent);
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
The methods of yourpdfview activity are:
public int getPreviousPageImageResource() { return R.drawable.left_arrow; }
public int getNextPageImageResource() { return R.drawable.right_arrow; }
public int getZoomInImageResource() { return R.drawable.zoom_in; }
public int getZoomOutImageResource() { return R.drawable.zoom_out; }
public int getPdfPasswordLayoutResource() { return R.layout.pdf_file_password; }
public int getPdfPageNumberResource() { return R.layout.dialog_pagenumber; }
public int getPdfPasswordEditField() { return R.id.etPassword; }
public int getPdfPasswordOkButton() { return R.id.btOK; }
public int getPdfPasswordExitButton() { return R.id.btExit; }
public int getPdfPageNumberEditField() { return R.id.pagenum_edit; }
I wrote a code which takes picture from android device and then upload it on server.Can also upload pic from gallery. Uploading from gallery works perfectly.It is able to intent to mobile camera when clicked on capture button but when i return i didn't got any image and when i checked the gallery no image was captured.
Got menifest permission also
android.permission.WRITE_EXTERNAL_STORAGE"
android.permission.READ_EXTERNAL_STORAGE"
android.permission.CAMERA"
This is code in my Fragments onCreateView() class:
mTakePhoto = (Button) rootView.findViewById(R.id.take_photo);
mselectPhoto = (Button) rootView.findViewById(R.id.select_photo);
mImageView = (ImageView) rootView.findViewById(R.id.imageview);
mTakePhoto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,
TAKE_PICTURE);
}
});
mselectPhoto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i,
IMAGE_PICKER_SELECT);
}
});
In the above code i think intents works perfectly
In bellow code, the (requestCode == IMAGE_PICKER_SELECT) condition works perfectly. But it seems like i didn't get any data when i took PICTURE
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == IMAGE_PICKER_SELECT
&& resultCode == Activity.RESULT_OK) {
Bitmap bitmap = getBitmapFromCameraData(data, getActivity());
int nh = (int) (bitmap.getHeight() * (512.0 / bitmap.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 512, nh, true);
mImageView.setImageBitmap(scaled);
new UploadTask().execute(bitmap);
}
if (requestCode == TAKE_PICTURE && resultCode == Activity.RESULT_OK
&& data != null) {
// get bundle
Bundle extras = data.getExtras();
// get bitmap
cameraBitmap = (Bitmap) extras.get("data");
int nh = (int) (cameraBitmap.getHeight() * (512.0 / cameraBitmap
.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(cameraBitmap, 512, nh,
true);
mImageView.setImageBitmap(scaled);
new UploadTask().execute(cameraBitmap);
// setPic();
}
}
I m also giving the Code of my Multipartentity class
public class MultipartEntity implements HttpEntity {
enter code here
private String boundary = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;
public MultipartEntity() {
this.boundary = System.currentTimeMillis() + "";
}
public void writeFirstBoundaryIfNeeds(){
if(!isSetFirst){
try {
out.write(("--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
isSetFirst = true;
}
public void writeLastBoundaryIfNeeds() {
if(isSetLast){
return ;
}
try {
out.write(("\r\n--" + boundary + "--\r\n").getBytes());
} catch (final IOException e) {
}
isSetLast = true;
}
public void addPart(final String key, final String value) {
writeFirstBoundaryIfNeeds();
try {
out.write(("Content-Disposition: form-data; name=\"" +key+"\"\r\n").getBytes());
out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
out.write(value.getBytes());
out.write(("\r\n--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
}
public void addPart(final String key, final String fileName, final InputStream fin){
addPart(key, fileName, fin, "application/octet-stream");
}
public void addPart(final String key, final String fileName, final InputStream fin, String type){
writeFirstBoundaryIfNeeds();
try {
type = "Content-Type: "+type+"\r\n";
out.write(("Content-Disposition: form-data; name=\""+ key+"\"; filename=\"" + fileName + "\"\r\n").getBytes());
out.write(type.getBytes());
out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());
final byte[] tmp = new byte[4096];
int l = 0;
while ((l = fin.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
} catch (final IOException e) {
} finally {
try {
fin.close();
} catch (final IOException e) {
}
}
}
public void addPart(final String key, final File value) {
try {
addPart(key, value.getName(), new FileInputStream(value));
} catch (final FileNotFoundException e) {
}
}
#Override
public long getContentLength() {
writeLastBoundaryIfNeeds();
return out.toByteArray().length;
}
#Override
public Header getContentType() {
return new BasicHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
}
#Override
public boolean isChunked() {
return false;
}
#Override
public boolean isRepeatable() {
return false;
}
#Override
public boolean isStreaming() {
return false;
}
#Override
public void writeTo(final OutputStream outstream) throws IOException {
outstream.write(out.toByteArray());
}
#Override
public Header getContentEncoding() {
return null;
}
#Override
public void consumeContent() throws IOException,
UnsupportedOperationException {
if (isStreaming()) {
throw new UnsupportedOperationException(
"Streaming entity does not implement #consumeContent()");
}
}
#Override
public InputStream getContent() throws IOException,
UnsupportedOperationException {
return new ByteArrayInputStream(out.toByteArray());
}
}
I m stuck for almost the fullday. Help!!
Open your camera with below code and check with it:
private Uri mImageCaptureUri;
mImageCaptureUri = Uri.parse("content://YOUR PACKAGE NAME/");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,mImageCaptureUri);
intent.putExtra("return-data", true);
startActivityForResult(intent,TAKE_PICTURE);
I created a method to call whn button is clicked
mTakePhoto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
takePhoto();
}
});
method to intent and getTempFile() to keel temporary file..
private void takePhoto(){
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(getActivity())) );
startActivityForResult(intent, TAKE_PICTURE);
}
private File getTempFile(Context context){
final File path = new File( Environment.getExternalStorageDirectory(), context.getPackageName() );
if(!path.exists()){
path.mkdir();
}
return new File(path, "image.tmp");
}
this link help me
http://www.tutorialforandroid.com/2010/10/take-picture-in-android-with.html
My application should take pictures in background at a specific time of the day. I am going to use AlarmManager but I am wondering whether the class which implements the behavior of my application (i.e., taking a picture) should extend Service or BroadcastReceiver. What do you think?
You should use IntentSerivce with AlaramManger and define the BroadcastReceiver on your activity.
public class DownloadService extends IntentService {
private int result = Activity.RESULT_CANCELED;
public static final String URL = "urlpath";
public static final String FILENAME = "filename";
public static final String FILEPATH = "filepath";
public static final String RESULT = "result";
public static final String NOTIFICATION = "com.vogella.android.service.receiver";
public DownloadService() {
super("DownloadService");
}
// Will be called asynchronously be Android
#Override
protected void onHandleIntent(Intent intent) {
String urlPath = intent.getStringExtra(URL);
String fileName = intent.getStringExtra(FILENAME);
File output = new File(Environment.getExternalStorageDirectory(),
fileName);
if (output.exists()) {
output.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
stream = url.openConnection().getInputStream();
InputStreamReader reader = new InputStreamReader(stream);
fos = new FileOutputStream(output.getPath());
int next = -1;
while ((next = reader.read()) != -1) {
fos.write(next);
}
// Successful finished
result = Activity.RESULT_OK;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
publishResults(output.getAbsolutePath(), result);
}
private void publishResults(String outputPath, int result) {
Intent intent = new Intent(NOTIFICATION);
intent.putExtra(FILEPATH, outputPath);
intent.putExtra(RESULT, result);
sendBroadcast(intent);
}
}
public class MainActivity extends Activity {
private TextView textView;
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
String string = bundle.getString(DownloadService.FILEPATH);
int resultCode = bundle.getInt(DownloadService.RESULT);
if (resultCode == RESULT_OK) {
Toast.makeText(MainActivity.this,
"Download complete. Download URI: " + string,
Toast.LENGTH_LONG).show();
textView.setText("Download done");
} else {
Toast.makeText(MainActivity.this, "Download failed",
Toast.LENGTH_LONG).show();
textView.setText("Download failed");
}
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.status);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, new IntentFilter(DownloadService.NOTIFICATION));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
public void onClick(View view) {
Intent intent = new Intent(this, DownloadService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
// Start every 30 seconds
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);
}
}