I have a fragment in which I am trying to call a new activity on a button click.
btnLoadLimit.setOnClickListener(v -> {
Intent intent = new Intent(getActivity(), DataActivity.class);
startActivity(intent);
});
Data Activity
public class DataActivity extends AppCompatActivity {
Context mContext;
#BindView(R.id.smart_msn_spinner)
Spinner msnSpinner;
ArrayList<String> msnArrayList = new ArrayList<>(Arrays.asList("Select MSN","002998002010" )); //"002999002020"
ArrayAdapter<String> msnAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
msnAdapter = new ArrayAdapter<>(mContext, android.R.layout.simple_spinner_dropdown_item, msnArrayList);
msnSpinner.setAdapter(msnAdapter);
msnSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedMeterNo = msnArrayList.get(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
When I click on btnLoadLimit button my app is closing with the following error
Unable to start activity ComponentInfo{com.thumbsol.accuratemobileassetsmanagament/com.thumbsol.accuratemobileassetsmanagament.fragment.DataActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
at com.thumbsol.accuratemobileassetsmanagament.fragment.DataActivity.onCreate(DataActivity.java:122)
The line 122 is msnAdapter = new ArrayAdapter<>(mContext, android.R.layout.simple_spinner_dropdown_item, msnArrayList);
The same method I have applied in my fragment and it's working but in my new activity it's not.
Note: The activity is displaying if none of the methods are invoked.
Looks like you don't initialize your mContext. meaning you're passing null to your ArrayAdapter().
You shouldn't be storing your context anyway, since your context is your activity..
You can just use this:
msnAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, msnArrayList);
Related
The app does not work when you click the button. It "crashes" straight. Here is the code and the error:
FeedFragment, the code:
public class FeedFragment extends Fragment {
private RecyclerView rv;
private PostAdapter postAdapter;
private List<PostBean> postBeans;
private Button button_public_to_feed;`
public FeedFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_feed, container, false);
button_public_to_feed = (Button) view.findViewById(R.id.button_public_to_feed);
button_public_to_feed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity(), PublicFeedActivity.class);
startActivity(i);
}
});
the err:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.hits/com.example.hits.Canvas.Activity.PublicFeedActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984)
Already tried:
Intent i = new Intent(getActivity(), PublicFeedActivity.class);
Already tried:
Intent i = new Intent(getContext(), PublicFeedActivity.class);
Already tried:
Intent i = new Intent(v.getContext(), PublicFeedActivity.class);
Already tried:
Intent i = new Intent(new FeedFragment().getActivity, PublicFeedActivity.class);
everyone returned the same error to me
A help please !!!!
A friend of mine helped me, I found the error. The error caused was in the activity, the problem was that I had put a method that closes the activity in onCreate
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
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!
I'm trying to add a spinner to my android app but gives me this error(Compilation failed; see the compiler error output for details.) and this part (MainActivity.this,) has a red line under it when the cursor is under it says 'com.example.myapplication.MainActivity' is not an enclosing class. I'm doing this from another activity not from the main activity. No changes in the MainActivity.
AddEmployee class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_employee);
Spinner myspinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter myAdapter = ArrayAdapter.createFromResource(MainActivity.this, R.array.types, android.R.layout.simple_list_item_1);
myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
myspinner.setAdapter(myAdapter);
}
try with like this
List<String > strings = new ArrayList<>();
ArrayAdapter<String> adapter = new ArrayAdapter<>(activity,android.R.layout.simple_list_item_1,strings);
spinner.setAdapter(adapter);
You need a valid context, so you should use your current activity
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_employee);
Spinner myspinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter myAdapter = ArrayAdapter.createFromResource(SecondActivity.this, R.array.types, android.R.layout.simple_list_item_1);
myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
myspinner.setAdapter(myAdapter);
}
}
or you can use this or getApplicationContext() instead of MainAcitvity.this
but I prefer to use this
createFromResource's first parameter is context. You can get context in two way:
Application Context: getApplicationContext()
Activity's Context: ActivityName.this
Application context is general context of project, you can get it from all activity.
Activity contexs are specific to the activity. So you can access it from only it's own activity. You tried to access an activity context from another activity so it gave this error. You can try getApplicationContext() or AddEmployee.this
Here is a working example :
public class Main extends AppCompatActivity implements AdapterView.OnItemSelectedListener
{
String[] item_list= {"Select your option", "item1", "item2", "item3", "item4"};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_employee);
Spinner spin = (Spinner) findViewById(R.id.spinner);
spin.setOnItemSelectedListener(this);
ArrayAdapter aa = new ArrayAdapter(this, android.R.layout.simple_spinner_item, item_list);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
I have an Activity A with a fragment frag2. Inside the fragment I have a RecyclerView and Adapter to show a list of custom class objects. Adding objects to the adapter is handled programmatically. I have a button inside TwoFragment that opens a FragmentDialog. I'd like to add an object to my Adapter by confirming this dialog, but it seems that the adapter is null when called from the FragmentDialog.
The same adapter is not null, and works if I call it from the fragment OnClick.
Moreover the adapter is null only after screen rotation, it works fine before rotating.
To communicate between the two Fragments I implement a communicator class in activity A.
Activity A
public void respond(String type) {
frag2.addSupport(type);
}
frag2
public RecyclerView rv;
public ArrayList<support> supports;
public myAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supports = new ArrayList<>();
adapter = new myAdapter(supports);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layout = inflater.inflate( R.layout.fragment_two, container, false);
layout.setId(R.id.frag2);
if (savedInstanceState!=null)
{
supports = savedInstanceState.getParcelableArrayList("supports");
}
rv = (RecyclerView) layout.findViewById(R.id.rv);
adapter = new myAdapter(supports);
rv.setAdapter(myAdapter);
rv.setLayoutManager(new LinearLayoutManager(getActivity()));
rv.setItemAnimator(new DefaultItemAnimator());
#Override
public void onClick(View v) {
int id = v.getId();
switch (id){
case R.id.button1:
addSupport(type); // THIS WORKS ALWAYS, even after screen rotate
break;
case R.id.button2:
showDialog();
break;
}
}
public void showDialog(){
FragmentManager manager = getFragmentManager();
myDialog dialog = new myDialog();
dialog.show(manager, "dialog");
}
public void addSupport(String type){
adapter.addItem(new support(type)); // this line gives null pointer on adapter, but only if called after screen rotate and only if called from the dialog
}
dialog
communicator comm;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog, null);
comm = (myCommunicator) getActivity();
create = (Button) view.findViewById(R.id.button_ok);
create.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.button_ok)
{
// some controls to set type
comm.respond(type)
dismiss();
}
else {
dismiss();
}
myAdapter
public class myAdapter extends RecyclerView.Adapter<myAdapter.VH> {
private LayoutInflater inflater;
private ArrayList<support> data = new ArrayList<>();
// settings for viewholder
public myAdapter (ArrayList<support> data)
{
this.data=data;
}
public void addItem(support dataObj) {
data.add(dataObj);
notifyItemInserted(data.size());
}
}
logcat
FATAL EXCEPTION: main
java.lang.NullPointerException: Attempt to invoke virtual method 'myAdapter.addItem(myObject)' on a null object reference
I hope there are no mistakes, I shortened the code for better understanding. Keep in mind that everything works if I never rotate the screen.
I'm a beginner with android and I'm stuck with this for several days now. Please, help.
To understand the problem, it's as you say:
.. everything works if I never rotate the screen
So firstly to understand what happens on rotation, this is a quote from the Android Developer website:
Caution: Your activity will be destroyed and recreated each time the user rotates the screen. When the screen changes orientation, the system destroys and recreates the foreground activity because the screen configuration has changed and your activity might need to load alternative resources (such as the layout).
Ok, now to understand the error:
FATAL EXCEPTION: main
java.lang.NullPointerException: Attempt to invoke virtual method 'myAdapter.addItem(myObject)' on a null object reference
Essentially, in your dialog class, you have created a strong dependency by declaring :
comm = (myCommunicator) getActivity();
because comm references objects which would have been destroyed on rotation, hence the NullPointerException.
To further understand runtime changes, such as orientation changes, I'd recommend going through Handling Runtime Changes.
Update
Thank you for your answer, what would you recommend instead of comm = (myCommunicator) getActivity(); ?
The solution comes in 3 parts:
Make sure the onCreate of Activity A has the following:
#Override
public void onCreate(Bundle savedInstanceState) {
......
// find the retained fragment on activity restarts
FragmentManager fm = getFragmentManager();
frag2 = (Frag2) fm.findFragmentByTag(“frag2”);
// create frag2 only for the first time
if (frag2 == null) {
// add the fragment
frag2 = new Frag2();
fm.beginTransaction().add(frag2 , “frag2”).commit();
}
......
}
Add setRetainInstance(true) to the onCreate of frag2.
Remove the implicit referencing i.e. comm = (myCommunicator) getActivity();, and implement something more loosely coupled for dialog.
dialog
public interface Communicator {
void respond(String type);
}
Communicator comm;
....
public void addCommunicator(Communicator communicator) {
comm = communicator;
}
public void removeCommunicator() {
comm = null;
}
#Override
public void onClick(View v) {
if((v.getId()==R.id.button_ok) && (comm!=null))
{
// some controls to set type
comm.respond(type);
}
// Regardless of what button is pressed, the dialog will dismiss
dismiss();
}
This allows you do the following in frag2 (or any other class for that matter):
frag2
<pre><code>
public class Frag2 extends Fragment implements dialog.Communicator {
........
public void showDialog() {
FragmentManager manager = getFragmentManager();
myDialog dialog = new myDialog();
dialog.addCommunicator(this);
dialog.show(manager, "dialog");
}
#Override
public void respond(String type){
adapter.addItem(new support(type));
}
}