setBackgroundResource on ImageView return null - java

I'm using ListFragment in my android project. I decided to make a listView, each listview item consist of music frequency imageView. I will try to animate the imageView of music frequency. Each listView has a button called play, once the play is clicked, the music frequency start to animate.
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragmentmusiclist, container, false);
lv = (ListView) v.findViewById(R.id.list);
mp = new MediaPlayer();
mp = null;
Song s1 = new Song("Love Story",(float) 2.5, onMusicPlayListener);
Song s2 = new Song("Sad Story",(float) 1.0, onMusicPlayListener);
Song s3 = new Song("Breakup Story",(float) 3.5, onMusicPlayListener);
songs = new ArrayList<Song>();
songs.add(s1);
songs.add(s2);
songs.add(s3);
adapter = new MusicListAdapter(getActivity(),songs);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
OnClickListener onMusicPlayListener = new OnClickListener() {
#Override
public void onClick(View v) {
final int position = getListView().getPositionForView((LinearLayout)v.getParent());
animMusicFreq = (ImageView) v.findViewById(R.id.music_anim);
animMusicFreq.setBackgroundResource(R.anim.anim_music);
animMusicFreq.post(new Runnable() {
#Override
public void run() {
AnimationDrawable frameAnimation =
(AnimationDrawable) animMusicFreq.getBackground();
frameAnimation.start();
}
});

You are inflating your view inside onCreateView, but you don't pass it to the system. Instead you tell it to inflate its own (you return super). It doesn't make any sense.
You should return your v view like so:
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragmentmusiclist, container, false);
// ...
return v;
}

Related

Changing an image when button click from another fragment

I want to be able to click a button on my settings fragment, which will change an image on another fragment called home fragment. My app keeps crashing once i click the button and im not sure why.
Settings Fragment :
public class SettingsFragment extends Fragment {
public Button button;
public ImageView Torso;
public ImageView ShopGreenTorso;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
button = (Button) getView().findViewById(R.id.button1);
Torso = (ImageView) getView().findViewById(R.id.Torso);
ShopGreenTorso= (ImageView) getView().findViewById(R.id.ShopGreenTorso);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Purchased", Toast.LENGTH_SHORT).show();
Intent i = new Intent(SettingsFragment.this.getActivity(), AvatarFragment.class);
//i.putExtra("resID", R.drawable.torso2green);
Bundle b= new Bundle();
b.putInt("resID", R.drawable.torso2green);
SettingsFragment.this.setArguments(b);
//setArguments(bundle);
startActivity(i);
}
});
}
Avatar Fragment:
public class AvatarFragment extends Fragment {
public ImageView IV;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_avatar, container, false);
// init image view
IV = (ImageView) rootView.findViewById( R.id.Torso );
// getting extras
//Bundle bundle = getActivity().getIntent().getExtras();
// Bundle bundle=getArguments();
Bundle b=getArguments();
if(b!= null)
{
int resid = b.getInt("resID");
IV.setBackgroundResource(resid);
}
return rootView;
}
}
I believe the error is coming from IV.setImageResource(resid) but im not entirely sure, any help would be much appreciated.
It's hard to tell without seeing the exception, but it might be because Bundle mappings are case-sensitive.
Your SettingsFragment uses "ResId", but your HomeFragment is expecting "resID". If no mapping is found in the Bundle, you'll be given the default value of 0 for resID. It's possible that you're crashing when calling IV.setImageResource(0);.
Your image implementation in code is wrong, you need to init your image view like this :
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_avatar, container, false);
// init image view
IV = (ImageView) rootView.findViewById( R.id.Torso );
// getting extras
Bundle bundle = getActivity().getIntent().getExtras();
if(bundle!= null)
{
int resid = bundle.getInt("resId");
IV.setImageResource(resid);
}
return rootView;
}
Don't pass value from Fragment to Fragment directly.
You should use setArguments from SettingsFragment and getArguments in HomeFragment

Error when show data to recycler view in fragment

I have an problem when show data in fragment. I send data from another activity to fragment and show it but it's show. Here is my code.
Function in activity:
public void sendResultRoundtripDomestic(ArrayList<ItemSearch> listOutbound, ArrayList<ItemSearch> listInbound) {
listItemOutbound = ListItem.createSearchOnewayDomesticResult(listOutbound);
outboundFragment = new OutboundFragment(listItemOutbound, 0);
listItemInbound = ListItem.createSearchOnewayDomesticResult(listInbound);
inboundFragment = new InboundFragment(listItemInbound, 1);
setupViewPager(viewPager);
}
And here is my fragment I want to show
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rv = inflater.inflate(R.layout.fragment_outbound, container, false);
rvResultOutbound = (RecyclerView) rv.findViewById(R.id.roundtrip_outbound);
adapterOutbound = new OnewayAdapter(rv.getContext(), list);
rvResultOutbound.setAdapter(adapterOutbound);
rvResultOutbound.setLayoutManager(new LinearLayoutManager(rv.getContext(), LinearLayoutManager.VERTICAL, false));
return rv;
}
public OutboundFragment(ArrayList<ListItem> list, int position) {
this.list = list;
this.position = position;
}
Can you help me fix this?

Button does not respond

Ive got a Button in one of my Fragments. But it seems to be "not-clickable". There is no Log.d. Message when I click the Button (In another Fragment (Same onclicklistenercode) everything is fine.
For greater overview I added the whole Class and the part of my layout file which defindes the button.
public class ListViewFragment extends Fragment {
DbHelper mydb;
Button buttondeletedb;
Button buttonexport;
private EditText roomnr;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_listview, container, false);
Context context = getContext();
mydb = new DbHelper(context);
buttondeletedb = (Button) view.findViewById(R.id.button_deletelist_list);
buttonexport = (Button) view.findViewById(R.id.button_export);
String dataList = mydb.getAllElements();
String [] dataListArray = dataList.split("\n");
List<String> dataListFinal = new ArrayList<>(Arrays.asList(dataListArray));
ArrayAdapter<String> dataListAdapter = new ArrayAdapter<>(
getActivity(),
R.layout.list_item_datalist,
R.id.list_item_datalist_textview,
dataListFinal);
View rootView=inflater.inflate(R.layout.fragment_listview, container, false);
ListView dataListListView = (ListView) rootView.findViewById(R.id.datalist);
dataListListView.setAdapter(dataListAdapter);
buttondeletedb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("buttondeletelist", "clicked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
mydb.deleteAll();
}
});
return rootView;
}
}
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/deletelist"
android:id="#+id/button_deletelist_list"
android:layout_gravity="center_horizontal" />
You can not click the button because the root view of Fragment is not view, you returned rootView. The button is child view of view.
Change return rootView; to return view;.
It should work
//Remove rootView and return view instead of rootView
public class ListViewFragment extends Fragment {
DbHelper mydb;
Button buttondeletedb;
Button buttonexport;
private EditText roomnr;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_listview, container, false);
Context context = getContext();
mydb = new DbHelper(context);
buttondeletedb = (Button) view.findViewById(R.id.button_deletelist_list);
buttonexport = (Button) view.findViewById(R.id.button_export);
String dataList = mydb.getAllElements();
String [] dataListArray = dataList.split("\n");
List<String> dataListFinal = new ArrayList<>(Arrays.asList(dataListArray));
ArrayAdapter<String> dataListAdapter = new ArrayAdapter<>(
getActivity(),
R.layout.list_item_datalist,
R.id.list_item_datalist_textview,
dataListFinal);
// Change made here. replace view instead of rootView and remove rootView
ListView dataListListView = (ListView) view.findViewById(R.id.datalist);
dataListListView.setAdapter(dataListAdapter);
buttondeletedb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("buttondeletelist", "clicked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
mydb.deleteAll();
}
});
// Replace rootView with view.
return view;
}
}
Link between XML file and Class file of the Element (Button) is not there.Add this line in your onCreateView()
Button buttondeletedb = (Button) view.findViewById(R.id.buttonid);

How to pass values from one Fragment to another in a ViewPager?

I'm completely new to Android programming. I'm writing an where there are two Fragments: Query and Results. There is a Button and an EditText in the Query Fragment. When the user clicks on the Button, the results from the EditText should be displayed in the TextView that is present the Results Fragment.
Here is the Main Activity (Starting Point):
public class StartingPoint extends FragmentActivity
{
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
viewPager = (ViewPager)findViewById(R.id.pager);
viewPager.setAdapter(new FragmentsPagerAdapter(getSupportFragmentManager()));
}
}
Here is the QueryFragment.java:
public class QueryFragment extends Fragment
{
EditText queryET, endpointET;
Button execute;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// Get the view from fragmenttab1.xml
View view = inflater.inflate(R.layout.query_fragment, container, false);
queryET = (EditText) view.findViewById(R.id.sparqlQueryET);
endpointET = (EditText) view.findViewById(R.id.sparqlEndpointET);
execute = (Button) view.findViewById(R.id.executeButton);
execute.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
String query = queryET.toString();
String endpoint = endpointET.toString();
Query q = QueryFactory.create(query, Syntax.syntaxARQ);
q.setOffset(1);
QueryExecution qe = QueryExecutionFactory.sparqlService(endpoint, query);
ResultSet rs = qe.execSelect();
StringBuffer results = new StringBuffer();
List<String> columnNames = rs.getResultVars();
while(rs.hasNext())
{
QuerySolution qs = rs.next();
for(String var: columnNames)
{
results.append(var +":");
if(qs.get(var) == null)
results.append("{null}");
else if (qs.get(var).isLiteral())
results.append(qs.getLiteral(var).toString());
else
results.append(qs.getResource(var).getURI());
results.append('\n');
}
results.append("----------------\n");
}
qe.close();
}
});
return view;
}
}
Here is the ResultsFragment:
public class ResultsFragment extends Fragment
{
TextView r;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// Get the view from fragmenttab1.xml
View view = inflater.inflate(R.layout.results_fragment, container, false);
r = (TextView) view.findViewById(R.id.resultsTV);
return view;
}
}
Now my question is how do I pass the result processed in the onClick method (of the QueryFragment), which is a String, to the ResultsFragment where the String would be displayed in a TextView?
Simple approach will be : Make public static String field in parent activity. onClick method will set info into this value, and onCreateView result fragment will try to take it from there.
onClick(View v){
MainActivity.myResultString = "result code";
}
and get it when you need it;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.results_fragment, container, false);
r = (TextView) view.findViewById(R.id.resultsTV);
r.setText(MainActivity.myResultString);
return view;
}
Something like this. Its not completed solution but can help you ) good luck.

I am getting Null Pointer Exception in GridView Android

I am getting null pointer exception in fragment using Gridview.
My code is
public class HomeFragment extends Fragment {
GridView grid;
String[] web = { "Bata", "Service", "puma", "Hush" };
int[] imageId = { R.drawable.shoesmall, R.drawable.shoe1, R.drawable.shoe3,
R.drawable.shoe4 };
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
// ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_home, container);
CustomGrid adapter = new CustomGrid(getActivity().getApplicationContext(), web, imageId);
grid = (GridView) getView().findViewById(R.id.gridview);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity().getApplicationContext(),
"You Clicked at " + web[+position], Toast.LENGTH_SHORT)
.show();
}
});
return rootView;
}
}
Can anyone guide why it is happing? I don't use fragments commonly.
your getView() is null,because view not yet created,So change
grid = (GridView) getView().findViewById(R.id.gridview);
to
grid = (GridView) rootView.findViewById(R.id.gridview);

Categories

Resources