Saving path of pdf file in internal storage into Sqlite - android

I am new to android and i am making an application which is take information from visitor's and make a pdf from it and save it internal storage,it also have the option for printing the information via printers connected through wifi
Here is my main java file Visitor_pass -
package com.example.sayedshazeb.practical1;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.nfc.Tag;
import android.print.PrintManager;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.os.CancellationSignal;
import android.os.ParcelFileDescriptor;
import android.print.PageRange;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.content.Context;
import android.print.PrintDocumentInfo;
import android.print.pdf.PrintedPdfDocument;
import android.graphics.pdf.PdfDocument;
import android.widget.TextView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
public class Visitor_pass extends ActionBarActivity implements ImageAndTextContainer {
ImageView iv;
public Context c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visitor_pass);
iv = (ImageView) findViewById(R.id.image);
Button cbtn = (Button)findViewById(R.id.captureimage);
cbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,0);
}
});
Button pbtn = (Button) findViewById(R.id.print);
pbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
printDocument(v);
}
});
Button s =(Button)findViewById(R.id.Dbsave);
s.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bm = (Bitmap) data.getExtras().get("data");
iv.setImageBitmap(bm);
}
#TargetApi(Build.VERSION_CODES.KITKAT)
public void printDocument(View view)
{
// Get a PrintManager instance
PrintManager printManager = (PrintManager) this.getSystemService(Context.PRINT_SERVICE);
// Give the job a name.
String jobName = this.getString(R.string.app_name) +
" Document";
// Start a print job, passing a printDocumentAdapter as
//argument to handle the generation of a print document
MyPrintDocumentAdapter printDoc = new MyPrintDocumentAdapter(this);
printManager.print(jobName, printDoc, null);
}
#Override
public Bitmap getImage() {
ImageView imageView = (ImageView) findViewById(R.id.image);
Bitmap image = null;
// Get the image
if ((imageView.getDrawable()) != null) {
// Send it to the print helper
image = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
}
return image;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
public class MyPrintDocumentAdapter extends PrintDocumentAdapter
{
private ImageAndTextContainer imageAndTextContainer;
Context context;
private int pageHeight;
private int pageWidth;
public PdfDocument myPdfDocument;
public int totalpages = 1;
String pts;
String ats;
String cts;
public MyPrintDocumentAdapter(ImageAndTextContainer container) {
this.context =context;
this.imageAndTextContainer = container;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras) {
myPdfDocument = new PrintedPdfDocument(context, newAttributes);
pageHeight =
newAttributes.getMediaSize().getHeightMils()/1000 * 72;
pageWidth =
newAttributes.getMediaSize().getWidthMils()/1000 * 72;
if (cancellationSignal.isCanceled() ) {
callback.onLayoutCancelled();
return;
}
if (totalpages > 0) {
PrintDocumentInfo.Builder builder = new PrintDocumentInfo
.Builder("print_output.pdf")
.setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
.setPageCount(totalpages);
PrintDocumentInfo info = builder.build();
callback.onLayoutFinished(info, true);
} else {
callback.onLayoutFailed("Page count is zero.");
}
}
#Override
public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback) {
for (int i = 0; i < totalpages; i++) {
if (pageInRange(pages, i))
{
PdfDocument.PageInfo newPage = new PdfDocument.PageInfo.Builder(pageWidth,
pageHeight, i).create();
PdfDocument.Page page =
myPdfDocument.startPage(newPage);
if (cancellationSignal.isCanceled()) {
callback.onWriteCancelled();
myPdfDocument.close();
myPdfDocument = null;
return;
}
drawPage(page, i);
myPdfDocument.finishPage(page);
}
}
try {
myPdfDocument.writeTo(new FileOutputStream(
destination.getFileDescriptor()));
} catch (IOException e) {
callback.onWriteFailed(e.toString());
return;
} finally {
myPdfDocument.close();
myPdfDocument = null;
}
callback.onWriteFinished(pages);
}
private boolean pageInRange(PageRange[] pageRanges, int page)
{
for (int i = 0; i<pageRanges.length; i++)
{
if ((page >= pageRanges[i].getStart()) &&
(page <= pageRanges[i].getEnd()))
return true;
}
return false;
}
private void drawPage(PdfDocument.Page page,
int pagenumber) {
Canvas canvas = page.getCanvas();
pagenumber++; // Make sure page numbers start at 1
int titleBaseLine = 72;
int leftMargin = 54;
EditText pt = (EditText)findViewById(R.id.textname);
EditText ct = (EditText)findViewById(R.id.textphone);
pts = pt.getText().toString();
EditText at = (EditText)findViewById(R.id.textaddress);
ats = at.getText().toString();
cts = ct.getText().toString();
DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker);
int day = datePicker.getDayOfMonth();
String d = ""+day;
int month = datePicker.getMonth() + 1;
String m = ""+month;
int year = datePicker.getYear();
String y=""+year;
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(40);
canvas.drawText("Visitor Details " + pagenumber, leftMargin, titleBaseLine, paint);
paint.setTextSize(25);
canvas.drawText("Name :", leftMargin, titleBaseLine + 400, paint);
canvas.drawText(pts ,leftMargin + 110,titleBaseLine + 400,paint);
canvas.drawText("Address :",leftMargin,titleBaseLine + 450,paint);
canvas.drawText(ats ,leftMargin + 110,titleBaseLine + 450,paint);
canvas.drawText("Number :",leftMargin,titleBaseLine + 500,paint);
canvas.drawText(cts ,leftMargin + 110,titleBaseLine + 500,paint);
canvas.drawText("Date :" ,leftMargin,titleBaseLine + 550,paint);
canvas.drawText( d + "/" +m+"/"+y ,leftMargin+110,titleBaseLine + 550,paint);
Rect imageRect = new Rect(100, 100, canvas.getWidth() - 240, canvas.getHeight() / 2 - 10);
drawImage(imageAndTextContainer.getImage(), canvas, imageRect);
}
private void drawImage(Bitmap image, Canvas canvas, Rect r) {
canvas.drawBitmap(image, null, r, new Paint());
}
}
}
And Here is my main Xml file-
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".Visitor_pass"
android:orientation="vertical"
android:weightSum="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Visitor&apos;s Pass"
android:id="#+id/visitorpass"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center"
android:textSize="20dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/textname"
android:layout_gravity="center"
android:layout_marginTop="15dp"
android:hint="Enter visitor&apos;s name"
android:focusableInTouchMode="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPostalAddress"
android:ems="10"
android:id="#+id/textaddress"
android:layout_gravity="center"
android:layout_marginTop="15dp"
android:hint="Enter Address"
android:focusableInTouchMode="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="phone"
android:ems="10"
android:id="#+id/textphone"
android:layout_gravity="center"
android:layout_marginTop="15dp"
android:focusableInTouchMode="true"
android:hint="Enter Number" />
<DatePicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/datePicker"
android:layout_gravity="center_horizontal"
android:calendarViewShown="false"
android:datePickerMode="spinner" />
<ImageView
android:layout_width="200dp"
android:layout_height="150dp"
android:id="#+id/image"
android:layout_gravity="center"
android:layout_marginTop="10dp" />
<Button
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="Capture Image"
android:id="#+id/captureimage"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="Save "
android:id="#+id/Dbsave"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="Print"
android:id="#+id/print"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="Discard"
android:id="#+id/button"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</ScrollView>
Here is the print_dialog xml -
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<WebView android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</RelativeLayout>
Now i want to save the path of a pdf file created and saved in internal storage to be saved in my sqlite database. I know how to store values into database i just wanna know how to get the path of a file stored in my internal storage??

"i just wanna know how to get the path of a file stored in my internal storage??"
Have you tried getFilesDir()? Example.
String path = this.getFilesDir().toString()+"/"+nameOfFile;

You can use the Environment.getExternalStorageDirectory()
This method returns the primary external storage directory.
For example, if you have a folder called /pdf, so the path of your file will be:
Environment.getExternalStorageDirectory() + "/pdf/" + <pd_file_name>
Note: don't be confused by the word "external" here. This directory can better be thought as media/shared storage. It is a filesystem that can hold a relatively large amount of data and that is shared across all applications (does not enforce permissions). Traditionally this is an SD card, but it may also be implemented as built-in storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer.
More info here

Related

Data doesn't show in recyclerView, need to go back to show it

I want to create an activity to search for users by full name. I created everything I needed and it worked properly, except for one thing. When I press search button the result are not show in recyclerview. I need to go back and the the results are shown. I need to do these 2 steps to see the results.
Yes the search bar and view holder are overlap, I will try to fixed later. Do you know how to make it so that once searched the results are displayed immediately without having to go back
This is my layout for view holder
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="75dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:id="#+id/parent_layout"
android:background="#drawable/recycler_view_border">
<com.mikhaellopez.circularimageview.CircularImageView
android:id="#+id/imageProfile"
android:layout_width="60dp"
android:layout_height="60dp"
android:tint="#808080"
android:layout_marginStart="10dp"
android:layout_marginTop="7dp"
app:civ_border_color="#color/dark_blue"
app:civ_border_width="2dp"
app:srcCompat="#drawable/defaultimage"/>
<TextView
android:id="#+id/userFullName"
android:layout_toEndOf="#+id/imageProfile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:layout_marginEnd="20dp"
android:layout_marginStart="10dp"
android:gravity="center"
android:text="#string/fullname"
android:textSize="16sp"
android:textColor="#color/black"/>
<com.google.android.material.button.MaterialButton
android:id="#+id/buttonAdd"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginTop="13dp"
android:layout_marginEnd="10dp"
android:layout_marginStart="340dp"
android:background="#drawable/btn_background"
app:cornerRadius="8dp"
android:drawableTop="#drawable/ic_action_add" />
</RelativeLayout>
This is my layout for activity
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SendFriendRequests">
<LinearLayout
android:id="#+id/linearlayout"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_marginLeft="13dp"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<EditText
android:id="#+id/searchUsername"
android:layout_width="318dp"
android:layout_height="45dp"
android:layout_marginTop="20dp"
android:background="#drawable/edt_background"
android:hint="#string/searchFriends"
android:imeOptions="actionNext"
android:importantForAutofill="no"
android:inputType="text"
android:paddingStart="16dp"
android:paddingEnd="16dp" />
<com.google.android.material.button.MaterialButton
android:id="#+id/buttonSearch"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginStart="333dp"
android:layout_marginTop="-47dp"
android:layout_marginEnd="10dp"
android:background="#drawable/btn_background"
android:drawableTop="#drawable/ic_action_search"
app:cornerRadius="8dp" />
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="580dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearlayout"
app:layout_constraintVertical_bias="0.99"
tools:layout_editor_absoluteX="-16dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is my adapter
package com.example.chatappjava;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.mikhaellopez.circularimageview.CircularImageView;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
public class SendFriendRequestAdapter extends RecyclerView.Adapter<SendFriendRequestAdapter.ViewHolder> {
private static final String TAG = "ContactsAdapter";
private ArrayList<UserData> arrayListUserData = new ArrayList<>();
private Context context;
public SendFriendRequestAdapter(ArrayList<UserData> arrayListUserData, Context context) {
this.arrayListUserData = arrayListUserData;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_send_friend_request_item, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(ViewHolder holder, #SuppressLint("RecyclerView") int position) {
Log.d(TAG, "onBindViewHolder: called.");
Glide.with(context)
.asBitmap()
.load(arrayListUserData.get(position).image)
.into(holder.userProfileImage);
holder.userFullName.setText(arrayListUserData.get(position).name);
holder.buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Connection conn = DatabaseConnection.createDatabaseConnection();
PreparedStatement st1 = conn.prepareStatement(
" insert into FRIEND_REQUESTS values (?,?,?)");
st1.setString(1, arrayListUserData.get(position).friendId);
st1.setString(2, arrayListUserData.get(position).userId);
st1.setInt(3, 0);
st1.execute();
showToast("Friend request is sended");
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("IdAccount", arrayListUserData.get(position).userId);
context.startActivity(intent);
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
});
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context.getApplicationContext(), specificchat.class);
intent.putExtra("userId", arrayListUserData.get(position).userId);
intent.putExtra("friendId", arrayListUserData.get(position).friendId);
intent.putExtra("friendName", arrayListUserData.get(position).name);
intent.putExtra("friendImage", arrayListUserData.get(position).image);
context.startActivity(intent);
}
});
}
private void showToast(String message) {
Toast.makeText(context.getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
#Override
public int getItemCount() {
return arrayListUserData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircularImageView userProfileImage;
TextView userFullName;
RelativeLayout parentLayout;
Button buttonAdd;
public ViewHolder(View itemView) {
super(itemView);
userProfileImage = itemView.findViewById(R.id.imageProfile);
userFullName = itemView.findViewById(R.id.userFullName);
parentLayout = itemView.findViewById(R.id.parent_layout);
buttonAdd = itemView.findViewById(R.id.buttonAdd);
}
}
}
And this is my java class which use the adapter
package com.example.chatappjava;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class SendFriendRequests extends AppCompatActivity {
private ArrayList<UserData> arrayListUserData = new ArrayList<>();
private Button searchButton;
private EditText searchUsername;
private String userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
userId = intent.getStringExtra("IdAccount");
setContentView(R.layout.activity_send_friend_request);
searchButton = findViewById(R.id.buttonSearch);
searchUsername = findViewById(R.id.searchUsername);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Connection conn = DatabaseConnection.createDatabaseConnection();
Statement statement = conn.createStatement();
ResultSet resultat = statement.executeQuery("select ID, FULLNAME, IMAGE from USERS where ID not in (select FRIEND_ID from FRIENDSLIST where USER_ID = " + userId + ") and FULLNAME like '%" + searchUsername.getText().toString() + "%' and ID not in (select RECEIVER_ID from FRIEND_REQUESTS where SENDER_ID = " + userId + ")");
while (resultat.next()) {
arrayListUserData.add(new UserData(resultat.getString("FULLNAME"), resultat.getString("IMAGE"), resultat.getString("ID"), userId));
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
initRecycleView();
}
});
}
private void initRecycleView() {
RecyclerView recyclerView = findViewById(R.id.recyclerView);
SendFriendRequestAdapter adapter = new SendFriendRequestAdapter(arrayListUserData, this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
}
I think it's the RecyclerView in your XML that needs to be adjusted at android:layout_height = "0dp"
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearlayout"/>

How to retrieve data from the firebase and show inside the CardView nicely

I have created the CreateEvent.java module to upload the data to firebase. But how to retrieve the data and show in the Cardlist? For example show in the xml file below. And also if there was more than 1 data in firebase, how to show in with multiple cardlist that I have created in the xml file?
CreateEvent.java
package com.example.edward.eventmanagementsystem.ManageEvent;
import android.Manifest;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.edward.eventmanagementsystem.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import static android.widget.Toast.LENGTH_SHORT;
public class CreateEvent extends Activity {
private static final String TAG = "activity_create_event";
private Uri filePath;
private TextView mDisplayDate;
private DatePickerDialog.OnDateSetListener mDateSetListener;
private DatabaseReference mDatabaseReference;
private Button mRegisterButton;
EditText mEventNameText, mContactNumText, mEventLocationText;
TextView mEventDate;
RadioGroup mEventType;
FirebaseStorage storage;
StorageReference storageRef,imageRef;
ProgressDialog progressDialog;
UploadTask uploadTask;
Uri uriImage = Uri.parse("com.example.edward.eventmanagementsystem.ManageEvent/"+ R.drawable.ic_launcher_background);
public static final int PICK_IMAGE = 1;
ImageView mimageToUpload;
#Override
protected void onCreate(Bundle savedInstanceState) {
FirebaseDatabase firebaseDatabase;
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("ListEventInformation").push();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_event);
mRegisterButton = (Button)findViewById(R.id.btnRegisterEvent);
storage = FirebaseStorage.getInstance();
storageRef = storage.getReference();
mDisplayDate = (TextView) findViewById(R.id.RegisterEventStartDate);
mDisplayDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(
CreateEvent.this,
android.R.style.Theme_Holo_Light_Dialog_MinWidth,
mDateSetListener,
year, month, day);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
month = month + 1;
Log.d(TAG, "onDateSet: date: mm/dd/yyyy: " + month + "/" + day + "/" + year);
String date = month + "/" + day + "/" + year;
mDisplayDate.setText(date);
}
};
//perform action upload image
mimageToUpload = (ImageView) findViewById(R.id.imageToUpload);
//insert data to database
mEventNameText = (EditText) findViewById(R.id.RegisterEventName);
mContactNumText = (EditText) findViewById(R.id.RegisterContactNumber);
mEventDate = (TextView) findViewById(R.id.RegisterEventStartDate);
mEventType = (RadioGroup) findViewById(R.id.RegisterEventRadiogroup);
mEventLocationText = (EditText) findViewById(R.id.RegisterEventLocation);
mimageToUpload = (ImageView) findViewById(R.id.imageToUpload);
mRegisterButton = (Button) findViewById(R.id.btnRegisterEvent);
mimageToUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(CreateEvent.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
selectPdf();
}
else {
ActivityCompat.requestPermissions(CreateEvent.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},9);
}
}
});
mRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int selectedId = mEventType.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton)findViewById(selectedId);
final String name = mEventNameText.getText().toString().trim();
final String contact = mContactNumText.getText().toString().trim();
final String date = mEventDate.getText().toString().trim();
final String type = radioButton.getText().toString().trim();
final String location = mEventLocationText.getText().toString().trim();
if (TextUtils.isEmpty(name)) {
mEventNameText.setError("Enter First Name!");
return;
}
if (TextUtils.isEmpty(date)) {
mEventDate.setError("Enter Date!");
return;
}
if (TextUtils.isEmpty(type)) {
radioButton.setError("Enter Phone Number!");
return;
}
if(isValidPhone(contact)){
Toast.makeText(getApplicationContext(),"Phone number is valid",Toast.LENGTH_SHORT).show();
}else {
mContactNumText.setError("Phone number is not valid");
Toast.makeText(getApplicationContext(),"Phone number is not valid",Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(location)) {
mEventLocationText.setError("Enter Location!");
return;
}
Map userInfo = new HashMap();
userInfo.put("mEventNameText", name);
userInfo.put("mContactNumText", contact);
userInfo.put("mEventDate", date);
userInfo.put("radioButton", type);
userInfo.put("mEventLocationText", location);
mDatabaseReference.updateChildren(userInfo);
final String fileName = System.currentTimeMillis()+"";
if(uriImage != null) {
StorageReference storageReference = storage.getReference();
storageReference.child("profileImageUrl").child(fileName).putFile(uriImage)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String url = taskSnapshot.getMetadata().getReference().getDownloadUrl().toString();
mDatabaseReference.child("profileImageUrl").setValue(url).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){ }
else{
Toast.makeText(getApplicationContext(),"File not Successfully Uploaded",LENGTH_SHORT).show(); }
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(),"File not Successfully Uploaded",LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
}
});
}else{
}
Toast.makeText(getApplicationContext(),"New event created successfully!",LENGTH_SHORT).show();
Intent ManageEventMenu = new Intent(CreateEvent.this, com.example.edward.eventmanagementsystem.ManageEvent.ManageEventMenu.class);
startActivity(ManageEventMenu);
}
});
}
public boolean isValidPhone(CharSequence phone) {
boolean check=false;
if(!Pattern.matches("[a-zA-Z]+", phone))
{
if(phone.length() < 10 || phone.length() > 11)
{
check = false;
}
else
{
check = true;
}
}
else
{
check=false;
}
return check;
}
private void selectPdf() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
startActivityForResult(intent,86);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 86 && resultCode == RESULT_OK && data != null){
final Uri imageUri = data.getData();
uriImage = imageUri;
mimageToUpload.setImageURI(uriImage);
}
else {
Toast.makeText(getApplicationContext(),"Please select file", LENGTH_SHORT).show();
}
}
}
I would like to show the data in this way.
The sample of xml file I would like to display the data create from Firebase in upload from CreateEvent.java
activity_list_of_event.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/gradientwallpaper">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Events"
android:layout_marginLeft="10dp"
android:textStyle="bold"
android:layout_marginTop="20dp"
android:textSize="24dp"
android:textColor="#color/white"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Total Created Event"
android:layout_marginLeft="10dp"
android:textSize="16dp"
android:textColor="#color/white"
android:layout_marginTop="10dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="10dp"
android:layout_marginBottom="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Upcoming"
android:layout_marginLeft="10dp"
android:textSize="16dp"
android:textColor="#color/white"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Pass"
android:gravity="right"
android:layout_marginRight="10dp"
android:textSize="16dp"
android:textColor="#color/white"/>
</LinearLayout>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:padding="10dp"
android:weightSum="10">
<LinearLayout
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="4"
android:orientation="vertical">
<TextView
android:id="#+id/item_month"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Month" />/ android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
<TextView
android:id="#+id/item_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Date" />/ android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:orientation="vertical">
<TextView
android:id="#+id/item_eventName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Event Name"
android:textStyle="bold" />/android:textScaleX="18sp"
<TextView
android:id="#+id/item_contactNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Contact Number"
android:textStyle="bold" />
<TextView
android:id="#+id/item_type"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Type of event"
android:textStyle="bold" />
<TextView
android:id="#+id/itemLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Location"
android:textStyle="bold" />
</LinearLayout>
<ImageView
android:id="#+id/item_image"
android:layout_width="75dp"
android:layout_height="75dp"
android:background="#color/white"
android:scaleType="centerCrop"
android:src="#drawable/pic1" />
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>

The PDF renderer class is not rendering a PDF on Android SDK 21

Here's the code I'm using to render a PDF called "answerkey.pdf" that's stored in "Download/Adobe Reader/answerkey.pdf"
package com.practice.pdftest;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.pdf.PdfRenderer;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
public class MainActivity extends Activity {
private ImageView imageView;
private Button next, previous;
private TextView tv;
private int currentPage = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
next = (Button)findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentPage++;
render();
}
});
previous = (Button)findViewById(R.id.previous);
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentPage--;
render();
}
});
// tv = (TextView)findViewById(R.id.testText);
// tv.setText(Environment.getExternalStorageDirectory().getAbsolutePath());
//
// Toast toast = Toast.makeText(getApplicationContext(),Environment.getExternalStorageDirectory().getAbsolutePath(),Toast.LENGTH_LONG);
// toast.show();
}
private void render() {
try {
imageView = (ImageView)findViewById(R.id.imageView);
int REQ_WIDTH = 1;
int REQ_HEIGHT = 1;
REQ_WIDTH = imageView.getWidth();
REQ_HEIGHT = imageView.getHeight();
Bitmap bitmap = Bitmap.createBitmap(REQ_WIDTH, REQ_HEIGHT, Bitmap.Config.ARGB_4444);
File file = new File(Environment.getDataDirectory().getPath()+"Adobe Reader/answerkey.pdf");
PdfRenderer pdfRenderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));
if(currentPage < 0) {
currentPage=0;
}
else if (currentPage > pdfRenderer.getPageCount()) {
currentPage = pdfRenderer.getPageCount()-1;
}
Matrix matrix = imageView.getImageMatrix();
Rect rect = new Rect(0,0,REQ_HEIGHT,REQ_WIDTH);
pdfRenderer.openPage(currentPage).render(bitmap,rect,matrix,PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
imageView.setImageMatrix(matrix);
imageView.setImageBitmap(bitmap);
imageView.invalidate();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here's the layout.xml file I've made -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.practice.pdftest.MainActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/imageView"
android:layout_weight="4"
android:background="#android:color/white"
android:layout_marginBottom="20dp"
/>
<!--<TextView-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:id="#+id/testText"-->
<!--android:text="Test"-->
<!--/>-->
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_weight="2"
android:gravity="center"
android:layout_height="wrap_content"
android:layout_marginTop="-100dp">
<Button
android:id="#+id/previous"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Previous"
/>
<Button
android:id="#+id/next"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Next" />
</LinearLayout>
</LinearLayout>
For some reason, the PDF just isn't being displayed on screen, I keep getting a white, blank background. What am I doing wrong? Is the path incorrect? I have no SD card on my device. Or am I doing something wrong with the bitmap?
Is the path incorrect?
Yes.
I have no SD card on my device
That is fine. That would be removable storage. I am interpreting "Download/Adobe Reader/answerkey.pdf" as referring to something on external storage.
The recommended way to get this location would be to replace:
File file = new File(Environment.getDataDirectory().getPath()+"Adobe Reader/answerkey.pdf");
with:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "Adobe Reader/answerkey.pdf");
Note that your app will need to request the READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE permission, and that will involve runtime permissions on Android 6.0+ (if your targetSdkVersion is 23 or higher).

Share text and image with android intent

That is my code java
intent.putExtra(Intent.EXTRA_SUBJECT, "My App name and some text");
intent.putExtra(Intent.EXTRA_TEXT, "a link");
intent.putExtra(Intent.EXTRA_STREAM,getImageUri(context,mBitmap));
intent.setType("image/*,text/plain");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
I want to share image and text. This code works on WhatsApp, Twitter, Gmail , etc .. but it does not work on Facebook
thank you in advance for your help
If you want to share the Image and text on Facebook without using Facebook SDK then you have to create the bitmap of your image plus text and then you can share that bitmap on facebook.
Download the source code from here (Share image and text on facebook using intent in android)
activity_main.xml
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
xmlns:android="http://schemas.android.com/apk/res/android">
<EditText
android:id="#+id/et_text"
android:layout_width="match_parent"
android:textSize="15dp"
android:layout_height="45dp"
android:layout_marginTop="10dp"
android:background="#drawable/edittext_drawable"
android:hint="Enter your text"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:paddingRight="10dp"
android:inputType="text"
android:imeOptions="actionDone"
android:paddingLeft="10dp"
android:singleLine="true"
android:textColorHint="#979797" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rl_main"
android:background="#ffffff"
android:layout_below="#+id/et_text"
android:layout_above="#+id/tv_share">
<ImageView
android:layout_width="match_parent"
android:layout_height="250dp"
android:src="#drawable/index"
android:scaleType="fitXY"
android:id="#+id/iv_image"
android:layout_marginTop="10dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
android:id="#+id/tv_text"
android:layout_below="#+id/iv_image"
android:layout_margin="10dp"
android:textColor="#000000"
android:maxLines="5"
/>
</RelativeLayout>
<TextView
android:id="#+id/tv_share"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#F38D0A"
android:gravity="center"
android:padding="10dp"
android:layout_margin="10dp"
android:text="Share"
android:textColor="#ffffff"
android:textSize="15dp"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
MainActivity.java
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText et_text;
ImageView iv_image;
TextView tv_share,tv_text;
RelativeLayout rl_main;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init(){
et_text = (EditText)findViewById(R.id.et_text);
iv_image = (ImageView)findViewById(R.id.iv_image);
tv_share = (TextView)findViewById(R.id.tv_share);
rl_main = (RelativeLayout)findViewById(R.id.rl_main);
tv_text= (TextView) findViewById(R.id.tv_text);
File dir = new File("/sdcard/Testing/");
try {
if (dir.mkdir()) {
System.out.println("Directory created");
} else {
System.out.println("Directory is not created");
}
} catch (Exception e) {
e.printStackTrace();
}
tv_share.setOnClickListener(this);
et_text.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
tv_text.setText(et_text.getText().toString());
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.tv_share:
Bitmap bitmap1 = loadBitmapFromView(rl_main, rl_main.getWidth(), rl_main.getHeight());
saveBitmap(bitmap1);
String str_screenshot = "/sdcard/Testing/"+"testing" + ".jpg";
fn_share(str_screenshot);
break;
}
}
public void saveBitmap(Bitmap bitmap) {
File imagePath = new File("/sdcard/Testing/"+"testing" + ".jpg");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
Log.e("ImageSave", "Saveimage");
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
public static Bitmap loadBitmapFromView(View v, int width, int height) {
Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b;
}
public void fn_share(String path) {
File file = new File("/mnt/" + path);
Bitmap bmp = BitmapFactory.decodeFile(file.getAbsolutePath());
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Share Image"));
}
}
Thanks!
You can share int value of an image as R.drawable.image and get it with getResources.getDrawable(int)

zxing fragment not working

I am trying to customize SimpleStretchedActivity in zxingfragmentlib-master project.
Here is activity_stretchd_sample.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:name="com.welcu.android.zxingfragmentlibsample.SampleFragment"
android:id="#+id/scanner_fragment"
android:layout_gravity="center"
tools:layout="#layout/capture"
android:layout_alignParentLeft="true"
android:layout_marginLeft="0dp"
android:layout_alignParentTop="true"
android:layout_marginTop="0dp"
/>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="350dp"
android:id="#+id/layout_content"
android:background="#FFF"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Fragment"
android:id="#+id/textView"
android:textColor="#000"/>
</LinearLayout>
</LinearLayout>
Here is SampleStretchedActivity.java:
package com.welcu.android.zxingfragmentlibsample;
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.welcu.android.zxingfragmentlib.BarCodeScannerFragment;
/**
* Created by joyarzun on 4/8/14.
*/
public class SampleStretchedActivity extends Activity {
boolean torchState = false;
Button mToggleButton;
LinearLayout layoutContent;
BarCodeScannerFragment mScannerFragment;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.welcu.android.zxingfragmentlibsample.R.layout.activity_stretched_sample);
FragmentManager fm = getFragmentManager();
mScannerFragment = (BarCodeScannerFragment) fm.findFragmentById(R.id.scanner_fragment);
layoutContent = (LinearLayout) findViewById(R.id.layout_content);
final ViewTreeObserver observer = layoutContent.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
// We're assuming that the other layout is under the scanner
int activityWidth = layoutContent.getWidth();
int activityHeight = findViewById(R.id.scanner_fragment).getHeight();
int usableWidth = layoutContent.getWidth();
int usableHeight = activityHeight - layoutContent.getHeight();
int desiredHeight = (int) (usableHeight * 0.8);
int desiredWidth = (int) (usableWidth * 0.75);
Rect framingRect = new Rect(
(usableWidth - desiredWidth) / 2, // left
(usableHeight - desiredHeight) / 2, // top
(usableWidth - desiredWidth) / 2 + desiredWidth, // right
(usableHeight - desiredHeight) / 2 + desiredHeight// bottom
);
Log.v("RECT", "left: " + framingRect.left + " top: " + framingRect.top + " right: " + framingRect.right + " bottom: " + framingRect.bottom + " activityHeight: " + activityHeight + " activitiWidth: " + activityWidth);
mScannerFragment.setFramingRect(framingRect);
}
});
// mToggleButton = (Button) findViewById(R.id.button_flash);
// mToggleButton.setOnClickListener(createToggleFlashListener());
}
private View.OnClickListener createToggleFlashListener() {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
torchState = !torchState;
mScannerFragment.setTorch(torchState);
}
};
}
}
Here is SimpleFragment.java:
package com.welcu.android.zxingfragmentlibsample;
import android.os.Bundle;
import android.widget.Toast;
import com.google.zxing.Result;
import com.welcu.android.zxingfragmentlib.BarCodeScannerFragment;
/**
* Created by mito on 9/17/13.
*/
public class SampleFragment extends BarCodeScannerFragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setmCallBack(new IResultCallback() {
#Override
public void result(Result lastResult) {
Toast.makeText(getActivity(), "Scan: " + lastResult.toString(), Toast.LENGTH_SHORT).show();
}
});
}
public SampleFragment() {
}
}
My only change is that I've changed layout_height in inner LinearLayout from 227dp to 350dp. The original code works fine but with this little change my fragment cannot scan any barcode and toast it.
What's the problem? I really need your help
Thanks

Categories

Resources