I am using a gridview in fragment. I am loading the gridview in doInBackground.However, I get AsyncTask#1 Fatal Exception. Below is the code that i have tried:
public class Home extends Fragment implements TabHost.OnTabChangeListener,
OnClickListener {
TabHost tabHost;
View vi;
StaggeredAdapter adapter;
TextView tv;
public String urls[] = {
"http://farm9.staticflickr.com/8462/8005636463_0cb4ea6be2.jpg",
"http://farm8.staticflickr.com/7232/6913504132_a0fce67a0e_c.jpg",
"http://farm5.staticflickr.com/4133/5096108108_df62764fcc_b.jpg",
"http://farm5.staticflickr.com/4074/4789681330_2e30dfcacb_b.jpg",
"http://farm9.staticflickr.com/8208/8219397252_a04e2184b2.jpg",
"http://farm9.staticflickr.com/8483/8218023445_02037c8fda.jpg",
"http://farm9.staticflickr.com/8335/8144074340_38a4c622ab.jpg",
"http://farm9.staticflickr.com/8060/8173387478_a117990661.jpg",
"http://farm9.staticflickr.com/8056/8144042175_28c3564cd3.jpg",
"http://farm9.staticflickr.com/8183/8088373701_c9281fc202.jpg",
"http://farm9.staticflickr.com/8185/8081514424_270630b7a5.jpg",
"http://farm9.staticflickr.com/8462/8005636463_0cb4ea6be2.jpg",
"http://farm9.staticflickr.com/8306/7987149886_6535bf7055.jpg",
"http://farm9.staticflickr.com/8444/7947923460_18ffdce3a5.jpg",
"http://farm9.staticflickr.com/8182/7941954368_3c88ba4a28.jpg",
"http://farm9.staticflickr.com/8304/7832284992_244762c43d.jpg",
"http://farm9.staticflickr.com/8163/7709112696_3c7149a90a.jpg",
"http://farm8.staticflickr.com/7127/7675112872_e92b1dbe35.jpg",
"http://farm8.staticflickr.com/7111/7429651528_a23ebb0b8c.jpg",
"http://farm9.staticflickr.com/8288/7525381378_aa2917fa0e.jpg",
"http://farm6.staticflickr.com/5336/7384863678_5ef87814fe.jpg",
"http://farm8.staticflickr.com/7102/7179457127_36e1cbaab7.jpg",
"http://farm8.staticflickr.com/7086/7238812536_1334d78c05.jpg",
"http://farm8.staticflickr.com/7243/7193236466_33a37765a4.jpg",
"http://farm8.staticflickr.com/7251/7059629417_e0e96a4c46.jpg",
"http://farm8.staticflickr.com/7084/6885444694_6272874cfc.jpg" };
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
vi = inflater.inflate(R.layout.home, container, false);
Button iv = (Button) vi.findViewById(R.id.btnMoreDialog);
iv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu homepopup = new PopupMenu(getActivity(), v);
MenuInflater inflater = homepopup.getMenuInflater();
inflater.inflate(R.menu.moredialog, homepopup.getMenu());
homepopup.show();
}
});
new Dialogs().execute(urls);
return vi;
}
private class Dialogs extends AsyncTask<String[] , Void, Void>
{
#Override
protected Void doInBackground(String[]... params) {
StaggeredGridView gridView = (StaggeredGridView) vi
.findViewById(R.id.staggeredGridView1);
int margin = getResources().getDimensionPixelSize(R.dimen.margin);
gridView.setItemMargin(margin);
gridView.setPadding(margin, 0, margin, 0);
// StaggeredAdapter adapter = new StaggeredAdapter(MainActivity.this,
// R.id.photoimageview, urls, R.layout.row_staggered_demo);
StaggeredAdapter adapter = new StaggeredAdapter(vi.getContext(),
R.id.photoimageview, params[0], R.layout.row_staggered_demo);
gridView.setAdapter(adapter);
return null;
}
#Override
protected void onPostExecute(Void result) {
}
#Override
protected void onPreExecute() {
}
}
}
Any ideas pls?
Thanks,
You are attempting to update ui in doInbackground which is not possible.
gridView.setAdapter(adapter);
You need to update ui on the ui thread.
Use runOnUiThread or update ui in onPostExecute
getActivity().runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
}
});
Related
in my Android app I have this class called "TripleTab2". TripleTab2 is a fragment that is called as part of a tabbed activity.
public class TripleTab2 extends Fragment {
private TextView nameAndNumberText;
private LinearLayout nameAndNumbersLayoutSMS;
private Map<String, String> nameToNumberMapping;
private View view;
private ArrayList<String> chosenSMSContacts;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.assign_pattern_tab_2, container, false);
nameAndNumberText = (TextView) view.findViewById(R.id.numAndNameView);
nameAndNumbersLayoutSMS = (LinearLayout) view.findViewById(R.id.nameAndNumbersLayoutSMS);
chosenSMSContacts = getArguments().getStringArrayList("numbersToMove");
createTextViews();
for(String chosenSMSContact : chosenSMSContacts){
nameAndNumberText.append(chosenSMSContact);
}
return view;
}
The following line of code causes a problem (NullPointerException):
chosenSMSContacts = getArguments().getStringArrayList("numbersToMove");
createTextViews();
Actually, that makes sense, because the actvity-class called "ChooseSMSContactActivity" (which sends this data) is called after the tripleTab2-class.
Here it is:
public class ChooseSMSContactActivity extends AppCompatActivity {
private LinearLayout nameAndNumbersLayoutSMS;
private Map<String, String> nameToNumberMapping;
private Button selectedNumberBtn;
private ArrayList<String> selectedNamesAndNumbers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_smscontact_to_add);
nameAndNumbersLayoutSMS = (LinearLayout) findViewById(R.id.dropDownMenuLayout);
selectedNumberBtn = (Button) findViewById(R.id.selectedNumberBtn);
createCheckboxes();
selectedNamesAndNumbers = new ArrayList<>();
selectedNumberBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for(int i=0; i < nameAndNumbersLayoutSMS.getChildCount(); i++){
if(nameAndNumbersLayoutSMS.getChildAt(i) instanceof CheckBox){
CheckBox checkBox = (CheckBox) nameAndNumbersLayoutSMS.getChildAt(i);
if(checkBox.isChecked()){
selectedNamesAndNumbers.add(checkBox.getText().toString());
Bundle bundle = new Bundle();
bundle.putStringArrayList("numbersToMove", selectedNamesAndNumbers);
TripleTab2 tripleTab2 = new TripleTab2();
tripleTab2.setArguments(bundle);
}
}
}
}
});
}
So, TripleTab2 does not have this data on creation, because it is called before ChooseSMSContactActivity.
Does anyone have suggestions on how to resolve this problem? Should I use a BroadcastReceiver or something like that?
I solved this by using the EventBus-library.
In TripleTab2 EventBus was registered, and an onEvent-method was created:
EventBus.getDefault().register(this);
#Subscribe
public void onEvent(CustomMessageEvent event){
TextView nameAndNum = new TextView(view.getContext());
nameAndNum.append(event.getCustomMessage());
nameAndNumbersLayoutSMS.addView(nameAndNum);
}
The CustomMessageEvent-class looks like this:
public class CustomMessageEvent {
private String customMessage;
public String getCustomMessage() {
return customMessage;
}
public void setCustomMessage(String customMessage) {
this.customMessage = customMessage;
}
In the button onClickListener in ChooseSMSActivity I added an EventBus event:
selectedNumberBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for(int i=0; i < nameAndNumbersLayoutSMS.getChildCount(); i++){
if(nameAndNumbersLayoutSMS.getChildAt(i) instanceof CheckBox){
CheckBox checkBox = (CheckBox) nameAndNumbersLayoutSMS.getChildAt(i);
if(checkBox.isChecked()){
selectedNamesAndNumbers.add(checkBox.getText().toString());
CustomMessageEvent event = new CustomMessageEvent();
event.setCustomMessage(checkBox.getText().toString());
EventBus.getDefault().post(event);
}
}
}
}
});
I want to send a list of bitmap i retreived from mysql database using asyncTask to the fragment Fragment_ListView.class, in this fragment class i want to set the adapter of the listView with the bitmap token from asyncTask but i don't know how to do that.
Async Task
#Override
protected void onPostExecute(ArrayList<Bitmap> bitmapArrayList) {
super.onPostExecute(bitmapArrayList);
loading.dismiss();
// now after getting images from server , i want to send this bitmapArrayList
// to Fragment_ListView where i set the adapter of the
}
#Override
protected ArrayList<Bitmap> doInBackground(String... params) {
imageList = new ArrayList();
String add1 = "http://192.168.1.11/save/load_image_from_db.php?id=1";
String add2 = "http://192.168.1.11/save/load_image_from_db.php?id=2";
String add3 = "http://192.168.1.11/save/load_image_from_db.php?id=3";
URL url;
Bitmap image = null;
String[] adds = {add1, add2, add3};
for (int i = 0; i < adds.length; i++) {
try {
url = new URL(adds[i]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
image = BitmapFactory.decodeStream(connection.getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
imageList.add(image);
image = null;
}
return imageList;
OnCreate of MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listfrg = new Fragment_ListView();
getFragmentManager().beginTransaction().add(R.id.frml, listfrg).commit();
}
Fragment_ListView :
public class Fragment_ListView extends Fragment {
ListView mListView;
static ArrayList<Bitmap> bitmaps;
static MySimpleArrayAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frglist, container, false);
mListView = (ListView) view.findViewById(R.id.listView);
bitmaps = new ArrayList<>();
adapter = new MySimpleArrayAdapter(getActivity(), bitmaps);
mListView.setAdapter(adapter);
return view;
}
Something like this,
Create a new interface file
public interface BitMapArrayCallBack {
abstract void bitmapArray(ArrayList<Bitmap> bitmaps);
}
Then in AsyncTask ... i don't know your class name so i will assume the class ServerRequest
public class ServerRequest {
Context context;
public ServerRequest(Context context) {
this.context = context;
}
public void doAsyncTask(BitMapArrayCallBack bitmapCallback) {
new MyAsyncTask(bitmapCallback).execute();
}
public class MyAsyncTask extends AsyncTask<Void, Void, Void> {
private BitMapArrayCallBack bitmapCallback;
public MyAsyncTask(BitMapArrayCallBack bitmapCallback) {
this.bitmapCallback = bitmapCallback;
}
//call do in background etc..
#Override
protected void onPostExecute(ArrayList<Bitmap> bitmapArrayList) {
super.onPostExecute(bitmapArrayList);
loading.dismiss();
bitmapCallback.bitmapArray(bitmapArrayList);
// This will hold and return your arraylist
}
}
}
Now you must call your asynctask in fragment listview
public class Fragment_ListView extends Fragment {
ListView mListView;
static MySimpleArrayAdapter adapter;
private ServerRequest serverRequest;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frglist, container, false);
mListView = (ListView) view.findViewById(R.id.listView);
serverRequest = new ServerRequest(getActivity);
serverRequest.doAsyncTask(new BitMapArrayCallBack {
#Override
void bitMapArray(ArrayList<Bitmap> bitmaps) {
// in here you have access to the bitmaps array
adapter = new MySimpleArrayAdapter(getActivity(), bitmaps);
mListView.setAdapter(adapter);
}
})
return view;
}
I have 3 fragment in viewpager (LeftFragment, MidFragment and Right Fragment)
LeftFragment contain a listview, when clicking on listview item, an image will be loaded on MidFragment. I've encountered a bug and spent a lot of time but still unresolved. Here is my code:
LeftFragmnet
public class LeftFragment extends Fragment{
private ListView listView;
private List<ParseObject> ob;
private ProgressDialog mProgressDialog;
private ListViewAdapter adapter;
private List<School> schoollist = null;
private View v;
MainActivity mainActivity = new MainActivity();
MidFragment midFragment = new MidFragment();
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.left_fragment, container, false);
initComponent();
new RemoteDataTask().execute();
return v;
}
private void initComponent() {
listView = (ListView)v.findViewById(R.id.lv_left);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mainActivity.viewPager.setCurrentItem(1);
School school = schoollist.get(position);
// midFragment.index = Integer.parseInt(school.getIndex());
midFragment.reloadData(Integer.parseInt(school.getIndex()));
}
});
}
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(getActivity());
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle("Please wait a moment...");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
schoollist = new ArrayList<School>();
try{
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("School");
query.orderByAscending("index");
ob = query.find();
for (ParseObject name : ob){
School map = new School();
map.setIndex(String.valueOf(name.get("index")));
map.setCount(String.valueOf(name.get("count")));
map.setName(String.valueOf(name.get("name")));
schoollist.add(map);
}
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
adapter = new ListViewAdapter(getActivity(), schoollist);
listView.setAdapter(adapter);
mProgressDialog.dismiss();
super.onPreExecute();
}
}
}
MidFragment
public class MidFragment extends Fragment {
// private ProgressDialog mProgressDialog;
private ImageView mImageView;
private VideoView mVideoView;
private DisplayImageOptions options;
private ImageLoader imageLoader = ImageLoader.getInstance();
private Context mContext;
private ImageLoadingListener animateFirstListener;
private ArrayList<ParseObject> objectList = new ArrayList<>();
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// imageLoader.init(ImageLoaderConfiguration.createDefault(mContext));
// mImageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.build();
animateFirstListener = new AnimateFirstDisplayListener();
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.mid_fragment, container, false);
initComponent(view);
mContext = container.getContext();
return view;
}
private void initComponent(View view) {
mImageView = (ImageView) view.findViewById(R.id.image);
mVideoView = (VideoView) view.findViewById(R.id.video);
mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mVideoView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
// mProgressDialog = new ProgressDialog(getActivity());
// mProgressDialog.setTitle("Please wait a moment...");
// mProgressDialog.setMessage("Loading...");
// mProgressDialog.setIndeterminate(false);
}
public void reloadData(int index){
// mProgressDialog.show();
objectList.clear();
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Data");
query.whereEqualTo("school",(Number)index);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
objectList = (ArrayList<ParseObject>) list;
// mProgressDialog.dismiss();
if (!list.isEmpty())
openFirst();
}
});
}
private void openFirst(){
ParseObject parseObject = objectList.get(0);
ParseFile parseFile = parseObject.getParseFile("file");
if (parseObject.getNumber("type") == (Number)1){
}else{
// mVideoView.setVisibility(View.GONE);
// mImageView.setVisibility(View.VISIBLE);
imageLoader.displayImage(parseFile.getUrl(), mImageView, options, animateFirstListener);
}
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
}
layout MidFragment
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<VideoView
android:id="#+id/video"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:visibility="gone" />
<ImageView
android:id="#+id/image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:contentDescription="#string/app_name" />
</RelativeLayout>
Logcat
05-28 15:41:56.116 19297-19297/animuco.com.ckemi E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: animuco.com.ckemi, PID: 19297
java.lang.IllegalArgumentException: view must not be null
at com.nostra13.universalimageloader.core.imageaware.ViewAware.<init>(ViewAware.java:70)
at com.nostra13.universalimageloader.core.imageaware.ViewAware.<init>(ViewAware.java:50)
at com.nostra13.universalimageloader.core.imageaware.ImageViewAware.<init>(ImageViewAware.java:44)
at com.nostra13.universalimageloader.core.ImageLoader.displayImage(ImageLoader.java:365)
at com.nostra13.universalimageloader.core.ImageLoader.displayImage(ImageLoader.java:340)
at animuco.com.ckemi.Fragment.MidFragment.openFirst(MidFragment.java:119)
at animuco.com.ckemi.Fragment.MidFragment.access$200(MidFragment.java:36)
at animuco.com.ckemi.Fragment.MidFragment$3.done(MidFragment.java:101)
at animuco.com.ckemi.Fragment.MidFragment$3.done(MidFragment.java:95)
at com.parse.Parse$6$1.run(Parse.java:944)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1016)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
I'm not sure but I think the error is due to update the view of viewpager
sorry for my weak english
Thanks for the interest of the people
There are a few issues with the code. IMO.
Your fragment holds a reference to its activity, you already have one call getActivity().
Left fragment holds a reference to Mid fragment - bad practice.
On your RemoteDataTask you call super.onPreExecute() at your
onPostExecute() method, its usually unimplemented but it may cause
you errors in the future.
And to answer your question. You are initilyzing a new instance of MidFragment at your left fragment which isnt attached anywhere therfore MidFragment doesnt start his lifecycle and doesnt call onCreateView(). The Midfragment that LeftFragment is using isnt the same as the one that the ViewPager is using.
I have a Fragment that contain a ListView with Adapters. I want when replace this Fragment the listview continue changing on background. To do it I create a method with a TimerTask inside a AsyncTask, because I want the ListView change to each 10 seconds. If the Fragment that contain the ListView is visible without replace its works fine, but if I make replace isn't works and throws an exception NullPointerException.
How can I solve it ?
I'm trying this.
Fragment
public class JogosAbertosFrag extends Fragment implements View.OnClickListener, AdapterView.OnItemClickListener {
private ImageButton btPerfil;
private Intent intentPerfil;
private ListView lvJogosFinalizados;
private ListView lvJogosAndamento;
protected ProgressDialog progressDialog;
private JogosListAdapter jogosListAdapterAndamento, jogosListAdapterFechado;
private TextView tvPontuacao;
private List<Batalha> listBatalhaAberto, listBatalhaFechado;
//clock
private Timer timer;
private TimerTask timerTask;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((CustomDrawerLayout)getActivity()).getSupportActionBar().show();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.jogosabertos, container, false);
lvJogosFinalizados = (ListView)rootView.findViewById(R.id.lvJogosFinalizados);
lvJogosFinalizados.setOnItemClickListener(this);
lvJogosAndamento = (ListView)rootView.findViewById(R.id.lvJogosAndamento);
lvJogosAndamento.setOnItemClickListener(this);
tvPontuacao = (TextView)rootView.findViewById(R.id.tvPontuacao);
tvPontuacao.setText(BatalhaConfigs.USUARIO_PONTUACAO);
btPerfil = (ImageButton)rootView.findViewById(R.id.btPerfil);
btPerfil.setOnClickListener(this);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
clockTask();
}
/** */
private void getAllBattles(){
ApplicationController app = new BatalhaDAO().getAllBattles(new BatalhaAdapter(){
#Override
public void getAllBattlesOpened(List<Batalha> list) {
if(!list.isEmpty()){
listBatalhaAberto = list;
if(jogosListAdapterAndamento == null){
jogosListAdapterAndamento = new JogosListAdapter(getView().getContext(), listBatalhaAberto);
lvJogosAndamento.setAdapter(jogosListAdapterAndamento);
}else{
jogosListAdapterAndamento.changeList(listBatalhaAberto);
}
}
}
#Override
public void getAllBattlesClosed(List<Batalha> list) {
if(!list.isEmpty()){
listBatalhaFechado = list;
if(jogosListAdapterFechado == null){
jogosListAdapterFechado = new JogosListAdapter(getView().getContext(), listBatalhaFechado);
lvJogosFinalizados.setAdapter(jogosListAdapterFechado);
}else{
jogosListAdapterFechado.changeList(listBatalhaFechado);
}
}
}
});
CustomVolleySingleton.getInstance(getView().getContext()).addToRequestQueue(app);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FragmentTransaction ft;
Fragment frag;
if(parent == lvJogosAndamento){
Batalha batalha = listBatalhaAberto.get(position);
Bundle params = new Bundle();
params.putSerializable("infoBatalha", batalha);
frag = new JogarComOponenteFrag();
frag.setArguments(params);
ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fl, frag);
ft.addToBackStack("back");
ft.commit();
}else if(parent == lvJogosFinalizados){
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
/** timer para atualizar o adapter */
private void clockTask(){
new AsyncTask<String, Void, String>() {
#Override
protected String doInBackground(String... params) {
timer = new Timer();
timerTask = new TimerTask() {
#Override
public void run() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
tvPontuacao.setText(BatalhaConfigs.USUARIO_PONTUACAO);
getAllBattles();
}
});
}
};
timer.scheduleAtFixedRate(timerTask, 100, 10000);
return "execute";
}
}.execute("execute");
}
#Override
public void onStop() {
super.onStop();
CustomVolleySingleton.getInstance(getView().getContext()).cancelPendingRequests(CustomVolleySingleton.TAG);
}
}
ListAdapter
public class JogosListAdapter extends BaseAdapter {
private List<Batalha> lista;
private Context context;
public JogosListAdapter(Context context, List<Batalha> list){
this.context = context;
this.lista = list;
}
#Override
public int getCount() {
return lista.size();
}
#Override
public Object getItem(int position) {
return lista.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void changeList(List<Batalha> lista){
this.lista = lista;
notifyDataSetChanged();
}
#Override
public View getView(int position, View view, ViewGroup parent) {
View layout;
if (view == null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout = inflater.inflate(R.layout.jogos_list_adapter, parent, false);
}else{
layout = view;
}
return layout;
}
Exception
FATAL EXCEPTION: main
java.lang.NullPointerException
at br.com.mypackage.myapp.frags.JogosAbertosFrag.getAllBattles(JogosAbertosFrag.java:113)
at br.com.mypackage.myapp.frags.JogosAbertosFrag.access$12(JogosAbertosFrag.java:84)
at br.com.mypackage.myapp.frags.JogosAbertosFrag$2$1$1.run(JogosAbertosFrag.java:170)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
Exception Lines
113 has -> CustomVolleySingleton.getInstance(getView().getContext()).addToRequestQueue(app);
84 has -> private void getAllBattles(){}
170 close -> private void clockTask(){
First of All, you need to assign the Anonymous Inner Type AsyncTask class to a class variable. Before doing that you need to create a nested AsyncTask class within your Activity.
Your extended AsyncTask class should look something like this :
public class MyContinousAsyncTask extends AsyncTask<String, Void, String>() {
#Override
protected String doInBackground(String... params) {
timer = new Timer();
timerTask = new TimerTask() {
#Override
public void run() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
tvPontuacao.setText(BatalhaConfigs.USUARIO_PONTUACAO);
getAllBattles();
}
});
}
};
timer.scheduleAtFixedRate(timerTask, 100, 10000);
return "execute";
}
}
Then you need to declare a class variable of this Class in your Activity:
private MyContinousAsyncTask myContinouslyRunningAsyncTask;
now after doing the above, just modify your clockTask() method like this:
/** timer para atualizar o adapter */
private void clockTask(){
myContinouslyRunningAsyncTask = new MyContinousAsyncTask();
myContinouslyRunningAsyncTask.execute("execute");
}
now you should stop this AsyncTask on the onPause() Event of your Fragment, other wise you will be getting NPE because of accessing the de-allocated UI Components.
The code should look like this:
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if(myContinouslyRunningAsyncTask != null)
{
myContinouslyRunningAsyncTask.cancel();
}
if(timer != null)
{
timer.cancel();
timer.purge();
}
}
To make your code further efficient, you should not call the clockTask(); in onActivityCreated(..) method, but in onResume() method, like this:
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
clockTask();
}
I hope this helps.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to parse an rss feed and since i'm a beginner in android i cannot find a way to do this through a fragment..
This is the activity i want to convert into a fragment
public class Clients extends Activity {
private Clients local;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
local = this;
GetRSSDataTask task = new GetRSSDataTask();
task.execute("http://www.itcuties.com/feed/");
Log.d("ITCRssReader", Thread.currentThread().getName());
}
private class GetRSSDataTask extends AsyncTask<String, Void, List<RssItem> > {
#Override
protected List<RssItem> doInBackground(String... urls) {
Log.d("ITCRssReader", Thread.currentThread().getName());
try {
RssReader rssReader = new RssReader(urls[0]);
return rssReader.getItems();
} catch (Exception e) {
Log.e("ITCRssReader", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(List<RssItem> result) {
ListView itcItems = (ListView) findViewById(R.id.listView);
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(local,android.R.layout.simple_list_item_1,result);
itcItems.setAdapter(adapter);
itcItems.setOnItemClickListener(new ListListener(result, local));
}
}
}
I already have tried to convert it but the onItemClick is getting some errors.
public void onItemClick(AdapterView parent, View view, int pos, long id) {
Intent intent = new Intent(activity, Clients.class);
intent.putExtra("description", listItems.get(pos).getLink());
activity.startActivity(intent);
}
Can someone please help me???
You should call the fragment without ui. It is needed to add ui, but not to make it visible.
public class MyFragmet extends Fragment {
public static final String TAG = "MyFragmet";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.MY_FRAGMENT_NULL_VIEW,
container, false);
local = this;
GetRSSDataTask task = new GetRSSDataTask();
task.execute("http://www.itcuties.com/feed/");
Log.d("ITCRssReader", Thread.currentThread().getName());
return view;
}
private class GetRSSDataTask extends AsyncTask<String, Void, List<RssItem> > {
#Override
protected List<RssItem> doInBackground(String... urls) {
Log.d("ITCRssReader", Thread.currentThread().getName());
try {
RssReader rssReader = new RssReader(urls[0]);
return rssReader.getItems();
} catch (Exception e) {
Log.e("ITCRssReader", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(List<RssItem> result) {
Intent intent = new Intent();
intent.setAction(TAG ); // also here you can add other information
sendBroadcast(intent);
}
}
}
and add this to activity
private BroadcastReceiver receiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ListView itcItems = (ListView) findViewById(R.id.listView);
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(local,android.R.layout.simple_list_item_1,result);
itcItems.setAdapter(adapter);
itcItems.setOnItemClickListener(new ListListener(result, local));
}
};
registerReceiver(receiver, new IntentFilter(MyFragmet.TAG));
FragmentManager fm = getFragmentManager();
Fragment fragment = fm.findFragmentByTag(MyFragmet.TAG);
if (fragment == null) {
getFragmentManager()
.beginTransaction()
.add(R.id.fragment, new MyFragmet(),MyFragmet.TAG)
.commit();
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
Ok, here's my attempt:
I've replaced your ArrayAdapter with a baseadapter (finer tuned control over what happens with your items) - define a layout similiar to the list item you have in your ArrayAdapter, point the BaseAdapter at it, and set up the views within the onCreateView block.
Other than that, I think it should drop in pretty well.
public class Clients extends Fragment implents ListView.OnItemClickListener {
private Clients local;
private ListView itcItems;
private RssItemBaseAdapter adapter;
private ArrayList<Rssitem> itemList = new ArrayList<RssItem>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
local = this;
GetRSSDataTask task = new GetRSSDataTask();
task.execute("http://www.itcuties.com/feed/");
Log.d("ITCRssReader", Thread.currentThread().getName());
}
#Override
public void onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
view rootView = infalter.inflate(R.layout.activity_my,container,false);
itcItems = (ListView)findViewById(R.id.listView);
itcItems.setOnItemClickListener(this);
adapter = new RssItemBaseAdapter(getActivity(),itemList);
itcItems.setAdapter(adapter);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i , long l){
RssItem item = adapter.getItem(i);
<Handle your Intent code here>
}
private class GetRSSDataTask extends AsyncTask<String, Void, List<RssItem> > {
#Override
protected List<RssItem> doInBackground(String... urls) {
Log.d("ITCRssReader", Thread.currentThread().getName());
try {
RssReader rssReader = new RssReader(urls[0]);
return rssReader.getItems();
} catch (Exception e) {
Log.e("ITCRssReader", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(List<RssItem> result) {
itemList = result;
adapter.swapList(itemList);
adapter.notifyDataSetChanged();
}
}
private class RssItemBaseAdapter extends BaseAdapter(){
private Context mContext;
private ArrayList<RssItem> mRssList;
public RssItemBaseAdapter(Context context, ArrayList<RssItem> obj){
mContext = context;
mRssList = obj;
}
#Override
public int getCount() {return mRssList.size(); }
#Override
public RssItem getItem(int i) {return mRssList.get(i); }
#Override
public long getItemId(int i) { return i }
#Override
public view getView(int i, View convertView, ViewGroup parent){
View rootView = convertView;
if (rootView == null){
View rootView = Inflater.from(mContext).inflate(R.layout.YOUR_SIMPLE_LAYOUT_HERE,parent,false);
}
<do your view setting here>
return rootView;
}
public ArrayList<RssItem> swapList (ArrayList<RssItem> newList){
ArrayList<RssItem> oldList = mRssList;
mRssList = newList;
return oldList;
}
}
}