How do I pass a command to the component of another activity? - java

I have two activities. When an item in a RecyclerView is selected, it takes the user to the second activity and fills in the details with the related RecyclerView item.
In the second RecyclerView activity, there is a Spinner. Depending on the item selected in the spinner, different RecyclerViews become visible/invisible to the user on the second activity.
How do I make it work so that the information is sent from the first activity to command the spinner on what to do?This is how Second Activity looks
SecondActivity.java
public class SecondActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private TextView tv_title, tv_description;
private ImageView PartiesThumbnailImg,PartiesCoverImg;
private RecyclerView RvPartyMembers;
private PartyMembersAdapter partyMembersAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parties_detail);
Spinner spinner = findViewById(R.id.spnConstituencies);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.constituencies, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
//ini views
iniViews();
//Setting up members list
setupRvPartyMembers();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String text = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
void iniViews() {
RvPartyMembers = findViewById(R.id.rv_party_members);
String partiesTitle = getIntent().getExtras().getString("title");
String partiesDescription = getIntent().getExtras().getString("description");
int imageResourceId = getIntent().getExtras().getInt("imgURL");
int imagecover = getIntent().getExtras().getInt("imgCover");
PartiesThumbnailImg = findViewById(R.id.detail_members_img);
Glide.with(this).load(imageResourceId).into(PartiesThumbnailImg);
PartiesThumbnailImg.setImageResource(imageResourceId);
PartiesCoverImg = findViewById(R.id.detail_members_cover);
Glide.with(this).load(imagecover).into(PartiesCoverImg);
tv_title = findViewById(R.id.tvPartyTitle);
tv_title.setText(partiesTitle);
tv_description = findViewById(R.id.tvPartyDesc);
tv_description.setText(partiesDescription);
}
void setupRvPartyMembers(){
List<PartyMembers> mdata = new ArrayList<>();
mdata.add(new PartyMembers("name",R.drawable.members_brendangriffin_fg));
mdata.add(new PartyMembers("name",R.drawable.members_brendangriffin_fg));
mdata.add(new PartyMembers("name",R.drawable.members_brendangriffin_fg));
partyMembersAdapter = new PartyMembersAdapter(this,mdata);
RvPartyMembers.setAdapter(partyMembersAdapter);
RvPartyMembers.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
}
These are the important pieces of code of the FirstActivity.java
#Override
public void onPartiesItemClick(PartiesOireachtas partiesOireachtas, ImageView partiesImageView) {
Intent intent = new Intent(getContext(),PartiesDetailActivity.class);
intent.putExtra("title", partiesOireachtas.getTitle());
intent.putExtra("description",partiesOireachtas.getDescription());
intent.putExtra("imgURL", partiesOireachtas.getThumbnail());
intent.putExtra("imgCover",partiesOireachtas.getCoverPhoto());
and
Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//RecyclerView Setup
//int data
lstPartiesOireachtas = new ArrayList<>();
lstPartiesOireachtas.add(new PartiesOireachtas("Fianna Fáil", "example1", R.drawable.fianna_fail_logo,R.drawable.fianna_fail_cover));
lstPartiesOireachtas.add(new PartiesOireachtas("Sinn Féin", "example2", R.drawable.sinn_fein_logo,R.drawable.sinn_fein_cover));
lstPartiesOireachtas.add(new PartiesOireachtas("Fine Gael", "example4", R.drawable.fine_gael_logo,R.drawable.fine_gael_cover));
lstPartiesOireachtas.add(new PartiesOireachtas("Green Party", "example9", R.drawable.green_party_logo,R.drawable.green_party_cover));
lstPartiesOireachtas.add(new PartiesOireachtas("Social Democrats", "example3", R.drawable.soc_dems_logo,R.drawable.soc_dems_cover));
lstPartiesOireachtas.add(new PartiesOireachtas("Independent", "example2", R.drawable.independent_party_logo,R.drawable.independent_party_cover));

As you probably noticed an activity doesn't have a default constructor, but uses an onCreate(Bundle savedInstanceState) method. This means you should pass your information using this Bundles, or use something like SharedPreferences / SQLite. Since SharedPreferences / SQLite is a bit overkill for this in my opinion, you can add the object upon creating an intent.
Intent intent = new Intent();
intent.putExtra("name", parcelableObject);
If you want to pass a custom object you have to implement the Parcelable interface, this is pretty straightforward since you can basically auto generate all code for this in Android studio (just hit alt-enter a few times). For more information you can check out the following link.
https://developer.android.com/reference/android/os/Parcelable
In the receiving activity you can do the following:
Bundle bundle = getIntent().getExtras();
Object object = bundle.getObject("name"); //Don't forget to cast!

Related

How to pass data from a activity to a recycler view adapter in android

I'm trying to design a page where address are stored in recycler view -> cardview.
When the user clicks the add address button from the Activity A the user is navigated to the add address page in Activity B. Here the user can input customer name, address line 1 and address line two.
And once save button is clicked in Activity B, a cardview should be created under the add address button in the Activity A.
This design is just like the amazon mobile app add address option.
Could anyone give me an example hoe to pass the saved data from activity to recycler adapter. I know how to pass data from recycler adapter to activity with putExtra etc..
Kindly help me. Million Thanks in advance!
Code In Activity A(Where the Add address button is available and where the recycler view is present)
public class ProfileManageAdressFragment extends AppCompatActivity {
RecyclerView recyclerView;
ProfileManageAddressRecyclerAdapter adapter;
ArrayList<ProfileManageAddressGetterSetter> reviews;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_profile_manage_adress);
Button addAddress = findViewById(R.id.addNewAddress);
reviews = new ArrayList<>();
addAddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Clicked", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(ProfileManageAdressFragment.this, AddNewAddress.class);
startActivity(intent);
}
});
}
}
Piece of Code that is responsible for adding a card view in Activity A. Kindly let me know how to invoke this below code on button click in Activity
reviews.add(new ProfileManageAddressGetterSetter("Customer Name", "address line 1", "address line 2"));
recyclerView = findViewById(R.id.addressRecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(ProfileManageAdressFragment.this));
adapter = new ProfileManageAddressRecyclerAdapter(this, reviews);
recyclerView.setAdapter(adapter);
Code in the Recycler adapter
public class ProfileManageAddressRecyclerAdapter extends RecyclerView.Adapter<ProfileManageAddressRecyclerAdapter.ViewHolder> {
private ArrayList<ProfileManageAddressGetterSetter> mDataset = new ArrayList<>();
private Context context;
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView customer_name, address_one, address_two;
private Button edit, remove;
public ViewHolder(View v) {
super(v);
customer_name = (TextView) v.findViewById(R.id.customerName);
address_one = (TextView) v.findViewById(R.id.addressLineOne);
address_two = v.findViewById(R.id.addressLineTwo);
}
}
public ProfileManageAddressRecyclerAdapter(View.OnClickListener profileManageAdressFragment, ArrayList<ProfileManageAddressGetterSetter> dataset) {
mDataset.clear();
mDataset.addAll(dataset);
}
#Override
public ProfileManageAddressRecyclerAdapter.ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_manage_address, parent, false);
ProfileManageAddressRecyclerAdapter.ViewHolder vh = new ProfileManageAddressRecyclerAdapter.ViewHolder(view);
return vh;
}
#Override
public void onBindViewHolder(#NonNull ProfileManageAddressRecyclerAdapter.ViewHolder holder, int position) {
ProfileManageAddressGetterSetter profileManageAddressGetterSetter = mDataset.get(position);
holder.address_one.setText(profileManageAddressGetterSetter.getAddress_line_1());
holder.address_two.setText(profileManageAddressGetterSetter.getGetAddress_line_2());
holder.customer_name.setText(profileManageAddressGetterSetter.getContractor_name());
}
#Override
public int getItemCount() {
return mDataset.size();
}
}
enter image description here - After trying the call from adapter using intent as mentioned above ended up with a 0.
Code in the Activity B
public class AddNewAddress extends AppCompatActivity {
private EditText customer_name, address_one, address_two;
private TextView cancel;
private Button add_address;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_new_address);
customer_name = findViewById(R.id.customerName);
address_one = findViewById(R.id.addressOne);
address_two = findViewById(R.id.addressTwo);
add_address = findViewById(R.id.addAddress);
cancel = findViewById(R.id.completeCancel);
String cancel_text = "Cancel";
SpannableString spanableObject = new SpannableString(cancel_text);
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View widget) {
Toast.makeText(AddNewAddress.this, "Clicked", Toast.LENGTH_SHORT).show();
}
#Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setColor(Color.BLUE);
}
};
spanableObject.setSpan(clickableSpan, 0, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
cancel.setText(spanableObject);
cancel.setMovementMethod(LinkMovementMethod.getInstance());
final ProfileManageAdressFragment profileManageAdressFragment = new ProfileManageAdressFragment();
add_address.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddNewAddress.this, ProfileManageAdressFragment.class);
startActivity(intent);
}
});
}
private void setFragment(android.support.v4.app.Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame, fragment).commit();
}
}
Update 1:
Kindly check my updated Recycler adapter. When I run this 0 is displayed in the text area as shown in the attached image. I'm new to android. Kindly help with example.
I finally achieved my goal with the use of ActivityResult. Now I'm able to pass data from Activity to Cardview.
Solution: When button is clicked in Activity A, I start the activity with startResultActivity(). Later, when the Activity B i triggered. The end-user inputs the data and that data is passed with the use of putExtra() and once the save button is clicked in Activity B next setResult() in Activity B and finish().
Finally i define onActivityResult() in Activity A to get the result. Works well!!
I would create a global variable and then store all the data in that variable and simply just call that variable in adapter.
declare a global variable and assign null value to it:
public static String checking = null;
a then store data in when you need it:
checking = check.getText().toString();
then call it in your adapter class.
first make interface listener inside listener make function with parameter like this
interface YourRecycleViewClickListener {
fun onItemClickListener(param1:View, param2: String)
}
now extend your activity
class YourActivity:YourRecycleViewClickListener{
override fun onItemClickListener(param1:View, param2: String) {
//do any thing
}
}
third step make interface constract in your recycle adapter
class YourAdapter(
private val listener: YourRecycleViewClickListener){
holder.constraintLayout.setOnClickListener{
listener.onItemClickListener(param1,param2)
}
}
this is by kotlin lang
and by java is same but change syntax
that all to do

RecyclerView - Get the selected position and pass the position to another activity where the same list will appear with that specific item selected

I have declared a ViewModel.class for the RecyclerView an Adapter and I have parsed to the MainActivity and to another Activity so I have the same adapter for both activities.
I can show the parsed data in both activities but the problem it is I cannot take the data of the selected item to MainActivity and then to set to that btnSearch for a click so then I can share between activities the data from the selected item.
Every time when the app is open the first item is selected. What I am trying to achieve is.
Get the item position to the MainActivity so when I click for a button search the data of the selectedItem will going to intent.putExtra and then get the data at another Activity.
If I click the second item and go to another Activity the same item will be selected.
Here is what I have tried so far.
The SearchEngineAdapter.class
public class SearchEngineAdapter extends RecyclerView.Adapter<SearchEngineAdapter.ViewHolder> {
private int selectedItem = 0;
private static RecyclerViewClickListener itemListener;
private Context context;
ArrayList<SearchEngine> arrayList = new ArrayList<>();
public SearchEngineAdapter(Context context, ArrayList<SearchEngine> arrayList, int selectedItem) {
this.context = context;
this.arrayList = arrayList;
this.selectedItem = selectedItem;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int i) {
holder.tvIcon.setImageResource(arrayList.get(i).getIcon());
holder.tvId.setText(arrayList.get(i).getId());
holder.tvSearchUrl.setText(arrayList.get(i).getUrl());
final String url = holder.tvSearchUrl.getText().toString();
SharedPreferences sp = context.getSharedPreferences("SavedSelected", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("selected", selectedItem);
editor.apply();
sp = context.getSharedPreferences("SavedSelected", Context.MODE_PRIVATE);
int myIntValue = sp.getInt("selected", -1);
Log.d("Selected", "SharedPreferences" + myIntValue);
if (selectedItem == i) {
holder.tvIcon.setBackgroundColor(Color.parseColor("#30000000"));
Intent intent = new Intent("search_engines");
intent.putExtra("url", url);
intent.putExtra("selected", selectedItem);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
} else {
holder.tvIcon.setBackgroundColor(Color.parseColor("#00000000"));
}
holder.tvIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("search_engines");
intent.putExtra("url", url);
int PreviousSelectedItem = selectedItem;
selectedItem = i;
intent.putExtra("selected", selectedItem);
holder.tvIcon.setBackgroundColor(Color.parseColor("#30000000"));
notifyItemChanged(PreviousSelectedItem);
notifyDataSetChanged();
}
});
}
// ... Other necessary functions.
}
Now the MainActivity.class
RecyclerView paramRecyclerView;
SearchEngineAdapter sEngineAdapter;
paramRecyclerView = findViewById(R.id.lvEngines);
paramRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
paramRecyclerView.setHasFixedSize(true);
Intent intent = getIntent();
int intValue = intent.getIntExtra("selected", 0);
sEngineAdapter = new SearchEngineAdapter(context, arrayList, intValue);
paramRecyclerView.setAdapter(sEngineAdapter);
// Calling network APIs to populate the arrayList.
The onResume function of the MainActivity looks like the following.
protected void onResume() {
super.onResume();
searchPlugin.setText("");
getChangeColor();
}
This is the click handler defined in MainActivity which send me to another Activity.
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = searchPlugin.getText().toString();
AddHistory(newEntry);
getFragmentRefreshListener().onRefresh();
Intent intent = new Intent(MainActivity.this, ActivitySearchEngine.class);
intent.putExtra("url", url );
intent.putExtra("name", newEntry);
intent.putExtra("selected", selectedItem2);
startActivity(intent);
}
});
And the other activity which is ActivitySearchEngine.class
public class ActivitySearchEngine extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
public String selectedName;
public int selectedID;
public String selectedSearchUrl;
RecyclerView mListView;
RecyclerView paramRecyclerView;
SearchEngineAdapter sEngineAdapter;
ArrayList<SearchEngine> arrayList = new ArrayList<>();
final Context context = this;
int selectedItem;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result);
// Variables initialization
// Setting up adapter
paramRecyclerView.setAdapter(sEngineAdapter);
sEngineAdapter.notifyDataSetChanged();
// Calling network APIs to populate the arrayList here
Intent receivedIntent = getIntent();
selectedName = receivedIntent.getStringExtra("name");
selectedID = receivedIntent.getIntExtra("id", 1); //NOTE: -1 is just the default value
selectedSearchUrl = receivedIntent.getStringExtra("url");
// Loading the url in a WebView for searching
}
}
I could share the selected item position between these two activities. However, I am not sure how to achieve the behavior of the item is being selected in the RecyclerView of the second activity as well. If I select another item in the RecyclerView of the second activity, the change should be reflected in the first (i.e. MainActivity) as well when I get back to it.
Any help would be appreciated.
There was a lot of changes in the question and hence the last update of this answer below is the final version.
As far as I could understand about the problem, I can see you are very close to the solution if I had understood correctly. The SearchEngineAdapter already has a selectedItem variable in it which can be used for highlighting the item selected in ActivitySearchEngine as well. You just have to modify the adapter a little bit like the following. I am rewriting the adapter here.
public class SearchEngineAdapter extends RecyclerView.Adapter<SearchEngineAdapter.ViewHolder> {
private int selectedItem = 0;
private static RecyclerViewClickListener itemListener;
private Context context;
ArrayList<SearchEngine> arrayList = new ArrayList<>();
// Added another argument to be passed in the constructor
public SearchEngineAdapter(Context context, ArrayList<SearchEngine> arrayList, int selectedItem) {
this.context = context;
this.arrayList = arrayList;
this.selectedItem = selectedItem;
}
#NonNull
#Override
public SearchEngineAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.s_engine_item, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int i) {
if (selectedItem == i) {
holder.tvIcon.setBackgroundColor(Color.parseColor("#30000000"));
} else {
holder.tvIcon.setBackgroundColor(Color.parseColor("#00000000"));
}
holder.tvIcon.setImageResource(arrayList.get(i).getIcon());
holder.tvId.setText(arrayList.get(i).getId());
holder.tvSearchUrl.setText(arrayList.get(i).getUrl());
holder.tvIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int PreviousSelectedItem = selectedItem;
selectedItem = i;
holder.tvIcon.setBackgroundColor(Color.parseColor("#30000000"));
notifyItemChanged(PreviousSelectedItem);
notifyDataSetChanged();
}
});
}
#Override
public int getItemCount() {
return arrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView tvId, tvSearchUrl;
ImageView tvIcon;
public ViewHolder(#NonNull View itemView) {
super(itemView);
tvId = itemView.findViewById(R.id.ivEngineText);
tvIcon = itemView.findViewById(R.id.ivEngine);
tvSearchUrl = itemView.findViewById(R.id.ivSearchUrl);
}
}
}
Check that, I just have modified the constructor of your adapter, taking another extra variable which is selectedItem. Just pass the selected item position when you are initializing the adapter in both activities. In the default case, you can pass -1, I think you get the idea.
You have passed the selected item position to the ActivitySearchEngine as well. Which can be used for initializing for the desired behavior. Hope that helps!
Update 1:
I would like to suggest you put the following code to your onResume function in the ActivitySearchEngine class. You might consider removing the lines from the onCreate function of your code as well.
#Override
public void onResume() {
super.onResume();
Intent receivedIntent = getIntent();
selectedName = receivedIntent.getStringExtra("name");
selectedID = receivedIntent.getIntExtra("id", 1); // NOTE: -1 is just the default value
selectedSearchUrl = receivedIntent.getStringExtra("url");
sEngineAdapter = new SearchEngineAdapter(context, arrayList, selectedID);
paramRecyclerView.setAdapter(sEngineAdapter);
}
Update 2:
The RecyclerView in your MainActivity is getting reloaded as you are setting the adapter again to the RecyclerView in the onResume function. Moreover, you are trying to get data from intent which is not available here I think because you have not set any data to be sent to the MainActivity when you return back from the ActivitySearchEngine. Hence, the RecyclerView is reloading again with a fresh set of data.
You might remove the code associated with your RecyclerView from the onResume function of the MainActivity to remove this complication as I think this is not necessary. So the updated onResume function will look like the following.
protected void onResume() {
super.onResume();
searchPlugin.setText("");
getChangeColor();
}
Update 3:
Take a public static variable in your MainAcitivity and declare it as a global variable like the following.
// Setting 0 as you wanted to put the first item at the first time
// If you do not want that, then initialize with -1
public static int selectedItem = 0;
Now inside your onCreate function, remove the lines for getting the intent.
paramRecyclerView = findViewById(R.id.lvEngines);
paramRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
paramRecyclerView.setHasFixedSize(true);
// Remove the following
// Intent intent = getIntent();
// int intValue = intent.getIntExtra("selected", 0);
// Move the adapter setup to the onResume
// sEngineAdapter = new SearchEngineAdapter(context, arrayList, selectedItem);
// paramRecyclerView.setAdapter(sEngineAdapter);
// Calling network APIs to populate the arrayList.
Modify the onResume function in the MainActivity to set up the adapter there.
protected void onResume() {
super.onResume();
searchPlugin.setText("");
getChangeColor();
// Set the adapter here
sEngineAdapter = new SearchEngineAdapter(context, arrayList, selectedItem);
paramRecyclerView.setAdapter(sEngineAdapter);
}
Modify the onClickListener in your adapter like the following. Just add a new line there.
holder.tvIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("search_engines");
intent.putExtra("url", url);
int PreviousSelectedItem = selectedItem;
selectedItem = i;
// Set the static value in the MainActivity
// This can be accessed from all other classes
MainActivity.selectedItem = i;
intent.putExtra("selected", selectedItem);
holder.tvIcon.setBackgroundColor(Color.parseColor("#30000000"));
notifyItemChanged(PreviousSelectedItem);
notifyDataSetChanged();
}
});
Hope that helps!

How to pass the previous data using spinner and image?

I have problem with my android coding. I want to make an update process. But first of all, I'm trying to collect all the data from edit text, spinner and image. But I have problem with spinner and image, could not get the previous data. How to get the previous data using spinner and image? Ex.. Image1
shows the complete retrieve process when user click on Submit Button, then it will go to this View Activity interface. While in Image2
shows the Edit Activity interface where the user can update all the data from there when the user click on Edit Button. The issue now is, I can not collect the previous data using spinner and image for editing/updating purposes as shown in the Image 2. Really hope someone can help me.. Thanks in advance...
Coding as follows:
1) Coding from View Activity:-
EditAdsButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent editAds = new Intent(ViewAdsActivity.this, EditAdsActivity.class);
startActivity(editAds);
String tn = ViewTuitionName.getText().toString();
String pn = ViewProviderName.getText().toString();
String pg = getIntent().getStringExtra("PG");
Intent i = new Intent(ViewAdsActivity.this, EditAdsActivity.class);
i.putExtra("TN", "" +tn); // Collected from EditText or any other source
i.putExtra("PN", "" +pn);
i.putExtra("PG", "" +pg);
startActivity(i);
}
});
2) Coding from Edit Activity (onCreate method):-
Intent i = getIntent();
String tn = i.getStringExtra("TN");
String pn = i.getStringExtra("PN");
String pg = getIntent().getStringExtra("PG");
EditTuitionName.setText(tn);
EditProviderName.setText(pn);
EditProviderGender.setSelection(pg);
Here is a solution:
Constant.java
public class Constant {
public static final String[] GENDER = {"Male", "Female", "Other"};
}
ViewAdsActivity.java
public class ViewAdsActivity extends AppCompatActivity {
private CircleImageView avatar;
private EditText name;
private Spinner gender;
private Button next;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_ads);
avatar = findViewById(R.id.avatar);
name = findViewById(R.id.edit_text_name);
gender = findViewById(R.id.spinner_gender);
next = findViewById(R.id.button_next);
// Render avatar
String imageUrl = "https://vignette.wikia.nocookie.net/spiritedaway/images/6/69/Chihiro.jpg/revision/latest?cb=20170308090934";
avatar.setTag(imageUrl);
Picasso.get()
.load(imageUrl)
.into(avatar);
// Render spinner
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, Constant.GENDER);
gender.setAdapter(adapter);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ViewAdsActivity.this, EditAdsActivity.class);
intent.putExtra("imageUrl", (String) avatar.getTag());
intent.putExtra("genderPosition", gender.getSelectedItemPosition());
intent.putExtra("name", name.getText().toString());
startActivity(intent);
}
});
}
}
EditAdsActivity.java
public class EditAdsActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_ads);
CircleImageView avatar = findViewById(R.id.avatar);
EditText nameEditText = findViewById(R.id.edit_text_name);
Spinner gender = findViewById(R.id.spinner_gender);
String imageUrl = getIntent().getStringExtra("imageUrl");
int genderPosition = getIntent().getIntExtra("genderPosition", 0);
String name = getIntent().getStringExtra("name");
// Render image view
Picasso.get()
.load(imageUrl)
.into(avatar);
// Render spinner
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, Constant.GENDER);
gender.setAdapter(adapter);
gender.setSelection(genderPosition);
// Render edit text
nameEditText.setText(name);
}
}
For the spinner you can use
Spinner mySpinner = (Spinner) findViewById(R.id.your_spinner);
String text = mySpinner.getSelectedItem().toString();
And then place the text in the intent like the other objects.
An image is trickier because you don't want to serialize the bitmap for the intent since serialization is on the main thread and the app would probably stutter or hang a bit. Instead you could store the bitmap in a class that is accessible from both activities, or if the image is already stored on the device you can pass the URI and just reopen it in the next activity.

Trying to get string variables from a seperate class causing app to crash

I have simple page to start up the app that has a spinner,editText, and a button. When the user clicks the button I want the app take the selection of the spinner and text and set them to text views in the new class. I tried using getters but when I try this the app crashes.
First Class:
public class MainActivity extends AppCompatActivity {
String pullerName;
String storeName;
Spinner spinner;
EditText etPuller;
public String getStoreName(){
return storeName;
}
public String getPullerName(){
return pullerName;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.store_list, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Button create = (Button) findViewById(R.id.btnCreate);
etPuller = (EditText) findViewById(R.id.editText);
create.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pullerName = etPuller.getText().toString();
storeName = spinner.getSelectedItem().toString();
Intent i = new Intent(MainActivity.this,MainActivity2.class);
startActivity(i);
}
});
}
}
Second Class:
public class MainActivity2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_main);
MainActivity main = new MainActivity();
TextView user = (TextView) findViewById(R.id.tvUser);
TextView store = (TextView) findViewById(R.id.tvStore);
user.setText(main.getPullerName());
store.setText(main.getStoreName());
When this code runs it crashes as soon as i click the button to move to the next activity.
To pass data to a new Activity you need to use Intent.
This is what you need to do:
MainActivity.class:
create.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pullerName = etPuller.getText().toString();
storeName = spinner.getSelectedItem().toString();
Intent i = new Intent(MainActivity.this,MainActivity2.class);
i.putExtra("puller-name", pullerName);
i.putExtra("store-name", storeName);
startActivity(i);
}
});
In the MainActivity2.class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_main);
TextView user = (TextView) findViewById(R.id.tvUser);
TextView store = (TextView) findViewById(R.id.tvStore);
Intent intent = getIntent();
if(intent != null){ //I always check this to avoid Exceptions
String pullerName = intent.getStringExtra("puller-name");
String storeName = intent.getStringExtra("store-name");
if(pullerName != null) user.setText(pullerName);
if(storeName != null) store.setText(storeName);
}
}
You was creating a new instance of MainActivity in MainActivity2. So, when you called the getters of this mainActivity will return null, because these values were never setters. If you want to use your method, you need to pass the same instance of the activity to MainActivity2, but this is not recommended. The official method to pass data to another activity is via intent. To learn more about Intent learn the official Android documentation: https://developer.android.com/training/basics/firstapp/starting-activity.html
You have used wrong way to get values from MainActivity to MainActivity2. Simply you can pass values using the technique below.
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
intent.putExtra("pullerName", pullerName);
To use this value pullerName in MainActivity2 class, just use the technique below.
String value = getIntent().getExtras().getString("pullerName");`

Beginner Android: ListView to affect the next class

I am a beginner programmer so please bear with me. I am trying to create an app where the item in the list view affects what will be displayed in the next activity. So far, I have the list activity:
public class Primary extends ListActivity{
private static final String[] items = {"Item1", "Item2", "Item3", "item4", "Item5"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items));
TextView heading =(TextView)findViewById(R.id.listViewHeading);
heading.setText("Primary");
}
public void onListItemClick(ListView parent, View v, int position, long id){
}
and for the second activity, I have this:
public class ImageActivity extends Activity{
TextView heading;
ImageView image;
TextView text;
public static final String[] headings={"heading 1", "heading 2", "heading 3", "heading 4", "heading 5",};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_activity);
heading = (TextView)findViewById(R.id.adHeading);
image = (ImageView)findViewById(R.id.adImage);
text =(TextView)findViewById(R.id.adText);
addInfo();
}
private void addInfo() {
heading.setText(headings[x]);
image.setImageResource(images[x]);
text.setText(text[x]);
}
How can i make it so that the heading, image, and text change based on what item in the list view was selected?
In the listview Activity.
Intent i = new Intent(this, ImageActivity.class);
i.putExtra("data", data);
startActivity(i);
The next Acitivty onCreate() method.
final String data = getIntent().getStringExtra("data");
I think u want to set the heading, image and text in second activity, related to first activity's selected index in list.
just do 1 thing, put following code in 1st activity
public void onListItemClick(ListView parent, View v, int position, long id)
{
Intent intent = new Intent(this.getApplicationContext(), ImageActivity.class);
intent.putExtra("pos", position);
startActivity(intent);
}
so, now u r passing the position of item selected in list.
now, put following code in next activity
private void addInfo()
{
Bundle ext = getIntent().getExtras();
if(ext != null)
{
int pos= ext.getInteger("pos");
// ext.getInt("pos");
heading.setText(headings[pos]);
// hey, frend, you don't have any array for selecting image-name and text
// image.setImageResource(images[x]);
// text.setText(text[x]);
}
}
Use the "extras" feature that are part of an Intent.
When you call start ImageActivity from Primary, you can use a 'extras' to pass information between the two.
See this link for details.
I'll give you a basic example here. When the list item is clicked, put the data that you want ImageActivity to have into the intent using "putExtra".
Intent intent = new Intent(getBaseContext(), ImageActivity.class);
String data = "somedata";
intent.putExtra("DATA", data);
startActivity(intent)
Then, in ImageActivity onCreate, retrieve the data like this:
Bundle extras = getIntent().getExtras();
if(extras !=null) {
String data= extras.getString("DATA"); // matches the tag used in putExtra
}
Once you have retrieved the data, set the necessary views.
use below code
public void onListItemClick(ListView parent, View v, int position, long id)
{
Intent intent = new Intent(Primary.this, ImageActivity.class);
intent.putExtra("selected value", item[position]);
startActivity(intent);
}
in ImageActivity class:in oncreate (or you can put item variable as global)
String item = getIntent().getStringExtra("Selected value");

Categories