I have the following problem.
Activity 1: Where do I send a user ID by PutExtra.
Activity 2: Get the data with GetExtra.
At some point in Activity 2 I send to Activity 3, sending is done again with PutExtra.
I want to go back to activity 2, sending the data as PutExtra. But in activity 2 you already have a GetExtra that expects the data from activity 1, so it is giving an error. How can I send this data from Activity 3 to Activity 2 and not conflict with Activity 2 because I already expect data with GetExtra from Activity 1.
Note: The data sent is always the same. It is always the user ID that is sent as PutExtra and also received as GetExtra.
EDIT:
Code sending or given from Activity 2 to Activity 3
public class PerfilEmpTab2 extends Fragment {
private RecyclerView mCardServicoList;
private String mId_Empresa = null;
private DatabaseReference mDatabaseServicos;
private boolean mProcessAddServico = false;
public PerfilEmpTab2() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_perfil_emp_tab2, container, false);
/* Recebe id de outra tela*/
mId_Empresa = getActivity().getIntent().getExtras().getString("id_empresa");
mDatabaseServicos = FirebaseDatabase.getInstance().getReference().child("Produtos_Empresas").child(mId_Empresa);
/*Recuperar REcyclerView*/
mCardServicoList = (RecyclerView) view.findViewById(R.id.cardListaServicos);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
//mCardCategList.setHasFixedSize(true);
mCardServicoList.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
/*Fim Recycler View*/
loadServicos();
return view;
}
private void loadServicos() {
FirebaseRecyclerAdapter<CardServico_row, CardServicosViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<CardServico_row, CardServicosViewHolder>(
CardServico_row.class,
R.layout.card_servicos_row,
CardServicosViewHolder.class,
mDatabaseServicos
) {
#Override
protected void populateViewHolder(final CardServicosViewHolder viewHolder, final CardServico_row model, int position) {
final String servico_key = getRef(position).getKey();
final String nome_produto = model.getNome_produto();
final String duracao = model.getDuracao();
final String valor = model.getValor();
final String valorOld = model.getValorOld();
viewHolder.setNome_produto(model.getNome_produto());
viewHolder.setDuracao(model.getDuracao());
viewHolder.setValor(model.getValor());
viewHolder.setValorOld(model.getValorOld());
/*Clique na view*/
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intentServicoDetalhes = new Intent(getActivity(), ServicoDetalhes.class);
intentServicoDetalhes.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentServicoDetalhes.putExtra("id_empresa", mId_Empresa);
startActivity(intentServicoDetalhes);
}
});
viewHolder.mAddBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Toast.makeText(Categorias.this, nome + post_key, Toast.LENGTH_LONG).show();
CharSequence opcoes[] = new CharSequence[] {"Editar Serviço", "Ver Detalhes"};
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//builder.setTitle("Opçoes");
//builder.setCancelable(false);
builder.setItems(opcoes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// the user clicked on colors[which]
switch (which) {
case 0:
Toast.makeText(getActivity().getApplication(), "Dados" + "-" + servico_key + "-" + nome_produto + "-" + duracao + "-" + valor + "-" + valorOld, Toast.LENGTH_LONG).show();
/*Intent criarSubC = new Intent(Categorias.this, CadastroSubCategorias.class);
criarSubC.putExtra("id_categ", post_key);
startActivity(criarSubC);*/
mProcessAddServico = false;
break;
case 1:
Toast.makeText(getActivity().getApplication(), "Dados" + "-" + servico_key + "-" + nome_produto + "-" + duracao + "-" + valor + "-" + valorOld, Toast.LENGTH_LONG).show();
mProcessAddServico = false;
break;
}
}
});
builder.show();
}
});
}
};
mCardServicoList.setAdapter(firebaseRecyclerAdapter);
}
public static class CardServicosViewHolder extends RecyclerView.ViewHolder{
View mView;
ImageButton mAddBtn;
public CardServicosViewHolder (View itemView){
super(itemView);
mView = itemView;
mAddBtn = (ImageButton) mView.findViewById(R.id.addServico_tab2);
}
public void setNome_produto(String nome_produto){
TextView card_nomeProduto = (TextView) mView.findViewById(R.id.tvNomeProduto);
card_nomeProduto.setText(nome_produto);
}
public void setDuracao(String duracao){
TextView card_duracao = (TextView) mView.findViewById(R.id.tvDuracao);
card_duracao.setText(duracao);
}
public void setValor(String valor){
TextView card_valor = (TextView) mView.findViewById(R.id.tvValor);
card_valor.setText(valor);
}
public void setValorOld(final String valorOld){
if ( valorOld != null ){
TextView card_valorOld = (TextView) mView.findViewById(R.id.tvValorOld);
card_valorOld.setText(valorOld);
card_valorOld.setPaintFlags(card_valorOld.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); // Risca o texto
//card_valorOld.setPaintFlags(card_valorOld.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG)); // Remove o Risca o texto
} else {
TextView card_valorOld = (TextView) mView.findViewById(R.id.tvValorOld);
card_valorOld.setText(valorOld);
card_valorOld.setVisibility(View.GONE);
}
}
}
}
In Activity 3 I get:
mId_Empresa = getIntent().getExtras().getString("id_empresa");
When you start activity 3 call startActivityForResult(intent, code) instead of startActivity(intint). Then in Activity 3 override finish() and call setResult(Activity.RESULT_OK, data) where data is an object that you have created new Intent() and called putExtra data.putExtra(key, value) on as you want. Then in Activity 2 override onActivityResult(int requestCode, int resultCode, Intent data) to handle it. requestCode is the code you started the activity with. Be aware that onActivityResult occurs before onResume so attempting to update the UI from onActivityResult might not work as expected eg notifying an adapter.
Refer to this doc for more info
https://developer.android.com/training/basics/intents/result.html
EDIT: added code example
Starting activity 3 from activity 2:
static final int SERVICO_DETALHES_REQUEST = 1; // The request code
#Override
public void onClick(View view) {
{
Intent intentServicoDetalhes = new Intent(getActivity(), ServicoDetalhes.class);
intentServicoDetalhes.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentServicoDetalhes.putExtra("id_empresa", mId_Empresa);
startActivityForResult(intentServicoDetalhes, SERVICO_DETALHES_REQUEST );
}
Setting the result from activity 3:
#Override
public void finish()
{
Intent data = new Intent();
data.putExtra("id_empresa", "new_id");
setResult(Activity.RESULT_OK, data);
super.finish();
}
Handling the result from activity 2:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == SERVICO_DETALHES_REQUEST && resultCode == RESULT_OK)
String newId = data.getStringExtra("id_empresa");
}
Related
I have a form where a person can enter details about a friend (name, age, gender, address). This friend is displayed in a list view and when a friend from the list is clicked on they have the choice to edit that record.
I can successfully update every detail about a friend except for the gender.
For example:
List view:
1) James Bond, 20, Male, Sydney NSW
Then I click edit and change it to
James smith, 21, Female, Canberra NSW
and then back in my list view it will show:
1) James smith, 21, Male, Canberra NSW
Notice how the gender doesn't change?
I can figure out why this is happening as I use the same logic to change the name and age as i did to change the gender
Here is the relevant code:
ViewFriend.java ( this class displays the list view and has the edit option)
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {
String text = listView.getItemAtPosition(position).toString();
final int ID = Integer.parseInt(String.valueOf(text.charAt(0)));
AlertDialog.Builder builder = new AlertDialog.Builder(viewFriends.this);
builder.setTitle("Notice");
builder.setMessage("Please select to to edit, delete a friend or cancel");
// add the buttons
builder.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), editOrDelete.class);
ArrayList<String> result1 = mydb.retrieveRow(ID);
name = result1.get(1);
age = result1.get(2);
gender = result1.get(3);
address = result1.get(4);
code = result1.get(0);
intent.putExtra("code", code);
intent.putExtra("name", name);
intent.putExtra("age", age);
intent.putExtra("gender", gender);
intent.putExtra("address", address);
startActivity(intent);
}
});
builder.setNeutralButton(" Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mydb.deleteTitle(ID);
finish();
Intent intent = new Intent(getApplicationContext(),viewFriends.class);
startActivity(intent);
}
});
builder.setNegativeButton("Cancel", null);
AlertDialog dialog = builder.create();
dialog.show();
}
});
The code above retrieves the details from the database and passes it to the intent. I have printed the contents of each variable (name, age, gender, address) and they print out correctly.
editFriend.java ( this class pre fills the form with the data passed through the intent that displays correctly)
public class editFriend extends AppCompatActivity {
private Intent intent;
private RadioGroup rg;
private Button update;
private RadioButton rb;
private String newName,newAddress,newGender;
private int newAge;
EditText ed, ed1;
public String name,address,gender,age,code;
private int selectedID,ages,codes;
NumberPicker numberPicker;
private databaseManager4 myDataBase;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_editordeletefriend);
intent= getIntent();
myDataBase = new databaseManager4(this);
rg = (RadioGroup)findViewById(R.id.radioGroup_update);
selectedID = rg.getCheckedRadioButtonId();
rb = (RadioButton) findViewById(selectedID);
ed = (EditText)findViewById(R.id.fullName_update);
numberPicker = (NumberPicker)findViewById(R.id.resultAge_update);
numberPicker.setMinValue(6);
numberPicker.setMaxValue(110);
numberPicker.setWrapSelectorWheel(false);
update = (Button)findViewById(R.id.update_button);
ed1 = (EditText)findViewById(R.id.address_update);
name = intent.getStringExtra("name");
age = intent.getStringExtra("age");
gender = intent.getStringExtra("gender");
address = intent.getStringExtra("address");
code = intent.getStringExtra("code");
codes = Integer.parseInt(code);
displayForm();
newName = ed.getText().toString();
newAge = numberPicker.getValue();
newGender = rb.getText().toString();
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = rg.getCheckedRadioButtonId();
rb = (RadioButton) findViewById(id);
if (myDataBase.updateRow(codes,newName,newAge,newGender,ed1.getText().toString())){
Toast.makeText(getApplicationContext(),"successfully updated the friend "
+ed.getText().toString(),Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(),"Could not update the friend "
+ed.getText().toString(),Toast.LENGTH_SHORT).show();
}
intent = new Intent(getApplicationContext(),viewFriends.class);
startActivity(intent);
}
});
}
public void displayForm(){
ed.setText(name);
ed1.setText(address);
if (gender.equals("Male")){
rb = (RadioButton)findViewById(R.id.resultGenderMale_update);
}
else if (gender.equals("Female"))
{
rb = (RadioButton)findViewById(R.id.resultGenderFemale_update);
}
rb.setChecked(true);
ages= Integer.parseInt(age);
numberPicker.setValue(ages);
}
public void clear(){
ed.setText("");
ed1.setText("");
}
}
This is where the issue lies, even if the user clicks on Male it registers as female and i am unsure why.
Any ideas how i can fix this?
Your problem is that you set value of rb variable to a single radio button, predefined with previous gender value here
if (gender.equals("Male")){
rb = (RadioButton)findViewById(R.id.resultGenderMale_update);
}
else if (gender.equals("Female"))
{
rb = (RadioButton)findViewById(R.id.resultGenderFemale_update);
}
And you read value of the same button then. To fix that in you click listener for update button you need to read checked radio button id using getCheckedRadioButtonId on radio group (your rg variable).
upd:
this is how your Edit Friend activity code might look like
public class EditFriendActivity extends AppCompatActivity {
private RadioGroup mGenderRadioGroup;
private Button mUpdateButton;
private EditText mNameField;
private EditText mAddressField;
private NumberPicker mAgePicker;
private databaseManager4 mDatabaseManager;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_editordeletefriend);
initUI();
mDatabaseManager = new databaseManager4(this);
}
private void initUI() {
Intent intent = getIntent();
mNameField = (EditText) findViewById(R.id.fullName_update);
mNameField.setText(intent.getStringExtra("name"));
mAddressField = (EditText) findViewById(R.id.address_update);
mAddressField.setText(intent.getStringExtra("address"));
mAgePicker = (NumberPicker) findViewById(R.id.resultAge_update);
mAgePicker.setMinValue(6);
mAgePicker.setMaxValue(110);
mAgePicker.setWrapSelectorWheel(false);
mAgePicker.setValue(Integer.parseInt(intent.getStringExtra("age")));
mUpdateButton = (Button) findViewById(R.id.update_button);
mUpdateButton.setOnClickListener(updateClickListener);
mGenderRadioGroup = (RadioGroup) findViewById(R.id.radioGroup_update);
RadioButton targetRadioButton = null;
switch (Gender.fromString(intent.getStringExtra("gender"))) {
case MALE:
targetRadioButton = (RadioButton) findViewById(R.id.resultGenderMale_update);
break;
case FEMALE:
targetRadioButton = (RadioButton) findViewById(R.id.resultGenderFemale_update);
break;
}
if (targetRadioButton != null) {
targetRadioButton.setChecked(true);
}
}
public void clear() {
mNameField.setText("");
mAddressField.setText("");
}
private Gender getSelectedGender() {
int checkedButtonId = mGenderRadioGroup.getCheckedRadioButtonId();
switch (checkedButtonId) {
case R.id.resultGenderMale_update:
return Gender.MALE;
case R.id.resultGenderFemale_update:
return Gender.FEMALE;
}
return Gender.UNDEFINED;
}
private View.OnClickListener updateClickListener =
new View.OnClickListener() {
#Override
public void onClick(View v) {
Gender newGender = getSelectedGender();
int code = Integer.parseInt(getIntent().getStringExtra("code"));
System.out.println("gender is" + newGender.stringValue);
if (mDatabaseManager.updateRow(
code,
mNameField.getText().toString(),
mAgePicker.getValue(),
newGender.stringValue,
mAddressField.getText().toString())) {
Toast.makeText(
getApplicationContext(),
"successfully updated the friend " + ed.getText().toString(),
Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(
getApplicationContext(),
"Could not update the friend " + ed.getText().toString(),
Toast.LENGTH_SHORT)
.show();
}
Intent viewFriendsIntent = new Intent(getApplicationContext(), viewFriends.class);
startActivity(viewFriendsIntent);
finish();
}
};
private enum Gender {
UNDEFINED("undefined"),
MALE("Male"),
FEMALE("Female");
private #Nullable String stringValue;
Gender(#Nullable String stringValue) {
this.stringValue = stringValue;
}
public static Gender fromString(#Nullable String value) {
if (value != null) {
for (Gender gender : Gender.values()) {
if (value.equals(gender.stringValue)) {
return gender;
}
}
}
return UNDEFINED;
}
}
}
My List is returning an item after clearing all the items by deleting ,On app fresh install its returing null which is good but after adding item and then by deleting all, this happens when go back from that activity and come again, list.size() is returning 1 and an item is remaing ,i don't know if it is loading from cache object instance here is my code of adapter class
[please look to the image attached ,list is empty but still counter 1 counter = cartModelList.size()]i have a list of cart itemsprivate List<CartModel> cartModelList;
It's returning null on app fresh install which is good but when i add item to the cart and then remove all the items then its returning 1.
I mean cartmodelList.size() is returning as far I know it's returning some items from cached objects or some thing like that.
The question is how to remove that List object cached or any alternative?
I tried on delete button but still cached coming
public static double p = 0;
private List<CartModel> cartModelList;
Database db;
Context context;
public CartAdapter(Context context, List<CartModel> cartModelList) {
this.cartModelList = cartModelList;
this.context = context;
db = new Database(context);
}
#NonNull
#Override
public Viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_layout_item, parent, false);
return new Viewholder(view);
}
#Override
public void onBindViewHolder(#NonNull final Viewholder holder, final int position) {
String namee = cartModelList.get(position).getName();
String manufacturere = cartModelList.get(position).getManufacturer();
String availabilitye = cartModelList.get(position).getAvailability();
String e_parte = cartModelList.get(position).getE_part();
String m_parte = cartModelList.get(position).getM_part();
String floatprice = cartModelList.get(position).getUnit_();
String int_quantity = cartModelList.get(position).getQuantity();
String float_line_total = cartModelList.get(position).getLine_total();
holder.setItemDetails(namee, manufacturere, availabilitye, e_parte, m_parte, floatprice, int_quantity, float_line_total);
int checker = SharedPrefManager.getInstance(context).cartcount().getCounter();
if (checker <= 0){
cartModelList.clear();
}
holder.btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (db.deleteProduct(cartModelList.get(position).getID())) {
cartModelList.remove(position);
notifyDataSetChanged();
Toast.makeText(context, "Product deleted from cart", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Product not deleted from cart", Toast.LENGTH_LONG).show();
}
CartList user111 = new CartList(--COUNTER_BADGE);
// Toast.makeText(context, "else", Toast.LENGTH_SHORT).show();
SharedPrefManager.getInstance(context).cartList(user111);
((Activity)context).invalidateOptionsMenu();
((Activity)context).finish();
Intent intent = new Intent(context, CartActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intent);
}
});
#Override
public int getItemCount() {
return cartModelList.size();
}
class Viewholder extends RecyclerView.ViewHolder {
private TextView name;
private TextView manufacturer;
private TextView availability;
private TextView e_part;
private TextView m_part;
private TextView price;
private EditText quantity;
private TextView linetotal;
private Button btn_delete;
private Button btn_update;
private Button adapter_livestock;
public SpinKitView progressbar;
public Viewholder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name);
manufacturer = itemView.findViewById(R.id.manufacturer);
availability = itemView.findViewById(R.id.availability);
e_part = itemView.findViewById(R.id.e_part);
m_part = itemView.findViewById(R.id.m_part);
price = itemView.findViewById(R.id.price);
quantity = itemView.findViewById(R.id.quantity);
linetotal = itemView.findViewById(R.id.linetotal);
btn_delete = itemView.findViewById(R.id.btn_delete);
btn_update = itemView.findViewById(R.id.btn_update);
adapter_livestock = itemView.findViewById(R.id.adapter_livestock);
progressbar = itemView.findViewById(R.id.adapterrprogresslivestockprogress);
}
private void setItemDetails(String namee, String manufacturere, String availabilitye, String e_parte, String m_parte, String floatprice, String int_quantity, String float_line_total) {
name.setText(namee);
manufacturer.setText(manufacturere);
availability.setText(availabilitye);
e_part.setText(e_parte);
m_part.setText(m_parte);
price.setText("£"+floatprice);
quantity.setText(int_quantity);
linetotal.setText("£"+float_line_total);
}
}
[https://i.stack.imgur.com/PxDTZ.jpg]
Okay... The first.
if (db.deleteProduct(cartModelList.get(position).getID()))
will not delete your item from cartModelList, you need to do it manually. Like this:
if (db.deleteProduct(cartModelList.get(position).getID())) {
cartModelList.remove(position)
And the second. You have to call notifyDataSetChanged() or itemChanged or itemRemoved etc. only in the end of your deletion method. Please, tell me, if it worked.
P.S. Your items do not cached. The problem is in your code order.
Edit 1. Also, you need to check your db.deleteProduct method. Is it worked? Is your if statement worked?
Edit 2. Try this.
holder.btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (db.deleteProduct(cartModelList.get(position).getID())) {
cartModelList.remove(position);
notifyItemRemoved(position);
Toast.makeText(context, "Product deleted from cart", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Product not deleted from cart", Toast.LENGTH_LONG).show();
}
CartList user111 = new CartList(cartModelList.size());
// Toast.makeText(context, "else", Toast.LENGTH_SHORT).show();
SharedPrefManager.getInstance(context).cartList(user111);
((Activity)context).invalidateOptionsMenu();
((Activity)context).finish();
Intent intent = new Intent(context, CartActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intent);
}
});
my problem is solved by putting cartModelList.clear on delete button when cartModelList.size() == 1 , so after deleting the last item it will clear the list.
I have a RecyclerView and a button for 'Binding' each item (Moving to another child at the DB).
Most of the time it works well, but sometimes i'm receiving indexOutOfBounds Exception.
This is a screen shot:
When I press at 'BIND' at the top recycler view item, i'm receiving this bug.
I made it print this line:
Log.d("dDebug","Almost bug! Size: " + ((MissionAdapter) MissionAdapter.this).mSnapshots.size() + " , index: " + missionPosition);
And it prints this:
D/dDebug: Almost bug! Size: 1 , index: 1
Here you can see the bug - size 1, index 1, so it will have indexOutOfBounds.
This is the code:
public class AvailableFragmentPilot extends Fragment {
private String TAG = "dDEBUG";
private RecyclerView mavailableList;
private DatabaseReference mAvailableMissionsDb, mPendingMissionsDb;
private FirebaseAuth mAuth;
private ProgressDialog mSubmitMsnProgress;
private String mCurrent_pilot_id;
private View mMainView;
// Query queries;
public AvailableFragmentPilot() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mMainView = inflater.inflate(R.layout.fragment_of_recycler_view_user, container, false);
mavailableList = (RecyclerView)mMainView.findViewById(R.id.mission_recycler_user);
mAuth = FirebaseAuth.getInstance();
mSubmitMsnProgress = new ProgressDialog(getContext());
mCurrent_pilot_id = mAuth.getCurrentUser().getUid();
mAvailableMissionsDb = FirebaseDatabase.getInstance().getReference().child("Missions").child("Available");
mAvailableMissionsDb.keepSynced(true);
mPendingMissionsDb = FirebaseDatabase.getInstance().getReference().child("Missions").child("Pending");
mPendingMissionsDb.keepSynced(true);
// queries = mAvailableMissionsDb.orderByChild("user_uid").equalTo(mCurrent_pilot_id);
mavailableList.setHasFixedSize(true);
mavailableList.setLayoutManager(new LinearLayoutManager(getContext()));
// Inflate the layout for this fragment
return mMainView;
}
#Override
public void onStart() {
super.onStart();
mavailableList.setAdapter(new MissionAdapter(mAvailableMissionsDb));
}
private class MissionAdapter extends FirebaseRecyclerAdapter<Mission, AvailableFragmentPilot.MissionsViewHolder> {
public MissionAdapter(Query queries){
super(Mission.class, R.layout.missions_single_layout, AvailableFragmentPilot.MissionsViewHolder.class, queries);
}
#Override
protected void populateViewHolder(AvailableFragmentPilot.MissionsViewHolder missionViewHolder, final Mission missionModel, final int missionPosition) {
Log.d(TAG, "inside populateViewHolder" + missionModel.getType() + " , " + missionModel.getDescription());
missionViewHolder.setMissionName(missionModel.getType());
missionViewHolder.setMissionDescription(missionModel.getDescription());
missionViewHolder.setMissionStatus(missionModel.getStatus());
missionViewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Mission clickedMission = null;
if (((MissionAdapter) MissionAdapter.this).mSnapshots.size()>missionPosition){
clickedMission = AvailableFragmentPilot.MissionAdapter.this.getItem(missionPosition);
Log.d("dDebug","Ein bug. Size: " + ((MissionAdapter) MissionAdapter.this).mSnapshots.size() + " , index: " + missionPosition + " , mission: " + clickedMission.getType() + ": " + clickedMission.getDescription());
}
else{
Log.d("dDebug","Almost bug! Size: " + ((MissionAdapter) MissionAdapter.this).mSnapshots.size() + " , index: " + missionPosition);
}
if (clickedMission != null){ // for the sake of being extra-safe
// String url_str = getRef(missionPosition).toString();
// String uuid_for_mission = url_str.split("/")[5];
Log.d(TAG,"The button was pressed for mission: " + clickedMission.getType() + " , uid: " + missionModel.getMission_uid());
// removeMission(uuid_for_mission);
bindMission(clickedMission);
}
}
});
}
}
public void bindMission(final Mission mission){
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setCancelable(false);
builder.setTitle("Mission bind");
builder.setMessage("Are you sure you want to bind this mission?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
mAvailableMissionsDb.child(mission.getMission_uid()).setValue(null);
final HashMap<String, String> missionMap = new HashMap<>();
missionMap.put("username", mission.getUsername());
missionMap.put("user_uid", mission.getUser_uid());
missionMap.put("mission_uid", mission.getMission_uid());
missionMap.put("type", mission.getType());
missionMap.put("status", "Pending");
missionMap.put("description", mission.getDescription());
missionMap.put("x", String.valueOf(mission.getX()));
missionMap.put("y", String.valueOf(mission.getY()));
missionMap.put("pilot_uid", mCurrent_pilot_id);
mPendingMissionsDb.child(mission.getMission_uid()).setValue(missionMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
// Log.d("dDebug","Before");
mSubmitMsnProgress.dismiss();
Toast.makeText(getContext(), ("Bind to mission " + mission.getType()),
Toast.LENGTH_LONG).show();
Log.d("dDebug","Painting in Red 1");
}
else {
Toast.makeText(getContext(), "Something went wrong",
Toast.LENGTH_SHORT).show();
}
}
});
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d("dDebug","ok, not binding");
}
});
// Create the AlertDialog object and return it
builder.create().show();
}
public static class MissionsViewHolder extends RecyclerView.ViewHolder {
View mView;
Button button ;
public MissionsViewHolder(View itemView) {
super(itemView);
mView = itemView;
button = (Button)mView.findViewById(R.id.mission_single_button);
button.setText("BIND");
}
public void setMissionName(String name){
TextView mMissionNameView = mView.findViewById(R.id.mission_single_name);
mMissionNameView.setText(name);
}
public void setMissionStatus(String status){
TextView mMissionStatusView = mView.findViewById(R.id.mission_single_status);
mMissionStatusView.setText(status);
if (status.equals("Available")){
mMissionStatusView.setTextColor(Color.parseColor("#008000"));;
} else {
mMissionStatusView.setTextColor(Color.parseColor("#FF0000"));;
}
}
public void setMissionDescription(String description){
TextView mMissionDescriptionView = mView.findViewById(R.id.mission_single_description);
mMissionDescriptionView.setText(description);
}
}
}
In addition - sometimes I will have 5 items, I'll press at the most upper one, (Should be index 0!) - and the SECOND item is being moved (at index 1).
So it means that probarely something is wrong with the way i'm getting the item that was clciked.
Rookie recycler view mistake: the view holder can move around and be reused (thus changing its position) while the onClick callback will only store a reference to the original position. To fix that, use viewHolder.getAdapterPosition(). 👍
Hey guys maybe someone of you can help me:
What im doing: I have a button in my ContactView that lets me select a phonecontact and inserts name and phonenumber into textviews.
The Problem I have is that when i swap between MainActivity and ContactActivity the Contact is deleted and i need to select again a contact
Here is my ContactView code
public class ContactView extends AppCompatActivity {
private static final int RESULT_PICK_CONTACT = 85;
private TextView textView1;
private TextView textView2;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_view);
textView1 = (TextView) findViewById(R.id.TxtName);
textView2 = (TextView) findViewById(R.id.TxtNumber);
editText = (EditText) findViewById(R.id.editText);
}
public void onClick(View v) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// check whether the result is ok
if (resultCode == RESULT_OK) {
// Check for the request code, we might be usign multiple startActivityForReslut
switch (requestCode) {
case RESULT_PICK_CONTACT:
contactPicked(data);
break;
}
} else {
Log.e("ContactView", "Failed to pick contact");
}
}
/**
* Query the Uri and read contact details. Handle the picked contact data.
*
* #param data
*/
private void contactPicked(Intent data) {
Cursor cursor = null;
try {
String phoneNo = null;
String name = null;
// getData() method will have the Content Uri of the selected contact
Uri uri = data.getData();
//Query the content uri
cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
// column index of the phone number
int phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
// column index of the contact name
int nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
phoneNo = cursor.getString(phoneIndex);
name = cursor.getString(nameIndex);
// Set the value to the textviews
textView1.setText(name);
textView2.setText(phoneNo);
} catch (Exception e) {
e.printStackTrace();
}
}
This is the code within my MainAcitivty for the ContactButton that lets me go to ContactView:
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if(id == R.id.action_contactView)
{
Intent ContactIntent = new Intent(this, ContactView.class);
startActivity(ContactIntent);
}
return true;
}
is there a way to check if my intent data is empty? or somehow save the strings as long they are not null?
WITH SHAREDPREFERENCE:
public class ContactView extends AppCompatActivity {
private static final int RESULT_PICK_CONTACT = 85;
private TextView textView1;
private TextView textView2;
private EditText editText;
public SharedPreferences settings = getSharedPreferences("SelectedContact", MODE_PRIVATE);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_view);
textView1 = (TextView) findViewById(R.id.TxtName);
textView2 = (TextView) findViewById(R.id.TxtNumber);
editText = (EditText) findViewById(R.id.editText);
SharedPreferences settings = getSharedPreferences("SelectedContact", MODE_PRIVATE);
String name = settings.getString("contactName", "");//the second parameter set a default data if “contactName” is empty
if (!name.isEmpty()){
textView1.setText(name);
}
String phoneNo = settings.getString("contactPhone", "");//the second parameter set a default data if “contactName” is empty
if (!phoneNo.isEmpty()){
textView2.setText(phoneNo);
}
}
public void onClick(View v) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// check whether the result is ok
if (resultCode == RESULT_OK) {
// Check for the request code, we might be usign multiple startActivityForReslut
switch (requestCode) {
case RESULT_PICK_CONTACT:
contactPicked(data);
break;
}
} else {
Log.e("ContactView", "Failed to pick contact");
}
}
/**
* Query the Uri and read contact details. Handle the picked contact data.
*
* #param data
*/
private void contactPicked(Intent data) {
Cursor cursor = null;
try {
String phoneNo = null;
String name = null;
// getData() method will have the Content Uri of the selected contact
Uri uri = data.getData();
//Query the content uri
cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
// column index of the phone number
int phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
// column index of the contact name
int nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
phoneNo = cursor.getString(phoneIndex);
name = cursor.getString(nameIndex);
// Set the value to the textviews
textView1.setText(name);
textView2.setText(phoneNo);
SharedPreferences.Editor editor = settings.edit();
editor.putString("contactName",name );
editor.putString("contactPhone", phoneNo);
editor.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
If you want to save the state of an activity use SharedPreferences
SharedPreferences settings = getSharedPreferences("SelectedContact", MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(“contactName”,name );
editor.putString(“contactPhone”,phoneNo);
editor.commit();
now in your onCreate of ContactView check if that variables contains data
SharedPreferences settings = getSharedPreferences(“SelectedContact”, MODE_PRIVATE);
String name = settings.getString(“contactName”, “”);//the second parameter set a default data if “contactName” is empty
if (!name.isEmpty()){
yourEditText.setText(name);
}
I hope this helps you.
Tell me if this works!
I wanted to add swipe to refresh for my listview in a Fragment but it doesn't seem to work as it doesn't update my list view at all. Here is how my activity works:
Users open up PictureFragment where a list of images (listview)
are shown.
Users press "add button" which will open up UploadImageActivity to add in image.
Once done, UploadImageActivity will close and users now get back to PictureFragment (not updated their latest image upload yet).
User swipes down to update, << Doesn't update the latest image into listview!
Hope a kind soul can help me resolve this.
public class PictureFragment extends Fragment {
private ListView listView;
private int smiley_id;
private String title, date, caption, image;
private ImageButton addPicButton;
private SwipeRefreshLayout swipeRefreshLayout;
private PictureAdapter adapter;
private TableDatabase tableDatabase;
private Cursor cursor;
#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_picture, container, false);
// Set listview
listView = (ListView) rootView.findViewById(R.id.piclistView);
adapter = new PictureAdapter(getActivity().getApplicationContext(), R.layout.row_feed);
listView.setAdapter(adapter);
// Retrieve data from database
tableDatabase = new TableDatabase(getActivity());
// Get rows of database
cursor = tableDatabase.getInformation(tableDatabase);
// Start from the last so that listview displays latest image first
// Check for existing rows
if(cursor.moveToLast()) {
do {
// Get items from each column
smiley_id = cursor.getInt(0);
title = cursor.getString(1);
date = cursor.getString(2);
caption = cursor.getString(3);
image = cursor.getString(4);
// Saves images added by user into listview
PictureItem pictureItem = new PictureItem(smiley_id, title, date, caption, image);
adapter.add(pictureItem);
} while (cursor.moveToPrevious());
}
// Swipe on refresh
swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh);
swipeRefreshLayout.setEnabled(false);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
(new Handler()).postDelayed(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
}, 1000);
}
});
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if(firstVisibleItem == 0) swipeRefreshLayout.setEnabled(true);
else swipeRefreshLayout.setEnabled(false);
}
});
// Lead user to UploadImageActivity to insert image to listview
addPicButton = (ImageButton) rootView.findViewById(R.id.addPictureButton);
addPicButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity().getApplicationContext(), UploadImageActivity.class));
}
});
return rootView;
}
UploadImageActivity.java
public class UploadImageActivity extends ActionBarActivity implements View.OnClickListener{
private Calendar cal = Calendar.getInstance();
private SimpleDateFormat dateFormatter = new SimpleDateFormat("dd MMM yyyy, EEE # hh:mm a");
EditText pic_title, pic_caption;
ImageView picture;
Button smiley1, smiley2, smiley3, smiley4, smiley5, selected_smiley;
// To store in database
int smiley_id = R.drawable.smile1; // Set default smiley as first smiley if not chosen
String title, date, caption;
String uriPicture; // Save uri in string format to store image as text format in database
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_picture);
// Removes shadow under action bar
getSupportActionBar().setElevation(0);
pic_title = (EditText) findViewById(R.id.picture_title);
pic_caption = (EditText) findViewById(R.id.picture_caption);
picture = (ImageView) findViewById(R.id.imagebutton);
smiley1 = (Button) findViewById(R.id.button1);
smiley2 = (Button) findViewById(R.id.button2);
smiley3 = (Button) findViewById(R.id.button3);
smiley4 = (Button) findViewById(R.id.button4);
smiley5 = (Button) findViewById(R.id.button5);
selected_smiley = (Button) findViewById(R.id.select_smiley);
picture.setOnClickListener(this);
smiley1.setOnClickListener(this);
smiley2.setOnClickListener(this);
smiley3.setOnClickListener(this);
smiley4.setOnClickListener(this);
smiley5.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_event, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_ok) {
title = pic_title.getText().toString();
date = dateFormatter.format(cal.getTime());
caption = pic_caption.getText().toString();
// Do not save data
if(title.isEmpty()) {
alertUser("Upload failed!", "Please enter title.");
}
else if(caption.isEmpty()) {
alertUser("Upload failed!", "Please enter caption.");
}
else if(uriPicture.isEmpty()) {
alertUser("Upload failed!", "Please upload an image.");
}
// Save data when title, caption and image are not empty
else {
// Add information into database
TableDatabase tableDatabase = new TableDatabase(this);
tableDatabase.putInformation(tableDatabase, smiley_id, title, date, caption, uriPicture);
Toast.makeText(getBaseContext(), "Details successfully saved", Toast.LENGTH_LONG).show();
finish();
}
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
// Show the image picked by user
case R.id.imagebutton:
picture.setImageDrawable(null);
Crop.pickImage(this);
break;
// Saves the user's smiley choice
case R.id.button1:
selected_smiley.setBackgroundResource(R.drawable.smile1);
selected_smiley.setText("");
setSmileyID(R.drawable.smile1);
break;
case R.id.button2:
selected_smiley.setBackgroundResource(R.drawable.smile2);
selected_smiley.setText("");
setSmileyID(R.drawable.smile2);
break;
case R.id.button3:
selected_smiley.setBackgroundResource(R.drawable.smile3);
selected_smiley.setText("");
setSmileyID(R.drawable.smile3);
break;
case R.id.button4:
selected_smiley.setBackgroundResource(R.drawable.smile4);
selected_smiley.setText("");
setSmileyID(R.drawable.smile4);
break;
case R.id.button5:
selected_smiley.setBackgroundResource(R.drawable.smile5);
selected_smiley.setText("");
setSmileyID(R.drawable.smile5);
break;
default:
break;
}
}
// This method sets the smiley ID according to what the user picks.
private void setSmileyID(int smileyID) {
this.smiley_id = smileyID;
}
// This method calls alert dialog to inform users a message.
private void alertUser(String title, String message) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(UploadImageActivity.this);
dialogBuilder.setTitle(title);
dialogBuilder.setMessage(message);
dialogBuilder.setPositiveButton("Ok", null);
dialogBuilder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == Crop.REQUEST_PICK && resultCode == RESULT_OK) {
beginCrop(data.getData());
} else if(requestCode == Crop.REQUEST_CROP) {
handleCrop(resultCode, data);
}
}
// This method allows users to crop image in square.
private void beginCrop(Uri source) {
Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
Crop.of(source, destination).asSquare().start(this);
}
// This method ensures there are no errors in cropping.
private void handleCrop(int resultCode, Intent result) {
if(resultCode == RESULT_OK) {
picture.setImageURI(Crop.getOutput(result));
uriPicture = Crop.getOutput(result).toString();
} else if(resultCode == Crop.RESULT_ERROR) {
Toast.makeText(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show();
}
}
TableDatabase.java
public class TableDatabase extends SQLiteOpenHelper {
public String query = "CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" +
TableData.TableInfo.SMILEY + " INTEGER NOT NULL, " +
TableData.TableInfo.TITLE + " TEXT, " +
TableData.TableInfo.DATE + " TEXT, " +
TableData.TableInfo.CAPTION + " TEXT, " +
TableData.TableInfo.IMAGE + " TEXT);";
public TableDatabase(Context context) {
super(context, TableData.TableInfo.DATABASE_NAME, null, TableData.TableInfo.DATABASE_VERSION);
// Check if database is created
Log.d("Database operations", "Database created");
}
#Override
public void onCreate(SQLiteDatabase db) {
// Create table
db.execSQL(query);
Log.d("Database operations", "Table created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// Insert user information into the database
public void putInformation(TableDatabase data, int smiley, String title, String date, String caption, String image) {
// Write data into database
SQLiteDatabase sqLiteDatabase = data.getWritableDatabase();
ContentValues contentValues = new ContentValues();
// Add value from each column into contentvalue
contentValues.put(TableData.TableInfo.SMILEY, smiley);
contentValues.put(TableData.TableInfo.TITLE, title);
contentValues.put(TableData.TableInfo.DATE, date);
contentValues.put(TableData.TableInfo.CAPTION, caption);
contentValues.put(TableData.TableInfo.IMAGE, image);
// Insert into sqlite database
sqLiteDatabase.insert(TableData.TableInfo.TABLE_NAME, null, contentValues);
Log.d("Database operations", "One row inserted");
}
// Retrieve data from database
public Cursor getInformation(TableDatabase data) {
// Read data from sqlite database
SQLiteDatabase sqLiteDatabase = data.getReadableDatabase();
String[] columns = { TableData.TableInfo.SMILEY, TableData.TableInfo.TITLE, TableData.TableInfo.DATE, TableData.TableInfo.CAPTION, TableData.TableInfo.IMAGE };
// Points to first row of table
return sqLiteDatabase.query(TableData.TableInfo.TABLE_NAME, columns, null, null, null, null, null);
}