Android app close with null exception [duplicate] - android

This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
I have a very simple android app being built. I have 2 buttons and 1 textview. I build them graphically in fragment_main.xml. Below is my full codes.
public class MainActivity extends ActionBarActivity {
TextView tvOut;
Button btnOk;
Button btnCancel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
View.OnClickListener oclBtnOk = new View.OnClickListener() {
public void onClick(View v) {
// change text of the TextView (tvOut)
tvOut.setText("Button OK clicked");
}
};
btnOk.setOnClickListener(oclBtnOk);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
If I comment this part of the codes it works well.
View.OnClickListener oclBtnOk = new View.OnClickListener() {
public void onClick(View v) {
// change text of the TextView (tvOut)
tvOut.setText("Button OK clicked");
}
};
btnOk.setOnClickListener(oclBtnOk);
Even though I use setContentView(R.layout.main_activity); all my button and text view appears and quite puzzle why even with main_activity my buttons and text view appears well.

You never assign values to your views. Use findViewById to get references to the views with the id's you gave them in your XML layout.
setContentView(R.layout.fragment_main);
// get the views
btnOk = (BUtton) findViewById(R.id.your_button_id);
tvOut = (TextView) findViewById(R.id.another_id);
btnOk.setOnClickListener(...);

Related

Clicking layout opens new fragment with same images

I am developing an app in which first screen contains 4 different layouts with different images as background. What i want to do is if I click on one layout new fragment opens up with that background image on the top. Can i use same fragment to display different images and textviews ? if yes how ?
[not able to upload image due to less points ]
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
// Click methods goes here
public void clickAboutUs(View v)
{
/*Intent aboutUs = new Intent(MainActivity.this, FragmentAboutUs.class);
startActivity(aboutUs);*/
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragmentAboutUs = new FragmentAboutUs();
fragmentTransaction.add(R.id.container,fragmentAboutUs);
fragmentTransaction.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
FragmentAboutUs.java
public class FragmentAboutUs extends Fragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.about_us, container,false);
return view;
}
}
on clicking an layout i want fresh fragment screen with same image as background image of that particular background image which is stored in my drawables folder.
[1]: http://i.stack.imgur.com/PKX4L.png
Yes you can use same fragment for displaying different images and texts. You can add image resource id or path and the texts you want to display in arguments. Just initialise your fragment from main activity as below;
MyFragment myFragment = new myFragment();
Bundle bundle = new Bundle();
bundle.putInt("image",<image resourse id>);
bundle.putString("text1",<your string1>);
bundle.putString("text2",<your string2>);
myFragment.putArgs(bundle);
And inside your my fragment in ONcreate or ONcreateView get the data as below
Bundle bundle = getArguments();
imageId=bundle.getInt("image");
text1=bundle.getString("text1");
text2=bundle.getString("text2");
Hope this helps. Any doubt let me know.

How to make visible a layout programatically in fragment which is called in parent activity

I have a layout defined in fragment.xml which is called in activity....
and I want to make it visible when a button in parent activity action bar is pressed which is in onOptionsItemSelected() .when i do this it make a error of null object reference....
fragment.xml
<RelativeLayout
android:visibility="invisible"
android:id="#+id/relative_layout_current_job"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/text_view_current_job"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/text_current_job"
android:layout_centerHorizontal="true" />
</RelativeLayout>
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_passenger_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.passenger_main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_job_confirm) {
Button b = (Button) findViewById(R.id.action_job_confirm);
RelativeLayout layoutCurrentJob = (RelativeLayout) findViewById(R.id.relative_layout_current_job);
TextView status = (TextView) findViewById(R.id.text_view_current_job_status_in_history);
if((b.getText().toString()) == "job confirm") {
status.setVisibility(View.INVISIBLE);
b.setText("Job Started");
layoutCurrentJob.setVisibility(View.VISIBLE);
} else {
status.setVisibility(View.VISIBLE);
b.setText("jon confirm");
layoutCurrentJob.setVisibility(View.INVISIBLE);
}
}
return super.onOptionsItemSelected(item);
}
mainmenu.xml
<item
android:id="#+id/action_job_confirm"
android:title="job confirm"
app:showAsAction="never"/>
Screenshot
On your code, Intializing
RelativeLayout layoutCurrentJob=(RelativeLayout) findViewById(R.id.relative_layout_current_job);
is wrong. Because the RelativeLayout you want to hide/show is part of your Fragment .you cannot initialized RelativeLayout by this.
It should be like as shown in below on your Fragment's onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View root = inflater.inflate(R.layout.fragment, container, false);
RelativeLayout layoutCurrentJob=(RelativeLayout) findViewById(R.id.relative_layout_current_job);
}`
You can access widgets of your Fragment by below method
RelativeLayout layoutCurrentJob = (RelativeLayout )fragmentobj.getView().findViewById(R.id.img_one));
layoutCurrentJob.setVisibility(View.VISIBLE);
Do it for your fragment like this:
public class testFragment extends Fragment implements Handler.Callback{
public final Handler handler = new Handler(testFragment.this);
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View root = inflater.inflate(R.layout.fragment, container, false);
}
#Override
public boolean handleMessage(Message msg) {
// TODO Auto-generated method stub
if (msg.what == 1) {
//do your job here
}
return false;
}
}
Call it from your activity like this:
testFragment frag = (testFragment) getFragmentManager()
.findFragmentByTag("Fragment_1");
Message ms = Message.obtain(frag.handler,1);
frag.handler.sendMessage(ms);

How to move to a new fragment after clicking a button in a list item

How can I ensure that a button inside a list item is clickable, because I am trying to make the button clickable so that it can transition to a different fragment?
Like the listview and the list items inside it are part of a fragment and I want to ensure that clicking a specific button inside a list item will transition to the new fragment.
MainActivity Code:
It contains tabs(not all of which are implemented yet, but thats not an issue right now)
public class MainActivity extends FragmentActivity implements HomeFragment.OnFragmentInteractionListener {
private FragmentTabHost mTabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set up the tabs which hold different fragments, it will currently crash because of the null
mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
mTabHost.setup(this,getSupportFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("home").setIndicator("Home"), HomeFragment.class , null);
// mTabHost.addTab(mTabHost.newTabSpec("search").setIndicator("Search"),null/*fragment here*/,null);
// mTabHost.addTab(mTabHost.newTabSpec("post").setIndicator("Post"),null/*fragment here*/,null);
// mTabHost.addTab(mTabHost.newTabSpec("books").setIndicator("Books"),null/*fragment here*/,null);
// mTabHost.addTab(mTabHost.newTabSpec("me").setIndicator("Me"),null/*fragment here*/,null);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//For home fragment...parameter might change
#Override
public void onFragmentInteraction(String id) {
Button viewPostings = (Button) findViewById(R.id.view_postings);
viewPostings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PostDetailFragment fragment = PostDetailFragment.newInstance();
getSupportFragmentManager().beginTransaction().replace(R.id.realtabcontent, fragment).addToBackStack(null).commit();
}
});
}
}
Im trying to launch the new activity from the implementation of onFragmentInteractionListener. The app loads the list view and its contents, but the individual buttons in it aren't clickable.
First off you need to add this line to make the items in the custom list item clickable:
android:descendantFocusability="blocksDescendants"
Add this property to the enclosing layout.
Secondly, you need to set the onClickListener in the getView method of the custom adapter that you have made for your custom ListView. For example, that would be something like this:
ImageButton deleteBtn = (ImageButton) view.findViewById(R.id.delete_btn);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// code here
}
});
Use some sort of ListAdapter such as an ArrayAdapter to populate your ListView. That way, you can use the adapter to handle the button clicks.
In your list fragment, use the onItemClick:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onFragmentInteraction(foodList.get(position));
}
}
Then in your parent activity, you will have something like this.
#Override
public void onFragmentInteraction(Food food) {
//going from ListFragment to DetailFragment
//call detail fragment here
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment fragment = DetailFragment.newInstance(food);
ft.replace(R.id.container, fragment);
ft.addToBackStack( "tag" );
ft.commit();
}

android fragment onorientationchange issue

I created a simple project that Button in Activity click to Show Toast from Fragment.Works fine when just click Button, but after orientation changed and clicking Button occurs error.
public class MainActivity extends Activity {
PlaceholderFragment pf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pf = new PlaceholderFragment();
Button b = (Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
pf.showToast();
}
});
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, pf)
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Log.i("TAG", "onCreateView");
return rootView;
}
public void showToast(){
Toast.makeText(getActivity(), "Show Toast from PlaceholderFragment", Toast.LENGTH_SHORT).show();
}
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
Log.i("TAG", "onAttach");
}
#Override
public void onDetach() {
// TODO Auto-generated method stub
super.onDetach();
Log.i("TAG", "onDetach");
}
}
}
I found out Fragment was calling onAttach and onDetach after orientating. How can i fix this problem?
When the device Orientation changes, the activity in which the fragment sits is by default destroyed and created again. You can avoid these changes by adjusting the android:configChanges in the manifest file. This code should work:
android:configChanges="keyboardHidden|orientation"

New Activity created every time Button is pressed

I am making an app that will has three activities. The user can navigate to a new activity pressing buttons (home, graph, and write). This part works fine, but I only want three activities to be created max. Right now if I push the buttons 10 times I get 10 separate activities. Is there a way to prevent this and have the button call an activity if it has already been created instead of creating a new one each time?
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button_toGraph = (Button) findViewById(R.id.home_to_graph);
button_toGraph.setOnClickListener(goToSecondListener);
Button button_toWrite = (Button) findViewById(R.id.home_to_write);
button_toWrite.setOnClickListener(goToThirdListener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private OnClickListener goToSecondListener = new OnClickListener(){
#Override
public void onClick(View arg0) {
doButton();
}};
private void doButton()
{
startActivity(new Intent(this, GraphScreen.class));
}
private OnClickListener goToThirdListener = new OnClickListener(){
#Override
public void onClick(View v) {
doBacktoThird();
}
private void doBacktoThird() {
startActivity(new Intent(MainActivity.this, WriteScreen.class));
}
};
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
Any help will be greatly appreciated! Thank you!
create three Boolean Variables.
if suppose button_toGraph is clicked .. make the
Boolean button_toGraph_IsCreated = true;
and when Activity is Finished ( YourActivity.finish ) make it Again false.
make a check on the button by using these variable like
if(button_toGraph_IsCreated) // if the variable is true
{
// do nothing as already activity created
}
else
{
doBacktoThird();
}
if you are using database then it should not be hard to get the values to main activity.

Categories

Resources