Need some help for design for layout in android - android

I have ListView which brings data from server using AsyncTask. After that onItemClick starts a new Activity which should show more detailed info of the clicked item from the ListView. Pretty simple . But problem is the individual pages should work like 9GAG android app (i.e Swipeable Fragment with ViewPager). The detail info is much more. What are your suggestion for design layout of that page. Currently I am using ViewPager on that single page and Design the fragment to get the required thing.
Code
public class IndividualPage extends ActionBarActivity{
ArrayList<Item> arrayOfList;
ViewPager pager;
CountryPageAdapter pageAdapter;
private ProgressBar mProgress;
#Override
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.secondpage);
mProgress = (ProgressBar) findViewById(R.id.linear_progress_bar);
new FilteredResult().execute();
pager = (ViewPager)findViewById(R.id.viewpager);
}
private List<Fragment> getFragments() {
List<Fragment> frags = new ArrayList<Fragment>();
System.out.println("fragments main ayya hai");
cats=arrayOfList;
for(int i = 0;i<cats.size();i++ ) {
System.out.println("number : "+i+"::"+cats.get(i).getSector());
frags.add(prepareFragment(cats.get(i).getImage(),cats.get(i).getName(),cats.get(i).getLocation(),cats.get(i).getSector(),cats.get(i).getStatus(),cats.get(i).getFounded(),cats.get(i).getFundRaising()));
}
return frags;
}
Fragment prepareFragment(String image,String name,String location,String Expertise,String sector,int founded,String fund) {
CountryFragment cf = new CountryFragment();
Bundle args = new Bundle();
args.putString(CountryFragment.STARTUP_IMAGE, image);
args.putString(CountryFragment.STARTUP_NAME, name);
args.putString(CountryFragment.STARTUP_LOCATION, location);
args.putString(CountryFragment.STARTUP_EXP, Expertise);
args.putString(CountryFragment.STARTUP_SEC, sector);
args.putInt(CountryFragment.STARTUP_FOUNDED, founded);
args.putString(CountryFragment.STARTUP_FUND, fund);
cf.setArguments(args);
return cf;
}
[![public class FilteredResult extends AsyncTask<String, Void, String> {
//onpreexcute nothing doing great in this
//onbackground
#Override
protected void onPostExecute(String result) {
List<Fragment> fragments = getFragments();
pageAdapter = new CountryPageAdapter(getSupportFragmentManager(), fragments);
pager.setAdapter(pageAdapter);
}
}]

I personally prefer ViewPagers to ScrollViews as they do not keep all of the fragment/views in the memory.
Also each individual item is independent of the other ones. For example if you want to be able to implement vertical scrolling for each item you cannot do it with HorizontalScrollView as all the views will scroll together.

Even im having the same kind of design i have done like this
Class File
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.widget.LinearLayout;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
public class TurfDetailsActivity extends BaseActivity{
private SliderLayout mDemoSlider;
ViewPager pager;
private ViewPager viewPager;
private TurfDetailsViewPagerAdapter mAdapter;
private ActionBar mActionBar;
LinearLayout SliderImg;
private PagerSlidingTabStrip tabs;
String Venue;
public static Bundle b;
public static ArrayList<ReviewModel> reviewList;
public static ArrayList<TimingModel> timigList;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_turf_details_1);
mDemoSlider = (SliderLayout)findViewById(R.id.turf_details_slider);
reviewList = new ArrayList<ReviewModel>();
timigList = new ArrayList<TimingModel>();
actionBarIdForAll("Turf Details");
String data = getIntent().getStringExtra("data");
Bundle object = getDataObject(data);
imageSlider(data);
tabs = (PagerSlidingTabStrip)findViewById(R.id.tabs);
viewPager = (ViewPager) findViewById(R.id.pager);
mActionBar = getSupportActionBar();
mAdapter = new TurfDetailsViewPagerAdapter(getSupportFragmentManager(), object);
viewPager.setAdapter(mAdapter);
mActionBar.setDisplayHomeAsUpEnabled(true);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
tabs.setViewPager(viewPager);
tabs.setIndicatorColor(Color.parseColor("#ffffff"));
tabs.setTextColor(Color.parseColor("#ffffff"));
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
outState = b;
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
b = savedInstanceState;
}
private Bundle getDataObject(String data) {
// TODO Auto-generated method stub
ReviewModel mReviewModel;
TimingModel mTimingModel;
b = new Bundle();
try {
JSONObject obj = new JSONObject(data).getJSONArray("venue").getJSONObject(0);
b.putString("vid", obj.getString("vid"));
b.putString("venueName", obj.getString("venue_name"));
Venue = obj.getString("venue_name");
b.putString("location", obj.getString("location"));
b.putString("address", obj.getString("address"));
b.putString("contact", obj.getString("booking_contact"));
b.putString("turfSize", obj.getString("turf_size"));
b.putString("formats", obj.getString("preferred_format"));
b.putString("floodlights", obj.getString("floodlights"));
b.putString("ball", obj.getString("ball"));
b.putString("shoeType", obj.getString("shoe_type"));
b.putString("parking", obj.getString("parking"));
b.putString("refreshments", obj.getString("refreshments"));
b.putString("washrooms", obj.getString("washrooms"));
b.putString("bibs", obj.getString("bibs"));
b.putString("otherGames", obj.getString("other_games_played"));
b.putString("coaching", obj.getString("coaching"));
b.putString("stands", obj.getString("stands"));
b.putString("website", obj.getString("website"));
b.putString("latitude", obj.getString("latitude"));
b.putString("longitude", obj.getString("longitude"));
b.putString("cost", obj.getString("cost"));
b.putString("rating", obj.getString("rating"));
b.putString("createdDate", obj.getString("created_date"));
b.putString("updatedDate", obj.getString("updated_date"));
JSONArray array = new JSONObject(data).getJSONArray("reviews");
if(array.length()!=0){
for(int i=0;i<array.length();i++){
JSONObject obj11 = array.getJSONObject(i);
String vid = obj11.getString("vid");
String uid = obj11.getString("uid");
String email = obj11.getString("email");
String created_date = obj11.getString("created_date");
String review = obj11.getString("review");
String review_user_image = obj11.getString("image");
String review_user_name = obj11.getString("name");
b.putString("review", review);
b.putString("review_user_image", review_user_image);
b.putString("review_user_name", review_user_name);
mReviewModel = new ReviewModel(vid, uid, review, review_user_image, review_user_name, email, created_date);
reviewList.add(mReviewModel);
}
}else {
b.putString("Review_count", "0");
}
JSONArray arrayCost = new JSONObject(data).getJSONArray("cost");
for(int i=0;i<arrayCost.length();i++){
JSONObject obj12 = arrayCost.getJSONObject(i);
String vid = obj12.getString("vid");
String tid = obj12.getString("tid");
String timing = obj12.getString("timing");
String created_date = obj12.getString("created_date");
String weekdays = obj12.getString("weekdays");
String weekends = obj12.getString("weekends");
b.putString("timing", timing);
b.putString("weekdays", weekdays);
b.putString("weekends", weekends);
Log.e("timing", timing);
Log.e("weekdays", weekdays);
Log.e("weekends", weekends);
mTimingModel = new TimingModel(vid, tid, timing, weekdays, weekends);
timigList.add(mTimingModel);
}
} catch (Exception e) {
// TODO: handle exception
}
return b;
}
public void imageSlider(String data){
try {
JSONArray array = new JSONObject(data).getJSONArray("media");
if(array.length()!=0){
for(int i=0;i<array.length();i++){
JSONObject obj = array.getJSONObject(i);
String url = obj.getString("path");
TextSliderView textSliderView = new TextSliderView(this);
// initialize a SliderLayout
textSliderView.description(Venue).image(url).setScaleType(BaseSliderView.ScaleType.Fit);
//add your extra information
textSliderView.getBundle().putString("extra","Where is my turf");
mDemoSlider.addSlider(textSliderView);
}
}else{
TextSliderView textSliderView = new TextSliderView(this);
// initialize a SliderLayout
textSliderView .description("Where is my turf").image(R.drawable.ic_launcher).setScaleType(BaseSliderView.ScaleType.Fit);
//add your extra information
textSliderView.getBundle() .putString("extra","Where is my turf");
mDemoSlider.addSlider(textSliderView);
}
} catch (Exception e) {
e.printStackTrace();
}
mDemoSlider.setPresetTransformer(SliderLayout.Transformer.Accordion);
mDemoSlider.setPresetIndicator(SliderLayout.PresetIndicators.Right_Bottom);
mDemoSlider.setCustomAnimation(new DescriptionAnimation());
mDemoSlider.setDuration(3000);
}
}
ADAPTER
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TurfDetailsViewPagerAdapter extends FragmentPagerAdapter {
private Bundle data;
public TurfDetailsViewPagerAdapter(FragmentManager fm, Bundle data) {
super(fm);
this.data = data;
}
#Override
public CharSequence getPageTitle(int position) {
// TODO Auto-generated method stub
if (position == 0)
{
return "ABOUT";
}
if (position == 1)
{
return "FEATURES";
}
if (position == 2)
{
return "COST";
}
if (position == 3)
{
return "REVIEWS";
}
return null;
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new AboutFragment(data);
case 1:
return new FeaturesFragment();
case 2:
return new CostFragment();
case 3:
return new ReviewsFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 4;
}
}
XML Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1" >
<LinearLayout
android:id="#+id/image_forward"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_weight=".35" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.daimajia.slider.demo.ImageSliderActivity" >
<com.daimajia.slider.library.SliderLayout
android:id="#+id/turf_details_slider"
android:layout_width="match_parent"
android:layout_height="match_parent"
custom:auto_cycle="true"
custom:indicator_visibility="visible"
custom:pager_animation="Accordion"
custom:pager_animation_span="1100" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_marginTop="2dp"
android:layout_weight=".65"
android:orientation="vertical" >
<com.PACKAGE.customviews.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip"
android:background="#5e5b5b"
android:paddingLeft="3dp" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</android.support.v4.view.ViewPager>
</LinearLayout>
</LinearLayout>
Result Image
IF YOU NEED ANY KIND OF HELP FEEL FREE TO ASK.....Happeee...Programming....

Related

ViewPager showing fragments with the same data when should be treating each fragment individually

I am a relative newbie to android programming and I am having some issues. I'm am trying to attach fragments to a view pager for a todo application. I have 7 fragments that repersent each day. Each fragment loads correctly, but when I add a task, it shows across all fragments instead of only the one I entered the task in. Code is below. Any help would be great, thank you!
ViewPager Activity
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import com.parse.Parse;
import com.parse.ParseObject;
import com.parse.ParseUser;
public class ToDoActivity extends FragmentActivity {
MyPageAdapter pageAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_view);
Parse.initialize(this, "uD7", "BrZkpvhY6Asi5oSq");
//ParseAnalytics.trackAppOpened(getIntent());
ParseObject.registerSubclass(Task.class);
ParseUser currentUser = ParseUser.getCurrentUser();
if(currentUser == null){
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
}
List<Fragment> fragments = getFragments();
pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager)findViewById(R.id.viewpager);
pager.setAdapter(pageAdapter);
}
private List<Fragment> getFragments(){
List<Fragment> fList = new ArrayList<Fragment>();
fList.add(ToDoListFragment.newInstance("Important And Urgent"));
fList.add(ToDoListFragment.newInstance("Important Not Urgent"));
fList.add(ToDoListFragment.newInstance("Not Important But Urgent"));
return fList;
}
private class MyPageAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
}
FragmentActivity.java
public class ToDoListFragment extends Fragment implements AdapterView.OnItemClickListener {
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
private EditText mTaskInput;
private ListView mListView;
private TaskAdapter mAdapter = null;
private Button mButton;
public static final ToDoListFragment newInstance(String message)
{
ToDoListFragment f = new ToDoListFragment();
Bundle bdl = new Bundle(1);
bdl.putString(EXTRA_MESSAGE, message);
f.setArguments(bdl);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String message = getArguments().getString(EXTRA_MESSAGE);
View v = inflater.inflate(R.layout.important_urgent, container, false);
TextView messageTextView = (TextView)v.findViewById(R.id.textView);
messageTextView.setText(message);
mAdapter = new TaskAdapter(getActivity(), new ArrayList<Task>());
mTaskInput = (EditText) v.findViewById(R.id.task_input);
mListView = (ListView) v.findViewById(R.id.task_list);
mButton = (Button) v.findViewById(R.id.submit_button);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(this);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mTaskInput.getText().length() > 0){
Task t = new Task();
t.setACL(new ParseACL(ParseUser.getCurrentUser()));
t.setUser(ParseUser.getCurrentUser());
t.setDescription(mTaskInput.getText().toString());
t.setCompleted(false);
t.saveEventually();
mAdapter.insert(t, 0);
mTaskInput.setText("");
}
}
});
updateData();
return v;
}
public void updateData(){
ParseQuery<Task> query = ParseQuery.getQuery(Task.class);
query.whereEqualTo("user", ParseUser.getCurrentUser());
query.setCachePolicy(ParseQuery.CachePolicy.CACHE_THEN_NETWORK);
query.findInBackground(new FindCallback<Task>() {
#Override
public void done(List<Task> tasks, ParseException error) {
if(tasks != null){
mAdapter.clear();
for (int i = 0; i < tasks.size(); i++) {
mAdapter.add(tasks.get(i));
}
}
}
});
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Task task = mAdapter.getItem(position);
TextView taskDescription = (TextView) view.findViewById(R.id.task_description);
task.setCompleted(!task.isCompleted());
if(task.isCompleted()){
taskDescription.setPaintFlags(taskDescription.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}else{
taskDescription.setPaintFlags(taskDescription.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
}
task.saveEventually();
}
}
FragmentXML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="25dp"
android:text="Hello"
android:layout_gravity="center"
android:id="#+id/textView"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:background="#color/red"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<EditText
android:id="#+id/task_input"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="text"
android:hint="Enter a Task">
<requestFocus />
</EditText>
<Button
android:id="#+id/submit_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" />
</LinearLayout>
<ListView
android:id="#+id/task_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
If you are using the same fragment XML file for each fragment, then when you update one, you are going to update all of them. You would need to create 7 different XML layouts (they could be the same layout, but would need different identifiers), and update that fragment layout individually.
Fragments are basically individual activities, running in a single Activity. You can reuse Fragments in different Activities, but each Fragment should have it's own layout.

Tabs content in Android fragments?

I am currently setting content for my tabs like
TabSpec spec1=tabHost.newTabSpec("TAB 1");
spec1.setContent(R.id.tab1);
spec1.setIndicator("", ressources.getDrawable(R.drawable.image_large));
But how can set activity as its content for this
spec1.setContent(ProfileMenuAllTopics.this,MainActivity.class);
It says it is not applicable for this
edited:
Can you help on this how to change it
public class ProfileMenuAllTopics extends Fragment {
SessionManager session;
JSONObject jsonobject,jsonobjectTwo;
JSONArray jsonarray,jsonarrayTwo;
ListView listview,listviewTwo;
ListViewAdapter adapter,adapterTwo;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
ArrayList<HashMap<String, String>> arraylistTwo;
static String TOPICID = "topicID";
static String RANK = "topicName";
static String COUNTRY = "topicPhone";
static String TOPICPHONE = "topicPhone";
static String POPULATION = "topicDesc";
static String FLAG = "topicImage";
static String TALKTIME = "balanceTalkTime";
private static String KEY_SUCCESS = "success";
RelativeLayout webViewHolderLayout,searchRelativeView,searchRelativeViewMyLists;
String UserID;
ImageView profile_btn;
private View view;
private TransparentProgressDialog pd;
private Handler h;
private Runnable r;
String tabClicked;
JSONObject whatAreYouLooking;
JSONObject myTopicsList;
Button load_more_btn;
Button loadMoreMyTopics;
int maxRecordsHere = 10;
int maxMyRecordsHere = 10;
TabHost tabHost;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi,SetJavaScriptEnabled")
#SuppressWarnings("deprecation")
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
view = inflater.inflate(R.layout.profile_menu_topics_list, null);
h = new Handler();
pd = new TransparentProgressDialog(inflater.getContext(), R.drawable.myspinner);
r =new Runnable() {
#Override
public void run() {
if (pd.isShowing()) {
pd.dismiss();
}
}
};
session = new SessionManager(inflater.getContext());
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
UserID = user.get(SessionManager.KEY_USER_ID);
Resources ressources = getResources();
load_more_btn = (Button) view.findViewById(R.id.loadMoreTopics);
loadMoreMyTopics = (Button) view.findViewById(R.id.loadMoreMyTopics);
tabHost=(TabHost)view.findViewById(R.id.tabHost);
webViewHolderLayout = (RelativeLayout) view.findViewById(R.id.webViewHolder);
searchRelativeView = (RelativeLayout) view.findViewById(R.id.searchRelativeView);
searchRelativeViewMyLists = (RelativeLayout) view.findViewById(R.id.searchRelativeViewMyLists);
Bundle args = getArguments();
tabHost.setup();
TabSpec spec1=tabHost.newTabSpec("TAB 1");
spec1.setContent(R.id.tab1);
spec1.setIndicator("", ressources.getDrawable(R.drawable.topics_image_large));
TabSpec spec2=tabHost.newTabSpec("TAB 2");
spec2.setIndicator("", ressources.getDrawable(R.drawable.my_calls_large));
spec2.setContent(R.id.tab2);
TabSpec spec3=tabHost.newTabSpec("TAB 3");
spec3.setContent(R.id.tab3);
spec3.setIndicator("", ressources.getDrawable(R.drawable.how_it_works_large));
tabHost.addTab(spec1);
tabHost.addTab(spec2);
tabHost.addTab(spec3);
for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
{
tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#2AC4EA"));
}
tabHost.getTabWidget().setCurrentTab(0);
tabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.parseColor("#FFFFFF"));
whatAreYouLookingFor();
myTopicsTab();
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
#Override
public void onTabChanged(String arg0) {
for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
{
tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#2AC4EA"));
}
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#FFFFFF"));
int selectTabHere = tabHost.getCurrentTab();
if(selectTabHere==0){
pd.show();
tabValueZero();
h.postDelayed(r,5000);
}else if(selectTabHere==1){
pd.show();
tabValueOne();
h.postDelayed(r,5000);
}else if(selectTabHere==2){
pd.show();
tabValueTwo();
h.postDelayed(r,5000);
}
}
});
load_more_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
pd.show();
maxRecordsHere = maxRecordsHere + 10;
getPaging(whatAreYouLooking,maxRecordsHere);
h.postDelayed(r,5000);
}
});
loadMoreMyTopics.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
pd.show();
maxMyRecordsHere = maxMyRecordsHere + 10;
getPagingMyTopics(whatAreYouLooking,maxRecordsHere);
h.postDelayed(r,5000);
}
});
tabValueZero();
return view;
}
private void whatAreYouLookingFor(){
UserFunctions userFunction = new UserFunctions();
whatAreYouLooking = userFunction.getTopicsList();
getPaging(whatAreYouLooking,maxRecordsHere);
}
private void myTopicsTab(){
UserFunctions userFunction = new UserFunctions();
myTopicsList = userFunction.getMyTabTopicsList(UserID);
getPagingMyTopics(myTopicsList,maxMyRecordsHere);
}
public void getPaging(JSONObject whatAreYouLooking,int maxRecords){
arraylist = new ArrayList<HashMap<String, String>>();
try {
if (whatAreYouLooking.getString(KEY_SUCCESS) != null) {
String search_res = whatAreYouLooking.getString(KEY_SUCCESS);
if(Integer.parseInt(search_res) == 1){
jsonarray = whatAreYouLooking.getJSONArray("result");
JSONArray jsonWhatAreYouLookingArray = new JSONArray(whatAreYouLooking.optString("result"));
int totalTopics = jsonWhatAreYouLookingArray.length();
if(totalTopics<=maxRecords){
load_more_btn.setVisibility(View.GONE);
}
for (int w = 0; w < maxRecords; w++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonLookingObject = jsonWhatAreYouLookingArray.getJSONObject(w);
map.put("topicID", jsonLookingObject.getString("topicID"));
map.put("Name", jsonLookingObject.getString("Name"));
map.put("Phone",jsonLookingObject.getString("Phone"));
arraylist.add(map);
listview = (ListView) view.findViewById(R.id.listview);
adapter = new ListViewAdapter(this.getActivity(), arraylist);
listview.setAdapter(adapter);
}
}else{
}
}else{
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
public void getPagingMyTopics(JSONObject myTopicsList,int maxMyRecordsHere){
arraylistTwo = new ArrayList<HashMap<String, String>>();
try {
if (myTopicsList.getString(KEY_SUCCESS) != null) {
String search_res_Two = myTopicsList.getString(KEY_SUCCESS);
if(Integer.parseInt(search_res_Two) == 1){
jsonarrayTwo = myTopicsList.getJSONArray("result");
JSONArray jsonWhatAreYouLookingArrayTwo = new JSONArray(myTopicsList.optString("result"));
int totalTopics = jsonWhatAreYouLookingArrayTwo.length();
if(totalTopics<=maxMyRecordsHere){
loadMoreMyTopics.setVisibility(View.GONE);
}
for (int w = 0; w < maxMyRecordsHere; w++) {
HashMap<String, String> mapTwo = new HashMap<String, String>();
JSONObject jsonLookingObjectTwo = jsonWhatAreYouLookingArrayTwo.getJSONObject(w);
mapTwo.put("topicID", jsonLookingObjectTwo.getString("topicID"));
mapTwo.put("Name", jsonLookingObjectTwo.getString("Name"));
mapTwo.put("Phone",jsonLookingObjectTwo.getString("Phone"));
arraylistTwo.add(mapTwo);
listviewTwo = (ListView) view.findViewById(R.id.listviewTwo);
adapterTwo = new ListViewAdapter(this.getActivity(), arraylistTwo);
listviewTwo.setAdapter(adapterTwo);
}
}else{
}
}else{
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
private void setWebViewHowItworks(){
WebView wv;
wv = (WebView) view.findViewById(R.id.webView1);
wv.setBackgroundColor(0);
wv.setBackgroundResource(android.R.color.black);
wv.setWebChromeClient(new WebChromeClient());
wv.setWebViewClient(new WebViewClient());
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setPluginsEnabled(true);
wv.getSettings().setUseWideViewPort(true);
wv.getSettings().setLoadWithOverviewMode(true);
wv.addJavascriptInterface(this, "webConnector");
wv.addJavascriptInterface(this, "toaster");
wv.clearView();
wv.loadUrl("www.google.com");
wv.requestLayout();
}
private class TransparentProgressDialog extends Dialog {
private ImageView iv;
public TransparentProgressDialog(Context context, int resourceIdOfImage) {
super(context, R.style.TransparentProgressDialog);
WindowManager.LayoutParams wlmp = getWindow().getAttributes();
wlmp.gravity = Gravity.CENTER_HORIZONTAL;
getWindow().setAttributes(wlmp);
setTitle(null);
setCancelable(false);
setOnCancelListener(null);
LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
iv = new ImageView(context);
iv.setImageResource(resourceIdOfImage);
layout.addView(iv, params);
addContentView(layout, params);
}
#Override
public void show() {
super.show();
RotateAnimation anim = new RotateAnimation(0.0f, 360.0f , Animation.RELATIVE_TO_SELF, .5f, Animation.RELATIVE_TO_SELF, .5f);
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(3000);
iv.setAnimation(anim);
iv.startAnimation(anim);
}
}
public void tabValueZero(){
searchRelativeView.setVisibility(View.VISIBLE);
searchRelativeViewMyLists.setVisibility(View.GONE);
webViewHolderLayout.setVisibility(View.GONE);
}
public void tabValueOne(){
searchRelativeView.setVisibility(View.GONE);
searchRelativeViewMyLists.setVisibility(View.VISIBLE);
webViewHolderLayout.setVisibility(View.GONE);
}
public void tabValueTwo(){
searchRelativeView.setVisibility(View.GONE);
searchRelativeViewMyLists.setVisibility(View.GONE);
webViewHolderLayout.setVisibility(View.VISIBLE);
setWebViewHowItworks();
}
}
below is edited code where I have given one sample to include Activity inside Fragment Tabs. Please let me know in case you couldn't understand anything:
//FragmentActivity having tabs
package com.example.tabhost;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TabHost;
import android.widget.TextView;
public class MainActivity extends FragmentActivity {
Context mContext;
Intent mIntent;
TabHost mTabHost;
ViewPager mViewPager;
TabsAdapterActivity mTabsAdapter;
//Setup tab
private void setupTabHost() {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
mViewPager = (ViewPager) findViewById(R.id.pager);
mTabsAdapter = new TabsAdapterActivity(this, mTabHost, mViewPager);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = MainActivity.this;
setupTabHost();
addTab(R.string.mycards,"My Cards Category", MyCardsActivity.class); //My Cards
addTab(R.string.yourcards,"Your Cards Category", YourCardsActivity.class); //Shared Cards
}
//Add tab
private void addTab(int headingTextId, String tabSpec, Class<?> fragmentclass){
LayoutInflater inflater_mycard = getLayoutInflater();
View view = inflater_mycard.inflate(R.layout.tab_style, null);
TextView tab_heading = (TextView) view.findViewById(R.id.tab_heading);
tab_heading.setText(getResources().getString(headingTextId));
mTabsAdapter.addTab(mTabHost.newTabSpec(tabSpec).setIndicator(view), fragmentclass, null);
}
}
//TabsAdapter designed to include Activity
package com.example.tabhost;
import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TabHost;
import android.widget.TabWidget;
import java.util.ArrayList;
import com.example.tabhost.TabsAdapterFragment.DummyTabFactory;
import com.example.tabhost.TabsAdapterFragment.TabInfo;
/**
* This is a helper class that implements the management of tabs and all
* details of connecting a ViewPager with associated TabHost. It relies on a
* trick. Normally a tab host has a simple API for supplying a View or
* Intent that each tab will show. This is not sufficient for switching
* between pages. So instead we make the content part of the tab host
* 0dp high (it is not shown) and the TabsAdapter supplies its own dummy
* view to show as the tab content. It listens to changes in tabs, and takes
* care of switch to the correct paged in the ViewPager whenever the selected
* tab changes.
*/
public class TabsAdapterActivity extends PagerAdapter
implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
private final Context mContext;
private final TabHost mTabHost;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
private final Rect mTempRect = new Rect();
private TabHost.OnTabChangeListener mOnTabChangeListener;
static final class TabInfo {
public final String tag;
private final Class<?> clss;
private final Bundle args;
TabInfo(String _tag, Class<?> _class, Bundle _args) {
tag = _tag;
clss = _class;
args = _args;
}
}
static class DummyTabFactory implements TabHost.TabContentFactory {
private final Context mContext;
public DummyTabFactory(Context context) {
mContext = context;
}
#Override
public View createTabContent(String tag) {
View v = new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
public TabsAdapterActivity(Activity activity, TabHost tabHost, ViewPager pager) {
mContext = activity;
mTabHost = tabHost;
mViewPager = pager;
mTabHost.setOnTabChangedListener(this);
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
tabSpec.setContent(new DummyTabFactory(mContext));
String tag = tabSpec.getTag();
TabInfo info = new TabInfo(tag, clss, args);
mTabs.add(info);
mTabHost.addTab(tabSpec);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mTabs.size();
}
#Override
public Class<? extends TabInfo> instantiateItem(ViewGroup container, int position) {
/*View view = mTabs.get(position).view;
container.addView(view);
return view;*/
return mTabs.get(position).getClass();
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View)object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
public void setOnTabChangedListener(TabHost.OnTabChangeListener listener) {
mOnTabChangeListener = listener;
}
#Override
public void onTabChanged(String tabId) {
int position = mTabHost.getCurrentTab();
mViewPager.setCurrentItem(position);
if (mOnTabChangeListener != null) {
mOnTabChangeListener.onTabChanged(tabId);
}
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
// Unfortunately when TabHost changes the current tab, it kindly
// also takes care of putting focus on it when not in touch mode.
// The jerk.
// This hack tries to prevent this from pulling focus out of our
// ViewPager.
TabWidget widget = mTabHost.getTabWidget();
int oldFocusability = widget.getDescendantFocusability();
widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
mTabHost.setCurrentTab(position);
widget.setDescendantFocusability(oldFocusability);
// Scroll the current tab into visibility if needed.
View tab = widget.getChildTabViewAt(position);
mTempRect.set(tab.getLeft(), tab.getTop(), tab.getRight(), tab.getBottom());
widget.requestRectangleOnScreen(mTempRect, false);
// Make sure the scrollbars are visible for a moment after selection
/*final View contentView = mTabs.get(position).view;
if (contentView instanceof CaffeinatedScrollView) {
((CaffeinatedScrollView) contentView).awakenScrollBars();
}*/
}
#Override
public void onPageScrollStateChanged(int state) {
}
}
//-------Supporting XML layouts & drawables-----------
// tab_style.xml place inside layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tabsLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/tab_bg_selector"
android:gravity="center"
android:orientation="vertical"
android:padding="10dip" >
<TextView
android:id="#+id/tab_heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#drawable/tab_text_selector"
android:textSize="15sp" />
</LinearLayout>
//place below in drawable folder
//tab_bg_selected.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tabsLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/tab_bg_selector"
android:gravity="center"
android:orientation="vertical"
android:padding="10dip" >
<TextView
android:id="#+id/tab_heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#drawable/tab_text_selector"
android:textSize="15sp" />
</LinearLayout>
//tab_bg_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<gradient
android:angle="-90"
android:centerColor="#2A85C4"
android:endColor="#1B73AD"
android:startColor="#1B73AD" />
</shape>
//tab_bg_unselected.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<gradient
android:angle="-90"
android:centerColor="#424242"
android:endColor="#5C5C5C"
android:startColor="#5C5C5C" />
</shape>
//tab_bg_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:color="#android:color/white"/>
<item android:state_focused="true" android:color="#android:color/white"/>
<item android:state_pressed="true" android:color="#android:color/white"/>
<item android:color="#f8f8f8"/>
</selector>

ListView no longer display inside Tab

I haven't touched this codebase in a couple of months. Now that I've picked it up again, some code that I didn't think I'd changed has stopped working: All listfragment listviews in the app populated by a simplecursoradapter have stopped working and are just blank. At first I thought the cursor or the database was at fault or that perhaps the adapter wasn't being set correctly, so I added some debugging to the onLoadFinished:
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
Log.d("IndexListFragment", "Rows returned: " + cursor.getCount());
Log.d("IndexListFragment", cursor.getColumnName(0));
Log.d("IndexListFragment", mAdapter.toString());
Log.d("IndexListFragment", this.getListView().getAdapter().toString());
mAdapter.swapCursor(cursor);
}
This returns what I'd expect:
IndexListFragment: Rows returned: 2324
IndexListFragment: _id
IndexListFragment: android.support.v4.widget.SimpleCursorAdapter#41d06a18
IndexListFragment: android.support.v4.widget.SimpleCursorAdapter#41d06a18
So as far as I can tell, the cursor is there and full of data, but swapping it in doesn't get the listview populated. Any ideas?
For completeness, here's the onCreate where the adapter is created and set:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] from = new String[] { GuidebookProvider.COL_NAME,
GuidebookProvider.COL_GRADE };
int[] to = new int[] { android.R.id.text1, android.R.id.text2 };
mAdapter = new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_2, null, from, to, 0);
setListAdapter(mAdapter);
getLoaderManager().initLoader(0, null, this);
}
And the onCreateLoader:
#Override
public Loader<Cursor> onCreateLoader(int loaderId, Bundle loaderArgs) {
String orderBy = GuidebookProvider.COL_NAME;
String[] projection = new String[] { GuidebookProvider.COL_ID, GuidebookProvider.COL_NAME, GuidebookProvider.COL_GRADE };
return new CursorLoader(getActivity(),
GuidebookProvider.CONTENT_URI_CLIMB, projection, null, null,
orderBy);
}
Edit: I've done a little more work debugging this issue. The fragment works fine if I run it directly from an activity like this:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.widget.FrameLayout;
public class TestActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout frame = new FrameLayout(this);
frame.setId(android.R.id.content);
if (savedInstanceState == null) {
Bundle args = new Bundle();
args.putInt(IndexListFragment.ARGUMENT_INDEX_TYPE, IndexListFragment.IndexType.ALPHA.value);
Fragment indexListFragment = new IndexListFragment();
indexListFragment.setArguments(args);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(android.R.id.content, indexListFragment).commit();
}
}
}
However, calling it as part of a Tab ends up with a blank tab:
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
public class TestActivity extends FragmentActivity {
private FragmentTabHost mTabHost;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_tab_host);
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
Bundle args = new Bundle();
args.putInt(IndexListFragment.ARGUMENT_INDEX_TYPE,
IndexListFragment.IndexType.ALPHA.value);
Drawable drawable = null;
mTabHost.addTab(mTabHost.newTabSpec("A-Z")
.setIndicator("A-Z", drawable), IndexListFragment.class, args);
}
}
Here's my xml for the tabhost:
<?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.support.v4.app.FragmentTabHost
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
<FrameLayout
android:id="#+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1" />
</android.support.v4.app.FragmentTabHost>
</LinearLayout>
The fact that the fragment populates correctly when called directly but not when called from within a tab seems to show that the problem isn't at all with the cursors or adapters but with the way the listfragment operating inside a tab.
Can anyone point out what I've done wrong (or what's changed in the last couple of updates of the SDK) to break this code? It used to work fine.
This Code may help you just try it
ViewAllLesson.java :
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import com.xyz.R;
import com.xyz.db.LessonDatabaseConnector;
import com.xyz.pojo.AssignmentPojo;
import com.xyz.pojo.LessonPojo;
public class ViewAllLessons extends Fragment {
public LessonDatabaseConnector dao;
private View rootView;
List<LessonPojo> lessons;
ArrayList<String> con = new ArrayList<String>();
LayoutInflater mInflater;
LessonCustomAdapter lessonCustomAdapter;
private ListView listView;
public static CheckBox selectAll;
private Button deleteBtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.add_exams);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.lesson_view_all_list, container,
false);
// dao = new AssignmentDatabaseConnector(getActivity());
listView = (ListView) rootView.findViewById(R.id.Lesson_ListAll);
selectAll = (CheckBox) rootView.findViewById(R.id.SelectAll);
deleteBtn = (Button) rootView.findViewById(R.id.LessonDeleteBtn);
Button addNew = (Button) rootView.findViewById(R.id.LessonAddNewBtn);
addNew.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(getActivity(), "hi",
// Toast.LENGTH_LONG).show();
Lesson lesson = new Lesson();
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, lesson).commit();
}
});
// viewgr.setScrollContainer(false);
dao = new LessonDatabaseConnector(getActivity());
lessons = dao.getAllLessonList();
lessonCustomAdapter = new LessonCustomAdapter(getActivity(), lessons,
this);
listView.setAdapter(lessonCustomAdapter);
/* To Check List View is empty */
if (lessons.size() <= 0) {
View empty = rootView.findViewById(R.id.empty);
ListView list = (ListView) rootView
.findViewById(R.id.Lesson_ListAll);
list.setEmptyView(empty);
listView.setVisibility(0);
empty.setVisibility(1);
}
selectAll.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(getActivity(), "hi",
// Toast.LENGTH_LONG).show();
if (((CheckBox) v).isChecked()) {
LessonCustomAdapter.flag = true;
lessonCustomAdapter.notifyDataSetChanged();
} else {
LessonCustomAdapter.flag = false;
LessonCustomAdapter.checkedvalue.clear();
lessonCustomAdapter.notifyDataSetChanged();
}
}
});
// Set the list adapter and get TODOs list via DAO
deleteBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LessonDatabaseConnector dao = new LessonDatabaseConnector(
getActivity());
for (int i = 0; i < LessonCustomAdapter.checkedvalue.size(); i++) {
//
System.out
.println("===========LessonCustomAdapter.checkedvalue.size()==========SIZE======>>>>"
+ LessonCustomAdapter.checkedvalue.size());
System.out
.println("===========DELETED LESSON=================>>>>"
+ LessonCustomAdapter.checkedvalue.get(i));
dao.DeleteLesson(LessonCustomAdapter.checkedvalue.get(i));
}
LessonCustomAdapter.flag = false;
ViewAllLessons viewAllLessons = new ViewAllLessons();
getFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, viewAllLessons)
.commit();
// finish();
}
});
return rootView;
}
private List<AssignmentPojo> getAllAssignmentsList() {
// TODO Auto-generated method stub
return null;
}
}
LessonCustomAdapter :
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import com.xyz.R;
import com.xyz.pojo.LessonPojo;
public class LessonCustomAdapter extends BaseAdapter {
protected static boolean flag = false;
private TextView mLessonTitle, mLessonDate;
private final Context context;
List<LessonPojo> Lessons;
private ViewAllLessons viewAllLessons;
private ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();
private CheckBox SingleChk;
public static ArrayList<Long> checkedvalue = new ArrayList<Long>();
LessonCustomAdapter(Context context, List<LessonPojo> Lessons2,
ViewAllLessons viewAllLessons) {
this.context = context;
this.Lessons = Lessons2;
this.viewAllLessons = viewAllLessons;
for (int i = 0; i < Lessons2.size(); i++) {
itemChecked.add(i, false); // initializes all items value with false
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return Lessons.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View rowView = convertView;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
rowView = inflater.inflate(R.layout.lesson_view_row_list, parent,
false);
}
mLessonDate = (TextView) rowView.findViewById(R.id.LessonDate);
mLessonDate.setText(Lessons.get(position).getLdate());
mLessonTitle = (TextView) rowView.findViewById(R.id.LessonTitle);
mLessonTitle.setText(Lessons.get(position).getLtitle());
SingleChk = (CheckBox) rowView.findViewById(R.id.singleChk);
/*
* if (flag) { System.out.println("66666666666666666666666666666666" +
* flag); for (int i = 0; i < Lessons.size(); i++) {
* SingleChk.setChecked(flag); SingleChk.setEnabled(!flag); }
*
* } else { SingleChk.setChecked(itemChecked.get(position)); }
*/
checkedvalue.clear();
if (ViewAllLessons.selectAll.isChecked()) {
SingleChk.setChecked(true);
Boolean val = false;
for (int i = 0; i < Lessons.size(); i++) {
checkedvalue.add(Long.parseLong(Lessons.get(i).getId()));
System.out
.println("ADD SUCCEFULLYYYYYYYY ====================== "
+ Long.parseLong(Lessons.get(position).getId()));
}
} else {
SingleChk.setChecked(false);
checkedvalue.clear();
}
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Bundle bundle = new Bundle();
ViewSingleLesson viewSingleLesson = new ViewSingleLesson();
bundle.putString("ID", Lessons.get(position).getId());
bundle.putString("TITLE", Lessons.get(position).getLtitle());
bundle.putString("COURSE", Lessons.get(position).getLcourse());
bundle.putString("LEVEL", Lessons.get(position).getLlevel());
bundle.putString("CLASS", Lessons.get(position).getLclass());
bundle.putString("DATE", Lessons.get(position).getLdate());
bundle.putString("DESC", Lessons.get(position).getLdesc());
bundle.putString("ATTACH", Lessons.get(position).getLfilepath());
viewSingleLesson.setArguments(bundle);
viewAllLessons.getFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, viewSingleLesson)
.commit();
}
});
SingleChk.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Boolean val = false;
Toast.makeText(context, "hi " + Lessons.get(position).getId(),
Toast.LENGTH_LONG).show();
if (((CheckBox) v).isChecked()) {
for (int i = 0; i < checkedvalue.size(); i++) {
if (checkedvalue.get(i) == Long.parseLong(Lessons.get(
position).getId())) {
val = true;
System.out
.println("DUPLICATE ====================== "
+ Long.parseLong(Lessons.get(
position).getId()));
} else {
val = false;
}
}
if (val == false) {
checkedvalue.add(Long.parseLong(Lessons.get(position)
.getId()));
System.out
.println("ADD SUCCEFULLYYYYYYYY ====================== "
+ Long.parseLong(Lessons.get(position)
.getId()));
}
} else {
ViewAllLessons.selectAll.setChecked(false);
checkedvalue.remove(Long.parseLong(Lessons.get(position)
.getId()));
System.out
.println("Removed SUCCEFULLYYYYYYYY ====================== "
+ Integer.parseInt(Lessons.get(position)
.getId()));
// itemChecked.set(position, false);
}
}
});
return rowView;
}
}
Got a chance to have a look at this today and finally sorted it out. The problem was in my xml layout setup. Oddly, according to my git repository, this file hasn't changed for 9 months so I guess I was doing something that only worked by accident. I found a tutorial FragmentTabHosts with a different layout and updated my layout to:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.app.FragmentTabHost
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
</android.support.v4.app.FragmentTabHost>
<FrameLayout
android:id="#+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1" />
</LinearLayout>
That somehow fixed the issue. A bit more hunting around revealed an example layout xml for FragmentTabHost in the TabActivity documentation: http://developer.android.com/reference/android/app/TabActivity.html
I updated to use the version found in the documentation and it also works:
<android.support.v4.app.FragmentTabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TabWidget
android:id="#android:id/tabs"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"/>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0"/>
<FrameLayout
android:id="#+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
Given I found it in Android's documentation, I'll stick with this version.

Dynamically changing the fragments inside a fragment tab host?

I have one main activity which is fragment activity here I am setting two tabs with two fragments A and B in the B fragment I have one button when the user click on the button I want to change fragment B to fragment C. But the tabs above are visible...
How I can achieve replacing fragments inside tabs?
Any solution are greatly appreciated.
Basic concept- We can achieve this by creating a container. Each tab will be assigned with a specific container. Now when we need a new fragment then we will replace same using this container.
Kindly follow undermentioned code step by step to have better understanding.
Step-1: Create Tabs for your app. Say "Home.java". It will contain code for creating tabs using fragment.
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.widget.TextView;
import app.drugs.talksooner.container.GoContainerFragment;
import app.drugs.talksooner.container.LearnContainerFragment;
import app.drugs.talksooner.container.MoreContainerFragment;
import app.drugs.talksooner.container.TalkContainerFragment;
import app.drugs.talksooner.container.WatchContainerFragment;
import app.drugs.talksooner.utils.BaseContainerFragment;
public class Home extends FragmentActivity {
private static final String TAB_1_TAG = "tab_1";
private static final String TAB_2_TAG = "tab_2";
private static final String TAB_3_TAG = "tab_3";
private static final String TAB_4_TAG = "tab_4";
private static final String TAB_5_TAG = "tab_5";
private FragmentTabHost mTabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
initView();
}
private void initView() {
mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
// mTabHost.addTab(mTabHost.newTabSpec(TAB_1_TAG).setIndicator("Talk", getResources().getDrawable(R.drawable.ic_launcher)), TalkContainerFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec(TAB_1_TAG).setIndicator("Talk"), TalkContainerFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec(TAB_2_TAG).setIndicator("Learn"), LearnContainerFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec(TAB_3_TAG).setIndicator("Go"), GoContainerFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec(TAB_4_TAG).setIndicator("Watch"), WatchContainerFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec(TAB_5_TAG).setIndicator("More"), MoreContainerFragment.class, null);
/* Increase tab height programatically
* tabs.getTabWidget().getChildAt(1).getLayoutParams().height = 150;
*/
for (int i = 0; i < mTabHost.getTabWidget().getChildCount(); i++) {
final TextView tv = (TextView) mTabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title);
if (tv == null)
continue;
else
tv.setTextSize(10);
}
}
#Override
public void onBackPressed() {
boolean isPopFragment = false;
String currentTabTag = mTabHost.getCurrentTabTag();
if (currentTabTag.equals(TAB_1_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_1_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_2_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_2_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_3_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_3_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_4_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_4_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_5_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_5_TAG)).popFragment();
}
if (!isPopFragment) {
finish();
}
}
}
Your home.xml file
<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/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1" />
<android.support.v4.app.FragmentTabHost
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dip"
android:layout_height="0dip"
android:layout_weight="0" />
</android.support.v4.app.FragmentTabHost>
</LinearLayout>
Step-2: Define Base container fragment which will be helpful for backtracking and replacment of fragments "check out replaceFragement() ". Our class "BaseContainerFragment.java"
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import app.drugs.talksooner.R;
public class BaseContainerFragment extends Fragment {
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.replace(R.id.container_framelayout, fragment);
transaction.commit();
getChildFragmentManager().executePendingTransactions();
}
public boolean popFragment() {
Log.e("test", "pop fragment: " + getChildFragmentManager().getBackStackEntryCount());
boolean isPop = false;
if (getChildFragmentManager().getBackStackEntryCount() > 0) {
isPop = true;
getChildFragmentManager().popBackStack();
}
return isPop;
}
}
Step3: Now here I am considering for one fragment only hoping that rest can be handled by you in same fashion. Defining container Fragment class. Each tab will have specific container. Say TalkContainerFragment.java for first tab
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import app.drugs.talksooner.R;
import app.drugs.talksooner.Talk;
import app.drugs.talksooner.utils.BaseContainerFragment;
public class TalkContainerFragment extends BaseContainerFragment {
private boolean mIsViewInited;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.e("test", "tab 1 oncreateview");
return inflater.inflate(R.layout.container_fragment, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.e("test", "tab 1 container on activity created");
if (!mIsViewInited) {
mIsViewInited = true;
initView();
}
}
private void initView() {
Log.e("test", "tab 1 init view");
replaceFragment(new Talk(), false);
}
}
It's xml file. "container_fragment.xml" this xml container contains frameLayout. we will use this id to replace different Fragments.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container_framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
Your main class. "Talk.java"
public class Talk extends Fragment {
/** Define global variables over here */
//private ProgressDialog pDialog;
StaticApiList sal;
TalkModelAll tma;
JSONObject myJasonObject = null;
private ListView lv;
private ArrayList<TalkModelAll> m_ArrayList = null;
//ArrayList<String> stringArrayList = new ArrayList<String>();
TalkArrayAdapter taa;
Set<String> uniqueValues = new HashSet<String>();
TextView rowTextView = null;
boolean vivek = false;
int postid;
String title;
String thumsrc;
String largeimg;
String excert;
String description;
String cat;
String myUrl;
String jsonString;
int mCurCheckPosition;
String check_state = null;
String ccc;
LinearLayout myLinearLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.talk, container, false);
Button btn = (Button) rootView.findViewById(R.id.your_btn_id);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Here TalkDetail is name of class that needs to open
TalkDetail fragment = new TalkDetail();
// if U need to pass some data
Bundle bundle = new Bundle();
bundle.putString("title", m_ArrayList.get(arg2).title);
bundle.putString("largeimg", m_ArrayList.get(arg2).largeimg);
bundle.putString("excert", m_ArrayList.get(arg2).excert);
bundle.putString("description", m_ArrayList.get(arg2).description);
bundle.putString("cat", m_ArrayList.get(arg2).cat);
//bundle.putInt("postid", m_ArrayList.get(arg2).postid);
fragment.setArguments(bundle);
((BaseContainerFragment)getParentFragment()).replaceFragment(fragment, true);
}
});
return rootView;
}
}
That's it. You are good to go. The whole magic lies in calling R.id. instead of R.layout.
Cheers!

Same class/layout in view pager

I am trying to add the same class several times to a viewpager to show different info which is read from a sqlite DB. The thing is when the view is created, always override the objects, textviews etc..., in the current view and not in the fragment for each page.
names = new ArrayList<String>();
for (int d : descritions) {
Description temp = DBCompanies.getDescriptionById(db_path,
GSSettings.DBCODE, d, Locale.getDefault().getLanguage(),
GSSettings.DEFAULTLANGUAGE, false);
names.add(temp.getTitle());
}
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// mViewPager.setCurrentItem(0);
mViewPager.refreshDrawableState();
...
How can I avoid this behavior?
thanks.
EDIT:
I added more code to clarify my question:
framecompany100.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ly_main"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbarDefaultDelayBeforeFade="500"
android:scrollbarFadeDuration="200"
android:scrollbarThumbVertical="#drawable/scrollbar_vertical_thumb_company" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Gallery
android:id="#+id/ga_image"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp" />
<RelativeLayout
android:id="#+id/ly_details"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/ga_image" >
<ImageView
android:id="#+id/iv_options"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_margin="5dp"
android:src="#drawable/ic_button_options" />
<RelativeLayout
android:id="#+id/ly_details_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:layout_toRightOf="#+id/iv_options"
android:background="#77ffffff" >
<TextView
android:id="#+id/tv_address" android:text="kldfjhskdjhfksj"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:textSize="15sp" />
</RelativeLayout>
</RelativeLayout>
<TextView
android:id="#+id/tv_description"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/ly_details"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:textSize="15sp"
android:textStyle="bold" />
</RelativeLayout>
and the class for this layout:
FrameCompany100.java
public class FrameCompany100 extends Fragment implements OnClickListener,
PictureUpdater, FragmentName {
private Bundle data = new Bundle();
private Gallery image;
private Description description;
private BaseAdapter adapter;
private String db_path;
private GuiParams main_params;
private Company company;
private String name = "";
#Override
public void onCreate(Bundle savedInstanceState) {
data = this.getArguments();
if (savedInstanceState != null)
data = savedInstanceState;
db_path = "/data/data/" + getActivity().getPackageName()
+ GSSettings.DB_PATH;
description = DBCompanies.getDescriptionById(db_path,
GSSettings.DBCODE, data.getInt("descriptionId"), Locale
.getDefault().getLanguage(), "es", false);
company = DBCompanies.getCompany(db_path, GSSettings.DBCODE,
description.getCompanyId());
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.framecompany100, container, false);
}
void init() {
try {
Display display = getActivity().getWindowManager()
.getDefaultDisplay();
int height = display.getHeight();
final int width = display.getWidth();
// params
main_params = DBCompanies.getGuiParams(db_path, GSSettings.DBCODE,
description.getCompanyId(), GSSettings.body);
if (main_params == null || main_params.getBackgroundcolor() == null
|| main_params.getBackgroundcolor().equals("")
|| main_params.getTextcolor() == null
|| main_params.getTextcolor().equals(""))
main_params = DBApp.getGuiParam(db_path, GSSettings.DBCODE,
GSSettings.body);
// main Layout
RelativeLayout ly_main = (RelativeLayout) getActivity()
.findViewById(R.id.ly_main);
try {
ly_main.setBackgroundColor(Color.parseColor(main_params
.getBackgroundcolor()));
} catch (Exception e) {
}
Typeface font_body = null;
try {
font_body = Typeface.createFromAsset(getActivity().getAssets(),
"fonts/" + main_params.getFont());
} catch (Exception e) {
font_body = Typeface.createFromAsset(
getActivity().getAssets(),
"fonts/"
+ DBApp.getGuiParam(db_path, GSSettings.DBCODE,
GSSettings.body).getFont());
}
TextView tv_description = (TextView) getActivity().findViewById(
R.id.tv_description);
try {
tv_description.setTextColor(Color.parseColor(main_params
.getTextcolor()));
} catch (Exception e) {
}
if (description == null) {
tv_description.setText(R.string.nodescription);
} else {
tv_description.setText(description.getText());
}
TextView tv_address = (TextView) getActivity().findViewById(
R.id.tv_address);
try {
tv_address.setTextColor(Color.parseColor(main_params
.getTextcolor()));
} catch (Exception e) {
}
.....
}
#Override
public void onResume() {
init();
// ((MainLayout) getActivity()).setDescription(description);
super.onResume();
}
the FragmentPagerAdapter
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Description temp = DBCompanies.getDescriptionById(db_path,
GSSettings.DBCODE, descritions[i], Locale.getDefault()
.getLanguage(), GSSettings.DEFAULTLANGUAGE, false);
Fragment fragment = null;
try {
fragment = new CompanyLayout100();
((FragmentName) fragment).setName(temp.getTitle());
Bundle bundle = new Bundle();
bundle.putInt("descriptionId", temp.getId());
fragment.setArguments(bundle);
} catch (Exception e) {
}
return fragment;
}
#Override
public int getCount() {
return descritions.length;
// return fragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
String name = "";
try {
name = names.get(position);
} catch (Exception e) {
}
return name;
}
}
what's happening is, the viewpager create the view for these frames but always is entering the data in the visible frame. I think is because the layout.xml is the same so there is only one id and all object are pointing at the visible layout.
You need a FragmentPagerAdapter that creates the instance ...
public class PagerAdapter extends FragmentPagerAdapter {
int pages;
public PagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public int getCount() {
return pages;
}
#Override
public Fragment getItem(int position) {
return MyFragment.newInstance(position);
}
public void setPages(int no) {
pages = no;
}
}
So in the main activity you attach the PagerAdapter ...
adapter = new PagerAdapter(getSupportFragmentManager());
adapter.setPages(noPages);
pager.setAdapter(adapter);
Finally you need your Fragment including the newInstance method. Check out this http://android-developers.blogspot.de/2011/08/horizontal-view-swiping-with-viewpager.html for more.
Cheers!
Edit #1: MyFragment; note: it is essential to pass the position as an argument
public class MyFragment extends SherlockFragment {
private static final String KEY_POSITION="position";
static MyFragment newInstance(int position) {
MyFragment frag=new MyFragment();
Bundle args=new Bundle();
args.putInt(KEY_POSITION, position);
frag.setArguments(args);
return(frag);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View result=inflater.inflate(R.layout.editor, container, false);
EditText editor=(EditText)result.findViewById(R.id.editor);
int position=getArguments().getInt(KEY_POSITION, -1);
editor.setHint(String.format(getString(R.string.hint), position + 1));
return(result);
}
}

Categories

Resources