The App opens up fine with the First Fragment being displayed correctly. On swipe, next fragment layout comes on the screen. There, on clicking the button, the app crashes.
The error that I get is:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
Some of the top entries from error stack are as follows:
at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:401)
at android.widget.ArrayAdapter.getView(ArrayAdapter.java:369)
at android.widget.AbsListView.obtainView(AbsListView.java:2346)
at android.widget.ListView.makeAndAddView(ListView.java:1876)
at android.widget.ListView.fillDown(ListView.java:702)
at android.widget.ListView.fillFromTop(ListView.java:763)
at android.widget.ListView.layoutChildren(ListView.java:1685)
at android.widget.AbsListView.onLayout(AbsListView.java:2148)
at android.view.View.layout(View.java:16636)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
The app's main activity is as follows:
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
default: return FirstFragment.newInstance("FirstFragment, Default");
}
}
}
}
SecondFragment.java is as follows:
public class SecondFragment extends ListFragment {
static public ArrayAdapter<String> adapter;
static String[] values = new String[3];
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.second_frag, container,
false);
final Button btn = (Button) rootView.findViewById(R.id.readWebpage);
if (btn != null) {
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
new HttpGetReq().execute("http://xxx.xxx.xxx.xxx");
adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
});
}
return rootView;
}
public static SecondFragment newInstance(String text) {
SecondFragment f = new SecondFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
On button click, HttpGetReq.java worker class gets data from the server and displays that to the list.
public class HttpGetReq extends AsyncTask<String , Void ,String> {
String server_response;
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
server_response = readStream(urlConnection.getInputStream());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.i("TAG", "Assigning new value");
SecondFragment.values[1] = server_response;
}
// Converting InputStream to String
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
}
second_Frag.xml is as follows:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/myView2">>
<Button
android:id="#+id/readWebpage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="Refresh"
android:layout_gravity="center_horizontal">
</Button>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#id/android:list"
android:background="#color/background_Color"
android:layout_width="fill_parent"
android:gravity="center"
android:layout_height="fill_parent"/>
</LinearLayout>
new HttpGetReq().execute("http://xxx.xxx.xxx.xxx");
adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
Here, you're setting adapter before getting the data from HttpGetReq. Since HttpGetReq is an AsyncTask so it executes the line right after you call execute, remaining your value array empty. You should set the data in adapter after you get the data from onPostExecute of your HttpGetReq.
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.i("TAG", "Assigning new value");
SecondFragment.values[1] = server_response;
// Set your data here
}
Related
I have a gallery of images that shows the images in a recyclerviewusing glide and by clicking on each image in the recyclerview that image open in a view pager. every thing is ok in the beginning the recyclerview is fine, the images open in a viewpager and sliding in viewpager are all fine. but when i press back to close the viewpager and goback to recyclerview suddenly the allocated memory raises to about 400 MB!!!
there are 8 images that are about 490*420 pixel and 72 KB size.
MainGallery.xml
<android.support.v7.widget.RecyclerView
android:id="#+id/recView_Gallery1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
>
</android.support.v7.widget.RecyclerView>
<Button
android:id="#+id/btn_retry_Gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="تلاش مجدد"
android:textSize="16sp"
android:visibility="gone"
android:layout_gravity="center"
android:gravity="center"/>
</android.support.design.widget.CoordinatorLayout>
GalleryEnter.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent">
<ImageView
android:id="#+id/iv_photoGallety"
android:adjustViewBounds="true"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:layout_margin="2dp"
android:layout_width="match_parent"
android:background="#android:color/white"/>
</LinearLayout>
ImageDetail.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorAccent"
tools:context="com.parsroyan.restaurant.imageDetailActivity">
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.design.widget.CoordinatorLayout>
MainGalleryActivity.java
public class GalleryMain_Activity extends AppCompatActivity {
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
public static RecyclerView recListMenuTypes;
public static ImageAdapter mta;
ArrayList<ImageGallery> data = new ArrayList<>();
Button btn_retry;
TextView tv_message;
ImageView imv_message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery_main_);
btn_retry = (Button) findViewById(R.id.btn_retry_Gallery);
recListMenuTypes = (RecyclerView) findViewById(R.id.recView_Gallery1)
;
recListMenuTypes.setHasFixedSize(true);
GridLayoutManager mLayoutManager = new
GridLayoutManager(GalleryMain_Activity.this, 2);
recListMenuTypes.setLayoutManager(mLayoutManager);
//LinearLayoutManager llm = new
LinearLayoutManager(GalleryMain_Activity.this);
//llm.setOrientation(LinearLayoutManager.VERTICAL);
//recListMenuTypes.setLayoutManager(llm);
recListMenuTypes.setItemAnimator(new DefaultItemAnimator());
mta = new ImageAdapter(GalleryMain_Activity.this, data);
recListMenuTypes.setAdapter(mta);
Check_Connection_Retrive();
btn_retry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Check_Connection_Retrive();
}
});
}
private void alertView1(String message,boolean success) {
final TypedArray styledAttributes =
GalleryMain_Activity.this.getTheme().obtainStyledAttributes(new int[] {
android.R.attr.actionBarSize });
int Y = (int) styledAttributes.getDimension(0, 0);
styledAttributes.recycle();
LayoutInflater inflater = getLayoutInflater();
View toastLayout = inflater.inflate(R.layout.custom_toast,
(ViewGroup)
findViewById(R.id.custom_toast_layout));
tv_message = (TextView)
toastLayout.findViewById(R.id.custom_toast_message);
tv_message.setText(message);
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP | Gravity.START |
Gravity.FILL_HORIZONTAL,0,Y);
toast.setView(toastLayout);
imv_message = (ImageView)
toastLayout.findViewById(R.id.custom_toast_image);
if(!success){
toastLayout.setBackgroundColor(Color.parseColor("#cc0000"));
imv_message.setBackgroundResource(android.R.drawable.ic_dialog_alert);
}
else {
imv_message.setBackgroundResource(android.R.drawable.ic_dialog_info);
}
toastLayout.setAlpha(.8f);
toast.show();
}
public void Check_Connection_Retrive()
{
if(InternetConnection.checkConnection(getApplicationContext(),this))
{
btn_retry.setVisibility(View.GONE);
new FetchGallery().execute();
}
else
{
btn_retry.setVisibility(View.VISIBLE);
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
private class FetchGallery extends AsyncTask<String, String, String> {
TransparentProgressDialog pdLoading = new
TransparentProgressDialog
(GalleryMain_Activity.this,R.drawable.progress_circle);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {`enter code here`
super.onPreExecute();
//pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
//pdLoading.setProgress(10);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
url = new URL("My_URL");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "1";
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return "2";
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return "3";
}
} catch (IOException e) {
return "4";
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
switch(result) {
case "1":
break;
case "2":
break;
case "3":
break;
case "4":
break;
default:
try {
btn_retry.setVisibility(View.GONE);
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
//JSONObject json_data = jArray.getJSONObject(i);
ImageGallery image = new ImageGallery();
//image.name = json_data.getString("name");
image.title = jArray.get(i).toString();
image.url = "MY_URL" + image.title;
data.add(image);
}
// Setup and Handover data to recyclerview
mta.notifyDataSetChanged();
recListMenuTypes.addOnItemTouchListener(new
RecyclerViewTouchListener(getApplicationContext(), recListMenuTypes, new
RecyclerViewClickListener() {
#Override
public void onClick(View view, int position) {
Intent intent = new Intent(GalleryMain_Activity.this,
imageDetailActivity.class);
intent.putParcelableArrayListExtra("data", data);
intent.putExtra("pos", position);
startActivity(intent);
}
#Override
public void onLongClick(View view, int position){
}
}));
} catch (JSONException e) {
Toast.makeText(GalleryMain_Activity.this,
e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
}
ImageAdapter.java
public class ImageAdapter extends
RecyclerView.Adapter<ImageAdapter.MenuViewHolder> {
private List<ImageGallery> imageGalleryList;
private Context context;
protected int lastPosition = -1;
public ImageAdapter(Context Context,List<ImageGallery> contactList)
{
this.imageGalleryList = contactList;
this.context = Context;
}
#Override
public int getItemCount() {
return imageGalleryList.size();
}
#Override
public void onBindViewHolder(ImageAdapter.MenuViewHolder menuViewHolder,
int i) {
final ImageGallery m = imageGalleryList.get(i);
Glide.with(context).load("MyURL"+m.title)
.thumbnail(.1f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.override(200,200).placeholder(R.drawable.logoback)
.into(menuViewHolder.vImage);
setFadeAnimation(menuViewHolder,i);
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
public ImageAdapter.MenuViewHolder onCreateViewHolder(ViewGroup
viewGroup, int i) {
final View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.activity_gallery_enter, viewGroup, false);
return new ImageAdapter.MenuViewHolder(itemView);
}
#Override
public void onViewDetachedFromWindow(ImageAdapter.MenuViewHolder holder)
{
((ImageAdapter.MenuViewHolder)holder).itemView.clearAnimation();
}
public class MenuViewHolder extends RecyclerView.ViewHolder{
protected ImageView vImage;
public MenuViewHolder(View v) {
super(v);
vImage = (ImageView) v.findViewById(R.id.iv_photoGallety);
}
}
private void setFadeAnimation(ImageAdapter.MenuViewHolder view, int
position) {
if (position > lastPosition) {
AlphaAnimation anim = new AlphaAnimation(0.0f, 2.0f);
anim.setDuration(1000);
view.itemView.startAnimation(anim);
lastPosition = position;
}
}
}
ImageDetailActivity.java
public class imageDetailActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
public ArrayList<ImageGallery> data = new ArrayList<>();
int pos;
Toolbar aboveToolbar;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_detail);
//aboveToolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.detail_toolbar);
//setSupportActionBar(aboveToolbar);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
data = getIntent().getParcelableArrayListExtra("data");
pos = getIntent().getIntExtra("pos", 0);
setTitle(data.get(pos).getName());
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), data);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setPageTransformer(true, new DepthPageTransformer());
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setCurrentItem(pos);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
//noinspection ConstantConditions
setTitle(data.get(position).getName());
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public ArrayList<ImageGallery> data = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm, ArrayList<ImageGallery> data) {
super(fm);
this.data = data;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position, data.get(position).getName(), data.get(position).getUrl());
}
#Override
public int getCount() {
// Show 3 total pages.
return data.size();
}
// #Override
//public CharSequence getPageTitle(int position) {
//return data.get(position).getName();
// }
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
String name, url;
ImageView ImageView;
int pos;
private static final String ARG_SECTION_NUMBER = "section_number";
//private static final String ARG_IMG_TITLE = "image_title";
private static final String ARG_IMG_URL = "image_url";
#Override
public void setArguments(Bundle args) {
super.setArguments(args);
this.pos = args.getInt(ARG_SECTION_NUMBER);
//this.name = args.getString(ARG_IMG_TITLE);
this.url = args.getString(ARG_IMG_URL);
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber, String name, String url) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
//args.putString(ARG_IMG_TITLE, name);
args.putString(ARG_IMG_URL, url);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_image_detail, container, false);
this.ImageView = (ImageView) rootView.findViewById(R.id.detail_image);
Glide.with(getActivity()).load(url).thumbnail(0.1f).crossFade()
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.override(200,200).placeholder(R.drawable.tiara3)
.into(this.ImageView);
return rootView;
}
}
}
error log:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.OutOfMemoryError
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:501)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:354)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:785)
at android.content.res.Resources.loadDrawable(Resources.java:1970)
at android.content.res.Resources.getDrawable(Resources.java:660)
at com.bumptech.glide.request.GenericRequest.getPlaceholderDrawable(GenericRequest.java:416)
at com.bumptech.glide.request.GenericRequest.clear(GenericRequest.java:323)
at com.bumptech.glide.request.ThumbnailRequestCoordinator.clear(ThumbnailRequestCoordinator.java:106)
at com.bumptech.glide.manager.RequestTracker.clearRequests(RequestTracker.java:94)
at com.bumptech.glide.RequestManager.onDestroy(RequestManager.java:221)
at com.bumptech.glide.manager.ActivityFragmentLifecycle.onDestroy(ActivityFragmentLifecycle.java:64)
at com.bumptech.glide.manager.SupportRequestManagerFragment.onDestroy(SupportRequestManagerFragment.java:147)
at android.support.v4.app.Fragment.performDestroy(Fragment.java:2322)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1240)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1290)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1272)
at android.support.v4.app.FragmentManagerImpl.dispatchDestroy(FragmentManager.java:2186)
at android.support.v4.app.FragmentController.dispatchDestroy(FragmentController.java:271)
at android.support.v4.app.FragmentActivity.onDestroy(FragmentActivity.java:388)
at android.support.v7.app.AppCompatActivity.onDestroy(AppCompatActivity.java:209)
at android.app.Activity.performDestroy(Activity.java:5273)
at android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1110)
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3438)
at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3469)
at android.app.ActivityThread.access$1200(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1287)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
real device result:
enter image description here
smulator result:
enter image description here
Add below line in Application tag in Menifest file:
android:largeHeap="true"
In my application I'm using pageviewer with two tabs. In each tab I populate view with some data after calling aysnctask. Also the fragment which contains these tab and viewpager have filter in it which filter the content of my view accordingly. Also I'm using Recycleview for populating data. On click of item of recycleview I open new fragment. The problem I'm facing is that when app is open first time , after data when I open my fragment on click events using getsupportFragmentmanager it working fine But when I change my data content using filter, when I click on item to open fragment using getsupportFragmentmanager it gives me following error.
java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.v4.app.FragmentManager android.support.v4.app.FragmentActivity.getSupportFragmentManager()' on a null object reference
ParentFragment code is here :
public class TabB extends Fragment {
ViewPager viewPager;
TabLayout tabLayout;
Clubs clubs = new Clubs();
Events events = new Events();
private static RecyclerView Genre;
private RecyclerView.LayoutManager mLayoutManager;
public static JSONArray jsonArrayResult = new JSONArray();
public static final String[] IMAGE_NAME = {"allevent", "rock", "jazz", "house", "bass", "chill","bollywood","commerial", "karaoke","sufi"};
ArrayList<Integer> arrayList = new ArrayList<>();
public static String Genrename = IMAGE_NAME[0];
public static GenreAdapter genreAdapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View RootView = inflater.inflate(R.layout.tabb, container, false);
viewPager = (ViewPager) RootView.findViewById(R.id.viewpager);
tabLayout = (TabLayout) RootView.findViewById(R.id.tabs);
Genre = (RecyclerView)RootView.findViewById(R.id.rvImages);
for (int i=0;i< IMAGE_NAME.length;i++){
String imageFileName = IMAGE_NAME[i];
int imgResId = getResources().getIdentifier(imageFileName, "drawable", "in.catalystapp.catalyst");
arrayList.add(imgResId);
}
mLayoutManager = new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL, false);
Genre.setLayoutManager(mLayoutManager);
genreAdapter = new GenreAdapter(arrayList, getActivity());
Genre.setAdapter(genreAdapter);
TabBviewPagerAdapter tabBviewPagerAdapter = new TabBviewPagerAdapter(getChildFragmentManager(),"allevent");
viewPager.setAdapter(tabBviewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
genreAdapter.SetOnItemClickListener(new GenreAdapter.OnItemClickListener() {
#Override
public void OnItemClick(View view, int position) {
FilterGenres( IMAGE_NAME[position], new PageviewCaller() {
#Override
public void PopulatePageViewer(String key) {
Log.d("key", key);
clubs.PopulateClubList(key);
events.FilterEvents(key);
}
});
}
});
return RootView;
}
#Override
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public void FilterGenres(String key,PageviewCaller pageviewCaller){
pageviewCaller.PopulatePageViewer(key);
}
one of child frgament code is here :
public class Clubs extends Fragment {
static ArrayList<ClubItem> mClubItems = new ArrayList<>();
static RecyclerView Clubcards;
static RecyclerView.LayoutManager layoutManager;
static ClubsAdapter clubsAdapter;
static Context context;
public String mKey;
Parcelable liststate;
static JSONArray jsonClubs = new JSONArray();
public Clubs(){}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View RootView = inflater.inflate(R.layout.clubs, container, false);
Log.d("clubs-life-cycle","oncreate");
Clubcards = (RecyclerView)RootView.findViewById(R.id.clubcard);
context = getActivity();
Bundle args = getArguments();
mKey = args.getString("key");
new GetClubDetails().execute();
return RootView;
}
#Override
public void onPause() {
Log.d("liststate", "saving listview state # onPause");
liststate = layoutManager.onSaveInstanceState();
super.onPause();
}
#Override
public void onResume(){
super.onResume();
if (liststate != null){
layoutManager.onRestoreInstanceState(liststate);
} else {
}
}
public class GetClubDetails extends AsyncTask<String,Void,Void> {
JSONObject jsonresult = new JSONObject();
ProgressDialog progressDialog = new ProgressDialog(getActivity());
#Override
protected void onPreExecute(){
super.onPreExecute();
progressDialog.setMessage("Fetching Feeds....");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(String... params) {
RESTfulAPI resTfulAPI = new RESTfulAPI();
jsonresult = resTfulAPI.getJSONfromurl("api/clubs/","GET","");
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
progressDialog.dismiss();
super.onPostExecute(aVoid);
if (jsonresult!=null){
Log.d("json", jsonresult.toString());
try {
jsonClubs = jsonresult.getJSONArray("datasets");
PopulateClubList("allevent");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
}
}
}
#Override
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public void PopulateClubList(String key){
mClubItems = new ArrayList<>();
clubsAdapter = null;
for (int i=0;i < jsonClubs.length();i++){
try {
if (key.equals("allevent") || key.equals(jsonClubs.getJSONObject(i).getString("genre")) ){
mClubItems.add(new ClubItem(jsonClubs.getJSONObject(i).getString("clubName"),jsonClubs.getJSONObject(i).getString("address")));
clubsAdapter = new ClubsAdapter(mClubItems,context);
layoutManager = new LinearLayoutManager(context);
Clubcards.setLayoutManager(layoutManager);
Clubcards.setAdapter(clubsAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
clubsAdapter.SetOnItemClickListener(new ClubsAdapter.OnItemClickListener() {
#Override
public void OnItemClick(View view, int position) {
getActivity().getSupportFragmentManager().beginTransaction().setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out).add(R.id.main_content, new Clubdetails()).addToBackStack(null).commit();
}
});
}
What I'm Doing Wrong?
This May cause Because You are Importing different version of Fragment.
Because there are two types of Fragment.
1 android.support.v4.app.Fragment
and
2 android.app.Fragment;
Make sure you're importing the same Fragment in each Fragmnet class or Activities.
Could you try to use getFragmentManager() instead of getSupportFragmentManager() ?
Maybe it due to your version of appcompat library
I am trying to set a string to a textview but everytime i click the button Quiz the activity is just refreshing instead going to fragment activity.
This summarize the situation.
I have dynamic viewPager inside activity called Quiz_Container
Use only one fragment(Module_Topics_Content_Quiz) in public Fragment getItem(int position) or FragmentStatePagerAdapter.
I want to change text of a textview in the fragment from activity everytime i swipe.
I am passing the string using newInstance with parameter from activity to fragment
The string came from quizQuestion.get(position)
I'm getting the right value with the Log.d but when setting it to textview the activity is just refreshing.
this is my code.
Quiz_Container.java
public class Quiz_Container extends AppCompatActivity implements Module_Topics_Content_Quiz.OnFragmentInteractionListener {
android.support.v7.app.ActionBar actionBar;
ViewPager quizPager;
private int topicID;
private int moduleID;
private int subModuleID;
private ArrayList<Integer> quizID;
private ArrayList<String> quizQuestion;
private ArrayList<String> choiceA;
private ArrayList<String> choiceB;
private ArrayList<String> choiceC;
private ArrayList<String> choiceD;
private ArrayList<String> quizAnswer;
private FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz__container);
actionBar = getSupportActionBar();
actionBar.setTitle("Quiz");
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#f1ad1e")));
Bundle extras = getIntent().getExtras();
topicID = extras.getInt("topicID");
moduleID = extras.getInt("moduleID");
subModuleID = extras.getInt("subModuleID");
Log.d("quizTopicID", "" + topicID);
Log.d("quizModuleID", "" + moduleID);
Log.d("quizSubModuleID", "" + subModuleID);
new quizTask().execute();
}
#Override
public void onFragmentInteraction(Uri uri) {
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
} // Check Internet Connection
class quizTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
BufferedReader reader = null;
try {
URL quizURL = new URL("http://192.168.1.110/science/index.php/users/get_quiz_items/" + topicID + "/" + moduleID + "/" + subModuleID + "" );
HttpURLConnection con = (HttpURLConnection)quizURL.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String quizResponse;
while ((quizResponse = reader.readLine()) != null) {
return quizResponse;
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
if(reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}
#Override
protected void onPostExecute(String quizResponses) {
Log.d("quizResponse", "" + quizResponses);
try {
JSONObject quizObject = new JSONObject(quizResponses);
boolean result = quizObject.getBoolean("success");
if (result) {
JSONArray quizArray = quizObject.getJSONArray("data");
quizID = new ArrayList<>();
quizQuestion = new ArrayList<>();
choiceA = new ArrayList<>();
choiceB = new ArrayList<>();
choiceC = new ArrayList<>();
choiceD = new ArrayList<>();
quizAnswer = new ArrayList<>();
for (int i = 0; i < quizArray.length(); i ++) {
JSONObject dataQuiz = quizArray.getJSONObject(i);
quizID.add(dataQuiz.getInt("id"));
quizQuestion.add(dataQuiz.getString("question"));
choiceA.add(dataQuiz.getString("a"));
choiceB.add(dataQuiz.getString("b"));
choiceC.add(dataQuiz.getString("c"));
choiceD.add(dataQuiz.getString("d"));
quizAnswer.add(dataQuiz.getString("answer"));
}
Log.d("quizSize", "" + quizID.size());
quizPager = (ViewPager) findViewById(R.id.quizPager);
fragmentManager = Quiz_Container.this.getSupportFragmentManager();
quizPager.setAdapter(new quizAdapter(getSupportFragmentManager()));
quizPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
else {
Toast.makeText(getApplication(), "no quiz yet", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} // end of quizTask
class quizAdapter extends FragmentStatePagerAdapter {
public quizAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
for (int i = 0; i < quizID.size; i++) {
if (i == position) {
fragment = Module_Topics_Content_Quiz.newInstance(quizQuestion.get(position));
Log.d("testQuestion", "" + quizQuestion.get(position)); // this code is working
}
}
return fragment;
}
#Override
public int getCount() {
return quizID.size();
}
}
}
Module_Topics_Content_Quiz.java
public class Module_Topics_Content_Quiz extends Fragment {
TextView textQuizQuestion;
private String qQuestion;
public Module_Topics_Content_Quiz() {
// Required empty public constructor
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
public static Module_Topics_Content_Quiz newInstance(String question) {
Module_Topics_Content_Quiz fragment = new Module_Topics_Content_Quiz();
Bundle args = new Bundle();
args.putString("question", question);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
qQuestion = getArguments().getString("question");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_module__topics__content__quiz, container, false);
textQuizQuestion = (TextView) getActivity().findViewById(R.id.textQuestion);
Log.d("question", "" + qQuestion); // this is working
// textQuizQuestion.setText(qQuestion); // error if enable
return rootView;
}
}
Please help. Thank you.
In your fragment, try inflating the TextView using the View returned rather than using getActivity()
You need to inflate the Fragment's view and call findViewById() on the View it returns.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_module__topics__content__quiz, container, false);
// inflate the View inside Fragment using the View returned
textQuizQuestion = (TextView) rootView.findViewById(R.id.textQuestion);
Log.d("question", "" + qQuestion); // this is working
textQuizQuestion.setText(qQuestion);
return rootView;
}
You can also use getView() from within the Fragment to get the root view.
If you wanna call from the enclosing Activity, use
getFragmentManager().findFragmentById(R.id.your_fragment_id).getView().findViewById(R.id.your_view);
I am using this Tutorial and its sourcecodes to make listview in android. I had implemented using this tutorial but during updating the setListAdapter i cannot update the listview dynamically.
I have gone through many stackoverflow questions and they are giving adapter.notifyDataSetChanged() as the solution. But i am unable to implement it in AsyncTask.
ItemListFragment.java
public class ItemListFragment extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = super.onCreateView(inflater, container, savedInstanceState);
setListAdapter(new ItemAdapter(getActivity(), setArray(getActivity())));
return v;
}
public ArrayList<Item> setArray(Context context)
{
ArrayList<Item> items = new ArrayList<Item>();
Realm realm = Realm.getInstance(context);
RealmResults<Books> bs = realm.where(Books.class).findAll();
for (int i = 0; i < bs.size(); i++) {
Bitmap url = BitmapFactory.decodeFile(bs.get(i).getCover());
String title = bs.get(i).getName();
String description = bs.get(i).getAuthor();
Item item = new Item(url, title, description);
items.add(item);
}
realm.close();
return items;
}
}
ItemAdapter.java
public class ItemAdapter extends ArrayAdapter<Item> {
public ItemAdapter(Context context, List<Item> items) {
super(context, 0, items);
}
public View getView(int position, View convertView, ViewGroup parent)
{
ItemView itemView = (ItemView) convertView;
if (null == itemView)
{
itemView = ItemView.inflate(parent);
}
itemView.setItem(getItem(position));
return itemView;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
if (BuildConfig.DEBUG)
ViewServer.get(this).addWindow(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
else if (id == R.id.update) {
Update update = new Update(getApplicationContext(), MainActivity.this);
update.execute();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (BuildConfig.DEBUG)
ViewServer.get(this).removeWindow(this);
}
#Override
protected void onResume() {
super.onResume();
if (BuildConfig.DEBUG)
ViewServer.get(this).setFocusedWindow(this);
}
}
Update.java
public class Update extends AsyncTask<Void,Void,Void>{
private Context context;
public Activity activity;
public Update(Context context, Activity activity)
{
this.context = context;
this.activity = activity;
}
#Override
protected Void doInBackground(Void... params) {
ServerAddress = context.getString(R.string.ServerAddress);
StringExtras = context.getString(R.string.CheckBook);
Realm realm = null;
try {
URL url = new URL(ServerAddress + StringExtras);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("Content-length", "0");
httpURLConnection.setUseCaches(false);
httpURLConnection.setAllowUserInteraction(false);
httpURLConnection.setConnectTimeout(1000);
httpURLConnection.setReadTimeout(1000);
httpURLConnection.connect();
int responseCode = httpURLConnection.getResponseCode();
Log.i("Response Code",responseCode+"");
BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String InputLine;
StringBuilder response = new StringBuilder();
while ((InputLine = br.readLine()) != null)
{
response.append(InputLine);
}
br.close();
httpURLConnection.disconnect();
Log.i("Response Data", response.toString());
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
JSONArray array = new JSONArray(response.toString());
//booksList = Arrays.asList(books);
//JSONArray jsonArray = object.getJSONArray("cover");
realm = Realm.getInstance(context);
for (int i=0; i< array.length(); i++ ) {
JSONObject object = array.getJSONObject(i);
Books books = gson.fromJson(object.toString(), Books.class);
Publish(books, realm);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (realm != null){
realm.close();
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//i want to call the setarray that contains my database data which has been updated on `doinbackground` and update the listview accordingly.
//The below codes are just the codes that i have tried but what should i do to update the listview.
activity.runOnUiThread(new Runnable() {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void run() {
ItemListFragment activity1 = new ItemListFragment();
ArrayList<Item> arrayList = activity1.setArray(context);
List<Item> list = new ArrayList<Item>();
int i = 0;
for (Item item : arrayList)
{
list.add(arrayList.get(i));
i++;
}
activity1.arrayAdapter.addAll(list);
activity1.arrayAdapter.notifyDataSetChanged();
}
});
}
I am trying to update the listview from postexcution. So, how can i update the view through it.
Error From AsyncTask
just incase you need but it's not the problem
8-30 16:31:47.976 1167-1167/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at np.com.thefourthgeneration.Update$1.run(Update.java:124)
at android.app.Activity.runOnUiThread(Activity.java:4673)
at np.com.thefourthgeneration.Update.onPostExecute(Update.java:108)
at np.com.thefourthgeneration.Update.onPostExecute(Update.java:34)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
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:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
layout/activity_list
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
layout/list_fragment
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
MainActivity
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
FragmentManager fm = getFragmentManager();
itemListFragment = (ItemListFragment) fm.findFragmentByTag(ItemListFragment.class.getSimpleName());
if (itemListFragment == null) {
itemListFragment = new ItemListFragment();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, itemListFragment, ItemListFragment.class.getSimpleName());
fragmentTransaction.commit();
}
if (BuildConfig.DEBUG) {
ViewServer.get(this).addWindow(this);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (BuildConfig.DEBUG) {
ViewServer.get(this).removeWindow(this);
}
}
#Override
protected void onResume() {
super.onResume();
if (BuildConfig.DEBUG) {
ViewServer.get(this).setFocusedWindow(this);
}
}
}
ItemListFragment
public class ItemListFragment extends Fragment
{
private ListView listView;
private ItemAdapter itemAdapter;
private ArrayList<Item> itemArrayList = new ArrayList<>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_fragment, container, false);
itemAdapter = new ItemAdapter(getActivity(), itemArrayList);
listView = (ListView) view.findViewById(R.id.listView);
listView.setAdapter(itemAdapter);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
return true;
case R.id.update:
new Update(getActivity()).execute();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public class Update extends AsyncTask<Void, Void, Void>
{
private Context context;
public Update(Context context) {
this.context = context;
}
#Override
protected Void doInBackground(Void... params) {
ServerAddress = context.getString(R.string.ServerAddress);
StringExtras = context.getString(R.string.CheckBook);
Realm realm = null;
try {
URL url = new URL(ServerAddress + StringExtras);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("Content-length", "0");
httpURLConnection.setUseCaches(false);
httpURLConnection.setAllowUserInteraction(false);
httpURLConnection.setConnectTimeout(1000);
httpURLConnection.setReadTimeout(1000);
httpURLConnection.connect();
int responseCode = httpURLConnection.getResponseCode();
Log.i("Response Code", responseCode + "");
BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String InputLine;
StringBuilder response = new StringBuilder();
while ((InputLine = br.readLine()) != null) {
response.append(InputLine);
}
br.close();
httpURLConnection.disconnect();
Log.i("Response Data", response.toString());
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
JSONArray array = new JSONArray(response.toString());
//booksList = Arrays.asList(books);
//JSONArray jsonArray = object.getJSONArray("cover");
realm = Realm.getInstance(context);
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
Books books = gson.fromJson(object.toString(), Books.class);
Publish(books, realm);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (realm != null) {
realm.close();
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
itemArrayList.clear();
itemArrayList.addAll(getArray(context));
itemAdapter.notifyDataSetChanged();
}
public ArrayList<Item> getArray(Context context) {
ArrayList<Item> items = new ArrayList<Item>();
Realm realm = Realm.getInstance(context);
RealmResults<Books> bs = realm.where(Books.class).findAll();
for (int i = 0; i < bs.size(); i++) {
Bitmap url = BitmapFactory.decodeFile(bs.get(i).getCover());
String title = bs.get(i).getName();
String description = bs.get(i).getAuthor();
Item item = new Item(url, title, description);
items.add(item);
}
realm.close();
return items;
}
}
public class ItemAdapter extends ArrayAdapter<Item>
{
public ItemAdapter(Context context, List<Item> items) {
super(context, 0, items);
}
public View getView(int position, View convertView, ViewGroup parent) {
ItemView itemView = (ItemView) convertView;
if (null == itemView) {
itemView = ItemView.inflate(parent);
}
itemView.setItem(getItem(position));
return itemView;
}
}
}
Its not the 100% work code, because i dont fully understand all structures (like Realm) and I dont test it, but its the main idea.
i'm new on android developing and i have to learn much much more. I have an activity that uses fragments. Opening main activity, it shows 3 fragments and using json i have created an Array that contains an ID and a Name. I haven't understood yet, how to put my array data in a gridview and then how use it on a fragment. Can someone help me? Here my MainActivity
public class MainActivity extends AppCompatActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
String myJSON;
private ProgressDialog pDialog;
private static final String TAG_RESULTS = "result";
private static final String TAG_ID = "ID";
private static final String TAG_NAME = "Nome";
JSONArray serv_man = null;
ArrayList<HashMap<String, String>> tableList = new ArrayList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getData();
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
}
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
serv_man = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<serv_man.length();i++){
JSONObject c = serv_man.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,name);
persons.put(TAG_ID, id);
tableList.add(persons);
}
// Here i should create view but i don't know how yet
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://mysite/get_collab.php");
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
Log.d("Log_Tag","xxx" + result);
// Here i can see that result is ok
} catch (Exception e) {
// Oops
Log.e("log_tag", "Error converting result " + e.toString());
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Obtaining list...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected void onPostExecute(String result){
pDialog.dismiss();
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new PpFragment();
break;
case 1:
fragment = new ScndFragment();
break;
case 2:
fragment = new thrdFragment();
}
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
}
// I should want to create a view with a gridview that shows Name and eventually a standard picture like a card view but probably it's really too much for me. I can only hope in your help.
Thanks
I haven't understood yet, how to put my array data in a gridview and
then how use it on a fragment.
To fill GridView with the data use Adapter. Official documantation describes what kind of adapter should you use for GridView and you can find many examples of adapters in the web.
If you want your Grid to be presented on fragment, rather on Activity itself, put Grid to Fragment, rather than Activity. It's the only difference.
For education purpose I advise you to fill Grid view in Activity (put it to layout xml) and add fragments later.
In my opinion, you can put your gridview and your http request in one fragment, such as PpFragment. And then you can init your gridview by using the data you get from the internet.
Here is the gridview adapter:
Part1:
private class ImageAdapter extends BaseAdapter{
public ImageAdapter() {
}
#Override
public int getCount() {
return tableList.size();
}
#Override
public Object getItem(int position) {
return tableList.get(position); //tableList is your data source
}
#Override
public long getItemId(int position) {
return 0;
}
class ViewHolder {
TextView name;
TextView id;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView==null){
//layout.item is your item layout of your gridview
convertView = getLayoutInflater().inflate(R.layout.item, null);
holder = new ViewHolder();
holder.name = (TextView)convertView.findViewById(R.id.name);
holder.id = (ImageView)convertView.findViewById(R.id.id);
//name and id is your view of your gridview item, for the ID and NAME
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(tableList.get(position).get("aaaa"));
holder.id.setText(tableList.get(position).get("xxxx"));
//Here you can assign values to your TextView with the value you get from the data source.
return convertView;
}
}
You can init your gridview below:
Part2:
//view is your layout of one fragment,such as PpFragment.
GridView gridView = (GridView)view.findViewById(R.id.gridviewss);
ImageAdapter imageAdapter = new ImageAdapter();
gridView.setAdapter(imageAdapter);
the gridview layout xml:
Part3: R.id.gridviewss:
<GridView
android:id="#+id/gridviewss"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="3"
android:horizontalSpacing="2dp"
android:verticalSpacing="7.5dp"
android:stretchMode="columnWidth"
android:gravity="center"
android:background="#F1F1F1"
android:paddingLeft="11.5dp"
android:paddingRight="11.5dp"
android:paddingTop="11.5dp"
>
</GridView>
You can start your http request(the getData() method you pasted above) in the fragment method, such as onCreateView of your fragment PpFragment, and then you can init your adapter with Part2 code when you get the data from the host(After you invoke the method showList()).
I hope this could be helpful.
Part4:
R.layout.frag_uno_item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/id"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/name"
/>
</LinearLayout>
And then Fragment_Uno.java:
package com.example.stackproject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
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.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
public class Fragment_Uno extends Fragment {
String myJSON;
private ProgressDialog pDialog;
private static final String TAG_RESULTS = "result";
private static final String TAG_ID = "ID";
private static final String TAG_NAME = "Nome";
JSONArray serv_man = null;
ArrayList<HashMap<String, String>> tableList = new ArrayList<HashMap<String, String>>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_uno, container, false);
getData();
return view;
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
serv_man = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<serv_man.length();i++){
JSONObject c = serv_man.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,name);
persons.put(TAG_ID, id);
tableList.add(persons);
}
View view = getActivity().getLayoutInflater().inflate(R.layout.frag_uno, null);
GridView gridView = (GridView) view.findViewById(R.id.gridView2);
ImageAdapter imageAdapter = new ImageAdapter();
gridView.setAdapter(imageAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://etc.collab.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
Log.d("Log_Tag", "xxx" + result);
//view is your layout of one fragment,such as PpFragment.
} catch (Exception e) {
// Oops
Log.e("log_tag", "Error converting result " + e.toString());
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// pDialog = new ProgressDialog(PpFragment.this);
// pDialog.setMessage("Obtaining list...");
// pDialog.setIndeterminate(false);
// pDialog.setCancelable(true);
// pDialog.show();
}
#Override
protected void onPostExecute(String result){
// pDialog.dismiss();
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private View layoutInflater;
public ImageAdapter(Context c) {
mContext = c;
}
public ImageAdapter() {
}
#Override
public int getCount() {
return tableList.size();
}
#Override
public Object getItem(int position) {
return tableList.get(position); //tableList is your data source
}
#Override
public long getItemId(int position) {
return 0;
}
class ViewHolder {
TextView name;
TextView id;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
//layout.item is your item layout of your gridview
convertView = getActivity().getLayoutInflater().inflate(R.layout.frag_uno_item, null);
holder = new ViewHolder();
holder.name = (TextView)convertView.findViewById(R.id.name);
holder.id = (TextView)convertView.findViewById(R.id.id);
//name and id is your view of your gridview item, for the ID and NAME
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(tableList.get(position).get(TAG_NAME));
holder.id.setText(tableList.get(position).get(TAG_ID));
//Here you can assign values to your TextView with the value you get from the data source.
return convertView;
}
}
}
First Change this
public long getItemId(int position) {
return 0;
}
To
public long getItemId(int position) {
return position;
}
Then you need to iterate in hash map .
holder.name.setText(tableList.get(position).get("aaaa"));
holder.id.setText(tableList.get(position).get("xxxx"));`
Edited
You dont need a hashmap for this forget it .. Just Create a molel Class and create entity and getter setter for it . And set the values and then pass a arrayList of its objects to adapter . Like Below example.
public class DataObject{
private boolean success;
private String message="";
private String hash;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
}
And then When you are parsing .create a object and set params to it and add it in a ArrayList .Then pass it to adapter .Thats it and Your updated method looks like
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
serv_man = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<serv_man.length();i++){
DataObject dt =new DataObject();
JSONObject c = serv_man.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
dt.setName(name);
dt.setId();
tableList.add(dt);
}
} catch (JSONException e) {
e.printStackTrace();
}
WheretableList=new ArrayList<DataObject>();
define it at class Level and use it in your adapter class to get the text.like this ..
holder.textView.setText(tableList.get(position).getName());
Okay .let me if you face any problem