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
Related
Please I would need your help to figure out, why these code lines doesn't add an imageView on my playSpace (FrameLayout) when I run it. I just get the playSpace layout without images. What I'm doing wrong ?
//java code
package com.code123.en.createObj;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import java.util.Date;
import java.util.Random;
public class MainActivity extends Activity implements View.OnClickListener {
private ViewGroup playSpace;
private float scale;
private Random randomNumber = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playSpace= (ViewGroup)findViewById(R.id.playSpace);
}
private void showAFly()
{
scale = getResources().getDisplayMetrics().density;
int width= playSpace.getWidth();
int height = playSpace.getHeight();
int fly_width = Math.round(scale*50);
int fly_height = Math.round(scale*42);
int left= randomNumber.nextInt(width- fly_width);
int top= randomNumber.nextInt(height- fly_height);
ImageView fly = new ImageView(this);
fly.setImageResource(R.drawable.fly);
fly.setOnClickListener(this);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(fly_width,fly_height);
params.leftMargin = left;
params.topMargin = top;
params.gravity = Gravity.TOP + Gravity.LEFT;
playSpace.addView(fly,params);
}
#Override
public void onClick(View v) {
doSomething();
}
//activity_main.xml code lines
//It works fine manually
<?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"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/playSpace"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimaryDark">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/fly" />
</FrameLayout>
</LinearLayout>
You need to set the layout parameters for the ImageView before adding the view to the Viewgroup.
fly.setLayoutParams(params);
Where are you calling showAFly()?
Try calling it after
playSpace= (ViewGroup)findViewById(R.id.playSpace);
So, I tried putting a recyclerView in a "popup" dialog using a firebaseRecyclerAdapter.
My problem is, that I know for sure the adapter gets filled because I was using the Logcat to tell me when it adds another "user" to the adapter, but it wont show anything in the recyclerview in the dialog.
I'm having this problem for a couple of days and couldn't find an answer yet, glad if you could help me :)
I'm using a main screen which changes fragments, and from a certain fragment I'm calling this specific dialog.
These are my files:
UserViewHolder - the class which holds the "sets" for the cardview:
public static class UserViewHolder extends RecyclerView.ViewHolder
{
View mView;
public UserViewHolder(View itemView)
{
super(itemView);
mView=itemView;
}
public void setName(String name)
{
TextView teacherName=(TextView) mView.findViewById(R.id.txtNameTea);
teacherName.setText(name);
}
public void setEmail(String email)
{
TextView txtEmailTea=(TextView) mView.findViewById(R.id.txtEmailTea);
txtEmailTea.setText(email);
}
public void setImage(final Context ctx, Uri imageUri, User cUser)
{
final ImageView imgProfileTea=(ImageView) mView.findViewById(R.id.imgProfileTea);
Picasso.with(ctx).load(cUser.getImageUri()).into(imgProfileTea);
if(imgProfileTea.getDrawable()==null) {
StorageReference load = FirebaseStorage.getInstance().getReference().child("usersProfilePic/" + cUser.getImageName());
load.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.with(ctx).load(uri.toString()).into(imgProfileTea);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_LONG);
}
});
}
}
}
Schedules - the fragment which calls the dialog from its toolbar:
package com.example.android.aln4;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.github.sundeepk.compactcalendarview.CompactCalendarView;
import com.github.sundeepk.compactcalendarview.domain.Event;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import static com.example.android.aln4.LoginActivity.myUser;
import static com.example.android.aln4.dataBase.mDatabaseReference;
import static com.example.android.aln4.dataBase.mFirebaseDatabase;
import static com.example.android.aln4.dataBase.mStorageRef;
import static com.example.android.aln4.navDrawerMain.firebaseRecyclerAdapter;
import static java.lang.System.in;
import static com.example.android.aln4.navDrawerMain.studentsQuery;
public class Schedules extends Fragment {
private Toolbar ScheduleToolbar;
private Button addEvent;
//private TextView txt;
private RecyclerView mRecyclerViewStudentEvent;
private CompactCalendarView compactCalendar;
private SimpleDateFormat dateFormatMonth = new SimpleDateFormat("MMMM-yyyy", Locale.getDefault());
private String[] monthName = {"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"};
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addEvent:
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(getContext());
View mView = getLayoutInflater().inflate(R.layout.dialog_event_creation, null);
mRecyclerViewStudentEvent = (RecyclerView) mView.findViewById(R.id.mRecyclerViewStudentEvent);
mRecyclerViewStudentEvent.setHasFixedSize(true);
mRecyclerViewStudentEvent.setLayoutManager(new LinearLayoutManager(getContext()));
setStudentsList();
mView = getLayoutInflater().inflate(R.layout.dialog_event_creation, null);
final EditText edtEventTitle = (EditText) mView.findViewById(R.id.edtEventTitle);
final TextView txtEventStartTime = (TextView) mView.findViewById(R.id.txtEventStartTime);
final TextView txtEventEndTime = (TextView) mView.findViewById(R.id.txtEventEndTime);
final EditText edtEventLocation = (EditText) mView.findViewById(R.id.edtEventLocation);
Button btnOfferEvent = (Button) mView.findViewById(R.id.btnOfferEvent);
mBuilder.setView(mView);
final AlertDialog dialog = mBuilder.create();
btnOfferEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar startTime = Calendar.getInstance();
Calendar endTime = Calendar.getInstance();
int startHour = Integer.parseInt(txtEventStartTime.getText().toString().substring(0, 2));
int startMinute = Integer.parseInt(txtEventStartTime.getText().toString().substring(3, 5));
startTime.set(Calendar.HOUR_OF_DAY, startHour);
startTime.set(Calendar.MINUTE, startMinute);
int endHour = Integer.parseInt(txtEventEndTime.getText().toString().substring(0, 2));
int endMinute = Integer.parseInt(txtEventEndTime.getText().toString().substring(3, 5));
endTime.set(Calendar.HOUR_OF_DAY, endHour);
endTime.set(Calendar.MINUTE, endMinute);
String mId =/*dataSelected+*/ String.valueOf(startHour) + String.valueOf(startMinute);//+selectedUserID
EventCreation newEvent = new EventCreation(mId, startTime, endTime, edtEventTitle.getText().toString(), edtEventLocation.getText().toString(), R.color.colorPrimary);
dialog.dismiss();
}
});
dialog.show();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
ScheduleToolbar = (Toolbar) getView().findViewById(R.id.schedule_toolbar);
// Setting toolbar as the ActionBar with setSupportActionBar() call
((AppCompatActivity) getActivity()).setSupportActionBar(ScheduleToolbar);
mFirebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mFirebaseDatabase.getReference("users");
mStorageRef = FirebaseStorage.getInstance().getReference();
Calendar cal = Calendar.getInstance();
String month = monthName[cal.get(Calendar.MONTH)];
int year = cal.get(Calendar.YEAR);
getActivity().setTitle(month + "-" + year);
compactCalendar = (CompactCalendarView) getView().findViewById(R.id.compactcalendar_view);
compactCalendar.setUseThreeLetterAbbreviation(true);
long millis = System.currentTimeMillis() % 1000;
Event ev1 = new Event(Color.RED, millis, "First try");
compactCalendar.addEvent(ev1);
compactCalendar.setListener(new CompactCalendarView.CompactCalendarViewListener() {
#Override
public void onDayClick(Date dateClicked) {
//put events into scroll view adapter
}
#Override
public void onMonthScroll(Date firstDayOfNewMonth) {
getActivity().setTitle(dateFormatMonth.format(firstDayOfNewMonth));
}
});
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.schedules, container, false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
}
private void setStudentsList() {
studentsQuery=mDatabaseReference.orderByChild("teacherNum").equalTo(myUser.getTeacherNum());
firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<User, navDrawerMain.UserViewHolder>(
User.class,R.layout.card_view_teacher,navDrawerMain.UserViewHolder.class,studentsQuery) {
#Override
protected void populateViewHolder(navDrawerMain.UserViewHolder viewHolder, User model, int position) {
viewHolder.setName(model.getFirstName() + " " + model.getLastName());
viewHolder.setEmail(model.getEmail());
viewHolder.setImage(getContext(), Uri.parse(model.getImageUri()), model);
}
};
mRecyclerViewStudentEvent.setAdapter(firebaseRecyclerAdapter);
}
}
The dialog xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="50dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_marginTop="20dp"
android:src="#mipmap/title"/>
<EditText
android:id="#+id/edtEventTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="כותרת"
android:layout_marginRight="50dp"/>
<android.support.v7.widget.RecyclerView
android:layout_marginTop="50dp"
android:id="#+id/mRecyclerViewStudentEvent"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginTop="20dp"
android:orientation="vertical">
<ImageView
android:layout_width="50dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_marginTop="20dp"
android:src="#mipmap/clock"/>
<TextView
android:layout_width="wrap_content"
android:layout_marginRight="50dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="שעת התחלה"
android:textSize="20dp" />
<TextView
android:id="#+id/txtEventStartTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="5dp"
android:layout_marginRight="50dp"
android:layout_marginTop="5dp"
android:text="21:00" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="25dp"
android:layout_marginRight="50dp"
android:background="#color/darkgray" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="50dp"
android:layout_alignParentRight="true"
android:layout_marginTop="26dp"
android:text="שעת סיום"
android:textSize="20dp" />
<TextView
android:id="#+id/txtEventEndTime"
android:layout_width="match_parent"
android:layout_marginRight="50dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="5dp"
android:layout_marginTop="30dp"
android:text="21:45" />
</RelativeLayout>
<RelativeLayout
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="50dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_marginTop="20dp"
android:src="#mipmap/location"/>
<EditText
android:id="#+id/edtEventLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="מיקום תחילת השיעור"
android:layout_marginRight="50dp"/>
</RelativeLayout>
<Button
android:id="#+id/btnOfferEvent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:layout_gravity="center_horizontal"
android:text="הצע שיעור"/>
</LinearLayout>
One more thing is that I know is that I'm already able to bring up users into the recyclerView in other fragments.. Here's the code in another fragment:
package com.example.android.aln4;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import static com.example.android.aln4.dataBase.mDatabaseReference;
import static com.example.android.aln4.dataBase.mFirebaseDatabase;
import static com.example.android.aln4.dataBase.mStorageRef;
import static com.example.android.aln4.navDrawerMain.firebaseRecyclerAdapter;
import static com.example.android.aln4.navDrawerMain.teachersQuery;
public class TeachersList extends Fragment {
private RecyclerView mRecyclerViewTeacher;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("מורים");
mFirebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mFirebaseDatabase.getReference("users");
mStorageRef = FirebaseStorage.getInstance().getReference();
mRecyclerViewTeacher=(RecyclerView) getView().findViewById(R.id.mRecyclerViewTeacher);
mRecyclerViewTeacher.setHasFixedSize(true);
mRecyclerViewTeacher.setLayoutManager(new LinearLayoutManager(getContext()));
setTeachersList();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.teachers_list_frag,container,false);
}
private void setTeachersList() {
teachersQuery=mDatabaseReference.orderByChild("type").equalTo("Teacher");
firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<User, navDrawerMain.UserViewHolder>(
User.class,R.layout.card_view_teacher,navDrawerMain.UserViewHolder.class,teachersQuery) {
#Override
protected void populateViewHolder(navDrawerMain.UserViewHolder viewHolder, User model, int position) {
viewHolder.setName(model.getFirstName()+" "+model.getLastName());
viewHolder.setEmail(model.getEmail());
viewHolder.setImage(getContext(), Uri.parse(model.getImageUri()),model);
}
};
mRecyclerViewTeacher.setAdapter(firebaseRecyclerAdapter);
}
}
and its xml file:
<?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">
<android.support.v7.widget.RecyclerView
android:id="#+id/mRecyclerViewTeacher"
android:layout_marginTop="57dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
It's one of my first questions here so I apologize if I missed something :)
Any help would be appriciated.
Solved. All I did was regenerating the SHA1 in the firebase settings, and removing the setHasFixedSize line from Schedules activity and it worked just fine.
What would be the best way to use a seekbar to mix two colors? My seekBar starts in the middle and a mixed color is displayed to a imageview (Average of red1,green1blue1,red2green2,blue2)When the seekbar is moved to the left it should move more towards the color (red1,green1,blue1,) then if moved to the right it should go more to the color (red2,green2blue2).Here is my code hope i explained it well.
<?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="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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.bignerdranch.android.colormixer.MixedColorScreen"
tools:showIn="#layout/activity_mixed_color_screen">
<SurfaceView
android:layout_width="match_parent"
android:layout_height="278dp"
android:background="#000000"
android:id="#+id/surfaceView3"></SurfaceView>
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/seekBar"
android:layout_below="#+id/surfaceView3"
android:layout_marginTop="57dp"
android:indeterminate="false"
android:progress="255"
android:max="510" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Your Color"
android:id="#+id/textView3"
android:layout_below="#+id/seekBar"
android:layout_centerHorizontal="true"
android:layout_marginTop="62dp" />
package com.bignerdranch.android.colormixer;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.SurfaceView;
import android.widget.SeekBar;
import android.widget.TextView;
public class MixedColorScreen extends AppCompatActivity {
private SeekBar mySeekBar;
private TextView seekText;
SurfaceView img;
private static final String TAG = "MYTAG";
private int red1,red2,green1,green2,blue1,blue2,
newRed,newGreen,newBlue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mixed_color_screen);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mySeekBar = (SeekBar) findViewById(R.id.seekBar);
seekText = (TextView) findViewById(R.id.textView3);
Intent i = getIntent();
red1 = i.getIntExtra("red1",150);
green1 = i.getIntExtra("green1",150);
blue1 =i.getIntExtra("blue1",150);
red2 = i.getIntExtra("red2",150);
green2 = i.getIntExtra("green2",150);;
blue2 = i.getIntExtra("blue2",150);
Log.i(TAG,"LOGING COLORS RED =" + red1 + red2 + "GREEN = " +
green1 + green2 + "BLUE = " + blue1 + blue2);
img = (SurfaceView) findViewById(R.id.surfaceView3);
newRed = (red1+red2)/2;
newGreen = (green1 +green2)/2;
newBlue = (blue1+blue2)/2;
Log.i(TAG,"RGB = " + newRed +" " + newGreen + " " + newBlue);
img.setBackgroundColor(Color.rgb(newRed, newGreen, newBlue));
mySeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
Log.i(TAG,"ONPROGRESSCHANGES");
seekText.setText("SHOWING VALS- myprogres = " + mySeekBar.getProgress() + "/Max = " + mySeekBar.getMax() + "METHOD PROGRES = " + progress);
//red1,green1,blue1 ;
//red2,green2,blue2;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
Log.i(TAG,"ONSTARTTRACHINGTOUCH");
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
Log.i(TAG,"ONSTOPTRACKING");
}
});
}
}
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'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'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
I try to get LinearLayout Height on Activity, but I get the height value is doubled. PS:height is 60 but I get 120.
Someone can help?
Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pull_to_refresh_head1"
android:layout_width="200dip"
android:layout_height="60dip"
android:layout_centerInParent="true"
android:orientation="horizontal" >
<TextView
android:id="#+id/t1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hello_world" />
</LinearLayout>
Java code:
package com.example;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.LinearLayout;
import android.widget.TextView;
public class GdomRefreshableActivity extends Activity {
private LinearLayout l1;
TextView t1;
#Override
//create
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gdom_refreshable);
l1=(LinearLayout)findViewById(R.id.pull_to_refresh_head1);
t1=(TextView)findViewById(R.id.t1);
ViewTreeObserver vto2 = l1.getViewTreeObserver();
vto2.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
l1.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int h = l1.getHeight();
int ht = t1.getHeight();
Log.d("GdomRefreshableActivity2",String.valueOf(h));
}
});
}
}