I have a RecyclerView that launches a new Activity when it is clicked (both long press and short). When I click it the corresponding action is being done 3 times (sometimes 2) in any case it is being done multiple times when I only want it done once. There is a thread that handles these actions but that thread is only executed once.
A quick run thru of the sequence is:
recyclerview is loaded, user can long press or quick click an item on the list.
A quick click calls a openConversation() method which will launch a new activity(in the current version it launches the activity many times because the activity stack has 2-3 instances of the launched activity)
Or if the boolean condition to launch the activity in openConversation() is false a toast message is sent (in this bug the toast is displayed 3 times from my tests)
Like wise on a long press the launched activity is launched 2-3 times when it should only be launched once, because there is more than one instance on the activity stack
public class EventListActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener {
private static final int VIBRATE_MILLISECONDS = 50;
private static final int REFRESH_ANI_MILLIS = 2500;
final Handler handler = new Handler();
private Context applicationContext;
private List<ParseObject> eventList;
final Runnable updateEventsHard = new Runnable() {
#Override
public void run() {
updateEventCards(true);
}
};
final Runnable updateEventsSoft = new Runnable() {
#Override
public void run() {
updateEventCards(false);
}
};
final Runnable initSwipeRefresh = new Runnable() {
#Override
public void run() {
initSwipeRefresh();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
applicationContext = getApplicationContext();
handler.post(updateEventsHard);
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);
View headerLayout = navigationView.inflateHeaderView(R.layout.nav_header_event_list);
TextView headerUsername = (TextView) headerLayout.findViewById(R.id.drawer_username);
headerUsername.setText(CurrentActiveUser.getInstance().getUsername());
handler.post(initSwipeRefresh);
}
private void initSwipeRefresh() {
final SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeView.setColorSchemeResources(android.R.color.holo_blue_dark, android.R.color.holo_blue_light, android.R.color.holo_green_light, android.R.color.holo_green_light);
swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeView.setRefreshing(true);
(new Handler()).postDelayed(new Runnable() {
#Override
public void run() {
updateEventCards(true);
swipeView.setRefreshing(false);
}
}, REFRESH_ANI_MILLIS);
}
});
}
#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 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 onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
switch (id) {
case (R.id.nav_my_profile):
Dialog.makeDialog(EventListActivity.this, getString(R.string.upcoming),
getString(R.string.profile_upcoming));
break;
case (R.id.nav_logout):
CurrentActiveUser.getInstance().logout();
Intent intent = new Intent(applicationContext, LoginActivity.class);
startActivity(intent);
finish();
break;
case (R.id.nav_share):
Intent share = new Intent(Intent.ACTION_SEND);
share.setType(StringResources.PLAIN_CONTENT_TYPE);
share.putExtra(Intent.EXTRA_TEXT, R.string.app_share);
startActivity(Intent.createChooser(share, getString(R.string.app_share_title)));
break;
case (R.id.nav_about):
Intent aboutIntent = new Intent(applicationContext, AboutActivity.class);
startActivity(aboutIntent);
break;
case (R.id.nav_legal):
Intent legalIntent = new Intent(applicationContext, LegalActivity.class);
startActivity(legalIntent);
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//display clickable a list of all users
#SuppressWarnings("unchecked")
private void updateEventCards(Boolean hard) {
ArrayList<EventObject> eventObjects = new ArrayList<>();
if (NetworkState.isConnected(applicationContext)) {
Query<ParseObject> query = new Query<>(Events.class);
query.orderByASC(Events.START_TIME);
if (hard) {
eventList = query.executeHard();
} else {
eventList = query.execute();
}
ParseObject current;
if (eventList != null) {
if (eventList.size() > 0) {
for (int i = 0; i < eventList.size(); i++) {
current = eventList.get(i);
eventObjects.add(
new EventObject(
current.getString(Events.NAME),
current.getString(Events.LOCATION),
current.getLong(Events.START_TIME),
current.getLong(Events.END_TIME),
current.getString(Events.IMAGE)
)
);
}
} else {
Dialog.makeToast(applicationContext, getString(R.string.no_events));
}
} else {
Dialog.makeToast(applicationContext, getString(R.string.error_loading_events));
}
} else {
Dialog.makeToast(applicationContext, getString(R.string.no_network));
}
attachToEventListAdapter(eventObjects);
}
private void attachToEventListAdapter(ArrayList<EventObject> eventObjects) {
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(applicationContext));
eventListClickListener(recyclerView);
EventListAdapter mAdapter = new EventListAdapter(eventObjects, applicationContext);
recyclerView.setAdapter(mAdapter);
recyclerView.setItemAnimator(new DefaultItemAnimator());
}
private synchronized void eventListClickListener(RecyclerView recyclerView) {
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(
EventListActivity.this, recyclerView,
new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Log.d("Click", "Quick");
openConversation(eventList.get(position));
}
#Override
public void onItemLongClick(View view, int position) {
Vibrator vibe = (Vibrator) applicationContext.getSystemService(Context.VIBRATOR_SERVICE);
vibe.vibrate(VIBRATE_MILLISECONDS);
openEventInfo(eventList.get(position));
}
}));
}
private void openConversation(ParseObject event) {
Live status = DateVerifier.goLive(event.getLong(Events.START_TIME), event.getLong(Events.END_TIME));
if (status.goLive()) {
Intent intent = new Intent(applicationContext, MessagingActivity.class);
intent.putExtra(IntentKeys.EVENT_ID, event.getObjectId());
intent.putExtra(IntentKeys.EVENT_NAME, event.getString(Events.NAME));
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} else {
Dialog.makeToast(applicationContext, String.valueOf(System.currentTimeMillis() % 1000));
}
}
private void openEventInfo(ParseObject event) {
Intent intent = new Intent(applicationContext, EventInfoActivity.class);
intent.putExtra(IntentKeys.EVENT_NAME, event.getString(Events.NAME));
intent.putExtra(IntentKeys.EVENT_INFO, event.getString(Events.INFO));
intent.putExtra(IntentKeys.EVENT_CARD, event.getString(Events.MATCH_CARD));
intent.putExtra(IntentKeys.EVENT_IMAGE, event.getString(Events.IMAGE));
intent.putExtra(IntentKeys.EVENT_START_TIME, event.getLong(Events.START_TIME));
intent.putExtra(IntentKeys.EVENT_LOCATION, event.getString(Events.LOCATION));
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
public void onStart(){
super.onStart();
handler.post(updateEventsSoft);
}
public void onResume() {
super.onResume();
handler.post(updateEventsSoft);
}
}
I think your events are being fired 3 times because every time on your RecyclerView you are calling .addOnItemTouchListener() which will add a new listener every time.
Your method eventListClickListener() should only be called once in your onCreate(), not every time in your updateEventsHard() or updateEventsSoft().
Related
I have a navigation drawer with fragments. At start, I display Home fragment as default.
There are options on navigation menu. In 2 fragments I have SwipeRefreshLayout. Until all recyclerview data are fetched then I display data and invisible SwipeRefreshLayout.
One of these fragments (included SwipeRefReshLayout) works fine but, in Home fragment something is wrong.
For example(use case)
You started app and you saw Home fragment
You clicked Profile fragment on navigation menu
You run onBackPressed(back button).
In this case data never loads and SwipeRefReshLayout is always spinning. (I also tried without refreshlayout, still same)
Any idea how to fix this? My thought is, its about displaying default fragment.
Navigation Drawer Activity
public class Page_Navigation extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Fragment fragment;
FragmentManager fragmentManager = getSupportFragmentManager();
NavigationView navigationView;
SharedPreferences mSharedPref;
DrawerLayout drawer;
private Tracker mTracker;
FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page__navigation);
//
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TextView toolbar_head = findViewById(R.id.toolbar_head);
ImageView toolbar_image = findViewById(R.id.toolbar_image);
ImageView toolbar_profile = findViewById(R.id.toolbar_profile);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();
mTracker.setScreenName("page_navigation");
mTracker.send(new HitBuilders.ScreenViewBuilder().build());
//FIRST SETTINGS
setSupportActionBar(toolbar);
Typeface customFont = Typeface.createFromAsset(getAssets(), "Montserrat-Medium.ttf");
toolbar_head.setTypeface(customFont);
//Get Sessions
mSharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String session_user_name = mSharedPref.getString("session_user_name", "");
String session_user_photo = mSharedPref.getString("session_user_photo", "");
//Navigation Drawer
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setItemIconTintList(null);
//
View headerView = navigationView.getHeaderView(0);
TextView nav_userName = (TextView) headerView.findViewById(R.id.textView_nav_userName);
CircleImageView imageView_navigation = (CircleImageView) headerView.findViewById(R.id.imageView_navigation);
Glide.with(getApplicationContext()).load(session_user_photo).into(imageView_navigation);
nav_userName.setText(session_user_name);
headerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerOpen(Gravity.START)) {
drawer.closeDrawer(Gravity.START);
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
showProfileFragment();
}
}, 300);
}
});
toolbar_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawer.openDrawer(GravityCompat.START);
}
});
toolbar_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment;
FragmentManager manager = getSupportFragmentManager();
fragment = new Nav_Profile();
fragmentTransaction = manager.beginTransaction();
fragmentTransaction.replace(R.id.navContent, fragment).addToBackStack(null).commit();
}
});
displayDefaultFragment();
}
#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.page__navigation, 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.
final int id = item.getItemId();
drawer.closeDrawer(GravityCompat.START);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
switch (id) {
case R.id.nav_home:
fragment = new Nav_Home();
break;
case R.id.nav_contact:
fragment = new Nav_Contact();
break;
case R.id.nav_articles:
fragment = new Nav_Article();
break;
case R.id.nav_about:
fragment = new Nav_AboutUs();
break;
case R.id.nav_suggest:
fragment = new Nav_Suggest();
break;
case R.id.nav_share:
fragment = new Nav_Share();
break;
case R.id.nav_rateApp:
fragment = new Nav_RateApp();
break;
}
fragmentManager.beginTransaction()
.replace(R.id.navContent, fragment)
.addToBackStack(null)
.commit();
}
}, 350);
return true;
}
public void displayDefaultFragment() {
fragment = new Nav_Home();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).commit();
}
public void showProfileFragment() {
fragment = new Nav_Profile();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).addToBackStack(null).commit();
}
}
Home Fragment
public class Nav_Home extends Fragment implements View.OnClickListener{
SharedPreferences mSharedPref;
private SwipeRefreshLayout swipeRefresh_home;
private CardView item_homeTop_coupons, item_homeTop_draws, item_homeTop_event;
private LinearLayout layout_all_article, layout_all_999;
private ScrollView shimmer_home;
private List<Model_ListItem> listNewItems;
private RecyclerView recyclerView_item_home;
private List<Model_Article> articleList;
private RecyclerView recyclerView_article_home;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fetchItemsNew();
fetchArticlesNew();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_nav__home, container, false);
item_homeTop_coupons = view.findViewById(R.id.item_homeTop_coupons);
item_homeTop_draws = view.findViewById(R.id.item_homeTop_draws);
item_homeTop_event = view.findViewById(R.id.item_homeTop_event);
recyclerView_item_home = view.findViewById(R.id.recyclerView_item_home);
recyclerView_article_home = view.findViewById(R.id.recyclerView_article_home);
layout_all_article = view.findViewById(R.id.layout_all_article);
layout_all_999 = view.findViewById(R.id.layout_all_999);
swipeRefresh_home = view.findViewById(R.id.swipeRefresh_home);
shimmer_home = view.findViewById(R.id.shimmer_home);
item_homeTop_coupons.setOnClickListener(this);
item_homeTop_draws.setOnClickListener(this);
item_homeTop_event.setOnClickListener(this);
layout_all_999.setOnClickListener(this);
layout_all_article.setOnClickListener(this);
//first settngs
mSharedPref = PreferenceManager.getDefaultSharedPreferences(view.getContext());
String session_user_email = mSharedPref.getString("session_user_email","");
swipeRefresh_home.setRefreshing(true);
return view;
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.item_homeTop_coupons:
startActivity(new Intent(getContext(), Page_Coupon.class));
break;
case R.id.item_homeTop_draws:
startActivity(new Intent(getContext(), Page_Draw.class));
break;
case R.id.item_homeTop_event:
startActivity(new Intent(getContext(), Page_Event.class));
break;
case R.id.layout_all_999:
//999 city search activity
startActivity(new Intent(getContext(), Page_SearchCity.class));
break;
case R.id.layout_all_article:
//article fragment
Fragment fragment;
FragmentManager fragmentManager = getFragmentManager();
fragment = new Nav_Article();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).addToBackStack(null).commit();
break;
}
}
public void fetchItemsNew(){
listNewItems = new ArrayList<>();
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<List<Model_ListItem>> call = api_service.fetchItemsNew();
call.enqueue(new Callback<List<Model_ListItem>>() {
#Override
public void onResponse(Call<List<Model_ListItem>> call, Response<List<Model_ListItem>> response) {
if(response.code() == 200){
listNewItems = response.body();
Adapter_HomeItem adapter_homeItem = new Adapter_HomeItem(getContext(), listNewItems);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
recyclerView_item_home.setHasFixedSize(true);
recyclerView_item_home.setLayoutManager(layoutManager);
recyclerView_item_home.setAdapter(adapter_homeItem);
SnapHelper helper = new LinearSnapHelper();
helper.attachToRecyclerView(recyclerView_item_home);
}
}
#Override
public void onFailure(Call<List<Model_ListItem>> call, Throwable t) {
}
});
}
public void fetchArticlesNew(){
articleList = new ArrayList<>();
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<List<Model_Article>> callArticle = api_service.fetchArticlesNew();
callArticle.enqueue(new Callback<List<Model_Article>>() {
#Override
public void onResponse(Call<List<Model_Article>> call, Response<List<Model_Article>> response) {
if(response.code() == 200){
articleList = response.body();
Adapter_HomeArticles adapter_homeArticles = new Adapter_HomeArticles(getContext(), articleList);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
recyclerView_article_home.setLayoutManager(layoutManager);
recyclerView_article_home.setHasFixedSize(true);
recyclerView_article_home.setAdapter(adapter_homeArticles);
}
}
#Override
public void onFailure(Call<List<Model_Article>> call, Throwable t) {
}
});
}
}
Firstly you must disable SwipeRefreshLayout spinning when successfully or not fetched data:
swipeRefresh_home.setRefreshing(false);
If you do not do this spinner will be spinning all the time.
Another problem is that you have one fragment and you try to assign to it Nav_Home fragment and Nav_Profile fragment.
Fragment fragment;
public void displayDefaultFragment() {
fragment = new Nav_Home();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).commit();
}
public void showProfileFragment() {
fragment = new Nav_Profile();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).addToBackStack(null).commit();
}
Try to separate them and show like this:
Fragment homeFragment;
Fragment profileFragment;
public void displayDefaultFragment() {
homeFragment = new Nav_Home();
fragmentManager.beginTransaction().replace(R.id.navContent, homeFragment).commit();
}
public void showProfileFragment() {
profileFragment = new Nav_Profile();
fragmentManager.beginTransaction().replace(R.id.navContent, profileFragment).addToBackStack(null).commit();
}
I read data from json file to an adapter and in the main.java under oncreate, when I try runing it,it doest show anything.
I tried the same code under menu onclick and it works, I want it to appear when the app is first runed.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
String url = "myjsonurl.php";
JSONArray jArray;
ProgressDialog dialog;
ListView mycustomlist = null;
WebView mywebview =null;
CustomAdapter myadapter = null;
ArrayList<news> mydatalist = new ArrayList<news>();
ArrayList<news> maşetData = new ArrayList<news>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myadapter = new CustomAdapter(this, mydatalist);
mycustomlist = (ListView)findViewById(R.id.listview);
mycustomlist.setAdapter(myadapter);
dialog = new ProgressDialog(this);
dialog.setMessage("Loading....");
dialog.show();
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String string) {
parseJsonData(string);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getApplicationContext(), "Some error occurred!!", Toast.LENGTH_SHORT).show();
dialog.dismiss();
dialog.cancel();
}
});
RequestQueue rQueue = Volley.newRequestQueue(MainActivity.this);
rQueue.add(request);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/* FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
*/
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);
}
public void parseJsonData(final String jsonString) {
try {
jArray = new JSONArray(jsonString);
for(int i=0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
news news1 = new news();
news1.setTitle(jObject.getString("title"));
news1.setContent(Html.fromHtml(jObject.getString("content")));
news1.setDate(jObject.getString("date"));
news1.setImage("http://www.bolgegundem.com/d/news/" + jObject.getString("image").concat(".jpg"));
news1.setId(jObject.getString("id"));
news1.setCategory(jObject.getString("category"));
news1.set__comment_count(jObject.getString("__comment_count"));
news1.setHeadline(jObject.getString("headline"));
mydatalist.add(news1);
// http://www.bolgegundem.com/d/gallery/81_2.jpg
/* images.add("http://www.bolgegundem.com/d/gallery/" + id + "_" + imgUrl.replace(",", ".jpg") );*/
// al.add(title);
//imagelinks[i] = "http://www.bolgegundem.com/d/gallery/" + id + "_" + i + ".jpg";
}
// ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_activated_1, al);
//listview.setAdapter(adapter);
// listview.setBackgroundColor(rgb(0, 255, 255));
/* listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if(i < links.length){
Uri uri = Uri.parse(links[i]);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
}
});*/
if (dialog.isShowing()){
dialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
dialog.dismiss();
}
}
#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.manşet) {
// Handle the camera action
} else if (id == R.id.Anasayfa) {
myadapter = new CustomAdapter(this, mydatalist);
mycustomlist = (ListView)findViewById(R.id.listview);
mycustomlist.setAdapter(myadapter);
} else if (id == R.id.ajansTv) {
} else if (id == R.id.foto) {
} else if (id == R.id.gundem) {
} else if (id == R.id.siyaset) {
}else if (id ==R.id.Ekonomi ){
}else if (id ==R.id.spor ){
}else if (id ==R.id.saglik ){
}else if (id ==R.id.nav_share ){
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
My adapter class is here
public class CustomAdapter extends BaseAdapter {
Context mycontext = null;
ArrayList<news> mydatalist;
public CustomAdapter(Context mycontext, ArrayList<news> mydatalist)
{
this.mycontext = mycontext;
this.mydatalist = mydatalist;
}
#Override
public int getCount() {
return this.mydatalist.size();
}
#Override
public Object getItem(int position) {
return this.mydatalist.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater myinflater = (LayoutInflater)mycontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewHolder myholder = null;
if(convertView == null)
{
convertView = myinflater.inflate(R.layout.customlayout, null);
myholder = new ViewHolder();
myholder.mytextview1 = (TextView)convertView.findViewById(R.id.mytextview1);
myholder.mytextview2 = (TextView)convertView.findViewById(R.id.mytextview2);
myholder.mytextview3 = (TextView)convertView.findViewById(R.id.mytextview3);
myholder.myimageview1 = (ImageView)convertView.findViewById(R.id.imageView);
convertView.setTag(myholder);
}
else
{
myholder = (ViewHolder)convertView.getTag();
}
myholder.mytextview1.setText(mydatalist.get(position).getTitle());
myholder.mytextview2.setText(mydatalist.get(position).getContent());
myholder.mytextview3.setText(mydatalist.get(position).getDate());
myholder.myimageview1.setImageResource(R.drawable.bolgegundem);
new DownloadImageTask(myholder.myimageview1).execute(mydatalist.get(position).getImage());
return convertView;
}
static class ViewHolder
{
public TextView mytextview1;
public TextView mytextview2;
public TextView mytextview3;
public ImageView myimageview1;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
How can I solve this?
Put the three lines
myadapter = new CustomAdapter(this, mydatalist);
mycustomlist = (ListView)findViewById(R.id.listview);
mycustomlist.setAdapter(myadapter);
in this method:
#Override
public void onResponse(String string) {
parseJsonData(string);
// put them here
}
This will work because it populates the list after the data is parsed add then adds it to the adapter. If you add the list to the adapter in OnCreate, the onResponse method will run later (when the data is returned) and the list will be empty.
you need to create fragments for every item which you declare in navigation and do parsing and all thing in it and that fragment is called from onNavigationItemSelected and if you want which is always show first than you have to call it in also from onCreate() method.
I have been trying to add my own icon to the ActionBarDrawerToggle (android.support.v7.app.ActionBarDrawerToggle). The custom icon is visible but it is not responding to clicks. I can see my side menu when i slide my finger from left to right but click is not working.
I have tried this solution but it is working and i don't want to use toolbar. I want solution to add this icon without toolbar, like this.
This is my code. Sorry for too many lines.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.layout_for_title);
CustomTextViewToolbar head=(CustomTextViewToolbar)findViewById(getResources().getIdentifier("mytext", "id", getPackageName()));
head.setText("Home");
ImageView gender = (ImageView)findViewById(getResources().getIdentifier("gender" , "id" , getPackageName()));
gender.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_dialog_gender);
dialog.show();
CircularImageView male = (CircularImageView)dialog.findViewById(R.id.male) ;
male.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
CircularImageView female = (CircularImageView)dialog.findViewById(R.id.female) ;
female.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
CircularImageView kids = (CircularImageView)dialog.findViewById(R.id.kids) ;
kids.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
});
ImageView imageView = (ImageView)findViewById(getResources().getIdentifier("show_cart" , "id" , getPackageName()));
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getBaseContext() , CustomerCartActivity.class));
}
});
setContentView(R.layout.customer_home_screen);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
mExpandableListView = (ExpandableListView) findViewById(R.id.navList);
initItems();
LayoutInflater inflater = getLayoutInflater();
View listHeaderView = inflater.inflate(R.layout.nav_header, null, false);
mExpandableListView.addHeaderView(listHeaderView);
mExpandableListData = ExpandableListDataSource.getData(this);
mExpandableListTitle = new ArrayList(mExpandableListData.keySet());
addDrawerItems();
setupDrawer();
if (savedInstanceState == null) {
selectFirstItemAsDefault();
}
mDrawerToggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerToggle.setHomeAsUpIndicator(R.drawable.menu_icon);
coverFlow = (FeatureCoverFlow) findViewById(R.id.coverflow);
mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
drawer.openDrawer(GravityCompat.START);
}
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
horizontal_recycler_view= (RecyclerView) findViewById(R.id.horizontal_recycler_view);
data = fill_with_data();
horizontalAdapter=new HorizontalAdapter(data, getApplication());
LinearLayoutManager horizontalLayoutManager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, false);
horizontal_recycler_view.setLayoutManager(horizontalLayoutManager);
horizontal_recycler_view.setAdapter(horizontalAdapter);
coverFlowOne = (FeatureCoverFlow) findViewById(R.id.coverflow_one);
coverFlowTwo = (FeatureCoverFlow) findViewById(R.id.coverflowtwo);
settingDummyData();
adapter = new CoverFlowAdapter(this, games);
coverFlow.setAdapter(adapter);
coverFlow.setOnScrollPositionListener(onScrollListener());
coverFlowOne.setAdapter(adapter);
coverFlowOne.setOnScrollPositionListener(onScrollListener());
coverFlowTwo.setAdapter(adapter);
coverFlowTwo.setOnScrollPositionListener(onScrollListener());
myHome = (LinearLayout)findViewById(R.id.c_home);
myOrder = (LinearLayout)findViewById(R.id.c_my_order);
myAccount = (LinearLayout)findViewById(R.id.c_profile);
myHome.setOnClickListener(this);
myOrder.setOnClickListener(this);
myAccount.setOnClickListener(this);
}
private void selectFirstItemAsDefault() {
if (mNavigationManager != null) {
String firstActionMovie = getResources().getStringArray(R.array.actionFilms)[0];
mNavigationManager.showFragmentAction(firstActionMovie);
}
}
private void initItems() {
items = getResources().getStringArray(R.array.film_genre);
}
private void addDrawerItems() {
mExpandableListAdapter = new CustomExpandableListAdapter(this, mExpandableListTitle, mExpandableListData);
mExpandableListView.setAdapter(mExpandableListAdapter);
mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
String selectedItem = ((List) (mExpandableListData.get(mExpandableListTitle.get(groupPosition))))
.get(childPosition).toString();
mDrawerLayout.closeDrawer(GravityCompat.START);
return false;
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout,
R.string.drawer_open,
R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu();
}
};
mDrawerToggle.setHomeAsUpIndicator(R.drawable.menu_icon);
mDrawerToggle.setDrawerIndicatorEnabled(false);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.requestLayout();
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Have you set you new icon to "clickable" in the xml?
Enable the Debug GPU Overdraw tool. It may give you an indication whether or not your icon is overlapped by another element that is consuming clicks (if so you will need to make that overlapping element clickable to false).
On your mobile device, go to Settings and tap Developer Options.
In the Hardware accelerated rendering section, select Debug GPU Overdraw.
In the Debug GPU overdraw popup, select Show overdraw areas.
https://developer.android.com/studio/profile/dev-options-overdraw.html
Alternatively add debugging onClick functions to potentially overlapping or conflicting elements.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm trying to send data from MainActivity to TimeActivity but the bundle received in TimeActivity is null. And a Null Pointer Exception is thrown when I do not put
s = extras.getString("key");
in the
if (extras != null) {
}
and a message saying "The App has unfortunately stopped".
but after pressing OK to the message, the TimeActivity starts and the value 125 is received in
String s;
This is MainActivity.
public class MainActivity extends AppCompatActivity {
SharedPreferences sharedpreferences;
TextView name;
TextView email;
public static final String mypreference = "mypref";
public static final String Name = "nameKey";
public static final String Email = "emailKey";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (TextView) findViewById(R.id.etName);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String n = name.getText().toString();
String e = "1";
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.commit();
if(n.length()==3){
Intent intent = new Intent(MainActivity.this, TimeActivity.class);
startActivity(intent);}else{
Toast.makeText(MainActivity.this,"The Roll Number Must be a 3 Digit number",Toast.LENGTH_LONG).show();
}
}
}
);
sharedpreferences=
getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if(sharedpreferences.contains(Name))
{
String s = sharedpreferences.getString(Name, "");
Intent i = new Intent(getApplicationContext(), TimeActivity.class);
i.putExtra("key", s);
startActivity(i);
}
else
{
}
}
}
This is TimeActivity
public class TimeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_time);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Timely");setSupportActionBar(toolbar);
String s="0";
Bundle extras = getIntent().getExtras();
if (extras != null) {
Intent i = new Intent(getApplicationContext(), TimeActivity.class);
startActivity(i);s = extras.getString("key");
}else{Toast.makeText(TimeActivity.this,"Bundle received Null. ",Toast.LENGTH_LONG).show();}
int r = Integer.parseInt(s);
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);
}
#Override
public void onBackPressed() {
System.exit(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.time, 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_home) {
} else if (id == R.id.nav_timetable) {
} else if (id == R.id.nav_about) {
startActivity(new Intent(TimeActivity.this, About.class));
} else if (id == R.id.nav_Develop) {
} 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;
}
}
Any kind of help will be appreciated.
I can see two possible problems here.
First, you don't pass the Bundle here in the MainActivity:
Intent intent = new Intent(MainActivity.this, TimeActivity.class);
startActivity(intent);
Second, you start the TimeActivity again in its onCreate() method.
if (extras != null) {
Intent i = new Intent(getApplicationContext(), TimeActivity.class);
startActivity(i);
s = extras.getString("key");
}
I am building an OpenGL live wallpaper. I decided to have a Navigation Drawer in my main activity since there are a lot of features the user will have access to.
The problem/issue
If I press the "hardware" back button to normally close an app the initial fragment that is shown just refreshes and the app never closes. If I hit the home button and go back to the app everything is a black screen. I've searched all throughout Google thinking that maybe I wasn't destroying the MainActivity properly or for a way to terminate a fragment. I've tried calling finish() in the main activity's onDestroy method. I've tried utilizing the remove method from fragment manager in each fragments onDetach method per posts that I've found online. Nothing has worked. I'm stumped. I've set debug points in the main activity on the onDestroy method and on the fragments onDetach method with no error being produced or any information being given. At this point I am clueless. Here's my MainActivity class.
public class MainActivity extends AppCompatActivity implements OnNavigationItemSelectedListener, OnPostSelectedListener{
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
TextView usrTag, tagrEmail;
CircleImageView tagrPic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
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.setDrawerListener(toggle);
toggle.syncState();
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.add(R.id.cLMain, new PreviewFragment()).addToBackStack("PreviewFragment").commit();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header = navigationView.getHeaderView(0);
usrTag = (TextView)header.findViewById(R.id.usrName);
tagrEmail = (TextView)header.findViewById(R.id.usrEmail);
tagrPic = (CircleImageView)header.findViewById(R.id.usrImg);
Log.i("MainActivity: ", "User Photo: " + getProfilePic(this));
usrTag.setText(getUserName(getBaseContext()));
tagrEmail.setText(getUserEmail(getBaseContext()));
GlideUtils.loadProfileIcon(getProfilePic(getBaseContext()), tagrPic);
}
#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) {
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.
Fragment fragment = null;
Class fragmentClass = null;
int id = item.getItemId();
if (id == R.id.nav_home) {
fragmentClass = PreviewFragment.class;
} else if (id == R.id.nav_custom) {
startCustomLabelCreator();
} else if (id == R.id.nav_mylabels) {
} else if (id == R.id.nav_commLabels) {
fragmentClass = PostsFragment.class;
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.cLMain, fragment).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void startCustomLabelCreator(){
Intent cLC = new Intent(getBaseContext(), CreateLabel.class);
startActivity(cLC);
}
#Override
public void onPostComment(String postKey) {
}
#Override
public void onPostLike(String postKey) {
}
#Override
public void onPhotoSelected(String photoUrl) {
}
#Override
protected void onDestroy() {
super.onDestroy();
finish();
}
}
My Fragments
public class PostsFragment extends Fragment implements ConfirmSelectedPhotoListener{
public static final String TAG = "PostsFragment";
private static final String KEY_LAYOUT_POSITION = "layoutPosition";
private int mRecyclerViewPosition = 0;
private OnPostSelectedListener mListener;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter<PostViewHolder> mAdapter;
public PostsFragment() {
// Required empty public constructor
}
public static PostsFragment newInstance() {
PostsFragment fragment = new PostsFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_posts, container, false);
rootView.setTag(TAG);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
mRecyclerView.setLayoutManager(linearLayoutManager);
Log.d(TAG, "Restoring recycler view position (all): " + mRecyclerViewPosition);
Query allPostsQuery = FirebaseUtil.getPostsRef();
mAdapter = getFirebaseRecyclerAdapter(allPostsQuery);
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
// TODO: Refresh feed view.
}
});
mRecyclerView.setAdapter(mAdapter);
}
private FirebaseRecyclerAdapter<Post, PostViewHolder> getFirebaseRecyclerAdapter(Query query) {
return new FirebaseRecyclerAdapter<Post, PostViewHolder>(
Post.class, R.layout.post_item, PostViewHolder.class, query) {
#Override
public void populateViewHolder(final PostViewHolder postViewHolder,
final Post post, final int position) {
setupPost(postViewHolder, post, position, null);
}
#Override
public void onViewRecycled(PostViewHolder holder) {
super.onViewRecycled(holder);
// FirebaseUtil.getLikesRef().child(holder.mPostKey).removeEventListener(holder.mLikeListener);
}
};
}
private void setupPost(final PostViewHolder postViewHolder, final Post post, final int position, final String inPostKey) {
postViewHolder.setPhoto(post.getThumb_url());
Log.d(TAG, post.getThumb_url());
postViewHolder.setText(post.getText());
postViewHolder.setTimestamp(DateUtils.getRelativeTimeSpanString(
(long) post.getTimestamp()).toString());
final String postKey;
if (mAdapter instanceof FirebaseRecyclerAdapter) {
postKey = ((FirebaseRecyclerAdapter) mAdapter).getRef(position).getKey();
} else {
postKey = inPostKey;
}
Author author = post.getAuthor();
postViewHolder.setAuthor(author.getFull_name(), author.getUid());
postViewHolder.setIcon(author.getProfile_picture(), author.getUid());
ValueEventListener likeListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
postViewHolder.setNumLikes(dataSnapshot.getChildrenCount());
if (dataSnapshot.hasChild(FirebaseUtil.getCurrentUserId())) {
postViewHolder.setLikeStatus(PostViewHolder.LikeStatus.LIKED, getActivity());
} else {
postViewHolder.setLikeStatus(PostViewHolder.LikeStatus.NOT_LIKED, getActivity());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
FirebaseUtil.getLikesRef().child(postKey).addValueEventListener(likeListener);
postViewHolder.mLikeListener = likeListener;
postViewHolder.setPostClickListener(new PostViewHolder.PostClickListener() {
#Override
public void showComments() {
Log.d(TAG, "Comment position: " + position);
mListener.onPostComment(postKey);
}
#Override
public void toggleLike() {
Log.d(TAG, "Like position: " + position);
mListener.onPostLike(postKey);
}
#Override
public void savePhotoUrl() {
//mListener.onPhotoSelected(post.getFull_url());
showLabelConfirm(post.getFull_url());
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
if (mAdapter != null && mAdapter instanceof FirebaseRecyclerAdapter) {
((FirebaseRecyclerAdapter) mAdapter).cleanup();
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save currently selected layout manager.
int recyclerViewScrollPosition = getRecyclerViewScrollPosition();
Log.d(TAG, "Recycler view scroll position: " + recyclerViewScrollPosition);
savedInstanceState.putSerializable(KEY_LAYOUT_POSITION, recyclerViewScrollPosition);
super.onSaveInstanceState(savedInstanceState);
}
private int getRecyclerViewScrollPosition() {
int scrollPosition = 0;
// TODO: Is null check necessary?
if (mRecyclerView != null && mRecyclerView.getLayoutManager() != null) {
scrollPosition = ((LinearLayoutManager) mRecyclerView.getLayoutManager())
.findFirstCompletelyVisibleItemPosition();
}
return scrollPosition;
}
#Override
public void onSelectedPhoto(String selectPhoto) {
mListener.onPhotoSelected(selectPhoto);
}
public interface OnPostSelectedListener {
void onPostComment(String postKey);
void onPostLike(String postKey);
void onPhotoSelected(String photoUrl);
}
private void showLabelConfirm(String uriBmp) {
FragmentManager fm = getFragmentManager();
PhotoDialogFragment editNameDialogFragment = PhotoDialogFragment.newInstance(uriBmp);
// SETS the target fragment for use later when sending results
editNameDialogFragment.setTargetFragment(PostsFragment.this, 300);
editNameDialogFragment.show(fm, "fragment_edit_name");
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnPostSelectedListener) {
mListener = (OnPostSelectedListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnPostSelectedListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
Second Fragment:
public class PreviewFragment extends RajBaseFragment {
#Override
public ISurfaceRenderer createRenderer() {
return new PreviewRenderer(getContext());
}
}
Which extends:
public abstract class RajBaseFragment extends Fragment implements IDisplay, View.OnClickListener {
protected FrameLayout mLayout;
protected ISurface mRajawaliSurface;
protected ISurfaceRenderer mRenderer;
public RajBaseFragment(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
// Inflate the view
mLayout = (FrameLayout) inflater.inflate(getLayoutID(), container, false);
mLayout.findViewById(R.id.relative_layout_loader_container).bringToFront();
// Find the TextureView
mRajawaliSurface = (ISurface) mLayout.findViewById(R.id.rajwali_surface);
// Create the loader
mRenderer = createRenderer();
onBeforeApplyRenderer();
applyRenderer();
return mLayout;
}
protected void onBeforeApplyRenderer() {
}
protected void applyRenderer() {
mRajawaliSurface.setSurfaceRenderer(mRenderer);
}
#Override
public void onClick(View v) {
}
#Override
public void onDestroyView() {
super.onDestroyView();
if (mLayout != null)
mLayout.removeView((View) mRajawaliSurface);
}
#Override
public int getLayoutID() {
return R.layout.rajawali_textureview_fragment;
}
}
I've tried all the recommendations below so far and the primary fragment that is set in the MainActivity's onCreate method still gets refreshed/reloaded when the back button is pressed rather than the app exiting/closing.
In your onNavigationItemSelected method, you are replacing the current fragment with fragment even in cases where fragment is null, which has undefined effects. You should not do that.
One fix is to replace this code block:
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
with this one:
if (fragmentClass != null) {
fragment = fragmentClass.newInstance();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.cLMain, fragment).addToBackStack().commit();
}
(and then leave out the fragment transaction below this point).
Also, there is a call to finish in the onDestroy method, which probably is not causing the problem but should be taken out because it does not make any sense there.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
}
return true;
}
replace your onOptionsItemSelected() with mine.
Don't include your first fragment into backstack.
Try to change you fragment transaction line code without addToBackStack
as below:
mFragmentTransaction.add(R.id.cLMain, new PreviewFragment()).commit();
While adding fragment with addToBackStack, this allows back
navigation for added fragment.Because of fragment in backstack,
empty(black) activity layout will be displayed.
Change onBackPressed() as below which automatically close app after if no any Fragment found in FragmentManager:
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
this.finish();
} else {
getSupportFragmentManager().popBackStack();
}
}
Also you can see some similar Q/A on below links which helps you get more idea to solve your problem:
Fragment pressing back button
In Fragment on back button pressed Activity is blank
Transaction of fragments in android results in blank screen
It's solved my blank screen problem. Hope its helps you.
Try this code, hope this helps you, take necessary stuffs which are required for you. Also, try running this project in Android studio, it works.
https://github.com/asifali22/Navigation_Health/blob/master/app/src/main/java/com/thenewboston/mynavigation/MainActivity.java
When user press to back button it'll check fragment manager's backstack and if backstack entity count is bigger than 0 (this means there's a fragment in backstack) it'll popBackStack else it'll finish activity.
If you add your initial fragment to backstack, when user press back button they'll see a blank screen.
Also when you init your activity if you need to put a fragment it's a best practice to check if saved instance state is null. Here i modified some part of your code.
if(savedInstanceState == null){
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.add(R.id.cLMain, new PreviewFragment()).commit();
}
I hope this'll help you. If you still have problem let me know.
Good luck.
create subclass for ISurface and override onKeyDown method like this
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
Log.e("Custom View", "onKeyDown");
//return super.onKeyDown(keyCode, event);
return false;
}
Could be related with the lifecycle...
Try using GLSurfaceView. I believe is easier for what you want, is special for OpenGL rendering and there is plenty information about it. Examples, lifecycle among others. Let me know if helped. If not, please, provide more info.