onClick method not found - java

I'm new to this and i'm doing an app for a university project and I wanted to put a VideoView in my app, so I watched this video ("https://www.youtube.com/watch?v=SrPHLj_q_OQ&t=421s") and did it and worked. But then I add to copy the code from content_main.xml to a fragment and it stopped working and giving an error on the "android:onClick" on the Button. And when I press CTRL+F1 to inspect it says this:
"Corresponding method handler'public void videoplay(android.view.View)' not found
Inspection info:The onClick attribute value should be the name of a method in this View's context to invoke when the view is clicked.This name must correspond to a public method that takes exactly one parameter of type View.
Must be a string value, using '\;' to escape characters such as '\n' or '\uxxxx' for a unicode character.
Issue id:OnClick "
Heres my xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:background="#003e6f"
android:orientation="vertical"
tools:context=".InicioFragment">
<VideoView
android:id="#+id/videoView"
android:layout_width="match_parent"
android:layout_gravity="center_horizontal"
android:layout_height="197dp" />
<Button
android:id="#+id/button2"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="#FF6600"
android:text="Play"
android:onClick="videoplay"
android:textColor="#ffffff" />
<ImageView
android:id="#+id/imagem2"
android:layout_width="match_parent"
android:layout_height="360dp"
android:layout_alignParentBottom="true"
android:adjustViewBounds="false"
android:background="#drawable/tech3" />
</LinearLayout>
Heres my java:
package intro.android.migueloliveiraapp;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;
import android.widget.VideoView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
clk = (Button) findViewById(R.id.button2);
videov = (VideoView) findViewById(R.id.videoView);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//Carregar o layout do fragent incial "InicioFragment"
InicioFragment inicioFragment = new InicioFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment, inicioFragment, inicioFragment.getTag())
.commit();
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_oliveira) {
Quem_Oliveira quem_oliveiraFragment = new Quem_Oliveira();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
quem_oliveiraFragment, quem_oliveiraFragment.getTag())
.commit();
Toast.makeText(this, "Oliveira", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_profissao) {
Profissao profissaoFragment = new Profissao();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
profissaoFragment, profissaoFragment.getTag())
.commit();
Toast.makeText(this, "Profissão", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_feitos) {
Principais_feitos principais_feitosFragment = new Principais_feitos();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
principais_feitosFragment, principais_feitosFragment.getTag())
.commit();
Toast.makeText(this, "Principais Feitos", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_academicas) {
Habilitacoes_Academicas habilitacoes_academicasFragment = new Habilitacoes_Academicas();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
habilitacoes_academicasFragment, habilitacoes_academicasFragment.getTag())
.commit();
Toast.makeText(this, "Habilitações Académicas", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_galeria) {
Galeria galeriaFragment = new Galeria();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
galeriaFragment, galeriaFragment.getTag())
.commit();
Toast.makeText(this, "Galeria", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_contactos) {
Contactos contactosFragment = new Contactos();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
contactosFragment, contactosFragment.getTag())
.commit();
Toast.makeText(this, "Contactos", Toast.LENGTH_SHORT).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//video view
Button clk;
VideoView videov;
public void videoplay(View v){
String videopath = "android.resource://intro.android.migueloliveiraapp/" + R.raw.oliveira;
Uri uri = Uri.parse(videopath);
videov.setVideoURI(uri);
videov.start();
}
}
Heres my InicioFragment java:
package intro.android.migueloliveiraapp;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class InicioFragment extends Fragment {
public InicioFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_inicio, container, false);
}
}
heres my updated InicioFragment.java:
package intro.android.migueloliveiraapp;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.net.Uri;
import android.widget.Button;
import android.widget.VideoView;
/**
* A simple {#link Fragment} subclass.
*/
public class InicioFragment extends Fragment {
public InicioFragment() {
// Required empty public constructor
}
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_inicio, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
clk = (Button) view.findViewById(R.id.button);
videov = (VideoView) view.findViewById(R.id.videoView);
// bind the views here.
Button button2 = view.findViewById(R.id.button);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something here.
}
});
}
Button clk;
VideoView videov;
public void videoplay(View v){
String videopath = "android.resource://intro.android.migueloliveiraapp/" + R.raw.oliveira;
Uri uri = Uri.parse(videopath);
videov.setVideoURI(uri);
videov.start();
}
}

You can use this for click.
Button mPlayVideo;
//In oncreate
mPlayVideo = findViewById(R.id.button2);
mPlayVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_SHORT).show();
}
});

In your xml your tools:context=".InicioFragment refers to your fragment and not your activity.
Your method is found inside the activity and not the fragment class and this is why are getting this error.
You can check Call an activity method from a fragment
But I can recommend using the onClick attribute inside your activities and inside fragment use normal click listener:
View view = findViewById(R.id.viewId);
view .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});

This is because you created videoplay() method inside your MainActivity.java . You should put your videoplay() method into the InicioFragment.java as it is the corresponding file for the xml layout you have mentioned above.
Initialize your variables like bellow inside your onCreateView method on InicioFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_inicio, container, false);
Button btn1 = view.findViewById(R.id.button_id);
.....
.....
return view;
}
public void videoplay(View v){
.........
.....
}

The following error:
"Corresponding method handler'public void videoplay(android.view.View)' not found
Inspection info:The onClick attribute value should be the name of a method in this View's context to invoke when the view is clicked.This name must correspond to a public method that takes exactly one parameter of type View.
Must be a string value, using '\;' to escape characters such as '\n' or '\uxxxx' for a unicode character.
Issue id:OnClick "
means that you forget to add the corresponding method in your Activity class when using android:onClick="videoplay" attribute. So, you need to add the following method to your activity:
public void videoplay(View v){
// do something here.
}
The most important part is, android:onClick tag is only working when you're using it inside the content layout of Activity.. So, android:onClick doesn't work when you're using it inside the fragment layout. You need to use the onClickListener instead.
You need to bind the view and add the onClickListener with something like this:
public class InicioFragment extends Fragment {
public InicioFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_inicio, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// bind the views here.
Button button2 = view.findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something here.
}
});
}
}

Pay attention on your xml file that this file's context is your InicioFragment (tools:context=".InicioFragment" )
Therefore, videoplay(View v) should be inside your InicioFragment class.
That's the reason why is not found. It won't search on your MainActivity.
public class InicioFragment extends Fragment {
public InicioFragment() {
// 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.testclassfragment, container, false);
Button clk = (Button) view.findViewById(R.id.button);
VideoView videov = (VideoView) view.findViewById(R.id.videoView);
return view;
}
public void videoplay(View v){
String videopath = "android.resource://intro.android.migueloliveiraapp/" + R.raw.oliveira;
Uri uri = Uri.parse(videopath);
videov.setVideoURI(uri);
videov.start();
}
}
Since you also have a variable for your button another option is to do:
clk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("TESTING", "Clicked");
}
});

Related

controlling a button in a fragment [duplicate]

This question already has answers here:
How to set onclick listener for a button in a fragment in android
(3 answers)
Closed 4 years ago.
I want to control button from fragment xml file in the fragment activity. In other activity we can easily control our button by findviewbyid method and after that we can apply setonclicklistener. But here in fragment how do i access the button and apply onclicklistener method.
My Fragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
/**
* A simple {#link Fragment} subclass.
*/
public class QuoteTypeFragment extends Fragment {
public QuoteTypeFragment() {
// Required empty public constructor
}
LinearLayout typeOne, typeTwo, typeThree, typeFour;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View vv = inflater.inflate(R.layout.fragment_quote_type, container, false);
return vv;
}
}
My Fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#3f525e"
tools:context=".QuoteTypeFragment">
<Button
android:id="#+id/submitbutton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Submit"/>
</FrameLayout>
So here I want to control the submit button in fragment.java. How can I acces the button by findviewbyid or findfragmentbyid. And in fragment.java where do I use that code to access submitbutton.
in OnCreateView
Button button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View vv = inflater.inflate(R.layout.fragment_quote_type, container, false);
button = vv.findViewById(R.id.submitbutton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
return vv;
}
In your QuoteTypeFragment.java
1) Cast the widget by using the view. (view.findViewById()).
2) Set the onClickistener.
3) Implement View.OnClickListener and the onClick method.
public class QuoteTypeFragment extends Fragment implements View.OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View vv = inflater.inflate(R.layout.fragment_quote_type, container, false);
Button mSubmitButton = vv.findViewById(R.id.submitbutton);
mSubmitButton.setonClickListener(this);
return vv;
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.submitbutton:
// Control the button
break;
}
}
It is very easy to control button from fragment XML file in the fragment activity.
In your onCreateView use these lines,
Button button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View vv = inflater.inflate(R.layout.fragment_quote_type, container, false);
button = vv.view.findViewById(R.id.submitbutton);
return vv;
}

Wrong 2nd argument type: calling .replace() from within fragment

I know this question is asked often but none of the accepted solutions have worked for me. (reference solution)
I'm getting the classic "Wrong 2nd argument type" error when I try to launch a Preference Menu fragment from within one of my otherfragments.
Unforunately, even after doing what the accepted answer in that question suggests (calling FragmentManager fragmentManager = getSupportFragmentManager() and importing android.support.v4.app.FragmentManager; I still see the "Wrong 2nd argument type" bug when I call .replace().
A quick overview: my MainActivity.java opens a fragment viewpager (MenuPager.java), from which I try to launch another fragment (FragmentSettingsMenu.java) when a button is clicked within FragmentTrackRecordMenu.java (a child fragment of MenuPager.java).
My code is below. I try to launch the settings menu fragment when the menu button (within FragmentTrackRecord) is clicked but I can't get around the aforementioned compiler error. How can I display my PreferencesFragment successfully from this onClick?
MainActivity.java
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity {
public static ViewPager menuPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
menuPager = (ViewPager) findViewById(R.id.pager);
PagerAdapter pageAdapter = new MenuPagerAdapter(getSupportFragmentManager());
menuPager.setAdapter(pageAdapter);
...
}
}
MenuPagerAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MenuPagerAdapter extends FragmentPagerAdapter {
public MenuPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
switch (arg0) {
case 0:
return new FragmentNeckDisplayMenu();
case 1:
return new FragmentCapoMenu();
case 2:
return new FragmentTrackRecordMenu();
default:
break;
}
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 3;
}
}
FragmentTrackRecordMenu.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
public class FragmentTrackRecordMenu extends Fragment {
private Button menuIcon;
public FragmentTrackRecordMenu(){ } //default constructor
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.menu_fragment_recorder, container, false);
menuIcon = (Button) v.findViewById(R.id.menuIcon);
menuIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { //open popup window
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(android.R.id.content, new FragmentSettingsMenu()) //COMPILER ERROR
.commit();
}
});
}
}
FragmentSettingsMenu.java
public class FragmentSettingsMenu extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from the XML resource
addPreferencesFromResource(R.xml.preferences);
}
}
getSupportFragmentManager() returns the fragment manager of android.support.v4.app.FragmentManager and your FragmentSettingMenu.java is of android.app.Fragment. That's why "Wrong 2nd argument type" error because they are incompatible.
your FragmentManager is of v4 type and FragmentSettingsMenu is not a v4 type.Hence it does not allow.Try the below line in activity.
getFragmentManager().beginTransaction().replace(android.R.id.content,
new PrefsFragment()).commit();
.try this link here
it may give you some help.

Onclick button Event in fragment

I've tried two types of code to get this to work and it keeps giving me force closes when I press the button to go into another Activity. I'm using a Fragment and there's a button in that Fragments code but I can't seem to get it to work.
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.androidbelieve.activity.LoginActivity;
import com.androidbelieve.helper.SQLiteHandler;
import com.androidbelieve.helper.SessionManager;
import java.util.HashMap;
public class PrimaryFragment extends Fragment {
private TextView txtName;
private Button btnLogout;
private SQLiteHandler db;
private SessionManager session;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
RelativeLayout rootView = (RelativeLayout) inflater.inflate(R.layout.primary_layout, container, false);
txtName = (TextView) rootView.findViewById(R.id.username);
btnLogout = (Button) rootView.findViewById(R.id.logout);
// SqLite database handler
db = new SQLiteHandler(getActivity().getApplicationContext());
// session manager
session = new SessionManager(getActivity().getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
// Fetching user details from SQLite
HashMap<String, String> user = db.getUserDetails();
String name = user.get("name");
// Displaying the user details on the screen
txtName.setText(name);
// Logout button click event
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logoutUser();
}
});
Button button = (Button) rootView.findViewById(R.id.saleentry);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateDetail();
}
});
return rootView;
}
public void updateDetail() {
Intent intent = new Intent(getActivity(), SentFragment.class);
startActivity(intent);
}
I was trying to go to another page using button, but it always fail.
Here is my stacktrace..this is the result when i used onclicklistener
04-07 22:42:37.285 27777-27777/com.androidbelieve.drawerwithswipetabs >E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.androidbelieve.drawerwithswipetabs, PID: 27777
Theme: themes:{default=overlay:system, iconPack:system, fontPkg:system, >com.android.systemui=overlay:system}
android.content.ActivityNotFoundException: Unable to find explicit >activity class >{com.androidbelieve.drawerwithswipetabs/com.androidbelieve.drawerwithswipet>abs.SentFragment}; have you declared this activity in your >AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1801)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1514)
at android.app.Activity.startActivityForResult(Activity.java:3930)
at android.app.Activity.startActivityForResult(Activity.java:3890)
at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:849)
at android.support.v4.app.FragmentActivity$HostCallbacks.onStartActivityFromFragment(FragmentActivity.java:907)
at android.support.v4.app.Fragment.startActivity(Fragment.java:916)
at com.androidbelieve.drawerwithswipetabs.PrimaryFragment.updateDetail(PrimaryFragment.java:75)
at com.androidbelieve.drawerwithswipetabs.PrimaryFragment$2.onClick(PrimaryFragment.java:67)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21156)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5456)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
firstly you have to add frame layout in your xml layout.
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
then use this code on click
Button button = (Button) rootView.findViewById(R.id.saleentry);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new SentFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.remove(new PrimaryFragment ());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});

setOnClickListener(this) crashes my app

I have a problem with btn.setOnClickListener(this). I have a simple project that works good, but when I add an action to the button I get the message:
unfortunatelay (app name) has stopped
When I comment btn.setOnClickListener(this) out the project works without any problem.
Here is my code:
package com.example.hello;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
public static final Context PlaceholderFragment = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).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 implements OnClickListener {
Button btn;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
btn=(Button)rootView.findViewById(R.id.Entrer);
btn.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
// here is the problem error: no eclosing istance of the type MainActivityis accessible in scope
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
}
}
My layout is as follows:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.hello.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="190dp"
android:text="#string/hello_world"
android:textSize="16dp" />
<Button
android:id="#+id/Entrer"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="61dp"
android:text="Entrer" />
</RelativeLayout>
I dont know if I have simple things that are not go correctly. I'm new to Android programming. Thank you!
btn is null, so when you set onClickListener you get NullPointerException. It's null because it's located in fragment_main.xml, not activity_main.xml. You should move this code from onCreate()
btn = (Button) findViewById(R.id.Entrer);
btn.setOnClickListener(this);
to PlaceholderFragment() as follows:
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);
btn=(Button) rootView.findViewById(R.id.Entrer);
btn.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), SecondActivity.class);
startActivity(intent);
}
});
return rootView;
}
}
btn=(Button)findViewById(R.id.Entrer);
btn.setOnClickListener(this);
Most likely, findViewById above is returning null. btn.setOnClickListener is crashing on a null pointer exception. (Because btn is null).
It is extremely likely, since you are using the default fragment structure created by the Eclipse solution, that the Button is really in the fragment layout file (fragment_main.xml) and not in activity_main.xml. (Hence, the button is not in the Activity view, it's in the fragment view).
If that's the case, then move the above two lines into the onCreateView method of the PlaceholderFragment.

Android ImageView not showing in SherlockFragment

I'm trying to make an ImageView, in the Graphical view it shows up but when I run it on my device and the emulator the image doesn't show up. Here's my XML code.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:scaleType="fitXY"
android:src="#drawable/map_mockup" />
and here's my Fragment1 code (I am using Fragment1 as the Fragment to display this ImageView)
import com.actionbarsherlock.app.SherlockFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import android.app.*;
import android.content.Intent;
public class Fragment1 extends SherlockFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, container, false);
return rootView;
}
}
I hope this is enough, but if you need more code of the application I'll post it.
This is the first time I'm asking a question on Stack Overflow so if I do something wrong PLEASE tell me so I can correct it, so that in the future my questions layout is correct.
Here's the code for the activity I am adding the fragment to.
import android.app.Activity;
import android.os.Bundle;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.Fragment;
import android.content.res.Configuration;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.support.v4.view.GravityCompat;
public class MainActivity extends SherlockFragmentActivity {
// Declare Variable
DrawerLayout mDrawerLayout;
ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
MenuListAdapter mMenuAdapter;
String[] title;
String[] subtitle;
int[] icon;
Fragment fragment1 = new Fragment1();
Fragment fragment2 = new Fragment2();
Fragment fragment3 = new Fragment3();
Fragment fragment4 = new Fragment4();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_main);
// Generate title
title = new String[] { "Main", "Nick Honegger",
"Discounts", "About" };
// Generate subtitle
subtitle = new String[] { "Check nearby markets", "View your profile",
"Coupons and deals!", "Find out more!" };
// Generate icon
icon = new int[] { R.drawable.action_about, R.drawable.profile_pic,
R.drawable.collections_cloud, R.drawable.action_about };
// Locate DrawerLayout in drawer_main.xml
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// Locate ListView in drawer_main.xml
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// Pass results to MenuListAdapter Class
mMenuAdapter = new MenuListAdapter(this, title, subtitle, icon);
// Set the MenuListAdapter to the ListView
mDrawerList.setAdapter(mMenuAdapter);
// Capture button clicks on side menu
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// Enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
// TODO Auto-generated method stub
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
return super.onOptionsItemSelected(item);
}
// The click listener for ListView in the navigation drawer
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Locate Position
switch (position) {
case 0:
ft.replace(R.id.content_frame, fragment1);
break;
case 1:
ft.replace(R.id.content_frame, fragment2);
break;
case 2:
ft.replace(R.id.content_frame, fragment3);
break;
case 3:
ft.replace(R.id.content_frame, fragment4);
}
ft.commit();
mDrawerList.setItemChecked(position, true);
// Close drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
I've tried using Log.d and it shows that Fragment1 is being loaded. I'm stumped, I don't know what to do and am completely lost right here.
If it matters, the resolution for the PNG is 900x1429.
Two things I can think of.
First, I'm not sure if your layout code shows us the whole file or a snippet. If it's the whole file, you're missing a closing tag on the relativeLayout. If it's a snippet then ignore me.
Second, can you post the code for the Activity that you are adding this Fragment to?
Did you try to add the in the onCreateView instead of the xml?That would be the first thing I'd try.Btw I used the same tutorial as you did and consider yourself lucky,mine doesnt even show the image on my device -.-
Please would you try this:
ft.replace(android.R.id.content, fragment1, "frag1");
instead of
ft.replace(R.id.content_frame, fragment1);
?
If this doesn't change anything, I suggest you use Log.d to confirm that your fragment1 is actually being loaded.
Edit:
Good, then follow Arkan's line or reasoning or place a textview in your xml like this, to determine whether or not the xml is being loaded:
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="if you can see me the problem must be with my image"
/>

Categories