Cannot get a value from EditText - java

i have a little problem, i have been solved my problem before thanks to Alex Mamo, and now i have another problem.
Here i attach my firebase realtime database screenshoot
Well at the ima i attach, te Cart should have a child refer to table number, i get a table number from edittext sing getText function, and i send it, to another activity, but, when i send it to another activiy and get it, it seems not getting any value. I try to Log, and it doesn't show anything, try to print too, and the reslut is same. My question is, how i can get a value from edittext in other way?
Here i attach my code fo getText function
DineIn.java
EditText txtTable;
ArrayList<Menu> menuItems = new ArrayList<Menu>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dine_in);
txtTable = findViewById(R.id.txtTable);
String tables = txtTable.getText().toString();
Log.e("Nomormeja", tables);
And this cod is for send it to another activity
DineIn.java (this code is outter from onCreate() method)
class CustomAdaptor extends BaseAdapter {
private Activity mContext;
private ArrayList<Menu> mItems;
public CustomAdaptor(Activity context, ArrayList<Menu> list) {
mContext = context;
mItems = list;
}
#Override
public int getCount() {
return menuItems.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.order_items, null);
TextView menuName = (TextView) convertView.findViewById(R.id.menuName);
TextView menuType = (TextView) convertView.findViewById(R.id.menuType);
TextView menuPrice = (TextView) convertView.findViewById(R.id.menuPrice);
ImageButton addcart = (ImageButton) convertView.findViewById(R.id.addBtn);
final String menuNames = menuItems.get(position).getMenuName();
final String tables = txtTable.getText().toString();
addcart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Like a Session variable ..it passes the dishName from the row that was clciked
SharedPreferences sharedPreferences=getSharedPreferences("shared preferences",MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("menuNames",menuNames);
editor.putString("tables", tables);
editor.commit();
startActivity(new Intent(DineIn.this,ProductDetails.class));
}
});
And this code is to get the value on destination activity
Product.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);
txtNama = findViewById(R.id.tvNama);
txtQuantity = findViewById(R.id.tvQuantity);
btnMin = findViewById(R.id.btnMin);
btnPls = findViewById(R.id.btnPls);
btnAdd = findViewById(R.id.btnAdd);
SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences sharedPreferences=getSharedPreferences("shared preferences",MODE_PRIVATE);
menuName = sharedPreferences.getString("menuNames", ""); // taking dishname from menu when clicked a
tables = sharedPreferences.getString("tables", "");
Log.d("meja", tables);
Log.d("menu", menuName);
And i set the vale for child at my Cart entry
if(invalid==false){
writeNewEntry(tables, menuName, date, quantity);
finish();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
}
private void writeNewEntry(String table, String name, String dates, int q){
Cart entry = new Cart(table, name, dates, q);
FirebaseDatabase.getInstance().getReference("Cart").child(tables).push().setValue(entry);
}
Thank you so much for every help

First of all, you should not pass content to another activity by SharedPreferences.
try send it through Intent...
Sender:
Intent intent = new Intent(DineIn.this,ProductDetails.class);
intent.putExtra("tables", tables);
startActivity(intent)
Receiver(Activity case):
Intent intent = getIntent();
tables = intent.getStringExtra("tables", "");

Related

Delete a listview item with a button in it self in android studio

As I am very new to java pls help me on this. I have a custom list view in my main activity and a Custom adapter with it. In my every list item there is a delete button that should delete that item when it clicked. I can not remove data from my arraylist when i am inside my custom adapter. Pls helm me in coding this delete button.
MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText getItem;
Button AddButton;
Button DellButton;
public static ArrayList<String> myData = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView list = (ListView)
findViewById(R.id.listView);
getItem = (EditText) findViewById(R.id.newItem);
AddButton = (Button) findViewById(R.id.AddButton);
MyAdapter adapter = new MyAdapter(this, myData);
list.setAdapter(adapter);
AddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String result = getItem.getText().toString();
myData.add(result);
adapter.notifyDataSetChanged();
}
});
}
MyAdapter.java
public class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, ArrayList<String> records) {
super(context, 0, records);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String item = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.listview_custom, parent, false);
}
final TextView lst_txt = (TextView) convertView.findViewById(R.id.list_Txt2);
Button plusbut = (Button) convertView.findViewById(R.id.plusbut);
Button minusbut = (Button) convertView.findViewById(R.id.minusbut);
final TextView sum = (TextView) convertView.findViewById(R.id.sum);
Button cal = (Button) convertView.findViewById(R.id.calButton);
Button delete = (Button) convertView.findViewById(R.id.btnDel);
lst_txt.setText(item);
minusbut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int sumAll = Integer.parseInt(sum.getText().toString());
int sum1 = sumAll - 1;
sum.setText(String.valueOf(sum1));
}
});
plusbut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int sumAll = Integer.parseInt(sum.getText().toString());
int sum1 = sumAll + 1;
sum.setText(String.valueOf(sum1));
}
});
cal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s = sum.getText().toString();
Intent intent = new Intent(getContext(), calll.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("sumFL", s);
getContext().startActivity(intent);
}
});
return convertView;
}
}
Please first try to remove object from list by using the position of item with check the validation with list size and then call notifyItemadapter to update the list view.
Use ViewHolder class for all view like textview, button etc. And initialize them inside the condition
if(convert view==null){
Initialize holder object here and
Inflate your layout and
Initialize button like
holder.deletebutton = convert view.findviewbyid from xml
settag(holder)
}
Again get the holdet using the gettag in
else{
//Here
}
Put All click event and text update etc. Outside of above condition
holder.deletbutton.setonclicklistener{
int pos = view.getag
list.remove(pos)
Notifyadapter here
}
holder.deletebutton.settag(position)

Not able to pass data between activities.Data is blank

I am trying to pass some data from one activity to another and I have made a toast in the other activity to see if data is being passed.When the toast shows up it is blank.I have done everything right and tried many different times with different methods I have also created another app but the problem still stays.It gives me null.
My java code in the first activity
public class titleandcuisine extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
public static final String TITLE_GET = "title";
public static final String CUISINE_GET = "cuisine";
ImageView imageView;
Button button;
Spinner spinner;
EditText dish;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_titleandcuisine);
dish = findViewById(R.id.editText);
spinner = findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.cuisines,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
button = findViewById(R.id.next);
imageView = findViewById(R.id.close);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), homepage.class));
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = dish.getText().toString();
String text2 = spinner.getSelectedItem().toString();
Intent data = new Intent(getBaseContext(),imagepost.class);
data.putExtra(TITLE_GET,text);
data.putExtra(CUISINE_GET,text2);
startActivity(data);
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
Second activity java code
public class reviewactivity extends AppCompatActivity {
TextView cuisine,title;
ImageView displayimage,back;
Uri myUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reviewactivity);
Intent intent = getIntent();
String titleget = intent.getStringExtra(titleandcuisine.TITLE_GET);
String cuisineget = intent.getStringExtra(titleandcuisine.CUISINE_GET);
Toast.makeText(this, titleget + cuisineget, Toast.LENGTH_SHORT).show();
cuisine = findViewById(R.id.reviewcuisine);
title = findViewById(R.id.reviewtitle);
back = findViewById(R.id.backtopostvideo);
displayimage = findViewById(R.id.reviewdisplaimage);
// cuisine.setText(cuisineget);
// title.setText(titleget);
// myUri = Uri.parse(uri);
displayimage.setImageURI(myUri);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),videopost.class));
}
});
}
}
You need to read the text from the EditText when the button is clicked. Something like:
title = dish.getText().toString(); // Add this
Intent data = new Intent(getBaseContext(),imagepost.class);
data.putExtra(Intent.EXTRA_TEXT, title);
...
One more thing: You are trying to read the Intent.EXTRA_TEXT at the reviewactivity activity. However, nothing is starting that activity (at least within the piece of code that you shared).

Why do "selectedCountry", "selectedAge", "selectedGender" return null?

When I run my app and go to the "EditProfile" activity. And then, I will immediately receive the toast message "Something is wrong" which means, the variables "selectedCountry", "selectedAge", and "selectedGender" are null.
public class EditProfile extends AppCompatActivity {
UserInfo userInfo;
UserInfo profileDetails;
Spinner spinnerFrom;
Spinner spinnerAge;
Spinner spinnerGender;
EditText hobbyEdit;
Button btnDone;
TextView textView;
String selectedCountry;
String selectedAge;
String selectedGender;
DatabaseHelper mydb = new DatabaseHelper(this, "MyUsers", null, 5);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Profile.class);
intent.putExtra("id", userInfo.getId());
intent.putExtra("username", userInfo.getUsername());
startActivity(intent);
}
});
Bundle extras = getIntent().getExtras();
int id = extras.getInt("id");
final String username = extras.getString("username");
// Username
userInfo = new UserInfo(id, username);
textView = (TextView) findViewById(R.id.usernameUnedit);
textView.setText(username);
// Country
spinnerFrom = (Spinner) findViewById(R.id.spinnerFrom);
Locale[] locales = Locale.getAvailableLocales();
final ArrayList<String> countries = new ArrayList<String>();
countries.add("-");
for (Locale locale : locales) {
String country = locale.getDisplayCountry();
if (country.trim().length() > 0 && !countries.contains(country)) {
countries.add(country);
}
}
Collections.sort(countries);
ArrayAdapter<String> countryAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, countries);
countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerFrom.setAdapter(countryAdapter);
spinnerFrom.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedCountry = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// Age
spinnerAge = (Spinner) findViewById(R.id.spinnerAge);
final ArrayList<String> ages = new ArrayList<String>();
ages.add("-");
for (int i = 18; i < 100; i++) {
ages.add(String.valueOf(i));
}
ArrayAdapter<String> ageAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, ages);
ageAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerAge.setAdapter(ageAdapter);
spinnerAge.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedAge = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// Gender
spinnerGender = (Spinner) findViewById(R.id.spinnerGender);
final ArrayList<String> genders = new ArrayList<String>();
genders.add("-");
genders.add("Male ♂");
genders.add("Female ♀");
genders.add("Other");
ArrayAdapter<String> genderAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, genders);
genderAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerGender.setAdapter(genderAdapter);
spinnerGender.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedGender = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// Hobby
hobbyEdit = (EditText) findViewById(R.id.hobbyEdit);
// Button done
btnDone = (Button) findViewById(R.id.btnDone);
btnDone.setEnabled(false);
/* Stuck at this if statement below */
if (selectedCountry != null && selectedAge != null && selectedGender != null) {
if (!mydb.isStoredProfileDetails(username, selectedCountry, selectedAge, selectedGender, hobbyEdit.getText().toString())) {
btnDone.setEnabled(true);
btnDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
profileDetails = new UserInfo(selectedCountry, selectedAge, selectedGender, hobbyEdit.getText().toString());
mydb.updateTable(username, profileDetails);
}
});
} else {
Toast.makeText(this, "Something is wrong 2.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "Something is wrong.", Toast.LENGTH_LONG).show();
}
}
}
I expect that after choosing an item from those 3 dropdown lists (spinners) and the values of the chosen items do not exist in database, then the "Done" button would be clickable. Once the button is clicked, it would store the selected values from the dropdown lists (spinners) into database by updating it.
Unfortunately, I am stuck at the if statement as stated in the given code as it keeps returning the "else" statement.
Set your variable as...
String selectedCountry = "";
String selectedAge = "";
String selectedGender = "";
And check condition as...
if (!selectedCountry.equals("") && !selectedAge.equals("") && !selectedGender.equals("")) {
//your code goes here
}
You have to check your both conditions in Spinner's OnItemSelectedListener, If both conditions will return true then enable your button. and call setonClickListener on button in onCreateView, like this.
spinnerGender.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedGender = parent.getItemAtPosition(position).toString();
//Conditions to enable button
if (selectedCountry != null && selectedAge != null && selectedGender != null) {
if (!mydb.isStoredProfileDetails(username, selectedCountry, selectedAge, selectedGender, hobbyEdit.getText().toString())) {
btnDone.setEnabled(true);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
add these lines in all spinners.
In your onCreate method, you have instantiated the views and attached listeners to them. That is perfectly fine. However, this does not mean that the logic in those listeners will be execute at the same time and order. You have just defined the behaviour of the listeners. After all that initialisation, your code directly checks the values of the three Strings mentioned in your question. It does not wait for a user to interact with the spinners.
What you want is to trigger the change in the "done" button when a user selects something from the spinner. So the logic of setting the strings and thereby checking if you could enable the "done" button must go in the listeners of the spinners.
I am not giving you a direct code solution to the problem, but an approach which you could employ.

How to implement OnClick item using firebase search query result item

I've created a firebase search query and it works perfectly.But now I can't seem to figure out how to do the onlick and get item position. Below is my firebase search activity:
mUserDatabase=FirebaseDatabase.getInstance().getReference("Users").child("UserProfile";
mSearchField = findViewById(R.id.search_field);
mSearchBtn = findViewById(R.id.search_btn);
mResultList = findViewById(R.id.result_list);
mResultList.setHasFixedSize(true);
mResultList.setLayoutManager(new LinearLayoutManager(this));
mSearchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String searchText = mSearchField.getText().toString();
firebaseUserSearch(searchText);
}
});
}
private void firebaseUserSearch(String searchText) {
Toast.makeText(SearchActivity.this, "Searching......", Toast.LENGTH_LONG).show();
Query firebaseSearchQuery = mUserDatabase.orderByChild("profession").startAt(searchText).endAt(searchText + "\uf8ff");
FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(
Users.class,
R.layout.search_list_layout,
UsersViewHolder.class,
firebaseSearchQuery
) {
#Override
protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {
viewHolder.setDetails(getApplicationContext(), model.getUsername(), model.getSummary(), model.getImageurl());
}
};
mResultList.setAdapter(firebaseRecyclerAdapter);
}
public static class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;
private TextView user_name;
private TextView user_summary;
private ImageView user_image;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDetails(Context ctx, String userName,String userSummary,String userImage){
user_name = mView.findViewById(R.id.name_text);
user_summary = mView.findViewById(R.id.summary_text);
user_image = mView.findViewById(R.id.profile_image);
user_name.setText(userName);
user_summary.setText(userSummary);
Glide.with(ctx).load(userImage).into(user_image);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
Snackbar.make(v, "Hello,How may i help you", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
});
}
How do i go about displaying the content in a details activity when a single item from the search result is clicked.
Based on Parag Pawar's suggestion, I tried the following, but it's not working>
#Override
protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {
viewHolder.setDetails(getApplicationContext(), model.getUsername(), model.getSummary(), model.getImageurl());
final String each_key = getRef(position).getKey();
}
};
Then in my UserViewHolder i initialized the onclick:
mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent pDetail = new Intent(SearchActivity.this, ProfileDetail.class);
Users each_key = each_key.get(getAdapterPosition());
pDetail.putExtra(ProfileDetail.EXTRA_POSITION, each_key.getUserId());
startActivity(pDetail);
}
});
But I am getting the error variable each_key might not have been initialized
Fixed my mistake according top advice from Parag Pawar and implemented he onclick inside populateView`holder as follows:
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*Here use intent.putExtra() to send each_key on other activity and fetch data there*/
Toast.makeText(SearchActivity.this, "u clicked......" +position, Toast.LENGTH_LONG).show();
Intent each_key = new Intent(SearchActivity.this, ProfileDetail.class);
Users user = mResultList.get(position);
each_key.putExtra(ProfileDetail.EXTRA_POSITION, user.getUserId());
startActivity(each_key);
} });
but I am getting the error here:
Users user = mResultList.get(position);
Cannot resolve method 'get(int)'
mReultList is the name of my Recyclerview and I initialized it as follows:
private RecyclerView mResultList;
but I don't know if I'm doing this correctly. I know I am supposed to attach the results to an adapter, but I don't know how to do that. So I tried:
listItems = new ArrayList<>();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<UsersList>(listItems,this);
But this doesn't seem to work either
Updated Code
I created an array:
private List<UsersList> listItems;//UsersList is my modal class
Then added it to my onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
listItems = new ArrayList<>();
I then Implemented putExtra as follows using this array as follows:
Intent each_key = new Intent(TestSearch.this, ProfileDetail.class);
UsersList user = listItems.get(position);
//Here use intent.putExtra() to send each_key on other activity and fetch data there
Toast.makeText(TestSearch.this, "u clicked......" +position, Toast.LENGTH_LONG).show();
each_key.putExtra(ProfileDetail.EXTRA_POSITION, user.getUserId());
startActivity(each_key);
But getting this error when i click an item:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:411)
at com.ecard.ecard.search.TestSearch$2$1.onClick(TestSearch.java:94)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
To get key from each item, in populateViewholder do
Example :-
final String each_key = getRef(position).getKey();
To set Click Listeners on each item, in populateViewholder do
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*Here use intent.putExtra() to send each_key on other activity and fetch data there*/
} }); }
In the activity that contains your current
items that you want to click on:
Create a String to reference from in your populateVieHolder:
final String single_view = getRef(position).getKey();
Then attach an onclick to your ViewHolder:
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
And in your OnClick place your intents and putExtras:
#Override
public void onClick(View view) {
//give your intent a name to reference from("moreDetail" in this case)
Intent moreDetail = new Intent(SearchActivity.this,MoreDetail.class);
//attach the intent reference to access each item and key
moreDetail.putExtra(MoreDetail.EXTRA_POSITION,single_view);
startActivity(moreDetail);//Start the new activity
Then in your more details activity:
Add the ExtraPosition String
String single_view = getIntent().getExtras().getString(MoreDetail.EXTRA_POSITION);//get extra position reference previous view
From here on,you need to display your data from firebase
For accessing Single Values from Firebase
firebaseRef.child(single_view).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//For single items
// for example:String user_name = (String) dataSnapshot.child("username").getValue();
Or
For accessing Values attached to your adapter using a Listview
firebaseRef.child(single_view).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ListItem data = dataSnapshot.getValue(ListItem.class);
listItems.add(data);
adapter.notifyDataSetChanged();
//if you are accessing your data from a ListView
There are so many ways to do this.Another way to accomplish this is to create an interface.declare an onclick listener and contex in your recycler adapter:
OnItemClickListener callback;
private Context mContext;
Then implement an Onclick listener to your view holder
public static class UsersViewHolder extends RecyclerView.ViewHolder implements OnItemClickListener {
add an onclick to access a position,to your View Holder using callback:
#Override
public void onClick(View v) {
callback.onItemClick(getAdapterPosition());
}
Then create an interface:
public interface OnItemClickListener {
void onItemClick(int pos);
}
Based on your context:
In your more main activity:
#Override
public void onItemClick(int pos) {
Intent pDetail = new Intent(this.getContext(), ProfileDetail.class);//get the context
ListItem listItem = listItems.get(pos);//get the position
//Then your puEtxra here followed by start activity
startActivity(pDetail);
}
And finally call EXTRA_POSITION in your detail view followed by your datasnapshots.
You can find more details from the firebase documentation and firebase quick start samples on github:
GitHub
FirebaseDocs
I said both the things go in populateViewHolder()
You are getting not initialized error because you're using each_key in the Viewholder class.
Copy this
final String each_key = getRef(position).getKey();
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*Here use intent.putExtra() to send each_key on other activity and fetch data there*/
} }); }
and paste it in the populateViewHolder method

Gathering multiple intent extras while saving the results during return to the main activity

I'm having problems storing intent extras from my previous activity when I use another intent to open an activity and return the result.
Logic:
Activity A: receive string from check box, uses intent hasExtra to pass to activity b
Activity B: List of edit text fields with buttons to activity c
Activity C: uses intent extra to get string and pass to another editTextField in activity b
Problem is that I keep losing the intentExtra from a to b.
I apologise if my description is not thorough, I'm new to Java.
Activity A
public class PipesInspection extends AppCompatActivity{
private static final String TAG = "PipesInspection";
ArrayList<String> pipesInspectionSelection = new ArrayList<String>();
Button nextButtonToPost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.residential_pipes_inspection_lv_selected);
Log.d(TAG, "onCreate: starting");
initialiseWidgets();
}
public void initialiseWidgets(){
nextButtonToPost = (Button) findViewById(R.id.nextButton);
nextButtonToPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String final_category_selection = "";
for (String Selections : pipesInspectionSelection){
final_category_selection = final_category_selection + Selections + ", ";
}
Log.v(TAG,"gotten text: " + final_category_selection);
String selectedChoices = pipesInspectionSelected.getText().toString();
Intent pipesInspectionIntent = new Intent(v.getContext(), PostAJobActivity.class);
pipesInspectionIntent.putExtra("selectedChoices", selectedChoices);
v.getContext().startActivity(pipesInspectionIntent);
}
});
}
}
Activity B
public class PostAJobActivity extends AppCompatActivity {
private static final String TAG = "PostAJobActivity";
EditText jobTitle, jobDescription, jobLocation;
String location, title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_a_job);
Log.d(TAG, "onCreate: starting");
jobDescription = (EditText)findViewById(R.id.input_job_description);
mapsButton = (ImageButton) findViewById(R.id.mapButton);
mapsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, LaunchMapsActivity.class);
startActivity(intent);
}
});
getIntentExtras();
}
public void getIntentExtras(){
jobLocation = (EditText) findViewById(R.id.location);
Intent intentLocation =getIntent();
location= intentLocation.getStringExtra("location");
jobLocation.setText(location);
jobTitle = (EditText) findViewById(R.id.title);
Intent pipesInspectionIntent = getIntent();
title = pipesInspectionIntent.getStringExtra("selectedChoices");
jobTitle.setText(title);
}
}
Activity C
public class PlaceListAdapter extends RecyclerView.Adapter<PlaceListAdapter.PlaceViewHolder> {
private Context mContext;
private PlaceBuffer mPlaces;
public PlaceListAdapter(Context context, PlaceBuffer places) {
this.mContext = context;
this.mPlaces = places;
}
#Override
public PlaceViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Get the RecyclerView item layout
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.maps_item_place_card, parent, false);
return new PlaceViewHolder(view);
}
#Override
public void onBindViewHolder(final PlaceViewHolder holder, int position) {
String placeName = mPlaces.get(position).getName().toString();
String placeAddress = mPlaces.get(position).getAddress().toString();
holder.nameTextView.setText(placeName);
holder.addressTextView.setText(placeAddress);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentLocation = new Intent(v.getContext(), PostAJobActivity.class);
intentLocation.putExtra("location",holder.nameTextView.getText().toString()+
", " + holder.addressTextView.getText().toString());
v.getContext().startActivity(intentLocation);
}
});
}
I think this article may be helpful
https://developer.android.com/training/basics/intents/result.html
I am not sure I understand the problem correctly...activity A starts first and passes data to activity B which invokes activity C and gets data from it return to activity B which uses the data collected from both activities to do something
....If this is your problem you should not start activity C the normal way you should use startActivityforresult() form activity B to start activty C
and wait for it to finish then return to B with the data collected from C....starting the activity B from activity C will create new instance of B without having the data collected form A while using this way the instance of B with data from A will wait to C to finish and take the data from it in addition to that move the getIntentExtras() function inside the onClick()

Categories

Resources