Why won't Fragment Transaction work? - java

I'm writing a simple program in which a two fragments and one activity is used. Both Fragments are displayed (one at a time) within the activity's Frame Layout. The first fragment is a listview that lists items from which the user can select, then the main activity should swap the first fragment with a detail fragment according to the item position determined by a listener within the first fragment. Trouble is, my program won't actually commence the swap. Here's the code for the activity:
package com.example.user.monkeys;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
public class ListActivity extends FragmentActivity implements
monkeyListFragment.OnMonkeySelectedListener {
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i("Activity", "onCreate Pre-Fragment 1");
super.onCreate(savedInstanceState);
setContentView(R.layout.monkey_list_frame);
if (findViewById(R.id.fragment_container) != null) {
if (savedInstanceState != null) {
return;
}
monkeyListFragment monkeyList = new monkeyListFragment();
monkeyList.setArguments(getIntent().getExtras());
// Add the fragment to the container
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, monkeyList);
Log.i("Activity", "made it end onCreate");
}
}
#Override
public void onMonkeyItemSelected(int position) {
Log.i("From Activity", "onMonkeyItemSelected");
monkeyDetailsFragment newDetailFrag = new monkeyDetailsFragment();
Bundle args = new Bundle();
args.putInt("itemPosition", position);
newDetailFrag.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newDetailFrag);
transaction.addToBackStack(null);
transaction.commit();
}
}
And the code for the listview fragment:
package com.example.user.monkeys;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class monkeyListFragment extends Fragment{
OnMonkeySelectedListener monkeyCallBack;
private ListView monkeyLV;
private String[] monkeyStrings;
public interface OnMonkeySelectedListener {
public void onMonkeyItemSelected(int position);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.i("Fragment 1", "Made it to onCreateView");
View view = inflater.inflate(R.layout.list_fragment, container, false);
monkeyLV = (ListView) view.findViewById(R.id.monkeyListView);
monkeyStrings = getResources().getStringArray(R.array.monkey_data_list);
ArrayAdapter<String> objAdapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1, monkeyStrings);
monkeyLV.setAdapter(objAdapter);
AdapterView.OnItemClickListener monkeyListen = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i("ListFragment-ClckLstnr", "Made it");
monkeyCallBack.onMonkeyItemSelected(position);
}
};
Log.i("Fragment 1", "Made it past OnItemClick Listener");
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
monkeyCallBack = (OnMonkeySelectedListener) activity;
}
catch (ClassCastException e) {
throw new ClassCastException(activity.toString());
}
}
}
and finally the code for the detail fragment (this isn't fully fleshed out but it should still swap I believe).
package com.example.user.monkeys;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class monkeyDetailsFragment extends Fragment {
ImageView monkeyPicture;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, #Nullable Bundle savedInstanceState) {
Log.i("From Detail Fragment", "Got here");
View view = inflater.inflate(R.layout.monkey_detail_fragment, container,
false);
return view;
}
}

I found your missing line of code for the listview fragment:
monkeyLV.setOnItemClickListener(monkeyListen)

Related

When I move from fragment b to fragment A after adding my new listitem, my new listitem is not showing in recyclerview

I am making note taking app.i have two fragments in my app first fragment A (ListFragment) contains the recycler adapter .
while when I press adding floating button first fragment A (ListFragment) is replaced with next fragment B(AddingFragment) in which I type new data and then again press adding floating button on fragment B(AddingFragment) to add that new data in data set and then press backfloating button on my fragment B to move back to Fragment A(with recycler adapter) .
This new data item is added to data list every time but never becomes visible in recycler adapter in Fragment A.
package com.example.anonymous.note_taking_app;
import android.app.ActionBar;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class AddingFragment extends Fragment {
public AddingFragment()
{
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_adding, container, false);
return view;
}
#Override
public void onResume()
{
super.onResume();
FloatingActionButton floating = (FloatingActionButton) getActivity().findViewById(R.id.addingfloatingbutton);
floating.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Log.i("floating_button", "floating button 2 clicked");
EditText title = (EditText) getActivity().findViewById(R.id.firsttextview);
EditText detial = (EditText) getActivity().findViewById(R.id.secondtextview);
DatabaseHelper db = new DatabaseHelper(getActivity().getApplication());
boolean insert = db.insert(title.getText()+"",detial.getText()+"");
if(insert==true)
{
com.example.anonymous.note_taking_app.ListAdapter l = new com.example.anonymous.note_taking_app.ListAdapter();
ListFragment.it.add(new ListItem(title.getText()+"",detial.getText()+""));
l.notifyItemInserted(ListFragment.it.size()-1);//DataSetChanged();
l.notifyDataSetChanged();
for(int i=0;i<ListFragment.it.size();i++)
{
Log.i("List item"+i+"", ListFragment.it.get(i).getNoteTitle());
}
Log.i("insertion", "is added");
}
else
{
Log.i("insertion", "is not added");
}
}
});
FloatingActionButton floatings = (FloatingActionButton) getActivity().findViewById(R.id.addcancelfloatingbutton);
floatings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
final FragmentManager fragmentManager = getFragmentManager();
fragmentManager.popBackStackImmediate();
}
});
}
}
//
package com.example.anonymous.note_taking_app;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Fragment;
import java.util.ArrayList;
/**
* Created by Anonymous on 12/13/2017.
*/
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.holderclas> implements EditDilogue.EditDilougeinterface
{
static ArrayList<ListItem> i;
Context context;
View view;
ImageButton share;
ImageButton edit;
static int lastposition;
android.app.FragmentManager fm;
public ListAdapter(ArrayList<ListItem> i,android.app.FragmentManager fm)
{
this.i=i;
this.fm=fm;
}
public ListAdapter()
{
}
#Override
public ListAdapter.holderclas onCreateViewHolder(ViewGroup parent, int viewType)
{
view= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,false);
holderclas h = new holderclas(view);
share = (ImageButton) view.findViewById(R.id.share);
edit = (ImageButton) view.findViewById(R.id.edit);
return h;
}
#Override
public void onBindViewHolder(ListAdapter.holderclas holder, final int position)
{
final int y= position;
lastposition = position;
final ListItem it = i.get(position);
holder.title.setText(it.getNoteTitle());
holder.details.setText(it.getNoteDetail());
ImageButton b =(ImageButton) view.findViewById(R.id.delete);
b.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Log.i("size", i.size()+"");
i.remove(y);
notifyDataSetChanged();
}
});
share.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Log.i("share", "share");
}
});
edit.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Log.i("edit", i.size()+"edit");
EditDilogue ed = new EditDilogue();
Bundle args = new Bundle();
args.putString("title", it.getNoteTitle());
args.putString("detail", it.getNoteDetail());
ed.setArguments(args);
ed.setTargetFragment(new ListFragment(),1);
ed.show(fm,"fragment");
}
});
}
#Override
public int getItemCount()
{
return i.size();
}
#Override
public void deleteandadd(String titlestring, String detailstring)
{
String oldtitle = i.get(lastposition).getNoteTitle();
String olddetail = i.get(lastposition).getNoteDetail();
Log.i("string", titlestring);
Log.i("string", detailstring);
}
public class holderclas extends RecyclerView.ViewHolder
{
TextView title;
TextView details;
public holderclas(View itemView)
{
super(itemView);
title=(TextView) itemView.findViewById(R.id.title);
details=(TextView) itemView.findViewById(R.id.detail);
}
}
}
//
package com.example.anonymous.note_taking_app;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import java.util.ArrayList;
/**
* Created by Anonymous on 12/13/2017.
*/
public class ListFragment extends Fragment implements EditDilogue.EditDilougeinterface
{
RecyclerView recyClerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
public static ArrayList<ListItem> it;
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState)
{
it = new ArrayList<>();
View view = inflater.inflate(R.layout.fragment_list, parent, false);
FloatingActionButton floating = (FloatingActionButton) view.findViewById(R.id.listfloatingbutton);
floating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Fragment frg = new AddingFragment();
FragmentManager manager = getFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.replace(R.id.placeholder,frg);
trans.addToBackStack("addingfragment");
trans.commit();
AddingFragment()).addToBackStack("addingfragment").commit();
}
});
for(int i=0;i<5;i++)
{
ListItem t = new ListItem("Time Bank",
"Bank should contain atleast $2000 rupees then i will leave this matter") ;
it.add(t);
}
recyClerView=(RecyclerView) view.findViewById(R.id.recycle);
FragmentManager fm = getFragmentManager();
com.example.anonymous.note_taking_app.ListAdapter l = new com.example.anonymous.note_taking_app.ListAdapter(it,fm);
recyClerView.setAdapter(l);
layoutManager = new LinearLayoutManager(getActivity());
recyClerView.setLayoutManager(layoutManager);
return view;
}
#Override
public void onResume()
{
super.onResume();
if(adapter!=null)
{
adapter.notifyDataSetChanged();
adapter.notifyItemInserted(ListFragment.it.size()-1);
}
}
#Override
public void deleteandadd(String titlestring, String detailstring)
{
String oldtitle = com.example.anonymous.note_taking_app.ListAdapter.i.get(com.example.anonymous.note_taking_app.ListAdapter.lastposition).getNoteTitle();
String olddetail = com.example.anonymous.note_taking_app.ListAdapter.i.get(com.example.anonymous.note_taking_app.ListAdapter.lastposition).getNoteDetail();
Log.i("string", titlestring);
Log.i("string", detailstring);
}
}

Can't add intentintegrator in fragment

I'm using zxing library to read qr codes. It works well in MainActivity. Then I want to add that code in a fragment. But intent integrator is not working for this fragment.
This is the code in QrFragment;
package com.myapp.agpj.qr;
import android.app.Activity;
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 com.google.zxing.integration.android.IntentIntegrator;
public class QrFragment extends Fragment {
public QrFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_qr, container, false);
Button scan = (Button) v.findViewById(R.id.bQr);
final Fragment activity = this;
scan.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view){
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
integrator.setPrompt("Scan QR codes in the school premises");
integrator.setCameraId(0);
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
}
});
return v;
}
}
This outputs an error "IntentIntegator can't applied to android.support.v4.fragment".

Callings fragments from listview

I have a fragment that contains a listview. When I press the position 0 of my listview I want to open another fragment but I can't call it. I think there is a problem with the managerFragment but I'm not sure.
Here is my code from Frm_principal that contains the listview in position 0
I want to call frmCliente
`package com.example.programacion.ventasje.Principal;
import android.content.res.Resources;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.internal.widget.AdapterViewCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.programacion.ventasje.Cliente.Frm_Cliente;
import com.example.programacion.ventasje.R;
import java.util.ArrayList;
/**
* Created by Programacion on 31/07/2015.
*/
public class Frm_principal extends Fragment {
TextView tv_funcion,tv_descripcion;
ImageView img_principal;
ListView listview_principal;
ArrayAdapter<Principal> adapter;
Principal dato;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.layout_frm_principal,container,false);
inicializarComponentesUi(rootView);
inicializarListaContactos();
inicializarDatosLista();
listview_principal.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position==0) {
Fragment newFragment = new Frm_Cliente();
FragmentTransaction asd = getActivity().getSupportFragmentManager().beginTransaction();
asd.replace(R.layout.layout_frm_principal,)
}
}
});
return(rootView);
}
private void inicializarDatosLista() {
Principal nuevo = new Principal("Cliente","Añadir modificar o anular clientes",getResources().getDrawable(R.drawable.ic_cliente));
adapter.add(nuevo);
}
private void inicializarListaContactos() {
adapter = new PrincipalAdapter(getActivity(),new ArrayList<Principal>());
listview_principal.setAdapter(adapter);
}
private void inicializarComponentesUi(final View view) {
tv_funcion = (TextView)view.findViewById(R.id.tv_funcion);
tv_descripcion = (TextView)view.findViewById(R.id.tv_descripcion);
img_principal =(ImageView)view.findViewById(R.id.img_principal);
listview_principal =(ListView)view.findViewById(R.id.listview_principal);
}
}
`
and here is the frm cliente class that i want to call
package com.example.programacion.ventasje.Cliente;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.programacion.ventasje.R;
/**
* Created by Programacion on 30/07/2015.
*/
public class Frm_Cliente extends Fragment {
private TextView tvCliente,tvCentro,tvOficio,tvLocalidad;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.layout_frmcliente,container,false);
inicializarComponentesUi(rootView);
return(rootView);
}
private void inicializarComponentesUi(final View view) {
tvCliente = (TextView)view.findViewById(R.id.tv_cliente);
tvCentro = (TextView)view.findViewById(R.id.tv_centro);
tvOficio = (TextView)view.findViewById(R.id.tv_oficio);
tvLocalidad = (TextView)view.findViewById(R.id.tv_localidad);
}
}
I think you forgot to commit the transaction.
Inside your onCLickListener
Frm_Cliente newFragment = new Frm_Cliente();
FragmentTransaction asd = getActivity().getSupportFragmentManager().beginTransaction();
asd.replace(R.layout.layout_frm_principal,newFragment)
ads.commit();

Dynamically update TextView inside Fragment (ViewPager Tab Layout)

I have a problem with createing a functionality in my app. I would like that the Button in one tab of my application update the TextViews which are located in the other tab of my application. Unfortunately my solutions does not work - throws NPE everytime I touch the Button1. My code:
Tab which should be updated:
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.TextView;
public class SummaryFragment extends Fragment {
TextView textViewOne;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View summary= inflater.inflate(R.layout.fragment_summary, container, false);
textViewOne = (TextView) summary.findViewById(R.id.books);
textViewOne.setText("You have read " + Stats.book + " books");
return summary;
}
public void updateStats() {
textViewOne.setText("You have read " + Stats.book + " books");
}
}
Tab on which the button is located:
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;
public class ReadingStarted extends Fragment {
static FirstPageFragmentListener firstPageListener;
public SummaryFragment summaryFragment;
public ReadingStarted() {
}
public ReadingStarted(FirstPageFragmentListener listener) {
firstPageListener = listener;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View started = inflater.inflate(R.layout.fragment_started, container, false);
Button button1 = (Button) started.findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Stats.book=Stats.book+1;
summaryFragment.updateStats();
}
});
return started;
}
}
Problems in your code:
SummaryFragment doesnot have a empty constructor every fragment requires it
SummaryFragment summaryFragment should be SummaryFragment summaryFragment = new SummaryFragmet();//no initialization done so npe in summaryFragment.updateStats();
Communication between fragments should be done through activity.
See the developer docs about Fragments.

Unable to launch app - java.lang.NullPointerException [duplicate]

This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
I'm having problems launching my app (crashes), while there is no errors in code.
This happend after i converted code of List View activity to List Fragment...
My main activity:
package com.example.eronetmarket;
import com.preporuceno_app.AppAdapter;
import android.R.drawable;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.itemmenu, menu);
return true;
}
ViewPager viewPager=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
final ActionBar actionBar=getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.RED));
//actionBar.setDisplayShowHomeEnabled(false);
addTabs(actionBar);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
Log.d("VIVZ","onPageScrolled "+i+" "+v+" "+i2);
}
#Override
public void onPageSelected(int i) {
actionBar.setSelectedNavigationItem(i);
Log.d("VIVZ","onPageSelected "+i);
}
#Override
public void onPageScrollStateChanged(int i) {
if(i==ViewPager.SCROLL_STATE_IDLE)
Log.d("VIVZ","onPageScrollStateChanged scroll state idle "+i);
if(i==ViewPager.SCROLL_STATE_DRAGGING)
Log.d("VIVZ","onPageScrollStateChanged scroll state dragging "+i);
if(i==ViewPager.SCROLL_STATE_SETTLING)
Log.d("VIVZ","onPageScrollStateChanged scroll state settling "+i);
}
});
}
private void addTabs(ActionBar actionBar)
{
ActionBar.Tab tab1=actionBar.newTab();
tab1.setText("PREPORUČENO");
tab1.setTabListener(this);
ActionBar.Tab tab2=actionBar.newTab();
tab2.setText("NAJPOPULARNIJE");
tab2.setTabListener(this);
ActionBar.Tab tab3=actionBar.newTab();
tab3.setText("KATEGORIJE");
tab3.setTabListener(this);
actionBar.addTab(tab1);
actionBar.addTab(tab2);
actionBar.addTab(tab3);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
// Log.d("VIVZ","onTabSelected "+tab.getText());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
// Log.d("VIVZ","onTabUnselected "+tab.getText());
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
// Log.d("VIVZ","onTabReselected "+tab.getText());
}
}
class MyAdapter extends FragmentStatePagerAdapter
{
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment=null;
if(i==0)
{
fragment=new FragmentA();
}
if(i==1)
{
fragment=new Preporuceno();
}
if(i==2)
{
fragment=new FragmentC();
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
}
And my fragment list:
package com.example.eronetmarket;
import java.io.FileNotFoundException;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class Preporuceno extends ListFragment {
private AppAdapter mAdapter;
private ListView siteList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.i("mobAppModel", "OnCreate()");
View rootView = inflater.inflate(R.layout.activity_preporuceno, container, false);
siteList = (ListView) getActivity().findViewById(R.id.listView1);
siteList.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,long id) {
String url = mAdapter.getItem(pos).getstoreURL();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
if(isNetworkAvailable()){
Log.i("mobAppModel", "starting download Task");
AppDownloadTask download = new AppDownloadTask();
download.execute();
}else{
mAdapter = new AppAdapter(getActivity().getApplicationContext(), -1, XMLsourcePullParser.getmobAppModel(getActivity()));
siteList.setAdapter(mAdapter);
}
return rootView;
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private class AppDownloadTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... arg0) {
//Download the file
try {
Downloader.DownloadFromUrl("http://minores.info/joomla30/stacksites.xml", getActivity().openFileOutput("XMLsource.xml", Context.MODE_PRIVATE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result){
//setup our Adapter and set it to the ListView.
mAdapter = new AppAdapter(getActivity().getApplicationContext(), -1, XMLsourcePullParser.getmobAppModel(getActivity()));
siteList.setAdapter(mAdapter);
Log.i("mobAppModel", "adapter size = "+ mAdapter.getCount());
}
}
}
Here is my LogCat messages:
In line 38 where LogCat shows error, I have this line public void onItemClick(AdapterView<?> parent, View v, int pos,long id) {
I don't understand where I went wrong?
Change this
siteList = (ListView) getActivity().findViewById(R.id.listView1);
to
siteList = (ListView) rootView.findViewById(R.id.listView1);
The view belongs to the inflated layout and you need to use the view object to initialize views.
java.lang.RuntimeException: Your content must have a ListView whose
id attribute is 'android.R.id.list'
ListActivity or ListFragment will have listview which occuppies the entire screen. If you want to have other views in the layout then your layout must have listview with id andorid.R.id.list
http://developer.android.com/reference/android/app/ListFragment.html
QUoting docs
ListFragment has a default layout that consists of a single list view.
However, if you desire, you can customize the fragment layout by
returning your own view hierarchy from onCreateView(LayoutInflater,
ViewGroup, Bundle). To do this, your view hierarchy must contain a
ListView object with the id "#android:id/list" (or list if it's in
code)

Categories