Application crashes when SetContentView set back to main activity - java

When I set content view on another layout its works perfectly, but when I set content view back to main layout its crashes.
My Main class and everything on it. Everything happens in public void firstTime().
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private MapFragment mapsFragment;
static MainActivity can;
static FloatingActionButton fab;
static FloatingActionButton show;
private String encoded_string;
private Bitmap bitmap;
private String picturePath;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
private void initializeMapsFragment() {
FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction();
mapsFragment = new MapFragment();
SupportMapFragment supportMapFragment = mapsFragment;
mTransaction.add(R.id.map, supportMapFragment);
mTransaction.commit();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("--***** MAP ", "::Loading Map");
can = this;
setContentView(R.layout.activity_main);
initializeMapsFragment();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fab = (FloatingActionButton) findViewById(R.id.fab);
show = (FloatingActionButton) findViewById(R.id.show);
show.hide();
fab.hide();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
callPopup();
}
});
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stats();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
Button searchButton = (Button) findViewById(R.id.searchButton);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText searchView = (EditText) findViewById(R.id.searchView1);
String text = searchView.getText().toString();
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input
// text
addresses = geocoder.getFromLocationName(text, 3);
if (addresses != null && !addresses.equals(""))
search(addresses);
} catch (Exception e) {
}
}
});
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
protected void search(List<Address> addresses) {
Address address = (Address) addresses.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
MapFragment.mapView.moveCamera(CameraUpdateFactory.newLatLng(latLng));
MapFragment.mapView.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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);
}
#RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
FragmentManager fm = getFragmentManager();
android.support.v4.app.FragmentManager sFm = getSupportFragmentManager();
int id = item.getItemId();
if (id == R.id.nav_camera) {
if (!mapsFragment.isAdded())
sFm.beginTransaction().add(R.id.map, mapsFragment).commit();
else
sFm.beginTransaction().show(mapsFragment).commit();
} else if (id == R.id.nav_share) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Check this app out --> link.kys";
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Best Free Parking app");
sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void firstTime() {
setContentView(R.layout.firsttime);
(findViewById(R.id.cancelBut))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
setContentView(R.layout.activity_main);
}
});
}
public static void load(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(can);
if (!prefs.getBoolean("firstTime", false)) {
can.firstTime();
//SharedPreferences.Editor editor = prefs.edit();
//editor.putBoolean("firstTime", true);
//editor.commit();
}
}
private void stats() {
setContentView(R.layout.stats);
RatingBar ratingbar = (RatingBar) findViewById(R.id.ratingBar);
ratingbar.setRating((float) 2.0);
ratingbar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
ratingBar.setRating((float) 2.0);
}
});
((Button) findViewById(R.id.cancBut)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setContentView(R.layout.content_main);
}
});
}
private void callPopup() {
final PopupWindow popupWindow;
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
popupWindow = new PopupWindow(popupView,
DrawerLayout.LayoutParams.WRAP_CONTENT, DrawerLayout.LayoutParams.MATCH_PARENT,
true);
popupWindow.setTouchable(true);
popupWindow.setFocusable(true);
popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
final EditText name = (EditText) popupView.findViewById(R.id.edtimageName);
((Button) popupView.findViewById(R.id.plcBut)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectPhoto();
}
});
((Button) popupView.findViewById(R.id.saveBtn))
.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void onClick(View arg0) {
new Encode_image().execute();
popupWindow.dismiss();
}
});
((Button) popupView.findViewById(R.id.cancelbtutton))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
popupWindow.dismiss();
}
});
}
private void selectPhoto() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 10);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 10 && resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
}
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
private class Encode_image extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
bitmap = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
bitmap.recycle();
byte[] array = stream.toByteArray();
encoded_string = Base64.encodeToString(array, 0);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
makeRequest();
}
}
private void makeRequest() {
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST, "http://185.80.129.86/upload.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> map = new HashMap<>();
map.put("encoded_string", encoded_string);
map.put("image_name", "testing123.jpg");
return map;
}
};
requestQueue.add(request);
}
}
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.robertas.parking.bestfreeparking, PID: 3501
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:3936)
at android.view.ViewGroup.addView(ViewGroup.java:3786)
at android.view.ViewGroup.addView(ViewGroup.java:3758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:810)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:143)
at com.robertas.parking.bestfreeparking.MainActivity$4.onClick(MainActivity.java:245)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Make changes this
Log.d("--***** MAP ", "::Loading Map");
can = this;
setContentView(R.layout.activity_main);
initializeMapsFragment();

Related

FirebaseRecyclerAdapter OnItemClick from fragment to fragment

I'm using the firebaseRecyclerAdaper on a fragment and i want to open an item from de populated list from firebase and send the data to a new fragment. Can u guys tell me please how can i start the FragmentDetail from the onCLickListener on FragmentAllPosts and pass the PostModel parameter to it?
Main Activity:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "TAG" ;
private FirebaseAuth firebaseAuth;
private DatabaseReference databaseReference , postsRef;
private StorageReference profileImgRef;
private CircleImageView circleImageViewMain;
private TextView nameEdtTxt, emailEdtTxt;
Fragment fragment= null;
private RecyclerView recyclerView;
private FloatingActionButton fab;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
progressDialog= new ProgressDialog(this);
progressDialog.setMessage("Please wait!");
progressDialog.setCanceledOnTouchOutside(false);
//Initialize Firebase modules
firebaseAuth=FirebaseAuth.getInstance();
databaseReference= FirebaseDatabase.getInstance().getReference().child("users");
postsRef= FirebaseDatabase.getInstance().getReference().child("posts");
profileImgRef= FirebaseStorage.getInstance().getReference();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header = navigationView.getHeaderView(0);
circleImageViewMain = (CircleImageView) header.findViewById(R.id.circleImageHeader);
nameEdtTxt = (TextView) header.findViewById(R.id.txtName);
emailEdtTxt =(TextView)header.findViewById(R.id.txtEmail);
if (firebaseAuth.getCurrentUser()!=null){
LoadUserData(CheckUserDataBase());
}
ViewPager vp_pages= (ViewPager) findViewById(R.id.vp_pages);
PagerAdapter pagerAdapter=new FragmentAdapter(getSupportFragmentManager());
vp_pages.setAdapter(pagerAdapter);
TabLayout tbl_pages= (TabLayout) findViewById(R.id.tabs);
tbl_pages.setupWithViewPager(vp_pages);
tbl_pages.setTabTextColors(ColorStateList.valueOf(Color.parseColor("#FFFFFF")));
tbl_pages.setHorizontalScrollBarEnabled(true);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fragment= new AddPostFrag();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction= fragmentManager.beginTransaction();
transaction.add(R.id.add_post_container, fragment).commit();
fab.hide();
}
});
}
class FragmentAdapter extends FragmentPagerAdapter {
public FragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new FragmentAllPosts();
case 1:
return new FragmentLosts();
case 2:
return new FragmentFounds();
}
return null;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
//
//Your tab titles
//
case 0:return "All";
case 1:return "Losts";
case 2: return "Founds";
default:return null;
}
}
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser user= firebaseAuth.getCurrentUser();
if (user == null){
SendUserToLogin();
} else {
CheckUserDataBase();
}
}
public static class PostsViewHolder extends RecyclerView.ViewHolder {
CircleImageView circleImageView;
ImageView imageView;
TextView authorNdate, location, description;
public PostsViewHolder(#NonNull View itemView) {
super(itemView);
circleImageView= itemView.findViewById(R.id.circleImageView_cv);
imageView= itemView.findViewById(R.id.imageView_cv);
authorNdate= itemView.findViewById(R.id.author_date_cv);
location = itemView.findViewById(R.id.location_cv);
description = itemView.findViewById(R.id.description_cv);
}
}
private void UpdateHome() {
}
private void LoadUserData(final String uid) {
try {
final File localFile =File.createTempFile("profile","png");
StorageReference filepath=profileImgRef.child(uid).child("profileImg/profile.png");
filepath.getFile(localFile)
.addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Picasso.get()
.load(localFile)
.placeholder(R.drawable.ic_account)
.into(circleImageViewMain);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this,
"Profile photo not found, please update your profile!",
Toast.LENGTH_SHORT).show();
SendUserToSetup();
}
});
} catch (IOException e) {
e.printStackTrace();
}
databaseReference.child(uid).child("userInfo").addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("name")){
String name = dataSnapshot.child("name").getValue().toString();
nameEdtTxt.setText(name);
String email = dataSnapshot.child("email").getValue().toString();
emailEdtTxt.setText(email);
} else {
Toast.makeText(MainActivity.this,
"Profile name does not exists, please update your profile",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}
);
}
#Override
protected void onStop() {
super.onStop();
}
private String CheckUserDataBase() {
final String userID =firebaseAuth.getCurrentUser().getUid();
databaseReference.addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.child(userID).hasChild("userInfo")){
SendUserToSetup();
} else {
UpdateHome();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}
);
return userID;
}
private void SendUserToSetup() {
Intent i = new Intent(this,SetupActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
}
private void SendUserToLogin() {
Intent i = new Intent(this,LoginActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (getSupportFragmentManager().getBackStackEntryCount() >0)
{
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
} else
{
super.onBackPressed();
}
fab.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
switch (id){
case R.id.nav_home:
super.onResume();
if (fragment!=null){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction= fragmentManager.beginTransaction();
transaction.remove(fragment).commit();
fab.show();
}
break;
case R.id.nav_profile:
super.onPause();
break;
case R.id.nav_my_posts:
super.onPause();
break;
case R.id.nav_messeges:
super.onPause();
break;
case R.id.nav_settings:
super.onPause();
break;
case R.id.nav_logout:
SendUserToLogin();
firebaseAuth.signOut();
break;
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Fragment with the FirebaseRecyclerAdapter
public class FragmentAllPosts extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private DatabaseReference postsRef;
private Context context= getContext();
Fragment mFragment;
Bundle mBundle;
public FragmentAllPosts() {
// Required empty public constructor
}
public static FragmentAllPosts newInstance(String param1, String param2) {
FragmentAllPosts fragment = new FragmentAllPosts();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
private RecyclerView recyclerAllPosts;
private ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
progressDialog= new ProgressDialog(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_all_posts,container,false);
postsRef= FirebaseDatabase.getInstance().getReference().child("posts");
recyclerAllPosts= v.findViewById(R.id.recycler_all_posts);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerAllPosts.setLayoutManager(linearLayoutManager);
return v;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context=context;
}
#Override
public void onStart() {
super.onStart();
progressDialog.show();
FirebaseRecyclerOptions<PostsModel> options=
new FirebaseRecyclerOptions.Builder<PostsModel>()
.setQuery(postsRef,PostsModel.class)
.setLifecycleOwner(this)
.build();
FirebaseRecyclerAdapter<PostsModel,PostsViewHolder> adapter=
new FirebaseRecyclerAdapter<PostsModel, PostsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final PostsViewHolder holder, int position, #NonNull final PostsModel model) {
String processedTime= CalculateTime(model.getData());
Picasso.get().load(Uri.parse(model.getUserImg())).into(holder.circleImageView);
Picasso.get().load(Uri.parse(model.getImageUri())).into(holder.imageView);
holder.authorNdate.setText(model.getAuthor()+" updated "+processedTime);
holder.location.setText(model.getLocation());
holder.description.setText(model.getDescription());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment frag= new FragmentDetail();
getFragmentManager().beginTransaction().replace(R.id.add_post_container,frag)
.addToBackStack(null).commit();
}
});
}
#NonNull
#Override
public PostsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view= LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.card_view,viewGroup,false );
PostsViewHolder viewHolder= new PostsViewHolder(view);
return viewHolder;
}
};
recyclerAllPosts.setAdapter(adapter);
progressDialog.dismiss();
adapter.startListening();
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
public String CalculateTime(String inputTime){
String timeOut;
Calendar currentTime= Calendar.getInstance();
SimpleDateFormat dateFormat= new SimpleDateFormat(getString(R.string.date_format));
dateFormat.format(currentTime.getTime());
SimpleDateFormat postFormat= new SimpleDateFormat(getString(R.string.date_format));
Calendar postTime = Calendar.getInstance();
try {
Date datePost=postFormat.parse(inputTime);
postTime.setTime(datePost);
} catch (ParseException e) {
e.printStackTrace();
}
long timeCurrent= currentTime.getTimeInMillis();
long timePost = postTime.getTimeInMillis();
long diff= timeCurrent- timePost;
long minutes= diff/(60*1000);
long hours = diff/(60 * 60 * 1000);
long days = diff/(24 * 60 * 60 * 1000);
if (minutes<59 && minutes>1){
timeOut=Long.toString(minutes)+" mins ago";
} else if (minutes<1){
timeOut=" just now";
}else if (hours<24 && minutes>59){
timeOut=Long.toString(hours)+" hour(s) ago";
}else {
timeOut=Long.toString(days)+" day(s) ago";
}
return timeOut;
}
static class PostsViewHolder extends RecyclerView.ViewHolder {
CircleImageView circleImageView;
ImageView imageView;
TextView authorNdate, location, description;
public PostsViewHolder(#NonNull View itemView) {
super(itemView);
itemView.setTag(this);
circleImageView= itemView.findViewById(R.id.circleImageView_cv);
imageView= itemView.findViewById(R.id.imageView_cv);
authorNdate= itemView.findViewById(R.id.author_date_cv);
location = itemView.findViewById(R.id.location_cv);
description = itemView.findViewById(R.id.description_cv);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Detail Fragment:
public class FragmentDetail extends Fragment {
public FragmentDetail() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_detail, container, false);
}
}
I'd suggest a read on the documentation. Passing data between two activities should be done via interfaces.
As suggested by the official site

I have created a wallpapers app using viewpager and urls of images but I am not able to set wallpapers I am placing my Urls in string

This is my mainactivity class and I am using my urls in the string. Anyone please tell me how to set wallpapers using multiple urls. I am using multiple urls to show in viewpager its working but I can't set wallpapers.
This is my main activity class.
I want to set wallpapers on floating button onclick listener
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private String[] imageUrls = new String[]{
"https://i.jj.cc/MGTTwJ7Q/Ant-Man-474b00d1-4bdc-3ea6-88a3-1702c46f061c.jpg",
"https://i.jj.cc/SKvKN1dt/fdg-min.jpg",
"https://i.jj.cc/fLSR37gW/uhd-antman18-min.jpg",
"https://i.jj.cc/Gt0hvBZF/uhd-antman7-min.jpg",
"https://i.jj.cc/ryWpMJrQ/Antman-And-The-Wasp-d4a753af-1dd1-4df2-aeb6-d39c732fd16a.jpg",
"https://i.jj.cc/RVLVnZGt/uhd-antman21-min.jpg",
"https://i.jj.cc/t4RRdGmM/Ant-man-and-the-wasp-a294bb80-e6f9-41c1-bf46-07af64e3e348.jpg",
"https://i.jj.cc/y8f1vpMY/Antman-d8033f49-b33c-4cd4-b3ca-651417df20da.jpg",
"https://i.jj.cc/yNkV5XKh/Antman-Abstract-HD-05ef2c84-e5d3-41e9-afa1-1400c315bf06.jpg",
"https://i.jj.cc/8C91VJk2/IMG-0139.jpg",
"https://i.jj.cc/Znh4CGdj/antman-70390c1f-2d63-41ea-a487-e34668167e7e.jpg",
"https://i.jj.cc/vTLM907y/antman-2fde23ba-9eac-4f11-acf7-b872b9b71121.jpg",
"https://i.jj.cc/66dBDpkP/Antman-d353b93b-5c57-4363-ad92-4a974423d2b5.jpg",
"https://i.jj.cc/rFMqcLcw/Antman-df2e8adb-b0a0-42b6-ade7-38d041349ed1.jpg",
"https://i.jj.cc/YCSkGfvc/Antman-32cb0b83-f4b6-4a24-854a-913b593c0291.jpg",
"https://i.jj.cc/zGPNnbhy/razakbaap49.jpg",
"https://i.jj.cc/tgZjDqd2/antman05-uhd.jpg"
};
private int indexOfImage = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ViewPager viewPager = findViewById(R.id.view_pager);
ViewPagerAdapter adapter = new ViewPagerAdapter(this, imageUrls);
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new MyPageChangeListener());
FloatingActionButton floatingActionButton = (FloatingActionButton)findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private class MyPageChangeListener implements ViewPager.OnPageChangeListener {
#Override
public void onPageScrolled(int i, float v, int i1) {
}
#Override
public void onPageSelected(int i) {
MainActivity.this.indexOfImage = i;
}
#Override
public void onPageScrollStateChanged(int i) {
}
}
}
This is my viewpager adapter class
public class ViewPagerAdapter extends PagerAdapter {
private Context context;
private String[] imageUrls;
ViewPagerAdapter(Context context, String[] imageUrls) {
this.context = context;
this.imageUrls = imageUrls;
}
#Override
public int getCount() {
return imageUrls.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
Picasso.with(context)
.load(imageUrls[position])
.fit()
.centerCrop()
.error(R.drawable.ic_error_outline_black_24dp)
.into(imageView);
container.addView(imageView);
return imageView;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
}
}
Add permission in manifest
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
Add this AsyncTask class in your MainActivity
public class SetWallpaper extends AsyncTask<String, Void, Bitmap> {
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
#Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap = null;
try {
bitmap = Picasso.get().load(params[0]).get();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute (Bitmap result) {
super.onPostExecute(result);
WallpaperManager wallpaperManager = WallpaperManager.getInstance(getBaseContext());
try {
wallpaperManager.setBitmap(result);
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Wallpaper changed", Toast.LENGTH_SHORT).show();
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
protected void onPreExecute () {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading image...");
progressDialog.setCancelable(false);
progressDialog.show();
}
}
Then try
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SetWallpaper sw = new SetWallpaper();
sw.execute(imageUrls[indexOfImage])
}
});

com.google.firebase.database.DatabaseException: Invalid Firebase Database path

when I try to store my location's latitude and longitude on my database I get this error
01-02 11:54:30.820 24616-24616/? E/Zygote: no v2
01-02 11:54:30.830 24616-24616/? E/SELinux: [DEBUG]
get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
01-02 11:54:33.823 24616-24616/com.rescuex_za.rescuex
E/AndroidRuntime: FATAL EXCEPTION: main
Process:
com.rescuex_za.rescuex,
PID: 24616
com.google.firebase.database.
DatabaseException:
Invalid Firebase Database path:
https://rescuex-8f9c9.firebaseio.com/Users/NcZ0McVHEuRfaMv39gHbDlpjI1X2. Firebase Database paths must not contain
'.', '#', '$', '[', or ']'
at com.google.android.gms.internal.zzelv.zzqh(Unknown Source)
at com.google.firebase.database.DatabaseReference.child(Unknown Source)
at com.rescuex_za.rescuex.MenuActivity.addEmergencyChat(MenuActivity.java:247)
at com.rescuex_za.rescuex.MenuActivity.access$100(MenuActivity.java:55)
at com.rescuex_za.rescuex.MenuActivity$1.onClick(MenuActivity.java:106)
at android.view.View.performClick(View.java:5076)
at android.view.View$PerformClick.run(View.java:20279)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5910)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
this is my class where i send the location's latitude AND Longitude
public class MenuActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,
OnMapReadyCallback,
ConnectionCallbacks,
OnConnectionFailedListener {
private static final String TAG = "RescueX";
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private DatabaseReference mLocationDatabase;
ImageButton fakeCallBtn;
Button mRescue;
ImageButton notif;
ImageButton flash;
private Double lati;
private GoogleMap mMap;
LocationManager locationManager;
private DatabaseReference mRootRef;
private String mCurrentUserId;
private String userName;
private DatabaseReference user_id;
private String mChatUser;
private String message;
private String value_lat = null;
private String value_long = null;
private FirebaseAuth mAuth;
private DatabaseReference mUserRef;
LocationTrack locationTrack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
FirebaseApp.initializeApp(this);
mRootRef = FirebaseDatabase.getInstance().getReference();
mLocationDatabase = mRootRef.child("EmergencyMessages");
mAuth = FirebaseAuth.getInstance();
mCurrentUserId = mAuth.getCurrentUser().getUid();
user_id = FirebaseDatabase.getInstance().getReference().child("Users").child(mCurrentUserId);
mChatUser = user_id.getRef().toString();
buildGoogleApiClient();
mRescue = (Button)findViewById(R.id.rescue);
mRescue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addEmergencyMessage();
addEmergencyChat();
}
});
fakeCallBtn = (ImageButton) findViewById(R.id.fake_callbtn);
fakeCallBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent fakecallIntent = new Intent(MenuActivity.this, FakeCalling.class);
startActivity(fakecallIntent);
}
});
flash = (ImageButton) findViewById(R.id.flash);
flash.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent flashIntent = new Intent(MenuActivity.this, FlashLight.class);
startActivity(flashIntent);
}
});
notif = (ImageButton) findViewById(R.id.notification_btn);
notif.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent notificationIntent = new Intent(MenuActivity.this, Notifications.class);
startActivity(notificationIntent);
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("RescueX ");
if (mAuth.getCurrentUser() != null) {
mUserRef = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid());
mUserRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userName = dataSnapshot.child("name").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Log.e("fist","error");
return ;
}
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//get latitude
double latitude = location.getLatitude();
//get longitude
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
String str = addressList.get(0).getCountryName() + ",";
str += addressList.get(0).getLocality();
mMap.addMarker(new MarkerOptions().position(latLng).title(str));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10.2f));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
private void addEmergencyChat() {
value_lat = String.valueOf(mLastLocation.getLatitude()).replace(".","d");
value_long = String.valueOf(mLastLocation.getLongitude()).replace(".","d");
String current_user_ref="Emergency_Messages/"+mCurrentUserId+"/"+mChatUser;
String chat_user_ref= "Emergency_Messages/"+mChatUser+"/"+mCurrentUserId;
DatabaseReference chat_push_key = mRootRef.child("Emergency_Messages").child(mCurrentUserId).
child(mChatUser).push();
String push_key = chat_push_key.getKey();
Map messageMap = new HashMap();
messageMap.put("userName", userName);
messageMap.put("latitude",value_lat);
messageMap.put("longitude", value_long);
messageMap.put("from",mCurrentUserId);
messageMap.put("seen",false);
messageMap.put("time", ServerValue.TIMESTAMP);
Map messageUserMap = new HashMap();
messageUserMap.put(current_user_ref+ "/"+push_key,messageMap);
messageUserMap.put(chat_user_ref+ "/"+push_key,messageMap);
mRootRef.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError!=null){
Log.d("TAG",databaseError.getMessage().toString());
}
}
});
}
private void addEmergencyMessage() {
mRootRef.child("Emergency_Chat").child(mCurrentUserId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChild(mChatUser)){
Map chatAddMap = new HashMap();
chatAddMap.put("seen",false);
chatAddMap.put("timestamp", ServerValue.TIMESTAMP);
Map chatUserMap = new HashMap();
chatUserMap.put("Emergency_Chat/"+mCurrentUserId+"/"+mChatUser, chatAddMap);
chatUserMap.put("Emergency_Chat/"+mChatUser+"/"+mCurrentUserId, chatAddMap);
mRootRef.updateChildren(chatUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError!= null){
Toast.makeText(MenuActivity.this, "Error: "+databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
mGoogleApiClient.connect();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser == null){
sendToStart();
} else {
mUserRef.child("online").setValue("true");
}
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected())
mGoogleApiClient.disconnect();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser != null) {
mUserRef.child("online").setValue(ServerValue.TIMESTAMP);
}
}
private void sendToStart() {
Intent startIntent = new Intent(MenuActivity.this, Home.class);
startActivity(startIntent);
finish();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if(item.getItemId()== R.id.log_out){
FirebaseAuth.getInstance().signOut();
sendToStart();
}
//noinspection SimplifiableIfStatement
if (item.getItemId() == R.id.action_settings) {
Intent notifIntent= new Intent(MenuActivity.this, Settings.class);
startActivity(notifIntent);
}
if(item.getItemId() == R.id.all_users){
Intent usersIntent= new Intent(MenuActivity.this, UsersActivity.class);
startActivity(usersIntent);
}
return true;
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_profile_layout) {
Intent searchIntent = new Intent(MenuActivity.this, Profile.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_users_activity) {
Intent searchIntent = new Intent(MenuActivity.this, UsersActivity.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_history_layout) {
Intent searchIntent = new Intent(MenuActivity.this, History.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_help_layout) {
Intent searchIntent = new Intent(MenuActivity.this, Help.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_feedback_layout) {
Intent searchIntent = new Intent(MenuActivity.this, Feedback.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_signout_layout) {
Intent searchIntent = new Intent(MenuActivity.this, SignOut.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_friends_layout) {
Intent searchIntent = new Intent(MenuActivity.this, FriendsActivity.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_share) {
Intent searchIntent = new Intent(MenuActivity.this, Share.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#SuppressLint("MissingPermission")
#Override
public void onConnected(#Nullable Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null){
value_lat = String.valueOf(mLastLocation.getLatitude()).replace(".","d");
value_long = String.valueOf(mLastLocation.getLongitude()).replace(".","d");
}
}
#Override
public void onConnectionSuspended(int cause) {
Log.i(TAG,"Connection suspended");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.i(TAG, " Connection Failed "+ connectionResult.getErrorMessage());
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
What I want to do is read the location that is being displayed when the user open's a page containing the above code, after reading the user's location I want to store those values in my database which I will later retrieve in another class.
Replacing the . with * didn't really work and from what Cao Minh Vu suggested that it might have a problem the mChatUser was pointing to a null value so I sorted that out and for may latitude and longitude is used:
String lat = String.ValueOf(latitude.getLatitude());
String long = String.valueOf(longitude.getLongitude());
Thanks to everyone who commented on my Post, I wasn't going to identify the problem because there's too many lines in my code it was hard to identify which one was giving me a problem

Android - Fragment not attached to activity

I have an activity which loads a fragment but when I press back button on the fragment it shows the error :-
"java.lang.IllegalStateException: Fragment ProductFragment{c46ba8a} not attached to Activity"
Code is below:-
Product Fragment:
public class ProductFragment extends Fragment implements TabLayout.OnTabSelectedListener, ViewPager.OnPageChangeListener {
private static final String PRODUCT_DATA = "product_data";
private TabLayout tabLayout;
private ViewPager viewPager;
NestedScrollView nestedScrollView;
//RecyclerView listView;
//ImageView ivHeader;
ProgressDialog pd;
Bundle bundle;
ViewPager viewPager1;
private LinearLayout pager_indicator;
public String DATA = "data";
public String PRODUCTS = "products";
//public String SPRODUCTS = "sproducts";
public String ID = "id";
public String NAME = "productName";
public String IMAGEURL = "productImg1";
public String DESCRIPTION = "description";
public String PRICE = "price";
public String DELIVERYTYPE = "deliverytype";
//String url = "https://chiraggohil.000webhostapp.com/product.php";
String url = "http://www.thinkdream.in/lunchbox2/product_api/getProductList";
String sliderImageUrl = "http://www.thinkdream.in/lunchbox2/assets/images/product/2.png";
ArrayList<Product> list = new ArrayList<>();
ArrayList<Product> sliderImagesList = new ArrayList<>();
private int dotsCount = 0;
private ImageView[] dots;
private static int CURRENT_PAGE = 0;
ViewPagerSliderAdapter viewPagerSliderAdapter;
ConnectivityManager cm;
NetworkInfo activeNetwork;
boolean isConnected;
//private boolean load = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_product, container, false);
viewPager1 = (ViewPager) v.findViewById(R.id.viewpager);
//listView = (RecyclerView) v.findViewById(R.id.gvProducts);
nestedScrollView = (NestedScrollView) v.findViewById(R.id.nestedSV);
pager_indicator = (LinearLayout) v.findViewById(R.id.viewPagerCountDots);
//nestedScrollView.setFillViewport(true);
//ivHeader = (ImageView) v.findViewById(R.id.ivHeader);
bundle = new Bundle();
tabLayout = (TabLayout) v.findViewById(R.id.tabLayout);
viewPager = (ViewPager) v.findViewById(R.id.pager);
viewPagerSliderAdapter = new ViewPagerSliderAdapter(getActivity(), sliderImagesList);
cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
activeNetwork = cm.getActiveNetworkInfo();
isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (savedInstanceState != null) {
sliderImagesList = savedInstanceState.getParcelableArrayList(PRODUCT_DATA);
viewPager1.setAdapter(viewPagerSliderAdapter);
viewPagerSliderAdapter.notifyDataSetChanged();
} else {
if (isConnected) {
new GetUrlData(getActivity()).execute();
} else {
Toast.makeText(getActivity(), "You are not connected to the internet!", Toast.LENGTH_SHORT).show();
}
}
tabLayout.addTab(tabLayout.newTab().setText("Pizza"));
tabLayout.addTab(tabLayout.newTab().setText("Sandwich"));
tabLayout.addTab(tabLayout.newTab().setText("Burger"));
Pager adapter = new Pager(getChildFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(this);
viewPager1.addOnPageChangeListener(this);
return v;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(PRODUCT_DATA, sliderImagesList);
}
#Override
public void onResume() {
super.onResume();
pager_indicator.removeAllViews();
//Picasso.with(getActivity()).load(sliderImageUrl).into(ivHeader);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for (int i = 0; i < dotsCount; i++) {
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
}
if (position >= dotsCount) {
dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
} else {
dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
private class GetUrlData extends AsyncTask<Void, Void, Void> {
GetUrlData(Context context) {
pd = new MyCustomProgressDialog(context, R.style.NewDialog);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.setCancelable(false);
pd.show();
}
#Override
protected Void doInBackground(Void... voids) {
ServiceHandler sh = new ServiceHandler();
String result = sh.Getdata(url);
//list.clear();
sliderImagesList.clear();
if (result != null) {
try {
list.clear();
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray(DATA);
//JSONArray jsonArray = jsonObject1.getJSONArray(PRODUCTS);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
String id = jsonObject2.getString(ID);
String name = jsonObject2.getString(NAME);
String imgpath = jsonObject2.getString(IMAGEURL);
String desc = jsonObject2.getString(DESCRIPTION);
String price = jsonObject2.getString(PRICE);
//String deliverytype = jsonObject2.getString(DELIVERYTYPE);
Product product = new Product();
product.setId(id);
product.setProductName(name);
product.setProductImage(imgpath);
product.setProductDescription(desc);
product.setProductPrice(price);
//list.add(product);
sliderImagesList.add(product);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
pd.dismiss();
// Picasso.with(getActivity()).load(sliderImageUrl).into(ivHeader);
if(isAdded()) {
viewPagerSliderAdapter = new ViewPagerSliderAdapter(getActivity(), sliderImagesList);
Log.e("slider",sliderImagesList.toString());
viewPager1.setAdapter(viewPagerSliderAdapter);
viewPagerSliderAdapter.notifyDataSetChanged();
slider();
setUiPageViewController();
}else {
Log.e("not added","not added");
}
}
}
private void slider() {
int NUM_PAGES = sliderImagesList.size();
final android.os.Handler handler = new android.os.Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
CURRENT_PAGE = viewPager1.getCurrentItem();
if (CURRENT_PAGE == 2) {
CURRENT_PAGE = -1;
}
viewPager1.setCurrentItem(CURRENT_PAGE + 1, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(runnable);
}
}, 100, 4000);
}
private void setUiPageViewController() {
dotsCount = 3;
dots = new ImageView[dotsCount];
for (int i = 0; i < dotsCount; i++) {
dots[i] = new ImageView(getActivity());
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(4, 0, 4, 0);
pager_indicator.addView(dots[i], params);
}
dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
}
I don't know where I am wrong. I have searched for the error and even tried the solution from the link below:
Fragment MyFragment not attached to Activity
I ask questions on SO but I don't get response/answers. May be there is a small mistake, grammatical/formating problem, or a duplicate question but there is a possibility of my case that is different then others.
So please help and response.
Thanks.
--Edited--
HomeActivity :
public class HomeActivity extends AppCompatActivity implements View.OnClickListener {
DrawerLayout drawerLayout;
NavigationView navigationView;
Toolbar toolbar;
TextView tvActionTitle;
SessionManager sessionManager;
GPSTracker gps;
int i = 0;
private FrameLayout redCircle;
private TextView countTextView;
int cartcount = 0;
Menu menu;
LunchBoxDB lunchBoxDB;
private String uid;
SharedPreferences pref;
private int totalquantity = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = (Toolbar) findViewById(R.id.toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.navigation);
tvActionTitle = (TextView) findViewById(R.id.tvActionTitle);
Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/Quicksand_Bold_Oblique.otf");
tvActionTitle.setTypeface(custom_font);
setSupportActionBar(toolbar);
//getSupportActionBar().setDisplayShowTitleEnabled(false);
lunchBoxDB = new LunchBoxDB(this);
pref = getSharedPreferences("loginPref", Context.MODE_PRIVATE);
uid = pref.getString("id", null);
ProductFragment pf = new ProductFragment();
getFragmentManager().beginTransaction().replace(R.id.content_frame, pf).commit();
sessionManager = new SessionManager(this);
toolbar.setNavigationIcon(R.mipmap.ic_menu_white_24dp);
toolbar.setNavigationOnClickListener(this);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Fragment frag = null;
int itemId = item.getItemId();
if (itemId == R.id.nav_home) {
drawerLayout.closeDrawers();
Intent i = new Intent(HomeActivity.this, HomeActivity.class);
startActivity(i);
HomeActivity.this.finish();
} else if (itemId == R.id.nav_profile) {
frag = new AccountFragment();
getFragmentManager().beginTransaction().replace(R.id.content_frame, frag).addToBackStack("Account").commit();
drawerLayout.closeDrawers();
} else if (itemId == R.id.nav_order) {
drawerLayout.closeDrawers();
OrdersFragment of = new OrdersFragment();
getFragmentManager().beginTransaction().replace(R.id.content_frame, of).addToBackStack("Orders").commit();
} else if (itemId == R.id.nav_store_locator) {
Intent i = new Intent(HomeActivity.this, LocationActivity.class);
startActivity(i);
drawerLayout.closeDrawers();
} else if (itemId == R.id.nav_logout) {
drawerLayout.closeDrawers();
sessionManager.logoutUser();
} else if (itemId == R.id.nav_help) {
drawerLayout.closeDrawers();
Intent i = new Intent(Intent.ACTION_DIAL);
i.setData(Uri.parse("tel:+918460765785"));
startActivity(i);
} else if (itemId == R.id.nav_corpinquiry) {
drawerLayout.closeDrawers();
CorpInquiryFragment crpf = new CorpInquiryFragment();
getFragmentManager().beginTransaction().replace(R.id.content_frame, crpf).addToBackStack("CorpInquiry").commit();
}
return false;
}
});
}
private void setNavigationDrawer() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
drawerLayout.openDrawer(GravityCompat.START);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.nav_drawer, menu);
final MenuItem alertMenuItem = menu.findItem(R.id.shopping_bag);
FrameLayout rootView = (FrameLayout) alertMenuItem.getActionView();
redCircle = (FrameLayout) rootView.findViewById(R.id.view_alert_red_circle);
countTextView = (TextView) rootView.findViewById(R.id.view_alert_count_textview);
rootView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onOptionsItemSelected(alertMenuItem);
}
});
badgeupdate();
return super.onCreateOptionsMenu(menu);
}
void badgeupdate() {
SQLiteDatabase db = lunchBoxDB.getReadableDatabase();
String query = "select sum(quantity) from cart where uid = " + uid;
Cursor c = db.rawQuery(query, null);
if (c != null && c.moveToFirst()) {
totalquantity = c.getInt(0);
}
c.close();
cartcount = totalquantity;
countTextView.setText(String.valueOf(cartcount));
redCircle.setVisibility((cartcount > 0) ? VISIBLE : GONE);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.shopping_bag) {
SharedPreferences pref = this.getSharedPreferences("couponPref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("discount", null);
editor.apply();
CartFragment cf = new CartFragment();
getFragmentManager().beginTransaction().replace(R.id.content_frame, cf, "CartFragment").addToBackStack(null).commit();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
}/*else if(i==0){
Toast.makeText(this, "Press back again to exit!", Toast.LENGTH_SHORT).show();
i=1;
}*/ else {
//i=0;
super.onBackPressed();
}
}
#Override
protected void onResume() {
super.onResume();
gps = new GPSTracker(this);
}
#Override
public void onClick(View view) {
setNavigationDrawer();
}
}
Logcat error :
FATAL EXCEPTION: main
Process: com.pisac.foodrestaurant, PID: 29700
java.lang.IllegalStateException: Fragment ProductFragment{13525074} not attached to Activity
at android.app.Fragment.getResources(Fragment.java:800)
at com.pisac.foodrestaurant.ProductFragment.onPageSelected(ProductFragment.java:149)
at android.support.v4.view.ViewPager.dispatchOnPageSelected(ViewPager.java:1967)
at android.support.v4.view.ViewPager.scrollToItem(ViewPager.java:685)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:669)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:630)
at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:622)
at com.pisac.foodrestaurant.ProductFragment$1.run(ProductFragment.java:244)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5910)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
You have problem with the line
pd.dismiss();
in onPostExecute of your GetUrlData. Put it inside if (isAdded ()) As per the answer of the question you reffered in your question. Your dialog uses the context of the activity.
EDIT
Add an if block in onPageSelected method that checks if Fragment if attached i.e.
#Override
public void onPageSelected(int position) {
if(!isAdded ())
return;
for (int i = 0; i < dotsCount; i++) {
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
}
if (position >= dotsCount) {
dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
} else {
dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
}
Thanks for helping me.
I got the answer.
I added onStop in the ProductFragment code as below :
#Override
public void onStop() {
viewPager1.setAdapter(null);
super.onStop();
}
and update the onResume :
#Override
public void onResume() {
super.onResume();
pager_indicator.removeAllViews();
if(viewPagerSliderAdapter==null){
new GetUrlData(getActivity()).execute();
}
}
Thanks once again.

Non-functioning of the application when adding Facebook Like Button

I am working on adding Facebook Like button to the application everything is normal but the problem when running the application and do not know what exactly is the problem
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
public static final String PROPERTY_REG_ID = "notifyId";
private static final String PROPERTY_APP_VERSION = "appVersion";
GoogleCloudMessaging gcm;
SharedPreferences preferences;
String reg_cgm_id;
static final String TAG = "MainActivity";
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Settings.sdkInitialize(this);
LikeView likeView = (LikeView) findViewById(R.id.like_view);
likeView.setObjectId("https://m.facebook.com/DZ.4.EverR");
likeView.setLikeViewStyle(LikeView.Style.STANDARD);
likeView.setAuxiliaryViewPosition(LikeView.AuxiliaryViewPosition.INLINE);
likeView.setHorizontalAlignment(LikeView.HorizontalAlignment.CENTER);
preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
//show admob banner ad
mAdView = (AdView) findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
mAdView.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
}
#Override
public void onAdFailedToLoad(int error) {
mAdView.setVisibility(View.GONE);
}
#Override
public void onAdLeftApplication() {
}
#Override
public void onAdOpened() {
}
#Override
public void onAdLoaded() {
mAdView.setVisibility(View.VISIBLE);
}
});
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mNavigationView = (NavigationView) findViewById(R.id.main_drawer) ;
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.frame_container, new FragmentRecent()).commit();
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
//setTitle(menuItem.getTitle());
if (menuItem.getItemId() == R.id.drawer_recent) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, new FragmentRecent()).commit();
}
if (menuItem.getItemId() == R.id.drawer_category) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, new FragmentCategory()).commit();
}
if (menuItem.getItemId() == R.id.drawer_favorite) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, new FragmentFavorite()).commit();
}
if (menuItem.getItemId() == R.id.drawer_rate) {
final String appName = getPackageName();
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appName)));
}
}
if (menuItem.getItemId() == R.id.drawer_more) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.play_more_apps))));
}
if (menuItem.getItemId() == R.id.drawer_setting) {
Intent i = new Intent(getBaseContext(), SettingsActivity.class);
startActivity(i);
}
return false;
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
// init analytics tracker
((Analytics) getApplication()).getTracker();
// GCM
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
String reg_cgm_id = getRegistrationId(getApplicationContext());
Log.i(TAG, "Play Services Ok.");
if (reg_cgm_id.isEmpty()) {
Log.i(TAG, "Find Register ID.");
registerInBackground();
}
} else {
Log.i(TAG, "No valid Google Play Services APK found.");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
else {
super.onBackPressed();
}
}
#Override
public void onStart() {
super.onStart();
// analytics
GoogleAnalytics.getInstance(this).reportActivityStart(this);
}
#Override
public void onStop() {
super.onStop();
// analytics
GoogleAnalytics.getInstance(this).reportActivityStop(this);
}
#Override
protected void onPause() {
mAdView.pause();
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
mAdView.resume();
}
#Override
protected void onDestroy() {
mAdView.destroy();
super.onDestroy();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
LikeView.handleOnActivityResult(this, requestCode, resultCode, data);
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(MainActivity.this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this, 9000).show();
} else {
Log.i(TAG, "This device is not supported.");
}
return false;
}
return true;
}
private void storeRegistrationId(Context context, String regId) {
int appVersion = getAppVersion(context);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
private String getRegistrationId(Context context) {
String registrationId = preferences.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
int registeredVersion = preferences.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "Analytics version changed.");
return "";
}
return registrationId;
}
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(MainActivity.this);
}
reg_cgm_id = gcm.register(getString(R.string.google_api_sender_id));
msg = "Device registered, registration ID=" + reg_cgm_id;
Log.d(TAG, "ID GCM: " + reg_cgm_id);
sendRegistrationIdToBackend();
storeRegistrationId(MainActivity.this, reg_cgm_id);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
}
}.execute(null, null, null);
}
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException("Could not get package name: " + e);
}
}
private void sendRegistrationIdToBackend() {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("token", reg_cgm_id));
new HttpTask(null, MainActivity.this, Config.SERVER_URL + "/register.php", nameValuePairs, false).execute();
}
}
This is the important part of your log:
java.lang.NullPointerException: Attempt to invoke virtual method
'void com.facebook.widget.LikeView.setObjectId(java.lang.String)'
on a null object reference at android.app.ActivityThread.performLaunchActivity
It's saying that you're trying to call the method setObjectId on a LikeView that is null. So, step through that part of the code and figure out why the LikeView is null.

Categories

Resources