I have been reading the different answers here on stackoverflow and on this blog post and tried to implement their solutions but I am still getting the error: No adapter attached; skipping layout.
RecyclerAdapter:
package vn.jupviec.frontend.android.monitor.app.ui.candidate;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.w3c.dom.Text;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import butterknife.BindView;
import vn.jupviec.frontend.android.monitor.app.R;
import vn.jupviec.frontend.android.monitor.app.domain.candidate.TrainingDTO;
import vn.jupviec.frontend.android.monitor.app.util.Utils;
/**
* Created by Windows 10 Gamer on 16/12/2016.
*/
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerViewHolder> {
private static final String TAG = "RecyclerView";
private List<TrainingDTO> mTrainingDTOs;
private Context mContext;
private LayoutInflater mLayoutInflater;
private String today;
private static final DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
AdapterInterface buttonListener;
public RecyclerAdapter(Context context, List<TrainingDTO> datas, AdapterInterface buttonListener) {
mContext = context;
mTrainingDTOs = datas;
this.mLayoutInflater = LayoutInflater.from(mContext);
this.buttonListener = buttonListener;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.candidate_item, parent, false);
// View itemView = mLayoutInflater.inflate(R.layout.candidate_item, parent, false);
return new RecyclerViewHolder(itemView);
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
final ObjectMapper mapper = new ObjectMapper();
final TrainingDTO trainingDTO = mapper.convertValue(mTrainingDTOs.get(position), TrainingDTO.class);
holder.tvName.setText(trainingDTO.getMaidName());
holder.status.setVisibility(View.GONE);
Date date = new Date();
String currentDate = sdf.format(date);
for (TrainingDTO.TrainingDetailDto td : trainingDTO.getListTrain()) {
today = Utils.formatDate((long) td.getTrainingDate(),"dd/MM/yyyy");
break;
}
if(currentDate.equals(today)) {
holder.status.setVisibility(View.VISIBLE);
holder.status.setText("(Mới)");
}
holder.btnHistory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext,R.string.msg_no_candidate_history,Toast.LENGTH_SHORT).show();
}
});
holder.btnTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonListener.showComment(trainingDTO);
}
});
}
#Override
public int getItemCount() {
int size ;
if(mTrainingDTOs != null && !mTrainingDTOs.isEmpty()) {
size = mTrainingDTOs.size();
}
else {
size = 0;
}
return size;
}
class RecyclerViewHolder extends RecyclerView.ViewHolder {
private TextView tvName;
private Button btnTest;
private Button btnHistory;
private TextView status;
public RecyclerViewHolder(View itemView) {
super(itemView);
tvName = (TextView) itemView.findViewById(R.id.txtName);
btnTest = (Button) itemView.findViewById(R.id.btnTest);
btnHistory = (Button) itemView.findViewById(R.id.btnHistory);
status = (TextView)itemView.findViewById(R.id.status);
}
}
public boolean removeItem(int position) {
if (mTrainingDTOs.size() >= position + 1) {
mTrainingDTOs.remove(position);
return true;
}
return false;
}
public interface AdapterInterface {
void showComment(TrainingDTO trainingDTO);
void showHistory(TrainingDTO trainingDTO);
}
}
FragmentTapNew:
package vn.jupviec.frontend.android.monitor.app.ui.candidate;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import vn.jupviec.frontend.android.monitor.app.R;
import vn.jupviec.frontend.android.monitor.app.domain.ResultDTO;
import vn.jupviec.frontend.android.monitor.app.domain.candidate.TrainingDTO;
import vn.jupviec.frontend.android.monitor.app.domain.training.CandidateService;
import vn.jupviec.frontend.android.monitor.app.util.Constants;
import vn.jupviec.frontend.android.monitor.app.util.Utils;
/**
* Created by Windows 10 Gamer on 09/12/2016.
*/
public class FragmentTapNew extends Fragment implements RecyclerAdapter.AdapterInterface {
private static final String TAG = FragmentTapNew.class.getSimpleName();
Activity myContext = null;
private OnItemSelectedListener listener;
ShapeDrawable shapeDrawable;
#BindView(R.id.lvToday)
RecyclerView lvToday;
#BindView(R.id.textView)
TextView textView;
#BindView(R.id.pb_loading)
ProgressBar pbLoading;
private Unbinder unbinder;
private boolean loading = true;
int pastVisiblesItems, visibleItemCount, totalItemCount;
ArrayList<TrainingDTO> mTrainingDTO ;
RecyclerAdapter mTrainingDTOAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_candidate_training, container, false);
unbinder = ButterKnife.bind(this, v);
initViews();
return v;
}
private void initViews() {
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
lvToday.setHasFixedSize(true);
lvToday.setNestedScrollingEnabled(false);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
today();
}
});
t.start();
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
Toast.makeText(getActivity(), R.string.err_cannot_establish_connection, Toast.LENGTH_SHORT).show();
return false;
} else
return true;
}
private void today() {
if(isNetworkConnected()){
String token = "a";
Integer date = 0;
setLoadingVisible(true);
CandidateService.getApiDummyClient(getContext()).getCandidate(
token,
date,
Constants.TRAINING,
Arrays.asList(Constants.TRAINING_DAY_NEW),
new Callback<ResultDTO>() {
#Override
public void success(ResultDTO resultDTO, Response response) {
setLoadingVisible(false);
mTrainingDTO = (ArrayList<TrainingDTO>) resultDTO.getData();
if (mTrainingDTO.size() == 0) {
if(textView!=null) {
textView.setVisibility(View.VISIBLE);
textView.setTextColor(Color.RED);
textView.setGravity(Gravity.CENTER | Gravity.BOTTOM);
}
} else {
if(textView!=null) {
textView.setVisibility(View.GONE);
}
if(null==mTrainingDTOAdapter) {
mTrainingDTOAdapter = new RecyclerAdapter(getActivity(), mTrainingDTO, FragmentTapNew.this);
lvToday.setAdapter(mTrainingDTOAdapter);
} else {
lvToday.setAdapter(mTrainingDTOAdapter);
mTrainingDTOAdapter.notifyDataSetChanged();
}
lvToday.invalidate();
}
}
#Override
public void failure(RetrofitError error) {
Log.e(TAG, "JV-ERROR: " + error.getMessage());
Log.e(TAG, "JV-ERROR: " + error.getSuccessType());
}
});
}
}
#Override
public void onResume() {
setLoadingVisible(false);
initViews();
lvToday.setAdapter(mTrainingDTOAdapter);
super.onResume();
}
#Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
private void setLoadingVisible(boolean visible) {
// pbLoading.getIndeterminateDrawable().setColorFilter(0xFFFF0000, android.graphics.PorterDuff.Mode.MULTIPLY);
if(pbLoading!=null) {
pbLoading.setVisibility(visible ? View.VISIBLE : View.GONE);
lvToday.setVisibility(visible ? View.GONE : View.VISIBLE);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof OnItemSelectedListener) {
listener = (OnItemSelectedListener) activity;
} else {
throw new ClassCastException(activity.toString()
+ " phải implemenet MyListFragment.OnItemSelectedListener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
#Override
public void showComment(TrainingDTO trainingDTO) {
Intent intent = new Intent(getContext(), CommentActivity.class);
intent.putExtra(Constants.ARG_NAME_DETAIL, trainingDTO);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(intent);
}
#Override
public void showHistory(TrainingDTO trainingDTO) {
Intent intent = new Intent(getContext(), HistoryActivity.class);
intent.putExtra(Constants.ARG_CANDIDATE_HISTORY_DETAIL, trainingDTO);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(intent);
}
public interface OnItemSelectedListener {
void showComment(TrainingDTO trainingDTO);
void showHistory(TrainingDTO trainingDTO);
}
}
The first, you don't need to set adapter multiple time, only set adapter at the first time in your method initView().
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
lvToday.setHasFixedSize(true);
lvToday.setNestedScrollingEnabled(false);
if(mTrainingDTO == null) {
mTrainingDTO = new ArrayList<>();
}
if(null == mTrainingDTOAdapter ) {
mTrainingDTOAdapter = new RecyclerAdapter(getActivity(), mTrainingDTO, FragmentTapNew.this);
}
lvToday.setAdapter(mTrainingDTOAdapter);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
today();
}
});
t.start();
After that, you don't need to call lvToday.setAdapter(mTrainingDTOAdapter);
many times. Just call mTrainingDTOAdapter.notifyDataSetChanged(); if having any changes in your data mTrainingDTO.
The errorlog - error:No adapter attached; skipping layout indicates that you've attached LayoutManager but you haven't attached an adapter yet, so recyclerview will skip layout. I'm not sure but, in other words recyclerView will skip layout measuring at the moment.
to prevent this errorLog Try to set an adapter with an empty dataSet i.e. ArrayList or
Attach LayoutManager just before you are setting your adapter.
Try this,
private void initViews() {
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(getActivity());
lvToday.setLayoutManager(mLinearLayoutManager);
lvToday.setHasFixedSize(true);
lvToday.setNestedScrollingEnabled(false);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
today();
}
});
t.start();
}
Related
Error caused
W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x4198dda0)
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.unimaseshop, PID: 21195
java.lang.NumberFormatException: Invalid int: "40.00"
Due to the section at onBindViewHolder; it couldn't run the java activity.
package com.example.ecommerce;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.unimaseshop.Model.CartModel;
import com.example.unimaseshop.Prevalage.Prevalage;
import com.example.unimaseshop.ViewHolder.CartViewHolder;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class Cart extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private Button NextProcessBtn;
private TextView txtTotalAmount;
private int overTotalPrice = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
recyclerView = findViewById(R.id.cart_list);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
NextProcessBtn = (Button) findViewById(R.id.next_process_btn);
txtTotalAmount = (TextView) findViewById(R.id.total_price);
NextProcessBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtTotalAmount.setText("Total Price = RM" + String.valueOf(overTotalPrice));
Intent intent = new Intent(Cart.this, ConfirmFinalOrder.class);
intent.putExtra("Total Price", String.valueOf(overTotalPrice));
startActivity(intent);
finish();
}
});
}
#Override
protected void onStart()
{
super.onStart();
txtTotalAmount.setText("Total Price = RM" + String.valueOf(overTotalPrice));
final DatabaseReference cartListRef = FirebaseDatabase.getInstance().getReference().child("Cart List");
FirebaseRecyclerOptions<CartModel> options =
new FirebaseRecyclerOptions.Builder<CartModel>()
.setQuery(cartListRef.child("User View").child(Prevalage.currentOnlineUser.getPhone())
.child("Products"),CartModel.class).build();
FirebaseRecyclerAdapter<CartModel, CartViewHolder> adapter
= new FirebaseRecyclerAdapter<CartModel, CartViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull CartViewHolder holder, int position, #NonNull final CartModel model)
{
holder.txtProductQuantity.setText("Quantity " + model.getQuantity());
holder.txtProductPrice.setText("Price = RM" + model.getPrice());
holder.txtProductName.setText(model.getPname());
***int oneTypeProductPrice = ((Integer.valueOf(model.getPrice()))) * Integer.valueOf(model.getQuantity());***
overTotalPrice = overTotalPrice + oneTypeProductPrice;
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CharSequence options[]= new CharSequence[]
{
"Edit",
"Remove",
};
AlertDialog.Builder builder = new AlertDialog.Builder(Cart.this);
builder.setTitle("Cart Options:");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
if (i == 0)
{
Intent intent = new Intent(Cart.this,ProductDetailActivity.class);
intent.putExtra("pid", model.getPid());
startActivity(intent);
}
if(i==1)
{
cartListRef.child("User View")
.child(Prevalage.currentOnlineUser.getPhone())
.child("Products")
.child(model.getPid())
.removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
Toast.makeText(Cart.this, "Item Removed Successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Cart.this,Home.class);
startActivity(intent);
}
}
});
}
}
});
builder.show();
}
});
}
#NonNull
#Override
public CartViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_items_layout, parent, false);
CartViewHolder holder = new CartViewHolder(view);
return holder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
}
use
(int) ParseDouble(model.getPrice())
instead of
Integer.valueOf(model.getPrice())
You can use this func.
double ParseDouble(String value) {
if (value != null && !value.isEmpty()) {
try {
return Double.parseDouble(value);
} catch(Exception e) {
return 0.0;
}
}
else return 0.0;
}
I have menu item in MainActivity it is filter(sort), I want that if user click on filter menu like A-z or z-a, in my MainActivity's onclick it is clicked but i want to get acknowledge in fragments as well
[nhewuhfduehiuhuewhucuewcueucueuncneincineincinencneincineinciniencineicnnecnnecneicniencnnecncncncnicnincincncnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnncncicieicieicicnicnncncicn]
code:
MainActivity:
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.TextAppearanceSpan;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.tabs.TabLayout;
import com.tekitsolutions.remindme.Adapter.ReminderListAdapter;
import com.tekitsolutions.remindme.Adapter.ViewPagerAdapter;
import com.tekitsolutions.remindme.Fragment.HomeFragment;
import com.tekitsolutions.remindme.Fragment.OfficeFragment;
import com.tekitsolutions.remindme.Fragment.OtherFragment;
import com.tekitsolutions.remindme.Interface.AdapterInterface;
import com.tekitsolutions.remindme.Interface.HamburgerMenuInterface;
import com.tekitsolutions.remindme.Interface.MenuItemListener;
import com.tekitsolutions.remindme.Interface.SearchListener;
import com.tekitsolutions.remindme.Model.General;
import com.tekitsolutions.remindme.Model.ParticularPayment;
import com.tekitsolutions.remindme.Model.Profile;
import com.tekitsolutions.remindme.Model.Reminder;
import com.tekitsolutions.remindme.R;
import com.tekitsolutions.remindme.RestApi.ApiClient;
import com.tekitsolutions.remindme.RestApi.ApiInterface;
import com.tekitsolutions.remindme.Sql.DatabaseAdapter;
import com.tekitsolutions.remindme.Utils.RemindMe;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.tekitsolutions.remindme.Utils.CommonUtils.CREATE_PASSCODE_ACTIVITY;
import static com.tekitsolutions.remindme.Utils.CommonUtils.GET_PROFILE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.IMAGE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PHONE_NUMBER;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PICK_SEARCH;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PROFILE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.USERNAME;
public class MainActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener, AdapterInterface, HamburgerMenuInterface, SearchListener, MenuItemListener {
private static final String TAG = MainActivity.class.getSimpleName();
#BindView(R.id.toolbar)
Toolbar toolbar;
#BindView(R.id.recycler_view)
RecyclerView listView;
private String phoneNum = null, getImage = null, getUsername = null;
private int first = 0, position = 0;
private ActionBar actionBar;
private DatabaseAdapter dbAdapter;
private ReminderListAdapter listAdapter;
private List<Reminder> listItems = new ArrayList<>();
private TabLayout tabLayout;
private ViewPager viewPager;
private MenuItemListener searchListener;
private DrawerLayout drawer;
private SharedPreferences profilePreference;
private TextView navUsername, navMobile;
private ImageView navImage;
private View headerView;
private NavigationView navigationView;
private SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
CREATE_PASSCODE_ACTIVITY = 0;
setThemeAndLoadLocale(MainActivity.this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
ButterKnife.bind(this);
setToolbar(toolbar, getString(R.string.app_name));
profilePreference = getSharedPreferences(PROFILE, MODE_PRIVATE);
getDataPhoneNumber();
tabLayout = findViewById(R.id.tab_layout);
viewPager = findViewById(R.id.view_pager);
drawer = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
headerView = navigationView.getHeaderView(0);
navUsername = headerView.findViewById(R.id.profile_name);
navMobile = headerView.findViewById(R.id.mobile_number);
navImage = headerView.findViewById(R.id.profile_image);
if (!phoneNum.isEmpty()) {
first = 1;
getProfileData();
}
Menu menu = navigationView.getMenu();
MenuItem tools = menu.findItem(R.id.nav_general_setting);
SpannableString s = new SpannableString(tools.getTitle());
s.setSpan(new TextAppearanceSpan(this, R.style.nav_header_color), 0, s.length(), 0);
tools.setTitle(s);
Menu menu2 = navigationView.getMenu();
MenuItem tools2 = menu2.findItem(R.id.nav_communicate);
SpannableString s2 = new SpannableString(tools2.getTitle());
s2.setSpan(new TextAppearanceSpan(this, R.style.nav_header_color), 0, s2.length(), 0);
tools2.setTitle(s2);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.AddFragment(new HomeFragment(), getResources().getString(R.string.fragment_home));
adapter.AddFragment(new OfficeFragment(), getResources().getString(R.string.fragment_office));
adapter.AddFragment(new OtherFragment(), getResources().getString(R.string.fragment_other));
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
listAdapter = new ReminderListAdapter(this, listItems, MainActivity.this, this, this);
listView.setHasFixedSize(true);
final LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(this);
listView.setLayoutManager(mLayoutManager);
listView.setItemAnimator(new DefaultItemAnimator());
try {
listView.setAdapter(listAdapter);
} catch (Exception exp) {
exp.printStackTrace();
}
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, AddReminderActivity.class));
}
});
dbAdapter = new DatabaseAdapter(this);
HomeFragment homeFragment = new HomeFragment();
homeFragment.setListener(this);
}
#Override
public void onClickFavoriteById(int isFavorite, long id) {
}
private void setData() {
if (getUsername != null && !getUsername.isEmpty()) {
navUsername.setText(getUsername.trim());
}
if (phoneNum != null && !phoneNum.isEmpty()) {
navMobile.setVisibility(View.VISIBLE);
navMobile.setText(phoneNum);
}
if (getImage != null && !getImage.isEmpty()) {
Bitmap bitmap = convertBase64ToBitMap(getImage);
navImage.setImageBitmap(bitmap);
} else {
navImage.setImageResource(R.drawable.user_image);
}
}
private void storeInSharedPreference() {
editor = getSharedPreferences(PROFILE, MODE_PRIVATE).edit();
editor.putString(USERNAME, getUsername);
editor.putString(IMAGE, getImage);
editor.apply();
}
private void getProfileData() {
ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call<List<Profile>> profileDetails = apiInterface.getProfileDetails(phoneNum);
profileDetails.enqueue(new Callback<List<Profile>>() {
#Override
public void onResponse(Call<List<Profile>> call, Response<List<Profile>> response) {
int statusCode = response.code();
if (statusCode == 200) {
List<Profile> responseList = response.body();
Profile profile = responseList.get(0);
showLog("username: " + profile.getProfileName());
getUsername = profile.getProfileName();
if (getUsername == null) {
showLog("Null");
} else {
showLog("Not null");
}
getImage = profile.getImage();
phoneNum = profile.getProfileNo();
setData();
storeInSharedPreference();
}
}
#Override
public void onFailure(Call<List<Profile>> call, Throwable t) {
showLog("Failed: " + t.getMessage());
}
});
}
private void getDataFromSharedPref() {
phoneNum = profilePreference.getString(PHONE_NUMBER, "");
getUsername = profilePreference.getString(USERNAME, "");
getImage = profilePreference.getString(IMAGE, "");
}
private void getDataPhoneNumber() {
phoneNum = profilePreference.getString(PHONE_NUMBER, "");
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Intent intent = null;
switch (item.getItemId()) {
case R.id.nav_profile:
intent = new Intent(this, ProfileActivity.class);
intent.putExtra(GET_PROFILE, true);
intent.putExtra(IMAGE, getImage);
intent.putExtra(USERNAME, getUsername);
startActivity(intent);
break;
case R.id.nav_favorite:
intent = new Intent(MainActivity.this, AddFavoriteReminder.class);
startActivity(intent);
break;
case R.id.nav_setting:
intent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(intent);
break;
case R.id.nav_passcode:
intent = new Intent(this, PasscodeActivity.class);
startActivity(intent);
break;
case R.id.nav_share:
String link = "https://drive.google.com/drive/folders/1sDS_hGb5s5SjyDIK3me3oY8cS1Oo1I4F?usp=sharing";
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
SpannableString ss = new SpannableString("Android is a Software stack");
String shareBodyText = link;
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBodyText);
startActivity(Intent.createChooser(sharingIntent, "Sharing Option"));
return true;
case R.id.nav_help:
intent = new Intent(MainActivity.this, HelpActivity.class);
startActivity(intent);
break;
case R.id.nav_feedback:
intent = new Intent(Intent.ACTION_SENDTO);
intent.setType("message/rfc822");
intent.setData(Uri.parse("mailto:"));
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"jimmytrivedi#outlook.com"});
intent.putExtra(Intent.EXTRA_SUBJECT, "Remind Me Feedback");
intent.putExtra(Intent.EXTRA_TEXT, "Developer Team,");
try {
startActivity(Intent.createChooser(intent, "Send Email"));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public void onClickReminderList(int position) {
}
private Bitmap convertBase64ToBitMap(String profileImage) {
try {
byte[] encodeByte = Base64.decode(profileImage, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
} catch (Exception e) {
showLog("" + e.getMessage());
return null;
}
}
#Override
protected void onResume() {
super.onResume();
CREATE_PASSCODE_ACTIVITY = 0;
if (RemindMe.isChanged()) {
RemindMe.setChanged(false);
recreate();
}
getDataFromSharedPref();
setData();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.search:
Intent intent = new Intent(MainActivity.this, SearchActivity.class);
startActivityForResult(intent, PICK_SEARCH);
break;
case R.id.filter:
break;
case R.id.ascending:
position = 1;
break;
case R.id.descending:
position = 2;
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_fragment_search, menu);
getMenuInflater().inflate(R.menu.menu_filter, menu);
return true;
}
#Override
public void onClickHamburger(long id) {
}
#Override
public void onClickListItem(int position) {
}
#Override
public void setToolbar(Toolbar toolBar, String title) {
super.setToolbar(toolBar, title);
}
private void showLog(String msg) {
Log.d(TAG, msg);
}
#Override
public void onSelectedProviderSearchItem(General general) {
}
#Override
public void onSelectedParticularPaymentSearchItem(ParticularPayment particularPayment) {
}
#Override
public void onSelectedReminderSearchItem(Reminder reminder) {
}
#Override
public void unused(int position) {
}
#Override
public void onFilterItem(int position) {
}
}
Interface
MenuItemListener
import com.tekitsolutions.remindme.Model.General;
import com.tekitsolutions.remindme.Model.ParticularPayment;
import com.tekitsolutions.remindme.Model.Reminder;
public interface MenuItemListener {
void onFilterItem(int position);
}
HomeFragment:
package com.tekitsolutions.remindme.Fragment;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.tekitsolutions.remindme.Activity.AddReminderActivity;
import com.tekitsolutions.remindme.Activity.MainActivity;
import com.tekitsolutions.remindme.Activity.ReminderDetailActivity;
import com.tekitsolutions.remindme.Adapter.ReminderListAdapter;
import com.tekitsolutions.remindme.Interface.AdapterInterface;
import com.tekitsolutions.remindme.Interface.HamburgerMenuInterface;
import com.tekitsolutions.remindme.Interface.MenuItemListener;
import com.tekitsolutions.remindme.Interface.SearchListener;
import com.tekitsolutions.remindme.Model.General;
import com.tekitsolutions.remindme.Model.ParticularPayment;
import com.tekitsolutions.remindme.Model.Reminder;
import com.tekitsolutions.remindme.R;
import com.tekitsolutions.remindme.Receiver.AlarmReceiver;
import com.tekitsolutions.remindme.RestApi.ApiClient;
import com.tekitsolutions.remindme.RestApi.ApiInterface;
import com.tekitsolutions.remindme.Sql.DatabaseAdapter;
import com.tekitsolutions.remindme.Utils.RecyclerViewClickListener;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_FAVORITE;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_ID;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_TYPE_ID;
import static com.tekitsolutions.remindme.Utils.CommonUtils.HOME;
import static com.tekitsolutions.remindme.Utils.CommonUtils.IS_EDIT;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PICK_HOME;
public class HomeFragment extends Fragment implements AdapterInterface, HamburgerMenuInterface, Callback<String>, SearchListener, MenuItemListener {
private static final String TAG = HomeFragment.class.getSimpleName();
public MainActivity activity;
public Context context;
View view;
private DatabaseAdapter dbAdapter;
private List<Reminder> listItems = new ArrayList<>();
private ReminderListAdapter listAdapter;
private MenuItemListener menuItemListener;
private RecyclerView listView;
private TextView tvNoData;
private AdapterInterface listener;
private HamburgerMenuInterface menuInterface;
private AlertDialog.Builder builder;
private Reminder reminder;
private long reminderId = 0;
private int getFavorite = 0;
public HomeFragment() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.home_fragment, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView = view.findViewById(R.id.recycler_view);
tvNoData = view.findViewById(R.id.tv_no_data);
dbAdapter = new DatabaseAdapter(getContext());
listAdapter = new ReminderListAdapter(getActivity(), listItems, HomeFragment.this, this, this);
listView.setHasFixedSize(false);
final LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(getActivity());
listView.setLayoutManager(mLayoutManager);
listView.setItemAnimator(new DefaultItemAnimator());
try {
listView.setAdapter(listAdapter);
} catch (Exception exp) {
exp.printStackTrace();
}
listView.addOnItemTouchListener(new RecyclerViewClickListener.RecyclerTouchListener(getContext(),
listView, new RecyclerViewClickListener.ClickListener() {
#Override
public void onClick(View view, int position) {
}
#Override
public void onLongClick(View view, int position) {
}
}
));
loadAllReminders();
}
#Override
public void onStart() {
super.onStart();
loadAllReminders();
}
private void loadAllReminders() {
listItems.clear();
List<Reminder> list = dbAdapter.getReminderById(REMINDER_TYPE_ID, HOME);
if (list.size() > 0) {
tvNoData.setVisibility(View.GONE);
listItems.addAll(list);
listAdapter.notifyDataSetChanged();
} else {
tvNoData.setVisibility(View.VISIBLE);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.menuItemListener = (MenuItemListener) getActivity();
}
private void showLog(String msg) {
Log.d(TAG, msg);
}
#Override
public void onFilterItem(int position) {
showLog("test: " + position);
}
public void setListener(MenuItemListener listener) {
this.menuItemListener = listener;
}
}
You can do this with EventBus or Interface. You can follow these steps for EventBus.
Implement EventBus
implementation 'org.greenrobot:eventbus:3.1.1'
EventBustDataEvents.class
public class EventBusDataEvents{
public static class isClick {
boolean isClick;
public isClick(boolean isClick) {
this.isClick = isClick;
}
public boolean getIsClick() {
return isClick;
}
public void setIsClick(boolean isClick) {
this.isClick = isClick;
}
}
}
MainActivity.class
EventBus.getDefault().postSticky(new EventBusDataEvents.isClick(true));
Fragment.class
#Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void isClick(EventBusDataEvents.isClick click) {
if (click.isClick()) {
}
}
#Override
public void onStart() {
super.onStart();
try {
EventBus.getDefault().register(this);
} catch (Exception e) {
}
}
#Override
public void onDestroy() {
super.onDestroy();
try {
EventBus.getDefault().unregister(this);
} catch (Exception e) {
}
}
Or Interface
IMainActivity.class // interface class
public interface IMainActivity {
void onClick();}
MainActivity.class
private IMainActivity listener; //This will be described above as a field.
public void setOnEventListener(IMainActivity listener) {
IMainActivity = listener;
}
//buttonClickEvent
listener.OnClick();
Fragment.class
//onCreateView
setOnEventListener(new IMainActivity() {
#Override
public void onClick() {
}
});
I have some code whose function is to show the name and age of a user in a RecyclerView but that same RecyclerView is always returning null no matter where I put it.
I tried to put getUserInfo() in onStart() and it didn't work.
I've already looked in other posts in StackOverflow and it still hasn't worked.
My MainActivity.java
package com.pap.diogo.pilltrack;
import android.accounts.Account;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity {
private RelativeLayout pills_layout, appoint_layout, add_pills_layout, add_appoints_layout, account_layout, add_button;
private View pills, appointments, add_pills, add_appoints, account;
private TextView AccountName0, AccountAge0;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
Home();
return true;
case R.id.navigation_pills:
Pills();
return true;
case R.id.navigation_appointment:
Appointment();
return true;
case R.id.navigation_account:
Account();
return true;
}
return false;
}
};
public MainActivity() {
}
private void Account(){
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) add_button.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.account);
pills_layout.removeView(pills);
appoint_layout.removeView(appointments);
add_pills_layout.removeView(add_pills);
add_appoints_layout.removeView(add_appoints);
//account_layout.removeAllViews();
//account_layout.addView(account);
add_button.setVisibility(View.VISIBLE);
getUserInfo();
}
private void Appointment() {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) add_button.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.add_appoints);
pills_layout.removeView(pills);
appoint_layout.removeView(appointments);
add_pills_layout.removeView(add_pills);
//account_layout.removeView(account);
add_appoints_layout.removeAllViews();
add_appoints_layout.addView(add_appoints);
add_button.setVisibility(View.VISIBLE);
}
private void Pills() {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) add_button.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.add_pills);
pills_layout.removeView(pills);
appoint_layout.removeView(appointments);
add_appoints_layout.removeView(add_appoints);
//account_layout.removeView(account);
add_pills_layout.removeAllViews();
add_pills_layout.addView(add_pills);
add_button.setVisibility(View.VISIBLE);
}
private void Home() {
add_appoints_layout.removeView(add_appoints);
add_pills_layout.removeView(add_pills);
//account_layout.removeView(account);
pills_layout.removeAllViews();
pills_layout.addView(pills);
appoint_layout.removeAllViews();
appoint_layout.addView(appointments);
add_button.setVisibility(View.GONE);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pills_layout = findViewById(R.id.pills_layout);
appoint_layout = findViewById(R.id.appoint_layout);
add_pills_layout = findViewById(R.id.add_pills);
add_appoints_layout = findViewById(R.id.add_appoints);
//account_layout = findViewById(R.id.account);
add_button = findViewById(R.id.add);
AccountName0 = findViewById(R.id.AccountName0);
AccountAge0 = findViewById(R.id.AccountAge0);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
pills = inflater.inflate(R.layout.pills, null);
appointments = inflater.inflate(R.layout.appointments, null);
add_pills = inflater.inflate(R.layout.add_pills, null);
add_appoints = inflater.inflate(R.layout.add_appoint, null);
account = inflater.inflate(R.layout.account, null);
pills_layout.addView(pills);
appoint_layout.addView(appointments);
add_button.setVisibility(View.GONE);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
public void getUserInfo(){
RecyclerView accountUsers;
if ((accountUsers = account.findViewById(R.id.AccountList)) != null)
{
accountUsers.setHasFixedSize(true);
accountUsers.setLayoutManager(new LinearLayoutManager(getBaseContext()));
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
final String userid = user.getUid();
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");
FirebaseRecyclerOptions<AccountLayout> AccountQ = new FirebaseRecyclerOptions.Builder<AccountLayout>().setQuery(ref, AccountLayout.class).setLifecycleOwner(this).build();
FirebaseRecyclerAdapter<AccountLayout, AccountInfo> AccountAdapter = new FirebaseRecyclerAdapter<AccountLayout, AccountInfo>(AccountQ){
#NonNull
#Override
public AccountInfo onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
return new AccountInfo(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.account_layout, viewGroup, false));
}
#Override
protected void onBindViewHolder(#NonNull final AccountInfo holder, int position, #NonNull final AccountLayout model) {
ref.child(userid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
final String name = dataSnapshot.child("name").getValue().toString();
final String age = dataSnapshot.child("idade").getValue().toString();
holder.setName(name);
holder.setAge(age);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
};
accountUsers.setAdapter(AccountAdapter);
}
}
public static class AccountInfo extends RecyclerView.ViewHolder{
View AccountL;
public AccountInfo(#NonNull View itemView) {
super(itemView);
AccountL = itemView;
}
public void setName(String name){
TextView AccountName = AccountL.findViewById(R.id.AccountName0);
AccountName.setText(name);
}
public void setAge(String age){
TextView AccountAge = AccountL.findViewById(R.id.AccountAge0);
AccountAge.setText(age);
}
}
}
My AccountLayout.java
package com.pap.diogo.pilltrack;
public class AccountLayout {
private String name, idade;
public AccountLayout() {
}
public AccountLayout(String name, String idade) {
this.name = name;
this.idade = idade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIdade() {
return idade;
}
public void setIdade(String idade) {
this.idade = idade;
}
}
My account.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/AccountList"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
Modify your code as below:
public void getUserInfo(){
RecyclerView accountUsers = (RecyclerView) account.findViewById(R.id.AccountList);
if (accountUsers != null)
{
...
I run my App on my phone. Everything works perfectly.. But after i check in my logcat for the debug.
It's show me this error.
E/HAL: hw_get_module_by_class: module name gralloc
E/HAL: hw_get_module_by_class: module name gralloc
It's show when user run the app for the first time. It's show just in time the app show splash screen. I'm not sure which code that make this thing happen.
So i'll show you my splash code and my fragment home code.
so this is my splasactivity code :
package com.apps.mathar;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Window;
import android.view.WindowManager;
import com.apps.utils.Constant;
import com.apps.utils.JsonUtils;
public class SplashActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
// hideStatusBar();
setStatusColor();
try {
Constant.isFromPush = getIntent().getExtras().getBoolean("ispushnoti", false);
Constant.pushID = getIntent().getExtras().getString("noti_nid");
} catch (Exception e) {
Constant.isFromPush = false;
}
try {
Constant.isFromNoti = getIntent().getExtras().getBoolean("isnoti", false);
} catch (Exception e) {
Constant.isFromNoti = false;
}
JsonUtils jsonUtils = new JsonUtils(SplashActivity.this);
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, Constant.GRID_PADDING, r.getDisplayMetrics());
Constant.columnWidth = (int) ((jsonUtils.getScreenWidth() - ((Constant.NUM_OF_COLUMNS + 1) * padding)) / Constant.NUM_OF_COLUMNS);
if(!Constant.isFromNoti) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
openMainActivity();
}
}, 2000);
} else {
openMainActivity();
}
}
private void openMainActivity() {
Intent intent = new Intent(SplashActivity.this,MainActivity.class);
startActivity(intent);
finish();
}
public void setStatusColor()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(getResources().getColor(R.color.statusBar));
}
}
}
And this is my fragmenthome code
package com.apps.mathar;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.apps.adapter.AdapterRecent;
import com.apps.item.ItemSong;
import com.apps.utils.Constant;
import com.apps.utils.DBHelper;
import com.apps.utils.JsonUtils;
import com.apps.utils.RecyclerItemClickListener;
import com.apps.utils.ZProgressHUD;
import com.google.android.gms.ads.AdListener;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class FragmentHome extends Fragment {
DBHelper dbHelper;
RecyclerView recyclerView;
ArrayList<ItemSong> arrayList;
ArrayList<ItemSong> arrayList_recent;
AdapterRecent adapterRecent;
ZProgressHUD progressHUD;
LinearLayoutManager linearLayoutManager;
public ViewPager viewpager;
ImagePagerAdapter adapter;
TextView textView_empty;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
setHasOptionsMenu(true);
dbHelper = new DBHelper(getActivity());
progressHUD = ZProgressHUD.getInstance(getActivity());
progressHUD.setMessage(getActivity().getResources().getString(R.string.loading));
progressHUD.setSpinnerType(ZProgressHUD.FADED_ROUND_SPINNER);
textView_empty = (TextView)rootView.findViewById(R.id.textView_recent_empty);
adapter = new ImagePagerAdapter();
viewpager = (ViewPager)rootView.findViewById(R.id.viewPager_home);
viewpager.setPadding(80,20,80,20);
viewpager.setClipToPadding(false);
viewpager.setPageMargin(40);
viewpager.setClipChildren(false);
// viewpager.setPageTransformer(true,new BackgroundToForegroundTransformer());
arrayList = new ArrayList<ItemSong>();
arrayList_recent = new ArrayList<ItemSong>();
recyclerView = (RecyclerView)rootView.findViewById(R.id.recyclerView_home_recent);
linearLayoutManager = new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL,false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setHasFixedSize(true);
if (JsonUtils.isNetworkAvailable(getActivity())) {
new LoadLatestNews().execute(Constant.URL_LATEST);
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.internet_not_conn), Toast.LENGTH_SHORT).show();
}
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
if(JsonUtils.isNetworkAvailable(getActivity())) {
Constant.isOnline = true;
Constant.arrayList_play.clear();
Constant.arrayList_play.addAll(arrayList_recent);
Constant.playPos = position;
((MainActivity)getActivity()).changeText(arrayList_recent.get(position).getMp3Name(),arrayList_recent.get(position).getCategoryName(),position+1,arrayList_recent.size(),arrayList_recent.get(position).getDuration(),arrayList_recent.get(position).getImageBig(),"home");
Constant.context = getActivity();
if(position == 0) {
Intent intent = new Intent(getActivity(), PlayerService.class);
intent.setAction(PlayerService.ACTION_FIRST_PLAY);
getActivity().startService(intent);
}
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.internet_not_conn), Toast.LENGTH_SHORT).show();
}
}
}));
return rootView;
}
private class LoadLatestNews extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
progressHUD.show();
arrayList.clear();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
String json = JsonUtils.getJSONString(strings[0]);
JSONObject mainJson = new JSONObject(json);
JSONArray jsonArray = mainJson.getJSONArray(Constant.TAG_ROOT);
JSONObject objJson = null;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
String id = objJson.getString(Constant.TAG_ID);
String cid = objJson.getString(Constant.TAG_CAT_ID);
String cname = objJson.getString(Constant.TAG_CAT_NAME);
String artist = objJson.getString(Constant.TAG_ARTIST);
String name = objJson.getString(Constant.TAG_SONG_NAME);
String url = objJson.getString(Constant.TAG_MP3_URL);
String desc = objJson.getString(Constant.TAG_DESC);
String duration = objJson.getString(Constant.TAG_DURATION);
String image = objJson.getString(Constant.TAG_THUMB_B).replace(" ","%20");
String image_small = objJson.getString(Constant.TAG_THUMB_S).replace(" ","%20");
ItemSong objItem = new ItemSong(id,cid,cname,artist,url,image,image_small,name,duration,desc);
arrayList.add(objItem);
}
return "1";
} catch (JSONException e) {
e.printStackTrace();
return "0";
} catch (Exception ee) {
ee.printStackTrace();
return "0";
}
}
#Override
protected void onPostExecute(String s) {
recyclerView.setAdapter(adapterRecent);
if(s.equals("1")) {
progressHUD.dismissWithSuccess(getResources().getString(R.string.success));
// setLatestVariables(0);
if(Constant.isAppFirst) {
if(arrayList.size()>0) {
Constant.isAppFirst = false;
Constant.arrayList_play.addAll(arrayList);
((MainActivity)getActivity()).changeText(arrayList.get(0).getMp3Name(),arrayList.get(0).getCategoryName(),1,arrayList.size(),arrayList.get(0).getDuration(),arrayList.get(0).getImageBig(),"home");
Constant.context = getActivity();
}
}
viewpager.setAdapter(adapter);
loadRecent();
// adapterPagerTrending = new AdapterPagerTrending(getActivity(),Constant.arrayList_trending);
// viewPager_trending.setAdapter(adapterPagerTrending);
// adapterTopStories = new AdapterTopStories(getActivity(),Constant.arrayList_topstories);
// listView_topstories.setAdapter(adapterTopStories);
// setListViewHeightBasedOnChildren(listView_topstories);
adapterRecent.notifyDataSetChanged();
} else {
progressHUD.dismissWithFailure(getResources().getString(R.string.error));
Toast.makeText(getActivity(), getResources().getString(R.string.server_no_conn), Toast.LENGTH_SHORT).show();
}
super.onPostExecute(s);
recyclerView.setAdapter(adapterRecent);
}
}
private void loadRecent() {
arrayList_recent = dbHelper.loadDataRecent();
adapterRecent = new AdapterRecent(getActivity(),arrayList_recent);
recyclerView.setAdapter(adapterRecent);
if(arrayList_recent.size() == 0) {
recyclerView.setVisibility(View.GONE);
textView_empty.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
textView_empty.setVisibility(View.GONE);
}
}
private class ImagePagerAdapter extends PagerAdapter {
private LayoutInflater inflater;
public ImagePagerAdapter() {
// TODO Auto-generated constructor stub
inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View imageLayout = inflater.inflate(R.layout.viewpager_home, container, false);
assert imageLayout != null;
ImageView imageView = (ImageView) imageLayout.findViewById(R.id.imageView_pager_home);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading_home);
TextView title = (TextView) imageLayout.findViewById(R.id.textView_pager_home_title);
TextView cat = (TextView) imageLayout.findViewById(R.id.textView_pager_home_cat);
RelativeLayout rl = (RelativeLayout)imageLayout.findViewById(R.id.rl_homepager);
title.setText(arrayList.get(position).getMp3Name());
cat.setText(arrayList.get(position).getCategoryName());
Picasso.with(getActivity())
.load(arrayList.get(position).getImageBig())
.placeholder(R.mipmap.app_icon)
.into(imageView, new Callback() {
#Override
public void onSuccess() {
spinner.setVisibility(View.GONE);
}
#Override
public void onError() {
spinner.setVisibility(View.GONE);
}
});
rl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(JsonUtils.isNetworkAvailable(getActivity())) {
//showInter();
playIntent();
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.internet_not_conn), Toast.LENGTH_SHORT).show();
}
}
});
container.addView(imageLayout, 0);
return imageLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
/* private void showInter() {
Constant.adCount = Constant.adCount + 1;
if(Constant.adCount % Constant.adDisplay == 0) {
((MainActivity)getActivity()).mInterstitial.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
playIntent();
super.onAdClosed();
}
});
if(((MainActivity)getActivity()).mInterstitial.isLoaded()) {
((MainActivity)getActivity()).mInterstitial.show();
((MainActivity)getActivity()).loadInter();
} else {
playIntent();
}
} else {
playIntent();
}
}
*/
private void playIntent() {
Constant.isOnline = true;
int pos = viewpager.getCurrentItem();
Constant.arrayList_play.clear();
Constant.arrayList_play.addAll(arrayList);
Constant.playPos = pos;
((MainActivity)getActivity()).changeText(arrayList.get(pos).getMp3Name(),arrayList.get(pos).getCategoryName(),pos+1,arrayList.size(),arrayList.get(pos).getDuration(),arrayList.get(pos).getImageBig(),"home");
Constant.context = getActivity();
if(pos == 0) {
Intent intent = new Intent(getActivity(), PlayerService.class);
intent.setAction(PlayerService.ACTION_FIRST_PLAY);
getActivity().startService(intent);
}
}
}
Once more, i'm sure what's going on here.
I'm looking this error since 3 days ago but i have checked my code, i dont know what is wrong with this code.
This kind of error occurs when you have a loop that doesn't terminate.I also faced the similar kind of situation and It took me literally two days to find out the root cause of problem.
My problem was:
When I run the above code, I used to get this kind of error
hw_get module_by class _gralloc... .
I was really frustrated because I was not able to find out the root cause and luckily I found out that the above section of the code was the main cause because the loop never goes to terminate in the above section and when I found about the problem main cause I replaced it by:
Then, the problem was solved..
So maybe your problem lies within the loop or similar kind of situations..
I have a RecyclerView and each item is a button. Each button will call the same activity by passing a different parameter to this activity.
I tried many solutions found on the web but none of them had worked for me.
Here is my adapter :
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import java.util.List;
public class FormAdapter extends RecyclerView.Adapter<FormAdapter.FormViewHolder> {
private List<Form> forms;
private int rowLayout;
private Context context;
public class FormViewHolder extends RecyclerView.ViewHolder {
LinearLayout formsLayout;
Button form;
public FormViewHolder(View v) {
super(v);
formsLayout = (LinearLayout) v.findViewById(R.id.forms_layout);
form = (Button) v.findViewById(R.id.formButton);
}
}
public FormAdapter(List<Form> forms, int rowLayout, Context context) {
this.forms = forms;
this.rowLayout = rowLayout;
this.context = context;
}
#Override
public FormAdapter.FormViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
return new FormViewHolder(view);
}
#Override
public void onBindViewHolder(FormViewHolder holder, final int position) {
holder.form.setText(forms.get(position).getSubject());
}
#Override
public int getItemCount() {
return forms.size();
}
}
A form is represented by the following class :
public class Form {
private final String subject;
private final int idForm;
public Form(String subject,int idForm)
{
this.idForm=idForm;
this.subject=subject;
}
public String getSubject()
{
return subject;
}
public int getIdForm()
{
return idForm;
}
}
And here is my MainActivity :
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private final static int idCreator = 1;
private FormAdapter formAdapter;
private List<Form> forms;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Main activity");
final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerViewForm);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
Formable formService =
ApiClient.getClient().create(Formable.class);
Call<List<Form>> call = formService.getForms(idCreator);
call.enqueue(new Callback<List<Form>>() {
#Override
public void onResponse(Call<List<Form>> call, Response<List<Form>> response) {
forms = response.body();
formAdapter=new FormAdapter(forms, R.layout.one_form, getApplicationContext());
recyclerView.setAdapter(formAdapter);
}
#Override
public void onFailure(Call<List<Form>> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
}
}
I have my buttons on screen but I don't understand how to make them call the activity "QuestionsActivity" with a parameter "idForm" that I know.
Here is the MainActivity when I run the app
Thanks in advance for your help
You can get item data by following way when you click on recyclerview item:
Create Interface in your adapter and use it in your activity:
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
Now Your code look like below:
FormAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import java.util.List;
public class FormAdapter extends RecyclerView.Adapter<FormAdapter.FormViewHolder> {
private List<Form> forms;
private int rowLayout;
private Context context;
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
public class FormViewHolder extends RecyclerView.ViewHolder {
LinearLayout formsLayout;
Button form;
public FormViewHolder(View v) {
super(v);
formsLayout = (LinearLayout) v.findViewById(R.id.forms_layout);
form = (Button) v.findViewById(R.id.formButton);
}
}
public FormAdapter(List<Form> forms, int rowLayout, Context context) {
this.forms = forms;
this.rowLayout = rowLayout;
this.context = context;
}
#Override
public FormAdapter.FormViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
return new FormViewHolder(view);
}
#Override
public void onBindViewHolder(FormViewHolder holder, final int position) {
holder.form.setText(forms.get(position).getSubject());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mListener!=null)
{
mListener.onItemClick(view,position);
}
}
});
}
#Override
public int getItemCount() {
return forms.size();
}
public void setOnItemClick(OnItemClickListener listener)
{
this.mListener=listener;
}
}
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import com.newstory.android.R;
import com.newstory.android.activity.FormAdapter;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private final static int idCreator = 1;
private FormAdapter formAdapter;
private List<Form> forms;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Main activity");
final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerViewForm);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
Formable formService =
ApiClient.getClient().create(Formable.class);
Call<List<Form>> call = formService.getForms(idCreator);
call.enqueue(new Callback<List<Form>>() {
#Override
public void onResponse(Call<List<Form>> call, Response<List<Form>> response) {
forms = response.body();
formAdapter=new FormAdapter(forms, R.layout.one_form, getApplicationContext());
recyclerView.setAdapter(formAdapter);
setOnItemListener();
}
#Override
public void onFailure(Call<List<Form>> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
}
public void setOnItemListener(){
if(formAdapter!=null)
{
formAdapter.setOnItemClick(new FormAdapter.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Form clickedForm=forms.get(position);
// You can call QuestionsActivity here
//Now you can access [Form] data
Log.d("getIdForm->",String.valueOf(clickedForm.getIdForm()))
}
});
}
}
}
I hope it's helps you.
Do this way :
form.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something when the form is clicked
context.startActivity(new Intent(context, YourActivity.class)
.putExtra("idForm", someValue));
}
});
In your adapter's onBindViewHolder method, assign a click listener to the button view element, so it would look something like this:
#Override
public void onBindViewHolder(FormViewHolder holder, final int position {
holder.form.setText(forms.get(position).getSubject());
holder.form.setOnClickListener(v -> {
startQuestionsWithId(forms.get(position).getIdForm);
});
}
And then, your startQuestionsWithIdmethod would typically be like:
private void startQuestionsWithId(int idForm) {
Intent intent = new Intent(context, QuestionsActivity.class);
intent.putExtra("id_form", idForm);
context.startActivity(intent);
}