This issue has persisted repeatedly no matter how many times I redo this. According to Android Developers, the ID to an object in the View Hierarchy of a fragment is obtained during onCreateView, and all of the questions I've pored over on here confirm this. However for some reason it ALWAYS returns null during the check I have setup and therefore I can not proceed to work with the buttons. The Fragment gets loaded during "decision events" in this project, and each event has different decisions. Thus I want to use just one fragment and change the button texts as appropriate. However I can not seem to get them not to return null. I just need help to figure out what I am doing wrong that is causing the NPE.
DecisionFragment.java:
package com.saphiric.simproject.uimanipulation;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.saphiric.simproject.R;
import com.saphiric.simproject.datacontrols.DataCore;
public class DecisionFragment extends Fragment {
// Activity/Global variables
private static final String TAG = "DecisionFragment";
DataCore dataCore = DataCore.getInstance();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.i(TAG, "Begin: Inflate");
// Gets handles to important UI elements for scalability
View root = inflater.inflate(R.layout.fragment_decision, container, false);
Button buttonTrue = (Button) root.findViewById(R.id.btnChoiceOne);
Button buttonFalse = (Button) root.findViewById(R.id.btnChoiceTwo);
if(buttonTrue == null){
System.out.println("buttonTrue is null");
} else {
System.out.println("buttonTrue is working fine");
}
Log.i(TAG, "Finished: Inflate");
if (root == null){
Log.e(TAG, "omg Inflate == null");
}
switch (dataCore.controller.getCurrentDecision()){
case "OPSDecision":
// buttonTrue.setText(R.string.ops_decision_one);
// buttonFalse.setText(R.string.ops_decision_two);
break;
default:
System.out.println("ERROR: No decision set");
}
return root;
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
}
}
fragment_decision.xml:
<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="90dp"
android:orientation="horizontal"
android:weightSum="1.0"
tools:context="com.saphiric.simproject.uimanipulation.DecisionFragment">
<Button
android:id="#+id/decisionOne"
android:layout_width="0dp"
android:layout_height="90dp"
android:layout_weight=".5"
android:text="#string/defaul_btn"
android:onClick="cryingDecisionOne"/>
<Button
android:id="#+id/decisionTwo"
android:layout_width="0dp"
android:layout_height="90dp"
android:layout_weight=".5"
android:text="#string/defaul_btn"
android:onClick="cryingDecisionTwo"/>
</LinearLayout>
DayOne.java:
package com.saphiric.simproject.activities;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.saphiric.simproject.R;
import com.saphiric.simproject.datacontrols.DataCore;
import com.saphiric.simproject.uimanipulation.ControlsFragment;
import com.saphiric.simproject.uimanipulation.DecisionFragment;
/**
* Created by Saphiric on 11/12/14.
*/
public class DayOne extends Activity {
/**
* Necessary activity variables
*/
ControlsFragment controlsFragment = new ControlsFragment();
DecisionFragment decisionFragment = new DecisionFragment();
DataCore dataCore = DataCore.getInstance();
/**
* Android activity methods
*
* #param savedInstanceState is the apps savedInstanceState
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_day_one);
// Initializes the opening story text
// Initializes the dayProgress variable in DataController
String storyStart = getResources().getString(R.string.story_opening_one);
dataCore.controller.setCurrentText(storyStart);
dataCore.controller.setCurrentDecision("OPSDecision");
// Handles for fragment management
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// UI will add the ControlsFragment in it's starting state for that activity.
fragmentTransaction.add(R.id.fragmentContainer, controlsFragment);
fragmentTransaction.commit();
}
#Override
public void onResume(){
super.onResume();
}
public void cryingDecisionOne(View view) {
dataCore.controller.setDayProgress(dataCore.controller.getDayProgress());
// Sets cryingDecision Story Lock
dataCore.locks.setCryingDecision(true);
dataCore.controller.setCurrentDecision("HLSOne");
// Removes the decision fragment and replaces it with the controls fragment
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// Sets the text to be pulled to storyText
String decision = getResources().getString(R.string.crying_decision_true);
dataCore.controller.setCurrentText(decision);
fragmentTransaction.replace(R.id.fragmentContainer, controlsFragment);
fragmentTransaction.commit();
}
public void cryingDecisionTwo(View view) {
dataCore.controller.setDayProgress(dataCore.controller.getDayProgress());
// Sets cryingDecision choice
dataCore.locks.setCryingDecision(false);
dataCore.controller.setCurrentDecision("HWSOne");
// Removes the decision fragment and replaces it with the controls fragment
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// Updates the currentText for updating the story view
String decision = getResources().getString(R.string.crying_decision_false);
dataCore.controller.setCurrentText(decision);
fragmentTransaction.replace(R.id.fragmentContainer, controlsFragment);
fragmentTransaction.commit();
}
public void advanceGameFunction(View view) {
String textUpdate;
// Handles for fragment management
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// Obtains handles to UI components
TextView storyText = (TextView) findViewById(R.id.storyText);
RelativeLayout gameStart = (RelativeLayout) findViewById(R.id.gameStart);
ImageView charOne = (ImageView) findViewById(R.id.char_one);
ImageView charTwo = (ImageView) findViewById(R.id.char_two);
ImageView charThree = (ImageView) findViewById(R.id.char_three);
ImageView charFour = (ImageView) findViewById(R.id.char_four);
// Increments the data variable in DataController
dataCore.controller.setDayProgress(dataCore.controller.getDayProgress());
System.out.println(dataCore.controller.getDayProgress());
// Switch case for handling day progression
switch (dataCore.controller.getDayProgress()) {
case 1:
textUpdate = getResources().getString(R.string.story_opening_two);
dataCore.controller.setCurrentText(textUpdate);
storyText.setText(dataCore.controller.getCurrentText());
break;
case 2:
fragmentTransaction.replace(R.id.fragmentContainer, decisionFragment);
fragmentTransaction.commit();
break;
case 3:
if (dataCore.locks.getCryingDecision()) {
storyText.setText(dataCore.controller.getCurrentText());
} else {
storyText.setText(dataCore.controller.getCurrentText());
}
break;
case 4:
if (dataCore.locks.getCryingDecision()) {
textUpdate = getResources().getString(R.string.ops_d1_line1);
dataCore.controller.setCurrentText(textUpdate);
storyText.setText(dataCore.controller.getCurrentText());
} else {
textUpdate = getResources().getString(R.string.ops_d2_line1);
dataCore.controller.setCurrentText(textUpdate);
storyText.setText(dataCore.controller.getCurrentText());
}
break;
case 5: // Transition to hurt leg scene if Crying Decision is true, hallway scene if false
if (dataCore.locks.getCryingDecision()){
gameStart.setBackgroundResource(R.drawable.bg_gym_front);
textUpdate = getResources().getString(R.string.hls_line1);
dataCore.controller.setCurrentText(textUpdate);
storyText.setText(dataCore.controller.getCurrentText());
}else{
gameStart.setBackgroundResource(R.drawable.bg_hallway);
textUpdate = getResources().getString(R.string.hws_line1);
dataCore.controller.setCurrentText(textUpdate);
storyText.setText(dataCore.controller.getCurrentText());
}
break;
case 6:
if(dataCore.locks.getCryingDecision()){
textUpdate = getResources().getString(R.string.hls_line2);
dataCore.controller.setCurrentText(textUpdate);
storyText.setText(dataCore.controller.getCurrentText());
}else{
textUpdate = getResources().getString(R.string.hws_line2);
dataCore.controller.setCurrentText(textUpdate);
storyText.setText(dataCore.controller.getCurrentText());
}
break;
case 7:
if(dataCore.locks.getCryingDecision()){
charOne.setVisibility(View.VISIBLE);
textUpdate = getResources().getString(R.string.hls_line3);
dataCore.controller.setCurrentText(textUpdate);
storyText.setText(dataCore.controller.getCurrentText());
}else {
}
break;
case 8:
if(dataCore.locks.getCryingDecision()){
textUpdate = getResources().getString(R.string.hls_line4);
dataCore.controller.setCurrentText(textUpdate);
storyText.setText(dataCore.controller.getCurrentText());
}else{
}
break;
case 9:
if(dataCore.locks.getCryingDecision()){
}else{
}
break;
default:
System.out.println("Default case called");
}
}
}
You are using the wrong ids in your code! The buttons in your layout have the id decisionOne and decisionTwo but in your code you are using btnChoiceOne and btnChoiceTwo.
To fix it replace this:
Button buttonTrue = (Button) root.findViewById(R.id.btnChoiceOne);
Button buttonFalse = (Button) root.findViewById(R.id.btnChoiceTwo);
with this in your DecisionFragment:
Button buttonTrue = (Button) root.findViewById(R.id.decisionOne);
Button buttonFalse = (Button) root.findViewById(R.id.decisionTwo);
Your button ids in code do not match with the ones in xml layout.
In your xml, the id is 'decisionOne' but the code is looking for 'R.id.btnChoiceOne'
Related
I created a bottom navigation for my app and was wondering how could I make it so when the user opens the app, it returns to the last fragment they were viewing? At the moment even if you just switch apps for a second, it reverts to the home page immediately. Thanks in advance!
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.MenuItem;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomnav = findViewById(R.id.bottom_menu);
bottomnav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout, new HomeFragment()).commit();
mediaPlayer = MediaPlayer.create(this, R.raw.clickandboop);
}
private final BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()) {
case R.id.nav_home:
selectedFragment = new HomeFragment();
mediaPlayer.start();
break;
case R.id.nav_favourites:
selectedFragment = new FavFragment();
mediaPlayer.start();
break;
case R.id.nav_trophies:
selectedFragment = new TrophiesFragment();
mediaPlayer.start();
break;
case R.id.nav_info:
selectedFragment = new InfoFragment();
mediaPlayer.start();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout, selectedFragment).commit();
return true;
}
};
Fragments already restore you back to exactly where you were.
This means that you need to wrap your replace() call with a check of savedInstanceState == null to avoid destroying the just recreated Fragment:
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_layout, new HomeFragment())
.commit();
}
Just use sharedprefs and store the last fragment that the user was in. Use the onStop callback of the fragment to store it.
When the user opens the application just check this value if it's not set open homefragment otherwise just open the last fragment based on the value you have in your shared preferences
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");
}
});
How can you make it so that user can have several buttons with on click listeners. I tried it with 2 buttons, but it said that I had already defined the on-click listener so I could not make another on click listener as a result. The code I have so far is:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
private View btnRender;
private LinearLayout container;
private View btnRendered;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRender = (View)findViewById(R.id.btn_render);
container = (LinearLayout)findViewById(R.id.fragment_layout);
btnRendered = (View) findViewById(R.id.btn_rendered);
//set event handling for button
btnRender.setOnClickListener(onClickListener());
}
private View.OnClickListener onClickListener() {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
//replace fragment when clicked
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_layout, new PDFRenderFragment());
ft.commit();
//gone button after all
btnRender.setVisibility(View.GONE);
container.setVisibility(View.VISIBLE);
}
};
}
}
The btn_rendered is the other button that I want to set an on click listener for, but the software will not let me do this. Is it true that I need to set up a switch-case method for it to work?
I just tried out both codes and none of them seem to have doen the desired effect. Now whenever I click one of the buttons, the 2nd pdf always shows! (what I was using the button for)
You can handle like below.
btnRender.setOnClickListener(onClickListener());
btnRendered.setOnClickListener(onClickListener());
private View.OnClickListener onClickListener() {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btn_render:
//replace fragment when clicked
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_layout, new PDFRenderFragment());
ft.commit();
//gone button after all
btnRender.setVisibility(View.GONE);
container.setVisibility(View.VISIBLE);
break;
case R.id.btn_rendered:
// your logic here
break;
}
}
};
}
You can use same method for second button too and use if/else condition for identify which button is click in that method.
like below code.
//set event handling for button
btnRender.setOnClickListener(onClickListener());
second_btn.setOnClickListener(onClickListener());
Your onClickListener Method.
private View.OnClickListener onClickListener() {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
//replace fragment when clicked
if (v == btnRender) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_layout, new PDFRenderFragment());
ft.commit();
//gone button after all
btnRender.setVisibility(View.GONE);
container.setVisibility(View.VISIBLE);
} else if (v == second_btn) {
//second button click code
}
}
};
}
just getting started with Android development and I can't figure out why this won't work. Here is the error that I am getting (last line before bold block-quote):
package com.ample.ballv2;
import java.util.Random;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
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;
import android.widget.Toast;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
#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();
}
Button answer = (Button) findViewById(R.id.answerbutton);
answer.setOnClickListener(answerL);
}
private OnClickListener answerL = new OnclickListener(){
public void onClick(view v) {
Random token = random();
int tokenno = token.nextInt(10);
CharSequence ans = "";
switch(tokenno)
{case 0:ans=getString(R.string.msg0);break;
case 1: ans=getString(R.string.msg1);break;
case 2: ans=getString(R.string.msg2);break;
case 3: ans=getString(R.string.msg3);break;
case 4: ans=getString(R.string.msg4);break;
case 5: ans=getString(R.string.msg5);break;
case 6: ans=getString(R.string.msg6);break;
case 7: ans=getString(R.string.msg7);break;
case 8: ans=getString(R.string.msg8);break;
case 9: ans=getString(R.string.msg9);break;
case 10:ans=getString(R.string.msg10);break;
}
Context context = getApplicationContext();
Toast msg = Toast.makeText(context,ans,Toast.LENGTH_LONG);
msg.show();
}
}//error's popping up here
> Description Resource Path Location Type
Syntax error, insert ";" to complete FieldDeclaration MainActivity.java /8ballv2/src/com/ample/ballv2 line 56 Java Problem
#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;
}
}
}
Well, I tried your code in IDE and the problem - in provided sample - is in variable declaration:
private OnClickListener answerL = new OnClickListener(){
public void onClick(view v) {
Random token = random();
int tokenno = token.nextInt(10);
CharSequence ans = "";
switch(tokenno) {
case 0:ans=getString(R.string.msg0);break;
case 1: ans=getString(R.string.msg1);break;
case 2: ans=getString(R.string.msg2);break;
case 3: ans=getString(R.string.msg3);break;
case 4: ans=getString(R.string.msg4);break;
case 5: ans=getString(R.string.msg5);break;
case 6: ans=getString(R.string.msg6);break;
case 7: ans=getString(R.string.msg7);break;
case 8: ans=getString(R.string.msg8);break;
case 9: ans=getString(R.string.msg9);break;
case 10:ans=getString(R.string.msg10);break;
}
Context context = getApplicationContext();
Toast msg = Toast.makeText(context,ans,Toast.LENGTH_LONG);
msg.show();
}
}//here should be ';'
It occurs because View.OnClickListener has body with methods. If there were no methods (e.g. you created a
private class MyOnClickListener implements OnClickListener
(http://developer.android.com/reference/android/view/View.OnClickListener.html)
then it would be like that:
private MyOnClickListener answerL = new MyOnClickListener(); //<- semicolon here.
You can avoid such in future using autoformating tool (ctrl+shift+f as default in Eclipse/ADT and ctrl+alt+l (or something like that) in AndroidStudio) or declaring class fields strictly before/after methods.
Hope it helps)
just as it says you need to insert a semicolon there since you are declaring a field here. So this is how it should be
private OnClickListener answerL = new OnclickListener(){
public void onClick(view v) {
...............
}//onClick ends here
}; //OnClickListener ends here
OnclickListener is an interface and you are supposed to create its object like this:
private OnClickListener answerL = new OnclickListener(){
public void onClick(view v) {
//do stuffs here
}
};
Please notice the semi-colon at the end.
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"
/>