I am getting Error that i wrote below when showing custom Dialog from FragmentActivity.
Error i am getting :
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
Here is my DriverMapActivity that i show custom Dialog from :
Note: I removed some codes that they are not related to my question
DriverMap FragmentActivity
public class DriverMapActivity extends FragmentActivity{
private GoogleMap mMap;
GoogleApiClient googleApiClient;
SupportMapFragment mapFragment;
LocationRequest mLocationRequest;
private Location lastLocation;
private FirebaseAuth mAuth;
private Switch workingswitch;
private String customerId, userId;
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private DatabaseReference driverInfoDB;
private String name, surname, profileimageURL;
private String distancetopick,distancetodes;
private int distancefinal;
private Button yesBtn, noBtn;
private UserInfoShower cdd;
private int cameraupdatedandzoomed;
private Map<String,String> infoMap;
private LatLng pickupLoc;
private LatLng destiantionLoc;
private Marker pickupMarker, destinationMarker;
private float rideDistance;
private Button btnzoom;
private String customerprofileUrl;
private Button logoutbtn, settingsbtn, historybtn, opendrawer;
private boolean pickupgeted;
private String rideStatus = "";
private LatLng target;
#SuppressLint("NewApi")
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_driver_map);
customerId = "";
cameraupdatedandzoomed=0;
mAuth = FirebaseAuth.getInstance();
toolbar = findViewById(R.id.toolbar);
polylines = new ArrayList<>();
userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
btnzoom=findViewById(R.id.btnzoom);
pickupgeted = false;
startService(new Intent(DriverMapActivity.this,onAppKilled.class));
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(this);
// This method will trigger on item Click of navigation menu
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
setDriverStuffToNavView();
btnzoom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(lastLocation!=null)
{
}
else
{
Toast.makeText(DriverMapActivity.this, "Turn on Working
}
}
});
private void listenForCustomerRequest() {
String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReferencelistenerRef=FirebaseDatabase.getInstance().getReference()
.child("Users").child("Drivers").child(userId).child("CustomerRequest");
listenerRef.addChildEventListener(new ChildEventListener() {
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, String s) {
if (dataSnapshot.exists()) {
customerId = dataSnapshot.getKey();
showUserInfo();
}
}
});
}
Here is method that i show CustomDialog:
UserInfoShower Method
Note: I removed some codes that they are not related to my question
private void showUserInfo() {
DatabaseReferenceuserinfoRef=FirebaseDatabase.getInstance().getReference()
.child("Users").child("Customers").child(customerId);
Log.i("TEST", "CustomerId Comes Driver " + customerId);
infoMap=new HashMap<>();
cdd = new UserInfoShower(DriverMapActivity.this,infoMap);
DatabaseReferenceuserInfoDB=FirebaseDatabase.getInstance().getReference()
.child("Users").child("Customers").child(customerId);
userInfoDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists() && dataSnapshot.getChildrenCount() > 0) {
Map<String, Object> map = (Map<String, Object>)
dataSnapshot.getValue();
infoMap.put("DriverOrCus", "1");
infoMap.put("Name", map.get("name").toString());
infoMap.put("Surname", map.get("surname").toString());
if(map.get("profileimageURL") !=null)
{
infoMap.put("profileimageURL",
map.get("profileimageURL").toString());
customerprofileUrl=map.get("profileimageURL").toString();
}
infoMap.put("customerId", customerId);
cdd = new UserInfoShower(DriverMapActivity.this,infoMap);
cdd.show();
cdd.setCanceledOnTouchOutside(false);
yesBtn = cdd.findViewById(R.id.yesBtn);
noBtn = cdd.findViewById(R.id.noBtn);
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String userId=FirebaseAuth.getInstance().
getCurrentUser().getUid();
DatabaseReference decisionRef=FirebaseDatabase.
getInstance().getReference().
child("Users").child("Drivers").child(userId).child("CustomerRequest")
.child(customerId)
.child("driverDecision");
decisionRef.setValue("YES").addOnCompleteListener(newOnCompleteListener
<Void>() {
#Override
public void onComplete(#NonNull
Task<Void>task) {
cdd.cancel();
cdd.dismiss();
cdd=null;
getCustomerRideInfo();
}
});
}
});
}
Error happens when i call cdd.show();
Here is UserInfoShower Dialog:
public class UserInfoShower extends Dialog {
public Context c;
private Button noBtn, yesBtn;
private String name, surname, profileimageURL;
private TextView customerName, customerSurname;
private ImageView customerprofile;
private int position;
private String driverId;
private LatLng CustomerPickupLoc, CustomerDestinationLoc;
private String customerId, desName;
private SharedPreferences sharedpref;
Map<String,String> infoMap;
public UserInfoShower(Context a,Map<String,String> infoMap) {
super(a);
this.c = a;
this.infoMap=infoMap;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_customer_info_shower);
noBtn = findViewById(R.id.noBtn);
yesBtn = findViewById(R.id.yesBtn);
customerName = findViewById(R.id.customerName);
customerSurname = findViewById(R.id.customerSurname);
customerprofile = findViewById(R.id.customerprofile);
position = Integer.valueOf(infoMap.get("DriverOrCus"));
if (position == 1) {
showCusInfo();
} else {
showDriverInfo();
}
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (position == 1) // If user is Driver
{
dismiss();
} else //if user is Cusomer And Liked Driver
{
dismiss();
}
}
});
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (position == 1) //if User is Driver
{
dismiss();
} else// if User is Customer And not liked Driver
{
dismiss();
}
}
});
}
private void showCusInfo() {
name = infoMap.get("Name");
surname = infoMap.get("Surname");
customerId = infoMap.get("customerId");
customerName.setText("Name " + name);
customerSurname.setText("Surname " + surname);
}
#Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
}
public static boolean isValidContextForGlide(final Context context) {
if (context == null) {
return false;
}
if (context instanceof Activity) {
final Activity activity = (Activity) context;
if (activity.isDestroyed() || activity.isFinishing()) {
return false;
}
}
return true;
}
}
Here is My Dialog xml file:
<?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"
tools:context=".UserInfoShower">
<ImageView
android:id="#+id/customerprofile"
android:layout_width="90dp"
android:layout_height="102dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="30dp"
android:layout_marginTop="35dp"
android:src="#drawable/customer"
tools:ignore="RtlCompat" />
<TextView
android:layout_width="240dp"
android:layout_height="wrap_content"
android:id="#+id/customerName"
android:layout_alignParentTop="true"
android:layout_marginTop="36dp"
android:layout_toEndOf="#+id/customerprofile"
android:text="Name : Vuqar"
android:textColor="#color/colorPrimaryDark"
android:textSize="20sp"
tools:ignore="RtlCompat" />
<TextView
android:id="#+id/customerSurname"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="92dp"
android:layout_toEndOf="#+id/customerprofile"
android:text="Surname : Samed"
android:textColor="#color/colorPrimaryDark"
android:textSize="20sp"
tools:ignore="RtlCompat" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="219dp"
android:orientation="horizontal">
<Button
android:id="#+id/yesBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="OK.Looks Good" />
<Button
android:id="#+id/noBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Nope" />
</LinearLayout>
</RelativeLayout>
And finally here is whole error log :
Hope you can help me.Cheers !
Problem solved by : #dr3k
Here is solution. Solution
Related
I am using floating action button for navigation from one activity to another but when i am clicking then app is crashing, there is no problem in floating action button, problem is in another activity where its been navigated. And its been navigated to uploadPost class.
public class uploadPost extends Fragment implements SelectPhotoDialog.OnPhotoSelectedListener {
private static final String TAG = "uploadPost";
#Override
public void getImagePath(Uri imagePath) {
Log.d(TAG, "getImagePath: setting the image to imageview");
UniversalImageLoader.setImage(imagePath.toString(), mPostImage);
//assign to global variable
mSelectedBitmap = null;
mSelectedUri = imagePath;
}
#Override
public void getImageBitmap(Bitmap bitmap) {
Log.d(TAG, "getImageBitmap: setting the image to imageview");
mPostImage.setImageBitmap(bitmap);
//assign to a global variable
mSelectedUri = null;
mSelectedBitmap = bitmap;
}
//widgets
private ImageView mPostImage;
private EditText mTitle, mDescription, mPrice, mCountry, mStateProvince, mCity, mContactEmail,mCollege;
private Button mPost;
private ProgressBar mProgressBar;
//vars
private Bitmap mSelectedBitmap;
private Uri mSelectedUri;
private byte[] mUploadBytes;
private double mProgress = 0;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_upload_post, container, false);
mPostImage = view.findViewById(R.id.post_image);
mTitle = view.findViewById(R.id.input_title);
mDescription = view.findViewById(R.id.input_description);
mPrice = view.findViewById(R.id.input_price);
mCountry = view.findViewById(R.id.input_country);
mStateProvince = view.findViewById(R.id.input_state_province);
mCity = view.findViewById(R.id.input_city);
mContactEmail = view.findViewById(R.id.input_email);
mCollege = view.findViewById(R.id.input_clg);
mPost = view.findViewById(R.id.btn_post);
mProgressBar = (ProgressBar) view.findViewById(R.id.progressBar);
mCountry.setText("India");
mStateProvince.setText("Maharashtra");
mCity.setText("Pune");
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
init();
return view;
}
private void init(){
mPostImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: opening dialog to choose new photo");
SelectPhotoDialog dialog = new SelectPhotoDialog();
dialog.show(getFragmentManager(), getString(R.string.dialog_select_photo));
dialog.setTargetFragment(uploadPost.this, 1);
}
});
mPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: attempting to post...");
if(!isEmpty(mTitle.getText().toString())
&& !isEmpty(mDescription.getText().toString())
&& !isEmpty(mPrice.getText().toString())
&& !isEmpty(mCountry.getText().toString())
&& !isEmpty(mStateProvince.getText().toString())
&& !isEmpty(mCity.getText().toString())
&& !isEmpty(mContactEmail.getText().toString())){
//we have a bitmap and no Uri
if(mSelectedBitmap != null && mSelectedUri == null){
uploadNewPhoto(mSelectedBitmap);
}
//we have no bitmap and a uri
else if(mSelectedBitmap == null && mSelectedUri != null){
uploadNewPhoto(mSelectedUri);
}
}else{
Toast.makeText(getActivity(), "You must fill out all the fields", Toast.LENGTH_SHORT).show();
}
}
});
}
private void uploadNewPhoto(Bitmap bitmap){
Log.d(TAG, "uploadNewPhoto: uploading a new image bitmap to storage");
BackgroundImageResize resize = new BackgroundImageResize(bitmap);
Uri uri = null;
resize.execute(uri);
}
private void uploadNewPhoto(Uri imagePath){
Log.d(TAG, "uploadNewPhoto: uploading a new image uri to storage.");
BackgroundImageResize resize = new BackgroundImageResize(null);
resize.execute(imagePath);
}
public class BackgroundImageResize extends AsyncTask<Uri, Integer, byte[]>{
Bitmap mBitmap;
public BackgroundImageResize(Bitmap bitmap) {
if(bitmap != null){
this.mBitmap = bitmap;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(getActivity(), "compressing image", Toast.LENGTH_SHORT).show();
showProgressBar();
}
#Override
protected byte[] doInBackground(Uri... params) {
Log.d(TAG, "doInBackground: started.");
if(mBitmap == null){
try{
RotateBitmap rotateBitmap = new RotateBitmap();
mBitmap = rotateBitmap.HandleSamplingAndRotationBitmap(getActivity(), params[0]);
}catch (IOException e){
Log.e(TAG, "doInBackground: IOException: " + e.getMessage());
}
}
byte[] bytes = null;
Log.d(TAG, "doInBackground: megabytes before compression: " + mBitmap.getByteCount() / 1000000 );
bytes = getBytesFromBitmap(mBitmap, 100);
Log.d(TAG, "doInBackground: megabytes before compression: " + bytes.length / 1000000 );
return bytes;
}
#Override
protected void onPostExecute(byte[] bytes) {
super.onPostExecute(bytes);
mUploadBytes = bytes;
hideProgressBar();
//execute the upload task
executeUploadTask();
}
}
private void executeUploadTask(){
Toast.makeText(getActivity(), "uploading image", Toast.LENGTH_SHORT).show();
final String postId = FirebaseDatabase.getInstance().getReference().push().getKey();
final StorageReference storageReference = FirebaseStorage.getInstance().getReference()
.child("posts/users/" + FirebaseAuth.getInstance().getCurrentUser().getUid() +
"/" + postId + "/post_image");
UploadTask uploadTask = storageReference.putBytes(mUploadBytes);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getActivity(), "Post Success", Toast.LENGTH_SHORT).show();
//insert the download url into the firebase database
Uri firebaseUri = taskSnapshot.getDownloadUrl();
Log.d(TAG, "onSuccess: firebase download url: " + firebaseUri.toString());
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Post post = new Post();
post.setImage(firebaseUri.toString());
post.setCity(mCity.getText().toString());
post.setContact_email(mContactEmail.getText().toString());
post.setCountry(mCountry.getText().toString());
post.setDescription(mDescription.getText().toString());
post.setPost_id(postId);
post.setPrice(mPrice.getText().toString());
post.setState_province(mStateProvince.getText().toString());
post.setTitle(mTitle.getText().toString());
post.setUser_id(FirebaseAuth.getInstance().getCurrentUser().getUid());
post.setCollege(mCollege.getText().toString());
reference.child(getString(R.string.node_posts))
.child(postId)
.setValue(post);
resetFields();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), "could not upload photo", Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double currentProgress = (100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
if( currentProgress > (mProgress + 15)){
mProgress = (100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
Log.d(TAG, "onProgress: upload is " + mProgress + "& done");
Toast.makeText(getActivity(), mProgress + "%", Toast.LENGTH_SHORT).show();
}
}
});
}
public static byte[] getBytesFromBitmap(Bitmap bitmap, int quality){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, quality,stream);
return stream.toByteArray();
}
private void resetFields(){
UniversalImageLoader.setImage("", mPostImage);
mTitle.setText("");
mDescription.setText("");
mPrice.setText("");
mCountry.setText("India");
mStateProvince.setText("Maharashtra");
mCity.setText("Pune");
mContactEmail.setText("");
mCollege.setText("");
}
private void showProgressBar(){
mProgressBar.setVisibility(View.VISIBLE);
}
private void hideProgressBar(){
if(mProgressBar.getVisibility() == View.VISIBLE){
mProgressBar.setVisibility(View.INVISIBLE);
}
}
/**
* Return true if the #param is null
* #param string
* #return
*/
private boolean isEmpty(String string){
return string.equals("");
}
}
And it is been navigated from SearchActivity class
public class SearchActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private static final String TAG = "SearchActivity";
private static final int REQUEST_CODE = 1;
private FirebaseAuth.AuthStateListener mAuthStateListener;
//widgets
private TabLayout mTabLayout;
public ViewPager mViewPager;
//vars
public SectionsPagerAdapter mPagerAdapter;
//navigation drawer
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
//user info
TextView uname,uemail;
String pemail,pname;
ImageView pimage;
CoordinatorLayout navigation;
FloatingActionButton fab;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
mTabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager = (ViewPager) findViewById(R.id.viewpager_container);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
navigation = (CoordinatorLayout) findViewById(R.id.error);
mToggle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close)
{
/* Called when a drawer has settled in a completely close state. */
public void onDrawerClosed(View view) {
// fab.setVisibility(View.VISIBLE);
//navigation.setVisibility(View.VISIBLE);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
// fab.setVisibility(View.INVISIBLE);
// navigation.setVisibility(View.INVISIBLE);
}
};
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(this);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(getApplicationContext(),R.color.red4)));
View header = navigationView.getHeaderView(0);
pimage = (ImageView) header.findViewById(R.id.pimage);
uname = (TextView) header.findViewById(R.id.uname);
uemail = (TextView) header.findViewById(R.id.emailo);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(SearchActivity.this);
pemail = sharedPref.getString("email", "Not Available");
pname = sharedPref.getString("username", "Not Available");
uname.setText(pname);
uemail.setText(pemail);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(SearchActivity.this,uploadPost.class);
startActivity(intent);
}
});
setupFirebaseListener();
verifyPermissions();
}
private void setupFirebaseListener() {
Log.d(TAG, "setupFirebaseListener: setting up the auth state listener.");
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
Log.d(TAG, "onAuthStateChanged: signed_in: " + user.getUid());
} else {
Log.d(TAG, "onAuthStateChanged: signed_out");
Toast.makeText(SearchActivity.this, "Signed out", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(SearchActivity.this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
};
}
#Override
public void onStart() {
super.onStart();
FirebaseAuth.getInstance().addAuthStateListener(mAuthStateListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthStateListener != null) {
FirebaseAuth.getInstance().removeAuthStateListener(mAuthStateListener);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupViewPager(){
mPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mPagerAdapter.addFragment(new SearchFragment());
mPagerAdapter.addFragment(new WatchListFragment());
// mPagerAdapter.addFragment(new PostFragment());
mViewPager.setAdapter(mPagerAdapter);
mTabLayout.setupWithViewPager(mViewPager);
mTabLayout.getTabAt(0).setText(getString(R.string.fragment_search));
mTabLayout.getTabAt(1).setText(getString(R.string.fragment_watch_list));
// mTabLayout.getTabAt(2).setText(getString(R.string.fragment_post));
}
private void verifyPermissions(){
Log.d(TAG, "verifyPermissions: asking user for permissions");
String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA};
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
permissions[0]) == PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this.getApplicationContext(),
permissions[1]) == PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this.getApplicationContext(),
permissions[2]) == PackageManager.PERMISSION_GRANTED){
setupViewPager();
}else{
ActivityCompat.requestPermissions(SearchActivity.this,
permissions,
REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
verifyPermissions();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if(id == R.id.profile){
Intent intent = new Intent(SearchActivity.this,test.class);
startActivity(intent);
Toast.makeText(this,"Profile",Toast.LENGTH_SHORT).show();
}
if(id == R.id.aboutus){
Intent intent = new Intent(SearchActivity.this,Aboutus.class);
startActivity(intent);
Toast.makeText(this,"About Us",Toast.LENGTH_SHORT).show();
}
if(id == R.id.mypost){
Intent intent = new Intent(SearchActivity.this,MyPosts.class);
startActivity(intent);
Toast.makeText(this,"My Post",Toast.LENGTH_SHORT).show();
}
if(id == R.id.logout){
Log.d(TAG, "onClick: attempting to sign out the user.");
FirebaseAuth.getInstance().signOut();
}
return false;
}
}
I am not able to understand the error which i am seeing on my logs
FATAL EXCEPTION: main
Process: codingwithmitch.com.forsale, PID: 13518
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{codingwithmitch.com.forsale/codingwithmitch.com.forsale.uploadPost}: java.lang.ClassCastException: codingwithmitch.com.forsale.uploadPost cannot be cast to android.app.Activity
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2561)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Caused by: java.lang.ClassCastException: codingwithmitch.com.forsale.uploadPost cannot be cast to android.app.Activity
at android.app.Instrumentation.newActivity(Instrumentation.java:1100)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2551)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
my SearchActivity xml file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:fab="http://schemas.android.com/tools"
android:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/White"
android:fitsSystemWindows="true">
<android.support.design.widget.CoordinatorLayout
android:id="#+id/error"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:elevation="10dp"
android:fitsSystemWindows="true">
<android.support.design.widget.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="50dp"
app:layout_collapseMode="parallax">
</android.support.design.widget.TabLayout>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
</android.support.v4.view.ViewPager>
<com.getbase.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="42dp"
android:layout_height="53dp"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:scaleType="center"
android:src="#drawable/ic_camera_alt_black_24dp"
app:fabSize="normal"
fab:layout_editor_absoluteX="342dp"
fab:layout_editor_absoluteY="458dp">
</com.getbase.floatingactionbutton.FloatingActionButton>
</android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/header"
app:menu="#menu/nav_menu"></android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
You are getting the error :
cannot be cast to android.app.Activity
because you are trying to load uploadPost as an Activity but it extends Fragment so you get the "cannot be cast to android.app.Activity" error.
You must decide whether you want to load it as a Fragment or an Activity. If you want to load uploadPost as an Activity you need to extend to an Activity not Fragment
EDIT
If you wish to continue to use it as a Fragment you must use a FragmentTransaction to either add() the Fragment or replace() a Fragment in your activity layout.
You can replace a Fragment like this example:
Fragment fragment = new UploadPost();
if(fragment != null) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
//If you want to play around with different transaction animations
//fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
fragmentTransaction.replace(R.id.content_main, fragment, "0");
fragmentTransaction.commit();
}
Where R.id.content_main is just a RelativeLayout in my MainActivity which is replaced by the uploadPost fragment.
And as 0X0nosugar indicated: It is java naming convention to capitalize class names. Please adopt this convention--otherwise you will make it more difficult to understand your code.
EDIT 2
Often a Fragment will be used to swap views in an container Activity. For example I use them to swap views in combination with a DrawerLayout. In this case I will continue to replace fragments, but never really remove one explicitly.
For example I will have a xml layout file very similar to your "SearchActivity" file. Just below the </android.support.design.widget.AppBarLayout> tag I will introduce a RelativeLayout with the id android:id="#+id/content_main". This RelativeLayout is just a dummy container view and is being replaced with whatever is in my selected Fragment. So you would need to change the onClick code to replace the fragment as I showed above.
With another action you might want to either remove that fragment or replace it with another... that all depends on your app design--which I do not know.
Main Activity
public class MainActivity extends AppCompatActivity implements LocationEngineListener, PermissionsListener{
private MapView mapView;
private MapboxMap map;
private PermissionsManager permissionsManager;
private LocationLayerPlugin locationPlugin;
private LocationEngine locationEngine;
private Location originLocation;
private Marker destinationMarker;
private LatLng originCoord;
private LatLng destinationCoord;
private Point originPosition;
private Point destinationPosition;
private DirectionsRoute currentRoute;
private static final String TAG = "DirectionsActivity";
private NavigationMapRoute navigationMapRoute;
private Button button;
private ArrayList <String> mNames=new ArrayList<>();
private ArrayList <String> mImages=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this,getString(R.string.token));
setContentView(R.layout.activity_main);
mapView=(MapView)findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
button = findViewById(R.id.startnav);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Point origin = originPosition;
Point destination = destinationPosition;
// Pass in your Amazon Polly pool id for speech synthesis using Amazon Polly
// Set to null to use the default Android speech synthesizer
String awsPoolId = null;
boolean simulateRoute = true;
NavigationViewOptions options = NavigationViewOptions.builder()
.origin(origin)
.destination(destination)
.awsPoolId(awsPoolId)
.shouldSimulateRoute(simulateRoute)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(MainActivity.this, options);
}
});
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(final MapboxMap mapboxMap) {
map = mapboxMap;
enableLocationPlugin();
originCoord = new LatLng(originLocation.getLatitude(), originLocation.getLongitude());
mapboxMap.addOnMapClickListener(new MapboxMap.OnMapClickListener() {
#Override
public void onMapClick(#NonNull LatLng point) {
button.setEnabled(true);
button.setBackgroundResource(R.drawable.button_press);
if (destinationMarker != null) {
mapboxMap.removeMarker(destinationMarker);
}
destinationCoord = point;
destinationMarker = mapboxMap.addMarker(new MarkerOptions()
.position(destinationCoord)
);
destinationPosition = Point.fromLngLat(destinationCoord.getLongitude(), destinationCoord.getLatitude());
originPosition = Point.fromLngLat(originCoord.getLongitude(), originCoord.getLatitude());
getRoute(originPosition, destinationPosition);
}
});
}
});
getImages();
}
private void getImages() {
Log.d(TAG, "initImageBitmaps: preparing bitmaps");
mImages.add("https://c1.staticflickr.com/5/4636/25316407448_de5fbf183d_o.jpg");
mNames.add("Havasu Falls");
mImages.add("https://i.redd.it/tpsnoz5bzo501.jpg");
mNames.add("Trondheim");
mImages.add("https://i.redd.it/qn7f9oqu7o501.jpg");
mNames.add("Portugal");
mImages.add("https://i.redd.it/j6myfqglup501.jpg");
mNames.add("Rocky Mountain National Park");
mImages.add("https://i.redd.it/0h2gm1ix6p501.jpg");
mNames.add("Mahahual");
mImages.add("https://i.redd.it/k98uzl68eh501.jpg");
mNames.add("Frozen Lake");
mImages.add("https://i.redd.it/glin0nwndo501.jpg");
mNames.add("White Sands Desert");
mImages.add("https://i.redd.it/obx4zydshg601.jpg");
mNames.add("Austrailia");
mImages.add("https://i.imgur.com/ZcLLrkY.jpg");
mNames.add("Washington");
InitRecyclerView();
}
private void InitRecyclerView() {
Log.d(TAG, "InitRecyclerView: init recyclerview");
LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false);
RecyclerView recyclerView=findViewById(R.id.myrecyclerview);
recyclerView.setLayoutManager(linearLayoutManager);
MainAdapter adapter=new MainAdapter(this,mNames,mImages);
recyclerView.setAdapter(adapter);
}
#SuppressWarnings( {"MissingPermission"})
private void enableLocationPlugin() {
// verifica daca are permission si le cere
if (PermissionsManager.areLocationPermissionsGranted(this)) {
// Create an instance of LOST location engine
initializeLocationEngine();
locationPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationPlugin.setLocationLayerEnabled(LocationLayerMode.TRACKING);
} else {
permissionsManager = new PermissionsManager( this);
permissionsManager.requestLocationPermissions(this);
}
}
#SuppressWarnings( {"MissingPermission"})
private void initializeLocationEngine() {
locationEngine = new LostLocationEngine(MainActivity.this);
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.activate();
Location lastLocation = locationEngine.getLastLocation();
if (lastLocation != null) {
originLocation = lastLocation;
setCameraPosition(lastLocation);
} else {
locationEngine.addLocationEngineListener(this);
}
}
private void setCameraPosition(Location location) {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 13));
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
}
#Override
public void onPermissionResult(boolean granted) {
if (granted) {
enableLocationPlugin();
} else {
finish();
}
}
#Override
#SuppressWarnings( {"MissingPermission"})
public void onConnected() {
locationEngine.requestLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
originLocation = location;
setCameraPosition(location);
locationEngine.removeLocationEngineListener(this);
}
}
#Override
#SuppressWarnings( {"MissingPermission"})
protected void onStart() {
super.onStart();
if (locationEngine != null) {
locationEngine.requestLocationUpdates();
}
if (locationPlugin != null) {
locationPlugin.onStart();
}
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
if (locationEngine != null) {
locationEngine.removeLocationUpdates();
}
if (locationPlugin != null) {
locationPlugin.onStop();
}
mapView.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
if (locationEngine != null) {
locationEngine.deactivate();
}
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
private void getRoute(Point origin, Point destination) {
NavigationRoute.builder()
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().routes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
currentRoute = response.body().routes().get(0);
// Draw the route on the map
if (navigationMapRoute != null) {
navigationMapRoute.removeRoute();
} else {
navigationMapRoute = new NavigationMapRoute(null, mapView, map, R.style.NavigationMapRoute);
}
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Log.e(TAG, "Error: " + throwable.getMessage());
}
});
}
}
And the MainAdapter
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {
private static final String TAG="MainAdapter";
private ArrayList <String> mNames=new ArrayList<>();
private ArrayList <String> mImages=new ArrayList<>();
private Context mContext;
public MainAdapter(Context context , ArrayList<String> images, ArrayList<String> names) {
mNames=names;
mImages=images;
mContext=context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.d(TAG, "onCreateViewHolder: called ");
View view=LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_listitem,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
Log.d(TAG, "onBindViewHolder: called");
Glide.with(mContext)
.asBitmap()
.load(mImages.get(position))
.into(holder.image);
holder.name.setText(mNames.get(position));
holder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: clicked on a image"+mNames.get(position));
Toast.makeText(mContext,mNames.get(position),Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return mImages.size();
}
public class ViewHolder extends RecyclerView.ViewHolder
{
CircleImageView image;
TextView name;
public ViewHolder(View itemView) {
super(itemView);
image=itemView.findViewById(R.id.image_view);
name=itemView.findViewById(R.id.name);
}
}
}
This is activitymain layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mapbox="http://schemas.android.com/apk/res-auto"
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="com.example.matei.meetup.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/myrecyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" />
<com.mapbox.mapboxsdk.maps.MapView
android:id="#+id/mapView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
mapbox:mapbox_cameraTargetLat="38.9098"
mapbox:mapbox_cameraTargetLng="-77.0295"
mapbox:mapbox_styleUrl="mapbox://styles/mapbox/streets-v10"
mapbox:mapbox_cameraZoom="12" >
</com.mapbox.mapboxsdk.maps.MapView>
<Button
android:id="#+id/startnav"
android:layout_width="316dp"
android:layout_height="41dp"
android:layout_margin="20px"
android:background="#drawable/button_unpressed"
android:padding="5px"
android:text="Start navigation"
android:textColor="#color/mapboxWhite"
mapbox:layout_constraintBottom_toBottomOf="parent"
mapbox:layout_constraintLeft_toLeftOf="parent"
mapbox:layout_constraintRight_toRightOf="parent"
mapbox:layout_constraintTop_toBottomOf="#+id/mapView"
mapbox:layout_constraintVertical_bias="1.0" />
</android.support.constraint.ConstraintLayout>
And here is the other layout file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="1dp">
<android.support.v7.widget.CardView
android:layout_width="100dp"
android:layout_height="100dp"
app:cardCornerRadius="4dp"
app:cardElevation="1dp"
app:cardMaxElevation="2dp"
android:layout_centerInParent="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="70dp"
android:layout_height="70dp"
android:scaleType="centerCrop"
android:layout_centerHorizontal="true"
android:id="#+id/image_view"
android:src="#mipmap/ic_launcher"/>
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="18dp"
android:text="Chestie"
android:layout_below="#+id/image_view"
android:layout_centerHorizontal="true"
android:gravity="center"
android:layout_marginTop="5dp"
android:textColor="#000"
android:layout_marginBottom="5dp" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
The app does not crash on runtime, it only displays the map without the RecyclerView. In my gradle file i inlcuded the dependencies i needed. I tried messing around with the gradle file, nothing seems to work. In my logcat I have the following java.io.FileNotFoundException-No such file or directory.
Problem in library de.hdodenhof.circleimageview.CircleImageView. check this
https://github.com/hdodenhof/CircleImageView/issues/121
If you need to circle imageview you can use glide transformation with imageview
https://bumptech.github.io/glide/doc/transformations.html
Example glide v4:
RequestOptions options = new RequestOptions();
options.CircleCrop();
Glide.with(fragment)
.load(url)
.apply(options)
.into(imageView);
I am trying to implement "Swipe to load more" method in my application but I got that error when I swipe down in the first time. This is what it showed in the console:
E/SwipeRefreshLayout: Got ACTION_MOVE event but don't have an active
pointer id. E/SwipeRefreshLayout: Got ACTION_MOVE event but don't have
an active pointer id. E/SwipeRefreshLayout: Got ACTION_MOVE event but
don't have an active pointer id. E/SwipeRefreshLayout: Got ACTION_MOVE
event but don't have an active pointer id.
This is my layout code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
tools:context="training.com.chatgcmapplication.ChatActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipeLayout"
android:layout_width="match_parent"
android:layout_height="380dp">
<ListView
android:id="#+id/listMessage"
android:layout_width="match_parent"
android:layout_height="380dp"
android:layout_alignParentLeft="false"
android:layout_alignParentTop="false"
android:divider="#null"
android:listSelector="#android:color/transparent"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll" />
</android.support.v4.widget.SwipeRefreshLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:id="#+id/txt_chat"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.92"
android:inputType="text" />
<Button
android:id="#+id/btn_send"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="30dp"
android:text="#string/btn_send" />
</LinearLayout>
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
And when I swipe in the second time: it load double data.
This is ChatActivity, what implement that method:
public class ChatActivity extends AppCompatActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
private static EditText txt_chat;
private String registId;
private String chatTitle;
private MessageSender mgsSender;
private int userId;
private DatabaseHelper databaseHelper;
private TimeUtil timeUtil;
private MessageAdapter messageAdapter;
private int offsetNumber = 5;
private SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Button btn_send = (Button) findViewById(R.id.btn_send);
txt_chat = (EditText) findViewById(R.id.txt_chat);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeLayout);
swipeRefreshLayout.setOnRefreshListener(this);
ListView lv_message = (ListView) findViewById(R.id.listMessage);
timeUtil = new TimeUtil();
databaseHelper = DatabaseHelper.getInstance(getApplicationContext());
btn_send.setOnClickListener(this);
Bundle bundle = getIntent().getExtras();
chatTitle = bundle.getString("titleName");
if (getIntent().getBundleExtra("INFO") != null) {
chatTitle = getIntent().getBundleExtra("INFO").getString("name");
this.setTitle(chatTitle);
} else {
this.setTitle(chatTitle);
}
registId = bundle.getString("regId");
userId = databaseHelper.getUser(chatTitle).getUserId();
List<Message> messages = databaseHelper.getLastTenMessages(AppConfig.USER_ID, databaseHelper.getUser(chatTitle).getUserId(), 0);
messageAdapter = new MessageAdapter(getApplicationContext(), R.layout.chat_item, (ArrayList<Message>) messages);
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
if (messages.size() > 0) lv_message.setAdapter(messageAdapter);
}
private BroadcastReceiver onNotice = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
try {
Message messageObj = new Message();
messageObj.setMessage(message);
messageObj.setUserId(userId);
messageObj.setSender_id(AppConfig.USER_ID);
messageObj.setExpiresTime(timeUtil.formatDateTime(timeUtil.getCurrentTime()));
messageAdapter.add(messageObj);
} catch (ParseException e) {
e.printStackTrace();
}
messageAdapter.notifyDataSetChanged();
}
};
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(onNotice);
super.onDestroy();
}
private static MessageSenderContent createMegContent(String regId, String title) {
String message = txt_chat.getText().toString();
MessageSenderContent mgsContent = new MessageSenderContent();
mgsContent.addRegId(regId);
mgsContent.createData(title, message);
return mgsContent;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send:
String message = txt_chat.getText().toString();
databaseHelper = DatabaseHelper.getInstance(getApplicationContext());
mgsSender = new MessageSender();
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
MessageSenderContent mgsContent = createMegContent(registId, AppConfig.USER_NAME);
mgsSender.sendPost(mgsContent);
return null;
}
}.execute();
databaseHelper.addMessage(message, timeUtil.getCurrentTime(), userId, AppConfig.USER_ID);
txt_chat.setText("");
try {
Message messageObj = new Message();
messageObj.setMessage(message);
messageObj.setUserId(AppConfig.USER_ID);
messageObj.setSender_id(userId);
messageObj.setExpiresTime(timeUtil.formatDateTime(timeUtil.getCurrentTime()));
messageAdapter.add(messageObj);
} catch (ParseException e) {
e.printStackTrace();
}
messageAdapter.notifyDataSetChanged();
break;
}
}
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
List<Message> messages = databaseHelper.getLastTenMessages(AppConfig.USER_ID, databaseHelper.getUser(chatTitle).getUserId(), offsetNumber);
messageAdapter.insertToTheFirst(messages);
messageAdapter.notifyDataSetChanged();
offsetNumber += 5;
Log.i("Offset number", offsetNumber + "");
swipeRefreshLayout.setRefreshing(false);
}
}
UPDATE ISSUE's REASON
I found the reason of that issue. It due to I force the listview scroll to the bottom when it init with this code :
android:stackFromBottom="true"
I replace that code with this but still have same issue:
lv_message.post(new Runnable() {
#Override
public void run() {
lv_message.setSelection(lv_message.getCount() -1);
}
});
I think the problem is , You are trying to show , dismiss and refresh swipeRefreshLayout inside the same method i.e onRefresh().
Make seperate methods for showing and dismissing dialog and invoke them from the place where they are required as I have done below:
#Override
public void onRefresh() {
// refresh code here.
}
#Override
public void showDialog() {
swipeRef.post(new Runnable() {
#Override
public void run() {
if(swipeRef != null)
swipeRef.setRefreshing(true);
}
});
}
#Override
public void dismissDialog() {
if(swipeRef!=null && swipeRef.isShown() )
swipeRef.setRefreshing(false);
}
I am trying to implement the cwac camera library for taking picture and storing them. When i tested the code on htc desire hd there were few complications. This is the screenshot of camera preview.
And when I take picture it shows image preview as.
The codes I have for this are as follows.
This is Activity for implementing camera preview fragment.
public class Camera extends ActionBarActivity implements CameraPreviewFragment.Contract {
private static final String STATE_SINGLE_SHOT="single_shot";
private static final String STATE_LOCK_TO_LANDSCAPE=
"lock_to_landscape";
private static final int CONTENT_REQUEST=1337;
private CameraPreviewFragment std=null;
private CameraPreviewFragment ffc=null;
private CameraPreviewFragment current=null;
private boolean hasTwoCameras=(android.hardware.Camera.getNumberOfCameras() > 1);
private boolean singleShot=false;
private boolean isLockedToLandscape=false;
private Toolbar mToolbar;
private void setToolBar(int toolbarId){
mToolbar = (Toolbar) findViewById(toolbarId);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
getSupportActionBar().setLogo(R.drawable.ic_launcher);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
setToolBar(R.id.toolbar);
if (savedInstanceState == null) {
CameraPreviewFragment frag = new CameraPreviewFragment();
frag = CameraPreviewFragment.newInstance(false);
getFragmentManager().beginTransaction()
.add(R.id.container, frag)
.commit();
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
setSingleShotMode(savedInstanceState.getBoolean(STATE_SINGLE_SHOT));
isLockedToLandscape=
savedInstanceState.getBoolean(STATE_LOCK_TO_LANDSCAPE);
if (current != null) {
current.lockToLandscape(isLockedToLandscape);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(STATE_SINGLE_SHOT, isSingleShotMode());
outState.putBoolean(STATE_LOCK_TO_LANDSCAPE, isLockedToLandscape);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_menu_camera, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean isSingleShotMode() {
return true;
}
#Override
public void setSingleShotMode(boolean mode) {
}
}
And here is my camera preview fragment.(to load camera and has button for taking image)
public class CameraPreviewFragment extends CameraFragment implements SeekBar.OnSeekBarChangeListener, View.OnClickListener{
private static final String DEBUG = CameraPreviewFragment.class.getSimpleName();
private static final String KEY_USE_FFC=
"com.commonsware.cwac.camera.demo.USE_FFC";
private MenuItem singleShotItem=null;
private boolean singleShotProcessing=false;
private static final int FLASH_ALWAYS_OFF = 0;
private static final int FLASH_ALWAYS_ON = 1;
private static final int FLASH_AUTO_MODE = 2;
private SeekBar zoom=null;
private View mCameraView;
private ImageButton mTakePicture;
private Button mFlashButton;
private Button mGridButton;
private ImageView mGridLines;
private long lastFaceToast=0L;
private int flashState = 2;
String flashMode=null, autoFlashMode=null, noFlashMode= null;
private DemoCameraHost cameraHost;
static CameraPreviewFragment newInstance(boolean useFFC) {
CameraPreviewFragment f=new CameraPreviewFragment();
Bundle args=new Bundle();
args.putBoolean(KEY_USE_FFC, useFFC);
f.setArguments(args);
return(f);
}
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
setHasOptionsMenu(true);
cameraHost = new DemoCameraHost(getActivity());
SimpleCameraHost.Builder builder=
new SimpleCameraHost.Builder(cameraHost);
setHost(builder.useFullBleedPreview(true).build());
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
mCameraView=
super.onCreateView(inflater, container, savedInstanceState);
View results=inflater.inflate(R.layout.fragment_camera, container, false);
mCameraView.setOnClickListener(this);
mGridLines = (ImageView) results.findViewById(R.id.ivGridLines);
mTakePicture = (ImageButton) results.findViewById(R.id.ibCaptureButton);
mTakePicture.setOnClickListener(this);
mFlashButton = (Button) results.findViewById(R.id.bFlash);
mFlashButton.setOnClickListener(this);
mGridButton = (Button) results.findViewById(R.id.bGrid);
mGridButton.setOnClickListener(this);
((ViewGroup) results.findViewById(R.id.camera)).addView(mCameraView);
zoom=(SeekBar)results.findViewById(R.id.sbZoomControl);
zoom.setKeepScreenOn(true);
return(results);
}
#Override
public void onPause() {
super.onPause();
getActivity().invalidateOptionsMenu();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_camera, menu);
singleShotItem=menu.findItem(R.id.single_shot);
singleShotItem.setChecked(getContract().isSingleShotMode());
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.single_shot:
item.setChecked(!item.isChecked());
getContract().setSingleShotMode(item.isChecked());
return(true);
case R.id.show_zoom:
item.setChecked(!item.isChecked());
zoom.setVisibility(item.isChecked() ? View.VISIBLE : View.GONE);
return(true);
}
return(super.onOptionsItemSelected(item));
}
boolean isSingleShotProcessing() {
return(singleShotProcessing);
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (fromUser) {
zoom.setEnabled(false);
zoomTo(zoom.getProgress()).onComplete(new Runnable() {
#Override
public void run() {
zoom.setEnabled(true);
}
}).go();
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// ignore
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// ignore
}
Contract getContract() {
return((Contract)getActivity());
}
void takeSimplePicture() {
if (singleShotItem!=null && singleShotItem.isChecked()) {
singleShotProcessing=true;
mTakePicture.setEnabled(false);
}
PictureTransaction xact=new PictureTransaction(getHost());
xact.flashMode(getFlashMode());
takePicture(xact);
}
#Override
public void onClick(View v) {
if(v == mTakePicture){
takeSimplePicture();
}
if(v == mFlashButton){
if(flashState == FLASH_ALWAYS_OFF){
//flash to be always on
flashState = FLASH_ALWAYS_ON;
setFlashMode(flashMode);
Toast.makeText(getActivity(), "Flash! on", Toast.LENGTH_SHORT).show();
}else if(flashState == FLASH_ALWAYS_ON){
flashState = FLASH_AUTO_MODE;
setFlashMode(autoFlashMode);
Toast.makeText(getActivity(), "Flash! auto", Toast.LENGTH_SHORT).show();
}else if(flashState == FLASH_AUTO_MODE){
flashState = FLASH_ALWAYS_OFF;
setFlashMode(noFlashMode);
Toast.makeText(getActivity(), "Flash! off", Toast.LENGTH_SHORT).show();
}
}
if(v == mCameraView){
Log.i(DEBUG,"OnClick autofocus");
autoFocus();
}
if(v == mGridButton){
if(mGridLines.getVisibility() == View.VISIBLE){
mGridLines.setVisibility(View.GONE);
}else if(mGridLines.getVisibility() == View.GONE){
mGridLines.setVisibility(View.VISIBLE);
}
}
}
interface Contract {
boolean isSingleShotMode();
void setSingleShotMode(boolean mode);
}
class DemoCameraHost extends SimpleCameraHost implements
android.hardware.Camera.FaceDetectionListener {
boolean supportsFaces=false;
public DemoCameraHost(Context _ctxt) {
super(_ctxt);
}
#Override
protected File getPhotoDirectory() {
return CameraUtility.getOutputDirectory(CameraUtility.DIRECTORY_TYPE_CAMERA);
}
#Override
public boolean useFrontFacingCamera() {
if (getArguments() == null) {
return(false);
}
return(getArguments().getBoolean(KEY_USE_FFC));
}
#Override
public boolean useSingleShotMode() {
if (singleShotItem == null) {
return(false);
}
return(singleShotItem.isChecked());
}
#Override
public Camera.Size getPictureSize(PictureTransaction xact, Camera.Parameters parameters) {
return super.getPictureSize(xact, parameters);
}
#Override
public void saveImage(PictureTransaction xact, byte[] image) {
if (useSingleShotMode()) {
singleShotProcessing=false;
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
mTakePicture.setEnabled(true);
}
});
ImagePreviewActivity.imageToShow=image;
startActivity(new Intent(getActivity(), ImagePreviewActivity.class));
}
else {
String path = getPhotoFilename();
super.saveImage(xact, image);
}
}
#Override
public void autoFocusAvailable() {
if (supportsFaces)
startFaceDetection();
}
#Override
public void autoFocusUnavailable() {
stopFaceDetection();
}
#Override
public void onCameraFail(CameraHost.FailureReason reason) {
super.onCameraFail(reason);
Toast.makeText(getActivity(),
"Sorry, but you cannot use the camera now!",
Toast.LENGTH_LONG).show();
}
#Override
public android.hardware.Camera.Parameters adjustPreviewParameters(android.hardware.Camera.Parameters parameters) {
autoFlashMode =
CameraUtils.findBestFlashModeMatch(parameters,
android.hardware.Camera.Parameters.FLASH_MODE_RED_EYE,
android.hardware.Camera.Parameters.FLASH_MODE_AUTO,
android.hardware.Camera.Parameters.FLASH_MODE_ON);
flashMode = CameraUtils.findBestFlashModeMatch(parameters,
android.hardware.Camera.Parameters.FLASH_MODE_ON);
noFlashMode = CameraUtils.findBestFlashModeMatch(parameters,
Camera.Parameters.FLASH_MODE_OFF);
if (doesZoomReallyWork() && parameters.getMaxZoom() > 0) {
zoom.setMax(parameters.getMaxZoom());
zoom.setOnSeekBarChangeListener(CameraPreviewFragment.this);
}
else {
zoom.setEnabled(false);
}
if (parameters.getMaxNumDetectedFaces() > 0) {
supportsFaces=true;
}
else {
Toast.makeText(getActivity(),
"Face detection not available for this camera",
Toast.LENGTH_LONG).show();
}
return(super.adjustPreviewParameters(parameters));
}
#Override
public void onFaceDetection(android.hardware.Camera.Face[] faces, android.hardware.Camera camera) {
if (faces.length > 0) {
long now= SystemClock.elapsedRealtime();
if (now > lastFaceToast + 10000) {
Toast.makeText(getActivity(), "I see your face!",
Toast.LENGTH_LONG).show();
lastFaceToast=now;
}
}
}
#Override
protected File getPhotoPath() {
return super.getPhotoPath();
}
#Override
#TargetApi(16)
public void onAutoFocus(boolean success, android.hardware.Camera camera) {
super.onAutoFocus(success, camera);
mTakePicture.setEnabled(true);
}
}
}
This one is for viewing the image taken. ImagePreviewActivity
public class ImagePreviewActivity extends ActionBarActivity {
static byte[] imageToShow = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (imageToShow == null) {
Toast.makeText(this, R.string.no_image, Toast.LENGTH_LONG).show();
finish();
} else {
ImageView iv = new ImageView(this);
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inPurgeable = true;
opts.inInputShareable = true;
opts.inMutable = false;
opts.inSampleSize = 2;
iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
iv.setImageBitmap(BitmapFactory.decodeByteArray(imageToShow,
0,
imageToShow.length,
opts));
imageToShow = null;
iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
setContentView(iv);
}
}
}
And as for the xml layouts I have:
for CameraPrevirewFragment
<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"
tools:context="com.example.ballard.CWACCamera.Camera$PlaceholderFragment"
android:orientation="vertical"
android:weightSum="4">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="3">
<FrameLayout
android:id="#+id/camera"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#android:drawable/gallery_thumb"
android:id="#+id/ivGridLines"
android:visibility="gone"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1">
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/sbZoomControl"
android:layout_alignParentTop="true"
android:background="#null"
android:layout_toLeftOf="#+id/bFlash"
android:layout_alignBottom="#+id/bFlash"
android:layout_toRightOf="#+id/bGrid"
android:layout_toEndOf="#+id/bGrid" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ibCaptureButton"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:src="#android:drawable/ic_menu_camera"
android:background="#null"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Flash"
android:id="#+id/bFlash"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Grid"
android:id="#+id/bGrid"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
</LinearLayout>
and for the camera activity I have
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/rlHomeLayout"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context="com.example.ballard.Login.Home" tools:ignore="MergeRootFrame"
>
<include
android:id="#+id/toolbar"
layout="#layout/toolbar"/>
<FrameLayout`enter code here`
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar">
</FrameLayout>
</RelativeLayout>
I am using v7 toolbar as the actionbar and is as follows(toolbar.xml)
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimaryDark"/>
I tried the demo of the library and is working fine on the same mobile set. Also there seems to be no problem while I was testing it on Nexus 5. I am trying this library for the first time and have no clue for solving this
I am trying to develop an app with in app purchases in it, simply what I want to do is to have two buttons one to make the purchase(enabled) the second button to open the activity after purchase (at first is disabled then after purchase is enabled).
Two problems the first was to save the buttons state after the purchase as they were getting reset every time I restart the app. So I did some researches and found about shared preference and I did implemented it but the second problem came out that buttons statuses doesn’t seem to work right (between disabled to enabled) after implementing shared preference.
Note that in the app I have two buttons that do the same thing one enables the other buttons but with no purchase made and they work fine with shared preference, but the buttons associated with the in app purchase stopped changing their status from disabled to enabled after the purchase is made (they stay disabled after the purchase)
Here is my xml code:
<RelativeLayout 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=".MainScreen">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity 1"
android:id="#+id/act1"
android:onClick="Activity1"
android:layout_marginTop="84dp"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/buyall"
android:layout_toStartOf="#+id/buyall"
android:enabled="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Buy Act 1"
android:id="#+id/buyButton"
android:onClick="buyClick"
android:layout_alignTop="#+id/act1"
android:layout_toRightOf="#+id/act1"
android:layout_toEndOf="#+id/act1"
android:layout_marginLeft="45dp"
android:layout_marginStart="45dp"
android:enabled="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity 2"
android:id="#+id/act2"
android:layout_below="#+id/act1"
android:layout_alignLeft="#+id/act1"
android:layout_alignStart="#+id/act1"
android:onClick="Activity2"
android:enabled="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Buy act 2"
android:id="#+id/buyact2"
android:layout_alignBottom="#+id/act2"
android:layout_alignLeft="#+id/buyButton"
android:layout_alignStart="#+id/buyButton"
android:onClick="buyAct2"
android:enabled="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity 3"
android:id="#+id/act3"
android:layout_below="#+id/act2"
android:layout_alignLeft="#+id/act2"
android:layout_alignStart="#+id/act2"
android:onClick="Activity3"
android:enabled="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Buy act 3"
android:id="#+id/buyact3"
android:layout_alignBottom="#+id/act3"
android:layout_alignLeft="#+id/buyact2"
android:layout_alignStart="#+id/buyact2"
android:onClick="buyAct3"
android:enabled="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Buy all"
android:id="#+id/buyall"
android:onClick="buyAll"
android:enabled="true"
android:layout_below="#+id/eact4"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ACT 4"
android:id="#+id/act4"
android:onClick="ACT4"
android:layout_below="#+id/act3"
android:layout_alignLeft="#+id/act3"
android:layout_alignStart="#+id/act3"
android:enabled="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enable ACT 4"
android:id="#+id/eact4"
android:onClick="EACT4"
android:layout_below="#+id/buyact3"
android:layout_alignLeft="#+id/buyact3"
android:layout_alignStart="#+id/buyact3"
android:enabled="true" />
And that’s my java code:
package com.aseng90_test.smiap2;
import android.content.Intent;
import android.content.SharedPreferences;
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.Toast;
import com.aseng90_test.smiap2.util.IabHelper;
import com.aseng90_test.smiap2.util.IabResult;
import com.aseng90_test.smiap2.util.Purchase;
public class MainScreen extends ActionBarActivity {
private static final String TAG = "com.aseng90_test.smiap2";
IabHelper mHelper;
private static final String ITEM_SKU = "com.aseng90_test.smiap2_button555";
private static final String ITEM_SKU2 = "com.aseng90_test.smiap2_buyact222";
private static final String ITEM_SKU3 = "com.aseng90_test.smiap2_buyact333";
private static final String ITEM_SKU4 = "com.aseng90_test.smiap2_buyall_11";
private Button Activity1;
private Button Activity2;
private Button Activity3;
private Button buyButton;
private Button buyAct2;
private Button buyAct3;
private Button buyAll;
private Button EAct4;
private Button Act4;
private SharedPreferences prefs;
private String prefName = "MyPref";
boolean Activity1_isEnabled;
boolean Activity2_isEnabled;
boolean Activity3_isEnabled;
boolean Act4_isEnabled;
boolean buyButton_isEnabled;
boolean buyAct2_isEnabled;
boolean buyAct3_isEnabled;
boolean buyAll_isEnabled;
boolean EAct4_isEnabled;
private static final String Activity1_state = "Activity1_state";
private static final String Activity2_State = "Activity2_state";
private static final String Activity3_State = "Activity3_state";
private static final String buyButton_State = "buyButton_state";
private static final String buyAct2_State = "buyAct2_state";
private static final String buyAct3_State = "buyAct3_state";
private static final String buyAll_State = "buyAll_state";
private static final String Act4_State = "Act4_state";
private static final String EAct4_State = "EAct4_state";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
buyButton = (Button) findViewById(R.id.buyButton);
buyAct2 = (Button) findViewById(R.id.buyact2);
buyAct3 = (Button) findViewById(R.id.buyact3);
buyAll = (Button) findViewById(R.id.buyall);
Activity1 = (Button) findViewById(R.id.act1);
Activity2 = (Button) findViewById(R.id.act2);
Activity3 = (Button) findViewById(R.id.act3);
EAct4 = (Button) findViewById(R.id.eact4);
Act4 = (Button) findViewById(R.id.act4);
String base64EncodedPublicKey =
"";
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.startSetup(new
IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
Log.d(TAG, "In-app Billing setup failed: " + result);
} else {
Log.d(TAG, "In-app Billing is set up OK");
}
}
});
}
public void EACT4(View view) {
EAct4.setEnabled(false);
Act4.setEnabled(true);
}
public void ACT4(View view) {
Toast.makeText(MainScreen.this,
"ACt4 Clicked", Toast.LENGTH_LONG).show();
}
public void buyClick(View view) {
mHelper.launchPurchaseFlow(this, ITEM_SKU, 10001,
mPurchaseFinishedListener, "mypurchasetoken");
}
public void buyAct2(View view) {
mHelper.launchPurchaseFlow(this, ITEM_SKU2, 10002, mPurchaseFinishedListener, "buyact2");
}
public void buyAct3(View view) {
mHelper.launchPurchaseFlow(this, ITEM_SKU3, 10003, mPurchaseFinishedListener, "buyact3");
}
public void buyAll(View view) {
mHelper.launchPurchaseFlow(this, ITEM_SKU4, 10004, mPurchaseFinishedListener, "buyall");
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (!mHelper.handleActivityResult(requestCode,
resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener
= new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result,
Purchase purchase) {
if (result.isFailure()) {
// Handle error
return;
}
if (purchase.getSku().equals(ITEM_SKU)) {
Activity1.setEnabled(true);
buyButton.setEnabled(false);
}
if (purchase.getSku().equals(ITEM_SKU2)) {
Activity2.setEnabled(true);
buyAct2.setEnabled(false);
}
if (purchase.getSku().equals(ITEM_SKU3)) {
Activity3.setEnabled(true);
buyAct3.setEnabled(false);
}
if (purchase.getSku().equals(ITEM_SKU4)) {
Activity1.setEnabled(true);
Activity2.setEnabled(true);
Activity3.setEnabled(true);
buyAll.setEnabled(false);
buyButton.setEnabled(false);
buyAct2.setEnabled(false);
buyAct3.setEnabled(false);
}
}
};
public void Activity1(View view) {
startActivity(new Intent(MainScreen.this, Click1.class));
}
public void Activity2(View view) {
startActivity(new Intent(MainScreen.this, Activity2.class));
}
public void Activity3(View view) {
startActivity(new Intent(MainScreen.this, Activity3.class));
}
#Override
public void onDestroy() {
super.onDestroy();
if (mHelper != null) mHelper.dispose();
mHelper = null;
}
#Override
protected void onPause(){
super.onPause();
if (Act4.isEnabled()){
Act4_isEnabled = true;
}
else {
Act4_isEnabled = false;
}
if (Activity1.isEnabled()){
Activity1_isEnabled = true;
}
else {
Activity1_isEnabled = false;
}
if (Activity2.isEnabled()){
Activity2_isEnabled = true;
}
else {
Activity2_isEnabled = false;
}
if (Activity3.isEnabled()){
Activity3_isEnabled = true;
}
else {
Activity3_isEnabled = false;
}
if (buyButton.isEnabled()){
buyButton_isEnabled = true;
}
else {
buyButton_isEnabled = false;
}
if (buyAct2.isEnabled()){
buyAct2_isEnabled = true;
}
else {
buyAct2_isEnabled = false;
}
if (buyAct3.isEnabled()){
buyAct3_isEnabled = true;
}
else {
buyAct3_isEnabled = false;
}
if (buyAll.isEnabled()){
buyAll_isEnabled = true;
}
else {
buyAll_isEnabled = false;
}
prefs = getSharedPreferences(prefName,MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Activity1_state,this.getLocalClassName());
editor.putBoolean(Act4_State,Act4_isEnabled);
editor.putBoolean(EAct4_State,EAct4_isEnabled);
editor.putBoolean(Activity1_state,Activity1_isEnabled);
editor.putBoolean(Activity2_State,Activity2_isEnabled);
editor.putBoolean(Activity3_State,Activity3_isEnabled);
editor.putBoolean(buyButton_State,buyButton_isEnabled);
editor.putBoolean(buyAct2_State,buyAct2_isEnabled);
editor.putBoolean(buyAct3_State,buyAct3_isEnabled);
editor.putBoolean(buyAll_State,buyAll_isEnabled);
editor.apply();
}
#Override
protected void onResume(){
super.onResume();
prefs = getSharedPreferences(prefName,MODE_PRIVATE);
Act4.setEnabled(prefs.getBoolean(Act4_State,false));
Activity1.setEnabled(prefs.getBoolean(Activity1_state,false));
Activity2.setEnabled(prefs.getBoolean(Activity2_State,false));
Activity3.setEnabled(prefs.getBoolean(Activity3_State,false));
EAct4.setEnabled(prefs.getBoolean(EAct4_State,true));
buyButton.setEnabled(prefs.getBoolean(buyButton_State,true));
buyAct2.setEnabled(prefs.getBoolean(buyAct2_State,true));
buyAct3.setEnabled(prefs.getBoolean(buyAct3_State,true));
buyAll.setEnabled(prefs.getBoolean(buyAll_State,true));
}
So Any suggestions if I have something wrong in my code?
Thanks a lot.
Try to call methods from Java part , don't call from xml using android:onClick
Use default value of the button(buy) state to false in shared preference .
and in this screen implement this if check inside oncreate() method as:
if(button(buy) state ==false)
{
//make button(buy) state enable
//make activity button state disable
}
else
{
//make button(buy) state disable
//make activity button state enable
}
And make button(buy) and activity calling button state to true/false according to result after in app purchase and also update shared prefrence state according to result