Related
I have a MainAtivity which has some EditText and 2 button. Save button will save user input to ListView and List button to show ListView (which I display in second activity).
Is there anyway to collect data from multiple inputs then pass it to other activity. And after get that data how to combine it to a List item.
Please show me some code and explain cause I'm a beginner.
I have read some post and they suggest use startActivityForResult, intent, bundles but I still don't understand.
This is my Main class:
public class MainActivity extends AppCompatActivity {
String str, gender, vaccine, date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button okay = (Button) findViewById(R.id.btnOk);
Button list = (Button) findViewById(R.id.btnList);
EditText name = (EditText) findViewById(R.id.inputName);
EditText address = (EditText) findViewById(R.id.inputAdd);
EditText phone = (EditText) findViewById(R.id.inputPhone);
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
RadioButton female = (RadioButton) findViewById(R.id.inputFemale);
RadioButton male = (RadioButton) findViewById(R.id.inputMale);
CheckBox first = (CheckBox)findViewById(R.id.inputFirst);
CheckBox second = (CheckBox)findViewById(R.id.inputSecond);
CheckBox third = (CheckBox)findViewById(R.id.inputThird);
EditText datefirst = (EditText) findViewById(R.id.dateFirst);
EditText datesecond = (EditText) findViewById(R.id.dateSecond);
EditText datethird = (EditText) findViewById(R.id.dateThird);
TextView result = (TextView)findViewById(R.id.textResult);
okay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(female.isChecked()) gender = female.getText().toString();
if(male.isChecked()) gender = male.getText().toString();
if(first.isChecked()) {
vaccine = first.getText().toString();
date = datefirst.getText().toString();
}
if(second.isChecked()) {
vaccine = second.getText().toString();
date = datesecond.getText().toString();
}
if(third.isChecked()) {
vaccine = third.getText().toString();
date = datethird.getText().toString();
}
str = name.getText().toString() + "\n" + address.getText().toString() + "\n" + phone.getText().toString() + "\n" +
gender + "\n" + vaccine + "\n" + date;
result.setText(str);
Toast.makeText(getApplicationContext(),result.getText().toString(),Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, PersonView.class);
intent.putExtra("NAME",name.getText().toString());
startActivity(intent);
}
});
list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, PersonView.class);
startActivity(intent);
}
});
}
}
This is my ListView class:
public class PersonView extends AppCompatActivity {
ArrayList<Person> listPerson;
PersonListViewAdapter personListViewAdapter;
ListView listViewPerson;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
Intent intent = getIntent();
String message = intent.getStringExtra("NAME");
Button back = (Button) findViewById(R.id.btnBack);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(PersonView.this, MainActivity.class);
//startActivityForResult(intent,2);
}
});
listPerson = new ArrayList<>();
listPerson.add(new Person("Lieu Mai","25 Mac Dinh Chi", "0786867073", "female","3 injection", "24/07/2000"));
personListViewAdapter = new PersonListViewAdapter(listPerson);
listViewPerson = findViewById(R.id.listPerson);
listViewPerson.setAdapter(personListViewAdapter);
}
class Person {
String name, address, phone, gender, vaccine, date;
public Person( String name, String address, String phone, String gender, String vaccine, String date) {
this.name = name;
this.address = address;
this.phone = phone;
this.gender = gender;
this.vaccine = vaccine;
this.date = date;
}
}
class PersonListViewAdapter extends BaseAdapter {
final ArrayList<Person> listPerson;
PersonListViewAdapter(ArrayList<Person> listPerson) {
this.listPerson = listPerson;
}
#Override
public int getCount() {
return listPerson.size();
}
#Override
public Object getItem(int position) {
return listPerson.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View viewPerson;
if (convertView == null) {
viewPerson = View.inflate(parent.getContext(), R.layout.person_view, null);
} else viewPerson = convertView;
Person person = (Person) getItem(position);
((TextView) viewPerson.findViewById(R.id.txtName)).setText(String.format("Name: %s", person.name));
((TextView) viewPerson.findViewById(R.id.txtAddress)).setText(String.format("Address : %s", person.address));
((TextView) viewPerson.findViewById(R.id.txtPhone)).setText(String.format("Phone number: %s", person.phone));
((TextView) viewPerson.findViewById(R.id.txtGender)).setText(String.format("Gender: %s", person.gender));
((TextView) viewPerson.findViewById(R.id.txtVaccine)).setText(String.format("Vaccine: %s", person.vaccine));
((TextView) viewPerson.findViewById(R.id.txtDate)).setText(String.format("Date: %s", person.date));
return viewPerson;
}
}
}
You should look into the Singleton pattern. It is very simple as there is no external DB. What it essentially is a class that manages the data and lets other classes and activities use the data while not allowing duplication.
You have a model Person
public class Person {
private String name;
public String address;
...
constructors and getters and setters
Create a class PersonsSingelton something like this.
public class PersonManagerSingleton {
private PersonManagerSingleton() {
loadPersonsDataSet();
}
private static PersonManagerSingleton instance = null;
public static PersonManagerSingleton getInstance() {
// if there is a instance already created use that instance of create new instance
// instance created in MainActivity and you try to create a new instance in Details
// should not happen as that will cause data duplication.
if (instance == null) {
instance = new PersonManagerSingleton();
}
return instance;
}
private ArrayList<Person> personList = new ArrayList<Person>();
private void loadPersonsDataSet() {
this.personList.add(new Person(...));
this.personList.add(new Person(...));
this.personList.add(new Person(...));
this.personList.add(new Person(...));
}
public ArrayList<Person> getpersonList() {
return personList;
}
public Person getPersonByID(int PersonNumber) {
for (int i = 0; i < this.personList.size(); i++) {
Person curPerson = this.personList.get(i);
if (curPerson.getNumber() == PersonNumber) {
return curPerson;
}
}
return null;
}
// methods for adding a new person used in Activity with the form.
// other methods ...
}
This would be like a state in React. of the State Manager.
Your person adapter constructor has to accept an ArrayList<Person> listPerson. So modify the activity passing the data to pass only the position of the ListView clicked. You need to modify your Adapter for that.
Use the Singleton created to access the data.
PersonManagerSingleton personSingelton = PersonManagerSingleton.getInstance();
ArrayList<Person> listPerson = personSingelton.getPersonList();
PersonAdapter Person = new PersonAdapter(listPerson);
So now only things left is to modify the Persons adapter to pass position using Intent and nothing else. and then you can use the instance of Singleton in other files to access the data using the listPerson.get(position) and using getters and setters.
Link to a project like this.
https://github.com/smitgabani/anroid_apps_using_java/tree/main/pokemon_app
I really need your help. I've searched Google many days with many keywords, but I couldn't get it. So, I decided to ask to you.
So, here it is. Actually, I have one button in RecyclerView, but this button is repeated as much amount of data available, there are: Button with text "Baca 3x", "Baca 4x", and so on. I want, if I click button with text "Baca 3x" 3 times, it will change to "Baca 2x" >> "Baca 1x" >> remove item. Also if I click button with text "Baca 4x" 4 times, it will change to "Baca 3x" >> "Baca 2x" >> "Baca 1x" >> remove item.
But my problem is, I can't treat every button with different treatment, because every time the item has been deleted, position of data changes automatically. Because of this, I can't get specific button. For example: There is two button,
1. Button "Baca 3x" on position 0
2. Button "Baca 4x" on position 1
If button "Baca 3x" on position 0 has been deleted, so button "Baca 4x" changed it's position automatically to 0. The problem lays here.
Until now I just get every button based on their positions, which is a problem for me. Because of this I am thinking about How to Delete Item Without Deleting Position in Recycler View? Can you guys solve my problem? Should I use DiffUtil?And how to use it? Below the complete code I use:
ModelDoa.java
public class ModelDoa {
public static final int DOA_PAGI = 0;
public static final int DOA_SORE = 1;
public static final int DOA_MASJID = 2;
public static final int DOA_BANGUNT = 3;
public static final int DOA_MAU_TIDUR = 4;
private String mName;
private String bName;
private int mType;
public ModelDoa(String name, String butong, int type) {
this.mName = name;
this.bName = butong;
this.mType = type;
}
public String getName() {
return mName;
}
public void setName(String name) {
this.mName = name;
}
public int getType() {
return mType;
}
public void setType(int type) { this.mType = type; }
public String ambilName() {
return bName;
}
public void setNama(String butonk) {
this.bName = butonk;
}
}
AdapterDoa.java
public class AdapterDoa extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public List<ModelDoa> mList;
public AdapterDoa(List<ModelDoa> list) {
this.mList = list;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case DOA_PAGI:
View vieu = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
PagiViewHolder rcv = new PagiViewHolder(vieu, this);
return rcv;
case DOA_SORE:
View doa = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
SoreViewHolder mdoa = new SoreViewHolder(doa);
return mdoa;
case DOA_MASJID:
View dMasjid = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
MasjidViewHolder mMasjid = new MasjidViewHolder(dMasjid);
return mMasjid;
case DOA_BANGUNT:
View dBangunt = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
BanguntViewHolder mBangunt = new BanguntViewHolder(dBangunt);
return mBangunt;
case DOA_MAU_TIDUR:
View regut = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
MauTidurViewHolder turu = new MauTidurViewHolder(regut);
return turu;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ModelDoa object = mList.get(position);
if (object != null) {
switch (object.getType()) {
case DOA_PAGI:
((PagiViewHolder) holder).mTitle.setText(object.getName());
((PagiViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_SORE:
((SoreViewHolder) holder).mTitle.setText(object.getName());
((SoreViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_MASJID:
((MasjidViewHolder) holder).mTitle.setText(object.getName());
((MasjidViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_BANGUNT:
((BanguntViewHolder) holder).mTitle.setText(object.getName());
((BanguntViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_MAU_TIDUR:
((MauTidurViewHolder) holder).mTitle.setText(object.getName());
((MauTidurViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
}
}
}
public void deleteItem(int position) {
mList.remove(position); // hapus list
notifyItemRemoved(position); // hapus tampilan
// notifyItemRangeChanged( position, mList.size());
}
#Override
public int getItemCount() {
if (mList == null)
return 0;
return mList.size();
}
#Override
public int getItemViewType(int position) {
if (mList != null) {
ModelDoa object = mList.get(position);
if (object != null) {
return object.getType();
}
}
return 0;
}
}
PagiViewHolder.java
public class PagiViewHolder extends RecyclerView.ViewHolder {
public TextView mTitle;
public Button tombolbaca;
public Button teksbaca;
public Button tombolshare;
private RelativeLayout rl2;
private int klik10 = 10;
private AdapterDoa myAdapter;
public PagiViewHolder(View itemView, AdapterDoa myAdapter) {
super(itemView);
this.myAdapter = myAdapter;
itemView.setOnClickListener(mainViewClickListener);
mTitle = (TextView) itemView.findViewById(R.id.titleTextView);
tombolbaca = (Button) itemView.findViewById(R.id.buttonbaca);
tombolshare = (Button) itemView.findViewById(R.id.buttonshare);
tombolbaca.setOnClickListener(bacaClickListener);
tombolshare.setOnClickListener(shareClickListener);
rl2 = (RelativeLayout) itemView.findViewById(R.id.relmasjid);
}
private View.OnClickListener bacaClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
teksbaca = (Button) v.findViewById(R.id.buttonbaca);
// Baca 10x
if( getAdapterPosition() ==0 ) {
klik10--;
teksbaca.setText("Baca " + klik10 + "x");
if (klik10 <= 0)
{
// modify listItems however you want... add, delete, shuffle, etc
myAdapter.deleteItem(getAdapterPosition());
}
}
} // onclick
};
private View.OnClickListener shareClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do button click handling here
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, mTitle.getText().toString() + "\n \n download aplikasinya di: http://www.tauhid.or.id" );
sendIntent.setType("text/plain");
Intent.createChooser(sendIntent,"Share via");
v.getContext().startActivity(sendIntent);
}
};
private View.OnClickListener mainViewClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do button click handling here
}
};
}
DoaPagi.java
public class DoaPagi extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doa_pagi);
// toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//this line shows back button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
List<ModelDoa> rowListItem = getData();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(DoaPagi.this);
RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
AdapterDoa rcAdapter = new AdapterDoa(rowListItem);
mRecyclerView.setAdapter(rcAdapter);
}
private List<ModelDoa> getData() {
String[] data = getResources().getStringArray(R.array.doapagi);
String[] baca = getResources().getStringArray(R.array.bacapagi);
List<ModelDoa> list = new ArrayList<ModelDoa>();
for (int i = 0; i < data.length; i++) {
list.add(new ModelDoa(data[i], baca[i], ModelDoa.DOA_PAGI));
}
return list;
}
// Agar back button pada halaman induk settings berfungsi
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
UPDATE (FIX CODE) By: Krishna Sharma:
https://github.com/seadclark/RecyclerViewWithButtonClicks
Here is the fix. just update the ModelDoa constructor as below. I have verified myself and working as expected now. Also sent you pull request on github.
public ModelDoa(String name, String butong, int type) {
this.mName = name;
this.bName = butong;
this.mType = type;
String[] data = butong.split("\\s");
if (data.length > 0) {
String count = data[1].substring(0, data[1].length() - 1);
read10 = Integer.parseInt(count);
}
}
Instead of removing the item from your list AND updating the interface, have two methods. One of them (deleteItem) will only delete the item and the other (deleteItemAndUpdate) will delete the item and update the interface.
public void deleteItem(int position) {
mList.remove(position); // hapus list
}
public void deleteItemAndUpdate(int position) {
mList.remove(position); // hapus list
notifyItemRemoved(position); // hapus tampilan
}
In the future, you can decide whether you want to only remove the item from your list OR remove the item and update the UI.
EDIT 1:
You need to keep track of the amount of times that each item was clicked. We can call this value readCount. Every time that the item is clicked, we subtract 1 from this value. When this value reaches 0, we remove it from the list.
ModelDoa:
public class ModelDoa {
private int readCount = 10;
public int getReadCount() {
return this.readCount;
}
public void setReadCount(int readCount) {
this.readCount = readCount;
}
}
PagiViewHolder:
private View.OnClickListener bacaClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
teksbaca = (Button) v.findViewById(R.id.buttonbaca);
ModelDoa modelDoa = mAdapter.getItem(getAdapterPosition());
if (modelDoa != null) {
modelDoa.setReadCount(modelDoa.getReadCount() - 1);
if (modelDoa.getReadCount() <= 0) {
myAdapter.deleteItem(getAdapterPosition());
}
teksbaca.setText("Baca " + modelDoa.getReadCount() + "x");
}
}
};
AdapterDoa:
public ModelDoa getItem(int position) {
if (position > -1 && position < getItemCount()) {
return this.mList.get(position);
} else {
return null;
}
}
EDIT 2:
The idea is to set the readCount variable when you instantiate the object. You do not have multiple variables that do the same thing. You just change the single readCount variable to be either 7 or 10 when you are creating it and use the same getItem method when retrieving the model (not variable!) itself.
ModelDoa:
public class ModelDoa {
private String name;
private String butong;
private int type;
private int readCount;
public ModelDoa(String name, String butong, int type, int readCount) {
this.mName = name;
this.bName = butong;
this.mType = type;
this.readCount = readCount;
}
public int getReadCount() {
return this.readCount;
}
public void setReadCount(int readCount) {
this.readCount = readCount;
}
}
DoaPagi:
private List<ModelDoa> getData() {
String[] data = getResources().getStringArray(R.array.doapagi);
String[] baca = getResources().getStringArray(R.array.bacapagi);
List<ModelDoa> list = new ArrayList<ModelDoa>();
for (int i = 0; i < data.length; i++) {
// Here is where you would set the value of readCount.
list.add(new ModelDoa(data[i], baca[i], ModelDoa.DOA_PAGI, i));
}
return list;
}
I'm almost done making my app and I'm stuck trying to solve this last issue. I made an activity that displays data gotten from Firestore using FirestoreRecyclerAdapter and It works perfectly when running on my emulator. But after I generate a signed APK with minifyEnabled:true and Install it on my device, the RecyclerView just shows Blank. when I set minifyEnabled:false it works perfectly. Below are my codes
For TransactionRecycler class
public class TransactionRecycler {
private String payment_date;
private String status;
private String meternumber;
public String reference;
private String amount_formatted;
private Double PurchasedUnits;
private Double FreeUnits;
private Double Vat;
public String id;
private String payment_time;
// public String state;
private String token;
public String address;
private String account_name;
public TransactionRecycler(String payment_date, String status, String meternumber, String reference, String id, String amount_formatted, String payment_time, String token, Double PurchasedUnits,
Double FreeUnits, Double Vat, String account_name, String address){
this.payment_date = payment_date;
this.status = status;
this.meternumber = meternumber;
this.reference = reference;
this.amount_formatted = amount_formatted;
this.PurchasedUnits = PurchasedUnits;
this.Vat = Vat;
// this.state = state;
this.FreeUnits = FreeUnits;
this.id = id;
this.payment_time = payment_time;
this.token = token;
this.account_name = account_name;
this.address = address;
}
public TransactionRecycler(){};
public void setDate(String payment_date){this.payment_date = payment_date;}
public void setId(String id){this.id =id;}
// public void setState(String id){this.state =state;}
public String getPayment_date(){return payment_date;}
public String getStatus(){return status;}
public String getMeternumber(){return meternumber;}
public String getReference(){return reference;}
public String getAddress(){return address;}
public String getAmount_formatted(){return amount_formatted;}
public Double getPurchasedUnits(){return PurchasedUnits;}
public Double getFreeUnits(){return FreeUnits;}
public Double getVat(){return Vat;}
public String getId(){return id;}
// public String getstate(){return state;}
public String getPayment_time(){return payment_time;}
public String getToken(){return token;}
public String getAccount_name(){return account_name;}
}
And for TRansactionActivity
public class TransactionActivity extends AppCompatActivity {
private static final String TAG = "TransactionActivity";
private final static String strUrlId= "https://www.eliminateramp.com?exmen=";
private static final int SERVICE_CHARGE = 100;
private static final String PLEASE_CHECK_YOUR_METER_NUMBER_AND_TRY_AGAIN = "Please check your meter number and try again";
private static final String COULDN_T_CONNECT_AT_THIS_TIME_PLEASE_TRY_AGAIN = "Couldn't connect at this time, Please try again";
private static final String FAILLED = "failled";
private static final String NOT_FOUND = "NOT FOUND";
private FirebaseAuth mAuth;
private String userID;
private RecyclerView mTransactionList;
protected LinearLayoutManager linearLayoutManager;
public FirestoreRecyclerAdapter adapter;
private SlidingUpPanelLayout mLayout;
private NavigationView navigation;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private static final String SPACE = " ";
private static String phone;
private Button charname;
private TextView emailview;
private TextView fullnameview;
private TextView priceidrc;
private static TextView post_meterno;
private static String aamount;
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.top_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transaction);
mTransactionList = findViewById(R.id.friend_listinc);
mLayout = findViewById(R.id.sliding_layout);
mAuth = FirebaseAuth.getInstance();
userID = mAuth.getCurrentUser().getUid();
Log.d("Error","The UID is: "+userID);
Toolbar mToolbar = findViewById(R.id.nav_actionbar);
setSupportActionBar(mToolbar);
mDrawerLayout = findViewById(R.id.drawerlayout);
navigation = findViewById(R.id.navigationview);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
View headerView = navigation.getHeaderView(0);
emailview = headerView.findViewById(R.id.emailviewraw);
fullnameview = headerView.findViewById(R.id.fullnameviewid);
charname = headerView.findViewById(R.id.charnameid);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
try{
getUserData();
}catch (Exception e){
Log.d(TAG, "Failed to get user Data at this time coz: "+e);
}
ImageView imgview = findViewById(R.id.closeid);
imgview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mLayout.animate();
mLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
}
});
charname.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(TransactionActivity.this,UpdateActivity.class));
}
});
init();
inTrans();
initInstances();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return mToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
private void initInstances() {
// getSupportActionBar().setHomeButtonEnabled(true);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigation = findViewById(R.id.navigationview);
navigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id) {
case R.id.nav_home:
//Do some thing here
// add navigation drawer item onclick method here
Intent intent2 = new Intent(TransactionActivity.this, HomePageActivity.class);
startActivity(intent2);
break;
case R.id.nav_estimate:
mDrawerLayout.closeDrawer(GravityCompat.START);
break;
//Do some thing here
// add navigation drawer item onclick method here
case R.id.nav_Settings:
//Do some thing here
// add navigation drawer item onclick method here
Intent intent3 = new Intent(TransactionActivity.this, HelpActivity.class);
startActivity(intent3);
break;
case R.id.nav_hc:
//Do some thing here
// add navigation drawer item onclick method here
Intent intent = new Intent(TransactionActivity.this, HelpCenterActivity.class);
startActivity(intent);
break;
}
return false;
}
});
}
private void init(){
linearLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
mTransactionList.setLayoutManager(linearLayoutManager);
}
private void inTrans(){
Query query = FirebaseFirestore.getInstance().collection("user-orders").document(userID).collection("successful-orders").orderBy("RequestedOn");
FirestoreRecyclerOptions<TransactionRecycler> response = new FirestoreRecyclerOptions.Builder<TransactionRecycler>()
.setQuery(query, TransactionRecycler.class)
.build();
adapter = new FirestoreRecyclerAdapter<TransactionRecycler, TransactionRecyclerHolder>(response){
#Override
public TransactionRecyclerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.transaction_list, parent, false);
return new TransactionRecyclerHolder(view);
}
#Override
public void onError(#NonNull FirebaseFirestoreException e) {
Log.e("error", e.getMessage());
}
#Override
protected void onBindViewHolder(#NonNull TransactionRecyclerHolder holder, int position, #NonNull final TransactionRecycler model) {
//progressBar.setVisibility(View.GONE);
holder.setDate(model.getPayment_date());
holder.setStatus(model.getStatus());
holder.setReference(model.getId());
holder.setMeterno(model.getMeternumber());
holder.setPrice(model.getAmount_formatted());
mLayout.setFadeOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mLayout.animate();
mLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mLayout.setPanelHeight(4);
mLayout.animate();
// mLayout.setAnchorPoint(2.0f);
mLayout.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED);
priceidrc = findViewById(R.id.priceidsc);
TextView dateidrc = findViewById(R.id.dateidsc);
TextView referenceidrc = findViewById(R.id.refidsc);
TextView statusidrc = findViewById(R.id.statusidsc);
TextView meternoidrc = findViewById(R.id.meternoidsc);
TextView paymenttimeidrc = findViewById(R.id.paymenttimeidsc);
TextView tokenidrc = findViewById(R.id.tokenidsc);
TextView creditidrc = findViewById(R.id.creditidsc);
TextView freeunitsrc = findViewById(R.id.freeunitsidsc);
TextView vatrc = findViewById(R.id.vatidsc);
TextView accountnameidrc = findViewById(R.id.namesidsc);
TextView address = findViewById(R.id.addressidsc);
dateidrc.setText(model.getPayment_date());
statusidrc.setText(model.getStatus());
meternoidrc.setText(model.getMeternumber());
priceidrc.setText(model.getAmount_formatted());
referenceidrc.setText(model.getId());
paymenttimeidrc.setText(model.getPayment_time());
tokenidrc.setText(model.getToken());
creditidrc.setText(String.valueOf(model.getPurchasedUnits()));
freeunitsrc.setText(String.valueOf(model.getFreeUnits()));
vatrc.setText(String.valueOf(model.getVat()));
accountnameidrc.setText(model.getAccount_name());
address.setText(model.getAddress());
}
});
}
};
adapter.notifyDataSetChanged();
mTransactionList.setAdapter(adapter);
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
public static class TransactionRecyclerHolder extends RecyclerView.ViewHolder {
View mView;
TransactionRecyclerHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDate(String payment_date) {
TextView post_date = mView.findViewById(R.id.dateid);
post_date.setText(payment_date);
}
public void setStatus(String status) {
TextView post_status = mView.findViewById(R.id.statusid);
post_status.setText(status);
}
public void setMeterno(String meterno) {
post_meterno = mView.findViewById(R.id.meternoid);
post_meterno.setText(meterno);
}
public void setReference(String reference) {
TextView post_ref = mView.findViewById(R.id.refid);
post_ref.setText(reference);
}
public void setPrice(String price) {
TextView post_price = mView.findViewById(R.id.priceid);
post_price.setText(price);
aamount=price;
}
}
public void getUserData() {
mAuth= FirebaseAuth.getInstance();
try{
userID = mAuth.getCurrentUser().getUid();
}catch(Exception e){
Log.d(TAG, "Failled somehow");
}
Log.d(TAG, "ur uid => "+userID);
DocumentReference mDocRef = FirebaseFirestore.getInstance().collection("users").document(userID);
mDocRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
DocumentSnapshot doc = task.getResult();
String firstname = doc.get("firstName").toString();
String lastname = doc.get("lastName").toString();
phone = doc.get("phone").toString();
String fullname = firstname+SPACE+lastname;
fullnameview.setText(fullname);
try{
emailview.setText(mAuth.getCurrentUser().getEmail());
}catch(Exception e){
Log.d(TAG,"oops");
}
charname.setText(firstname.substring(0,1));
}
}
});
}
public void buyAgain(View view){
final Dialog dialog = new Dialog(TransactionActivity.this);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.setCanceledOnTouchOutside(false);
dialog.setContentView(R.layout.progressbar);
String price = aamount.replaceAll("\\D","");
final int amount = Integer.parseInt(price) + SERVICE_CHARGE;
final String mn = post_meterno.getText().toString();
final String ml = "amstadam";
final String ref = String.valueOf(Calendar.getInstance().getTimeInMillis());
#SuppressLint("StaticFieldLeak") AsyncTask<String, String, String> jesgetnames = new AsyncTask<String, String, String>() {
#Override
protected String doInBackground(String... params) {
String geMtName;
String urlMtName = strUrlId+post_meterno.getText().toString().trim();
Log.d(TAG, "The string:" + urlMtName);
try {
URL url = new URL(urlMtName);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.connect();
BufferedReader bf = new BufferedReader(new InputStreamReader(con.getInputStream()));
String value = bf.readLine();
Log.d(TAG, "Value of value is: " + value);
if(value.equals("not found")){
geMtName = "NOT FOUND";
}else{
JSONObject parentJson = new JSONObject(value);
String meternumber = parentJson.getString("xmen");
String metername = parentJson.getString("x_name");
String address = parentJson.getString("address");
geMtName = metername+"/"+meternumber+"/"+address;
}
Log.d(TAG, "meter name after get is: " + geMtName);
} catch (Exception e) {
// Log.d(TAG, "Faiiled coz: "+ e);
geMtName = "failled";
e.printStackTrace();
}
Log.d(TAG, "I dont know if this works " + geMtName);
return geMtName;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d(TAG, "pnPostExecute value: " + s);
String nameSubString;
String numberSubString;
String addressSubString;
// date and time creation
String stringDate = String.valueOf(DateFormat.getDateTimeInstance());
Date stringTime = Calendar.getInstance().getTime();
SimpleDateFormat curFormater = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH);
SimpleDateFormat timeFormat = new SimpleDateFormat("h:mm a", Locale.ENGLISH);
Date dateObj = new Date();
Date timeObj = new Date();
try {
dateObj = curFormater.parse(stringDate);
timeObj = timeFormat.parse(String.valueOf(stringTime));
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat postFormater = new SimpleDateFormat("d MMMM yyyy", Locale.ENGLISH);
SimpleDateFormat postTimeFormater = new SimpleDateFormat("h:mm a", Locale.ENGLISH);
String newDateStr = postFormater.format(dateObj);
String newtimeStr = postTimeFormater.format(timeObj);
switch (s) {
case FAILLED:
nameSubString = FAILLED;
numberSubString = FAILLED;
addressSubString = FAILLED;
break;
case NOT_FOUND:
nameSubString = FAILLED;
numberSubString = FAILLED;
addressSubString = FAILLED;
break;
default:
String[] split = s.split("/");
nameSubString = split[0];
numberSubString = split[1];
addressSubString = split[2];
break;
}
switch (s) {
//TODO: Change toast message to reflect Json in future
case FAILLED:
//TODO: after creating layout, go back to previous layout and display toast message
Toast.makeText(TransactionActivity.this, COULDN_T_CONNECT_AT_THIS_TIME_PLEASE_TRY_AGAIN, Toast.LENGTH_SHORT).show();
dialog.dismiss();
break;
case NOT_FOUND:
Toast.makeText(TransactionActivity.this, PLEASE_CHECK_YOUR_METER_NUMBER_AND_TRY_AGAIN, Toast.LENGTH_SHORT).show();
dialog.dismiss();
break;
default:
Intent meterIntent = new Intent(TransactionActivity.this, MeterNumActivity.class);
meterIntent.putExtra("meternum", mn);
meterIntent.putExtra("meterprice", amount);
meterIntent.putExtra("meterlocation", ml);
meterIntent.putExtra("reference", ref);
meterIntent.putExtra("meteracctname", nameSubString);
meterIntent.putExtra("meteracctnumber", numberSubString);
meterIntent.putExtra("meteracctaddress", addressSubString);
meterIntent.putExtra("uuid", userID);
meterIntent.putExtra("date_created", newDateStr);
meterIntent.putExtra("time_created", newtimeStr);
meterIntent.putExtra("phone", phone);
meterIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(meterIntent);
break;
}
}
};
dialog.show();
jesgetnames.execute();
}
#Override
public void onBackPressed() {
Intent i= new Intent(this,HomePageActivity.class);
startActivity(i);
finish();
}
}
and my Gradle is
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.example.menofx.xmen"
minSdkVersion 21
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:cardview-v7:26.1.0'
implementation 'com.firebaseui:firebase-ui-firestore:3.1.3'
implementation 'com.firebaseui:firebase-ui-auth:3.1.3'
implementation 'com.firebaseui:firebase-ui-database:3.1.3'
implementation "com.google.firebase:firebase-firestore:11.8.0"
implementation "com.android.support:recyclerview-v7:26.1.0"
implementation "com.google.android.gms:play-services-auth:11.8.0"
implementation 'co.paystack.android:paystack:3.0.9'
implementation 'br.com.simplepass:loading-button-android:1.8.4'
implementation 'com.github.faruktoptas:FancyShowCaseView:1.0.0'
implementation 'com.sothree.slidinguppanel:library:3.4.0'
implementation 'com.android.support:design:26.1.0'
implementation 'com.android.support:support-v4:26.1.0'
implementation 'com.android.support:support-vector-drawable:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:0.5'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:2.2.2'
implementation project(':library')
}
apply plugin: 'com.google.gms.google-services'
my proguard rules are empty if needed. This is my first time working with firebase UI so I dont even know how to diagnose the problem. Thanks for the help.
You need to put your POJOs (model classes) in a single package and add that package to your proguard rules, or you can add all of the packages where those classes are (I just personally use a single package for them). Firebase uses reflection in serialization and deserialization process so it can't use obfuscated class names. Once you've put all of them in one package add this rule to your proguard file to prevent obfuscation:
-keep class package.to.pojos.** { *; }
If you wish to keep them where they are just add a rule for each model class with the -keep class keywords followed by the complete path (packagewise) of the class.
Reason of your problem
When you set minifyEnabled to true, R8 compiler optimizes your code by removing unnecessary parameters, methods and other parts of your code, which R8 think is not usable and, also, shrinks the class name and other parameter's name to reduce app size. But sometimes R8 can not determine correctly, which code is useful and which code is not. That is why R8 removes useful code too. Maybe, in your case, R8 changed the keys of your data. You can find it by pushing different data from your signed app. For example, some input data from the user while setting up a user profile. Now go back to your firebase firestore console and check the keys the data you just pushed. You will find that the keys are different now. Similarly, as R8 has changed the calling keys when you try to fetch the data, you are unable to find that key-pair values. That is why, your recycler view is empty.
Solution
1. Add the following library to your module's build.gradle file.
implementation 'androidx.annotation:annotation:1.1.0'
Now add #keep annotation at all the concerned classes. If not the whole class, then only the methods concerned with pushing or pulling the data.
Regards,
Ramesh
I am receiving data with loop using an interface which is giving me JSONObject and "i" from loop. Each time I receive one different:
{
"Id_temp": "1",
"temperatura": "20",
"Insertado_temp": "2016-08-16 12:30:29"
}
And I need to keep all JsonObjects in one HashMap- But every time I try it, the data from interface overwrite it and then only one Object "the last one" is in Map and other ones get deleted.
I would high appreciate an exemple of how implementing it in my code. Here I write the code. As Key value of HashMap I need the parameter "Id_temp" that is being received in "Id"
public class GraficaBarometro extends AppCompatActivity implements OnLoopjCompletedBarometro {
private DrawerLayout drawerLayout;
private OnLoopjCompletedBarometro loopjListener;
// Progress Dialog Object
ProgressDialog prgDialog;
// Error Msg TextView Object
TextView errorMsg;
// Email Edit View Object
private String temeperatura;
private Timestamp timestamp;
List<Entry> presiones = new ArrayList<>();
List<Entry> temperaturas = new ArrayList<>();
List<String> dates = new ArrayList<>();
LineChart mChart;
LoopjTasksBarometro loopjTasks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actividad_grafica_barometro);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
String idObjeto = (String) getIntent().getExtras().getSerializable("IdentidadEnviada");
loopjTasks = new LoopjTasksBarometro(this, this);
loopjTasks.CaptarParametros(idObjeto);
mChart = (LineChart) findViewById(R.id.chartbarometro);
int currentTime = (int) System.currentTimeMillis();
timestamp = new Timestamp(currentTime);
// no description text
mChart.setDescription("");
mChart.setNoDataTextDescription("You need to provide data for the chart.");
// enable touch gestures
mChart.setTouchEnabled(true);
mChart.setDragDecelerationFrictionCoef(0.9f);
// enable scaling and dragging
mChart.setDragEnabled(true);
mChart.setScaleEnabled(true);
mChart.setDrawGridBackground(true);
mChart.setHighlightPerDragEnabled(true);
// limit the number of visible entries
mChart.setVisibleXRangeMaximum(5);
// if disabled, scaling can be done on x- and y-axis separately
mChart.setPinchZoom(true);
// set an alternative background color
mChart.setBackgroundColor(Color.LTGRAY);
mChart.animateX(2500);
// to draw X-axis for our graph
XAxis xAxis = mChart.getXAxis();
xAxis.setTextSize(11f);
xAxis.setEnabled(true);
xAxis.setPosition(com.github.mikephil.charting.components.XAxis.XAxisPosition.BOTTOM);
//xAxis.setAxisMaxValue(125f);
xAxis.setAxisMinValue(0f);
xAxis.setTextColor(Color.DKGRAY);
xAxis.setDrawGridLines(false);
xAxis.setDrawAxisLine(true);
// to draw axis line
//modify leftYaxis range similarly others
YAxis leftAxis = mChart.getAxisLeft();
leftAxis.setTextColor(ColorTemplate.getHoloBlue());
leftAxis.setAxisMaxValue(50f);
leftAxis.setAxisMinValue(10f);
leftAxis.setDrawGridLines(false);
leftAxis.setGranularityEnabled(true);
YAxis rightAxis = mChart.getAxisRight();
rightAxis.setTextColor(Color.RED);
rightAxis.setAxisMaxValue(50f);
rightAxis.setAxisMinValue(10f);
rightAxis.setDrawGridLines(false);
rightAxis.setDrawZeroLine(false);
rightAxis.setGranularityEnabled(false);
}
private void agregarToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
if (ab != null) {
// Poner ÃÂÂcono del drawer toggle
ab.setHomeAsUpIndicator(R.drawable.drawer_toggle);
ab.setDisplayHomeAsUpEnabled(true);
}
}
private void prepararDrawer(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
seleccionarItem(menuItem);
drawerLayout.closeDrawers();
return true;
}
});
}
private void seleccionarItem(MenuItem itemDrawer) {
Fragment fragmentoGenerico = null;
FragmentManager fragmentManager = getSupportFragmentManager();
switch (itemDrawer.getItemId()) {
/*
case R.id.item_inicio:
fragmentoGenerico = new FragmentoInicio();
break;
*/
case R.id.item_web:
startActivity(new Intent(this, WebOficial.class));
break;
//fragmentoGenerico = new BlankFragment();
case R.id.item_categorias:
startActivity(new Intent(this, ActividadListaObjeto.class));
break;
case R.id.item_acceso:
startActivity(new Intent(this, MainActivity.class));
break;
}
if (fragmentoGenerico != null) {
fragmentManager
.beginTransaction()
.replace(R.id.contenido_principal, fragmentoGenerico)
.commit();
/*
if(fragmentTransaction) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
*/
}
// Setear titulo actual
setTitle(itemDrawer.getTitle());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_actividad_principal, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
/*
public String parseHours(long millis){
String currentDate = new SimpleDateFormat("hh:mm").format(new Date(millis));
Log.i(UtilitiesGlobal.TAG, "parseHours: " + currentDate);
return currentDate;
}
*/
private void setData() {
linLineDataSet set1, set2;
// create a dataset and give it a type
//modifications with colour and stuf
set1 = new LineDataSet(temperaturas, "temperatura");
set1.setAxisDependency(YAxis.AxisDependency.LEFT);
set1.setColor(ColorTemplate.getHoloBlue());
set1.setCircleColor(Color.WHITE);
set1.setLineWidth(2f);
set1.setCircleRadius(2f);
set1.setFillAlpha(65);
set1.setFillColor(ColorTemplate.getHoloBlue());
set1.setHighLightColor(Color.rgb(244, 117, 117));
set1.setDrawCircleHole(false);
//set1.setFillFormatter(new MyFillFormatter(0f));
//set1.setDrawHorizontalHighlightIndicator(false);
//set1.setVisible(false);
//set1.setCircleHoleColor(Color.WHITE);
// create a dataset and give it a type
// similar above
set2 = new LineDataSet(presiones, "presion");
set2.setAxisDependency(YAxis.AxisDependency.RIGHT);
set2.setColor(Color.RED);
set2.setCircleColor(Color.WHITE);
set2.setLineWidth(2f);
set2.setCircleRadius(2f);
set2.setFillAlpha(65);
set2.setFillColor(Color.RED);
set2.setDrawCircleHole(false);
set2.setHighLightColor(Color.rgb(244, 117, 117));
//set2.setFillFormatter(new MyFillFormatter(900f));
mChart.getXAxis().setValueFormatter(new AxisValueFormatter() {
#Override
public String getFormattedValue(float value, AxisBase axis) {
return dates.get((int) value);
}
#Override
public int getDecimalDigits() {
return 0;
}
});
ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
dataSets.add(set1); // add the datasets
dataSets.add(set2);
// create a data object with the datasets
LineData data = new LineData(dataSets);
data.setValueTextColor(Color.BLACK);
data.setValueTextSize(9f);
// set data
Log.i("Lists Sizedata", temperaturas.size() + " and " + presiones.size());
mChart.setData(data);
// move to the latest entry
mChart.moveViewToX(data.getEntryCount());
}
#Override
public void onLoopjTaskCompletedBarometro(JSONObject parametrosdht11, int i) {
String temperatura = null;
String presion = null;
String fecha = null;
String Id = null;
String altitud = null;
try {
Id = parametrosdht11.getString("Id_temp");
temperatura = parametrosdht11.getString("temperatura");
fecha = parametrosdht11.getString("Insertado_temp");
presion = parametrosdht11.getString("presion");
altitud = parametrosdht11.getString("altitud");
} catch (JSONException e) {
e.printStackTrace();
}
temperaturas.add(new Entry(Float.valueOf(i), Float.valueOf(temperatura)));
presiones.add(new Entry(Float.valueOf(i), Float.valueOf(presion)));
dates.add(fecha); // reduce the string to just 12:13 etc
//rrefresh we don't need to refresh since we are setting data after completing task
mChart.notifyDataSetChanged();
// mChart.setVisibleXRangeMaximum(12);
//Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " + usuarioiJSONbject);
Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " + "temperatura: " + temperatura + " presion: "
+ presion + " Fecha Inserción: " + fecha);
}
#Override
public void onLoopCompleteBarometro() {
setData();
// it takes time to recieve time. so we set the map after loop is complete okay?
//mChart.setVisibleXRangeMaximum(5);
}
Now Here is class with hashcode and equals method
public class ParametrosBarometro {
int i;
String Id_temperatura;
String temperatura;
String fecha_temperatura;
String presion;
String altitud;
public ParametrosBarometro(String Id_temperatura, String temperatura, String fecha_temperatura, String presion, String altitud) {
this.Id_temperatura = Id_temperatura;
this.temperatura = temperatura;
this.fecha_temperatura = fecha_temperatura;
this.presion = presion;
this.altitud = altitud;
}
#Override
public boolean equals(Object o) {
if (o instanceof ParametrosBarometro) {
ParametrosBarometro p = (ParametrosBarometro) o;
return this.Id_temperatura.equals(p.Id_temperatura);
} else {
return false;
}
}
#Override
public int hashCode() {
return this.Id_temperatura.length() * this.Id_temperatura.length();
}
}
I am receiving data with loop using an interface which is giving me JSONObject and "i" from loop. [...] As Key value of HashMap I need the parameter "Id_temp" that is being received in "Id".
OK. As simple as this:
private final Map<Integer, MyBean> map=new HashMap<Integer, MyBean>();
private void createAndStoreObject(JsonObject json, int i)
throws ParseException
{
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
MyBean myBean=new MyBean(json.getInt("Id_temp"), json.getInt("temperatura"), format.parse(json.getString("Insertado_temp")));
this.map.put(myBean.getId(), myBean);
}
class MyBean
{
private final int id;
private final int temperature;
private final Date insertionDate;
public MyBean(int id, int temperature, Date insertionDate)
{
super();
this.id=id;
this.temperature=temperature;
this.insertionDate=insertionDate;
}
public int getId()
{
return this.id;
}
// ... getters ...
}
As you can see, being the key an Integer (which is a class bundled with the Java Runtime Environment), there is no need to override the hashCode nor equals methods (Integer has them already).
I have two spinners the first one for month and the second for years.I am trying to call a method send_date() if on Item Selected is called for any of the 2 spinners.
So I have two problems:- 1)send_date() gets called twice the first
time it gets the correct data as expected but the 2nd time it returns
a empty array. 2)When I select another month or year the old data does
not get removed that is the list does not refresh.
The following is my code for on Item Selected :-
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
int i = spinYear.getSelectedItemPosition();
selected_year = years.get(i);
Log.d("Selection Year",selected_year);
tv_year.setText(selected_year);
try {
send_date();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
And for the month spinner:-
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
int j = spinMonths.getSelectedItemPosition();
selected_month = Months[j];
Date date = null;
try {
date = new SimpleDateFormat("MMMM").parse(selected_month);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
tv_month.setText(String.valueOf(cal.get(Calendar.MONTH)+1));
Log.d("Selection Month",selected_month);
try {
send_date();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
On response I call the following method for populating the list view with data:-
public void showBS(String response)
{
ParseBS_all pb = new ParseBS_all(response);
pb.parseBS();
bl = new BS_allList(getActivity(),ParseBS_all.doc_no,ParseBS_all.balance,ParseBS_all.total,ParseBS_all.vat,ParseBS_all.profit);
lv_bsall.setAdapter(bl);
}
This is the code for the send_date method:-
//This method is used to send month and year
private void send_date() throws JSONException {
final String year = tv_year.getText().toString();
final String month = tv_month.getText().toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, SEND_DATE,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//display.setText("This is the Response : " + response);
String resp = response.toString().trim();
if (resp.equals("Nothing to display"))
{
Toast.makeText(getContext(), "Nothing to Display", Toast.LENGTH_SHORT).show();
// bl.clear();
lv_bsall.setAdapter(bl);
bl.notifyDataSetChanged();
}else
{
Toast.makeText(getContext(), "Response" + response, Toast.LENGTH_LONG).show();
Log.d("RESPONSE for date", response.toString().trim());
showBS(response);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
GlobalClass gvar = (GlobalClass) getActivity().getApplicationContext();
String dbname = gvar.getDbname();
Map<String, String> params = new HashMap<>();
params.put(KEY_DBNAME, dbname);
params.put(KEY_MONTH, month);
params.put(KEY_YEAR,year);
return params;
}
};
RequestQueue requestQ = Volley.newRequestQueue(getContext());
requestQ.add(stringRequest);
}
Adapter code for list view.
public class BS_allList extends ArrayAdapter<String>
{
private String[] doc_no;
private String[] balance;
private String[] total;
private String[] vat;
private String[] profit;
private Activity context;
public BS_allList(Activity context, String[] doc_no, String[]balance, String[] total, String[] vat, String[] profit)
{
super(context, R.layout.bs_list_all, doc_no);
this.context =context;
this.doc_no= doc_no;
this.balance = balance;
this.total = total;
this.vat=vat;
this.profit = profit;
}
#Override
public View getView(int position, View listViewItem, ViewGroup parent)
{
if (null == listViewItem)
{
LayoutInflater inflater = context.getLayoutInflater();
listViewItem = inflater.inflate(R.layout.bs_list_all, null, true);
}
TextView tv_docNo = (TextView) listViewItem.findViewById(R.id.tvdoc_no);
TextView tv_balance = (TextView) listViewItem.findViewById(R.id.tv_balance);
TextView tv_tot = (TextView) listViewItem.findViewById(R.id.tv_total);
TextView tv_vat = (TextView) listViewItem.findViewById(R.id.tv_vat);
TextView tv_pf = (TextView) listViewItem.findViewById(R.id.tv_profit);
tv_docNo.setText(doc_no[position]);
tv_balance.setText(balance[position]);
tv_tot.setText(total[position]);
tv_vat.setText(vat[position]);
tv_pf.setText(profit[position]);
return listViewItem;
}
}
Also note that I have set the spinner to point to the current month and year so the first time it works properly.
I am new to programming so any help or suggestion is appreciated.Thank you.
Hi #AndroidNewBee,
As per our discussion made following changes in your code and you will get proper output and it will resolve your issues.
if (resp.equals("Nothing to display"))
{
Toast.makeText(getContext(), "Nothing to Display", Toast.LENGTH_SHORT).show();
bl = new BS_allList(getActivity(),{""},{""},{""},{""},{""});
lv_bsall.setAdapter(bl);
}
And second is check validation as below,
try {
if((selected_year != null & selected_year.length > 0 ) & (tv_month.getText().toString() != null & tv_month.getText().toString().length > 0))
{
send_date();
}
} catch (JSONException e) {
e.printStackTrace();
}
First you shouldn't be using so many String[], instead wrap them in a class
Class BSDataModel{
private String doc_no;
private String balance;
private String total;
private String vat;
private String profit;
//getters and setters
}
Now the reponse result should be added as in ,it returns List<BSDataModel>
List<BSDataModel> reponseList = new ArrayList<>();
//for example adding single response
for(int i=0;i<jsonArrayResponse.length();i++){
BSDataModel singleResponse = new BSDataModel();
singleResponse.setDocNo(jsonArrayResponse.get(i).getString("doc_no"));
singleResponse.setBalace(jsonArrayResponse.get(i).getString("balance"));
//etc..finall add that single response to responseList
reponseList.add(singleResponse);
}
BS_allList.java
public class BS_allList extends ArrayAdapter<BSDataModel>
{
private List<BSDataModel> bsList;
private Activity context;
public BS_allList(Activity context,List<BSDataModel> bsList)
{
super(context, R.layout.bs_list_all, bsList);
this.context =context;
this.bsList = bsList;
}
#Override
public View getView(int position, View listViewItem, ViewGroup parent)
{
if (null == listViewItem)
{
LayoutInflater inflater = context.getLayoutInflater();
listViewItem = inflater.inflate(R.layout.bs_list_all, null, true);
}
TextView tv_docNo = (TextView) listViewItem.findViewById(R.id.tvdoc_no);
TextView tv_balance = (TextView) listViewItem.findViewById(R.id.tv_balance);
TextView tv_tot = (TextView) listViewItem.findViewById(R.id.tv_total);
TextView tv_vat = (TextView) listViewItem.findViewById(R.id.tv_vat);
TextView tv_pf = (TextView) listViewItem.findViewById(R.id.tv_profit);
BSDataModel bsData = bsList.get(position);
tv_docNo.setText(bsData.getDoc());
tv_balance.setText(bsData.getBalance());
tv_tot.setText(bsData.getTot());
tv_vat.setText(bsData.getVat());
tv_pf.setText(bsData.getPF());
return listViewItem;
}
}
Now in your class
BS_allList bl = new BS_allList(getActivity(),responseList);//which you got above
After receiving new Response
// remove old data
responseList.clear(); // list items in the sense list of array used to populate listview
if(newresponseArray.size() > 0){
for(int i=0;i<newjsonArrayResponse.length();i++){
BSDataModel singleResponse = new BSDataModel();
singleResponse.setDocNo(newjsonArrayResponse.get(i).getString("doc_no"));
singleResponse.setBalace(newjsonArrayResponse.get(i).getString("balance"));
//etc..finall add that single response to responseList
reponseList.add(singleResponse);
}
}
//refresh listview
bl.notifyDataSetChanged();
Try this way,
1. adapter.clear();
2. Add/Remove your list Items.
3. listview.setAdapter(adapter);
4. adapter.notifyDatasetChanged();
this procedure should work.