connecting parse api to android swipe layout - java

I'm doing a project using Android swipe layout. I'm getting problem when calling a datas from parse server to swiped tabs.
I'm getting this error when I'm calling a list fragment inside a fragment
below is my fragment class
please check
i updated code but some errors showing please check below screenshot
enter image description here
this error comes
import android.app.ListActivity;
import android.app.ListFragment;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import java.util.ArrayList;
import java.util.List;
public class IndividualsFragment extends ListFragment implements FindCallback<ParseObject> {
private List<ParseObject> mOrganization = new ArrayList<ParseObject>();
#Override
public void onViewCreated(View view, Bundle b) {
super.onViewCreated(view, b);
CustomAdaptor adaptor = new CustomAdaptor(getActivity(), mOrganization);
setListAdapter(adaptor);
// This is like calling fetchList()
ParseQuery.getQuery("Organization").findInBackground(this);
}
/**
* This is needed by implementing the callback on the class
**/
#Override
public void done(List<ParseObject> scoreList, ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + scoreList.size() + " Organization");
mOrganization.clear();
mOrganization.addAll(scoreList);
getListAdapter().notifyDataSetChanged();
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
}
MainActivity.class
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* 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_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// 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.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
Parse.initialize(new Parse.Configuration.Builder(this)
.applicationId("my-app-id")
.server("severn-name")
.build()
);
}
#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);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
Individuals t1 = new Individuals();
return t1;
case 1:
Events t2 = new Events();
return t2;
case 2:
Members t3 = new Members();
return t3;
}
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "INdividuals";
case 1:
return "Events";
case 2:
return "Members";
}
return null;
}
}
}
This is where I call parse data.
OrganizationActivity.class
public class OrganizationActivity extends ListActivity {
protected List<ParseObject> mOrganization;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_organization);
fetcAndList();
}
void fetcAndList() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Organization");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> scoreList, ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + scoreList.size() + " Organization");
mOrganization = scoreList;
CustomAdaptor adaptor = new CustomAdaptor(getListView().getContext(), mOrganization);
setListAdapter(adaptor);
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
}
public void onCreate() { }
}
This is tab1
Individuals.java
import android.database.DataSetObserver;
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.ListAdapter;
import android.widget.ListView;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import java.util.List;
/**
* Created by faizal on 1/17/17.
*/
public class Individuals extends Fragment implements ListAdapter {
public class IndividualsActivity extends Fragment {
ListView listview;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
OrganizationActivity.fetcAndList();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_organization, container, false);
listview = (ListView)v.findViewById(R.id.list);
super.onCreate(savedInstanceState);
return v;
}
}
I have created 5 xml files. This was automatically created when creating the Android Studio project.
activity_main.xml
This is list view xml
activity_organization.xml
<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</ListView>
</LinearLayout>
This is tab1.xml
This is the first tab , here I call the fields of list view.
t1.xml
<RelativeLayout 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="cmcom.com.fbcapp.swipe_new.MainActivity$PlaceholderFragment">
<ImageView
android:id="#+id/logo"
android:layout_gravity="left"
android:layout_height="80dp"
android:layout_width="80dp"
android:padding="5dp"
android:paddingLeft="5dp"
android:paddingEnd="5dp"
android:paddingBottom="5dp"
android:paddingRight="5dp"
android:paddingStart="5dp"
android:paddingTop="5dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="12dp"
android:layout_marginStart="12dp"
android:layout_marginTop="14dp">
</ImageView>
<TextView
android:id="#+id/name"
android:text="Name"
android:layout_width="204dp"
android:layout_height="wrap_content"
android:layout_below="#+id/user"
android:layout_alignLeft="#+id/user"
android:layout_alignStart="#+id/user"
android:layout_marginTop="13dp" />
<TextView
android:id="#+id/user"
android:text="Username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="17dp"
android:layout_marginStart="17dp"
android:layout_alignTop="#+id/logo"
android:layout_toRightOf="#+id/logo"
android:layout_toEndOf="#+id/logo" />
</RelativeLayout>
I tried many times but failed to load parse data inside the tab fragments
if anyone know please help me thank you.

Your ListView is not at all attached to the swipe views. Plus, it's an activity. You need to swipe between Fragments. So move the Parse code into a Fragment with a ListView
And a Fragment is not an Adapter, so you need to implement nothing
public class Individuals extends Fragment { // No implements needed
// Code
}
Then setAdapter is not a method of the Fragment class, so you have to use the method of the ListView itself or use a ListFragment
Here's an example of a ListFragment
(code untested)
public class IndividualsFragment
extends android.support.v4.app.ListFragment
implements FindCallback<ParseObject> {
private List<ParseObject> mOrganization = new ArrayList<ParseObject>();
#Override
public void onViewCreated(View view, Bundle b) {
super.onViewCreated(view, b);
CustomAdaptor adaptor = new CustomAdaptor(getActivity(), mOrganization);
setListAdapter(adaptor);
// This is like calling fetchList()
ParseQuery.getQuery("Organization").findInBackground(this);
}
/**
* This is needed by implementing the callback on the class
**/
#Override
public void done(List<ParseObject> scoreList, ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + scoreList.size() + " Organization");
mOrganization.clear();
mOrganization.addAll(scoreList);
((CustomAdaptor) getListAdapter()).notifyDataSetChanged();
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
}

you may need to call back listview in
OrganizationActivity.class

Related

Null Pointer on RecyclerView

I am getting a null pointer exception on the following statement within my recyclersetup method.
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
It is due to the following statement not setting a pointer to recyclerView in the previous statement which is
recyclerView = getView().findViewById(R.id.check_in_recent_row);
I cannot determine why I am not getting the recyclerView pointer established via this statement. the ID for the data is correct. What am I missing?
This is the entire fragment code
CheckInRecentList.java
package com.example.checkingin;
import android.content.Context;
import android.net.Uri;
import android.nfc.Tag;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProvider.Factory;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.List;
import static androidx.constraintlayout.widget.Constraints.TAG;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link CheckInRecentList.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link CheckInRecentList#newInstance} factory method to
* create an instance of this fragment.
*/
public class CheckInRecentList extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private RecyclerView recyclerView;
private RecyclerView.Adapter checkInListAdapter;
//private RecyclerView.LayoutManager layoutManager;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private MainViewModel mViewModel;
private CheckInListAdapter adapter;
private MainViewModelProviderFactory viewModelFactory;
private TextView checkInLastDateTime;
private TextView checkInTitle;
private TextView checkInDestinationName;
private TextView checkInComments;
private OnFragmentInteractionListener mListener;
public CheckInRecentList() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment CheckInRecentList.
*/
// TODO: Rename and change types and number of parameters
public static CheckInRecentList newInstance(String param1, String param2) {
CheckInRecentList fragment = new CheckInRecentList();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate: On Create");
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
// These were originally set up from the recycler view add to the fragment
// recyclerView = findViewById(R.id.check_in_recent_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
//recyclerView.setHasFixedSize(true);
/*
// use a linear layout manager
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
*/
// specify an adapter (see also next example)
//checkInListAdapter = new CheckInListAdapter();
// recyclerView.setAdapter(checkInListAdapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
Log.i(TAG, "onCreateView: On Create View");
// Inflate the layout for this fragment
return inflater.inflate(R.layout.recycler_view_item, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
Log.i(TAG, "onButtonPressed: ");
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
Log.i(TAG, "onAttach: OnAttach");
viewModelFactory = new MainViewModelProviderFactory(context.getApplicationContext());
mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
Log.i(TAG,"OnAttach completed");
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i(TAG, "onActivityCreated: On Activity Created");
mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
checkInLastDateTime = getView().findViewById(R.id.checkInLastDateTime);
checkInTitle = getView().findViewById(R.id.checkInTitle);
checkInDestinationName = getView().findViewById(R.id.checkInDestinationName);
checkInComments = getView().findViewById(R.id.checkInComments);
recyclerSetup();
Log.i(TAG,"OnActivityCreated: Recycler SetUp");
//listenerSetup();
//Log.i(TAG, "onActivityCreated: Listener SetUp");
observerSetup();
Log.i(TAG, "onActivityCreated: Observer SetUp");
}
#Override
public void onDetach() {
super.onDetach();
Log.i(TAG, "onDetach: ");
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private void clearFields() {
checkInLastDateTime.setText("");
checkInDestinationName.setText("");
checkInTitle.setText("");
checkInComments.setText("");
}
private void listenerSetup() {
ImageButton editCheckInButton = getView().findViewById(R.id.checkInEditButton);
ImageButton resendCheckInButton = getView().findViewById(R.id.checkInResendButton);
mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
Log.i(TAG, "listenerSetup: ");
editCheckInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//put in edit check in logic
}
});
resendCheckInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//put in resend logic
}
});
}
private void observerSetup() {
Log.i(TAG, "observerSetup:");
if(mViewModel.getAllCheckIn() != null)
mViewModel.getAllCheckIn().observe(getViewLifecycleOwner(), new Observer<List<CheckInTable>>(){
#Override
public void onChanged(#Nullable final List<CheckInTable> allCheckIn) {
adapter.setCheckInList(allCheckIn);
}
});
mViewModel.getAllCheckIn().observe(getViewLifecycleOwner(), new Observer<List<CheckInTable>>() {
#Override
public void onChanged(#Nullable final List<CheckInTable> allCheckIn) {
if (allCheckIn.size() > 0) {
Log.i(TAG, "onChanged: all check in size greater than zero");
checkInLastDateTime.setText(allCheckIn.get(0).getCheckInLastDateTime());
Log.i(TAG, "onChanged: running again");
checkInDestinationName.setText(allCheckIn.get(0).getCheckInDestinationName());
checkInTitle.setText(allCheckIn.get(0).getCheckInTitle());
checkInComments.setText(allCheckIn.get(0).getCheckInComments());
} else {
checkInLastDateTime.setText("None Found");
}
}
});
}
private void recyclerSetup() {
Log.i(TAG, "recyclerSetup: ");
adapter = new CheckInListAdapter(R.layout.fragment_check_in_recent_list);
RecyclerView recyclerView = getView().findViewById(R.id.check_in_recent_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(adapter);
//recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
}
}
The following are the xml files for the fragment
fragment_check_in_recent_list.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CheckInRecentList">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/check_in_recent_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:listitem="#layout/recycler_view_item"/>
</FrameLayout>
and recycler_view_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:padding="8dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableLayout
android:id="#+id/check_in_recent_row"
android:layout_width="389dp"
android:layout_height="match_parent"
android:layout_gravity="center"
android:padding="30dp">
<TableRow
android:layout_width="346dp"
android:layout_height="match_parent">
<TextView
android:id="#+id/checkInLastDateTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"/>
<TextView
android:id="#+id/checkInTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/checkInDestinationName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<ImageButton
android:id="#+id/checkInEditButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_menu_edit"
android:tooltipText="Edit Check In" />
<ImageButton
android:id="#+id/checkInResendButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_menu_share"
android:tooltipText="Resend Check In" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/checkInComments"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</TableRow>
</TableLayout>
</LinearLayout>
CheckInListAdapter
package com.example.checkingin;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Activity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import static androidx.constraintlayout.widget.Constraints.TAG;
public class CheckInListAdapter extends RecyclerView.Adapter<CheckInListAdapter.ViewHolder>{
private int checkInListLayout;
private List<CheckInTable> checkInList;
public CheckInListAdapter(int layoutId) {
checkInListLayout = layoutId;
}
public void setCheckInList(List<CheckInTable> allCheckIn) {
checkInList = allCheckIn;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return checkInList == null ? 0 : checkInList.size();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.i(TAG, "onCreateViewHolder: ");
View view = LayoutInflater.from(
parent.getContext()).inflate(checkInListLayout, parent, false);
ViewHolder checkInListViewHolder = new ViewHolder(view);
return checkInListViewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int listPosition) {
TextView checkInLastDateTime = holder.checkInLastDateTime;
TextView checkInTitle = holder.checkInTitle;
TextView checkInDestinationName = holder.checkInDestinationName;
TextView checkInComments = holder.checkInComments;
ImageView checkInEditButton = holder.checkInEditButton;
ImageView checkInResendButton = holder.checkInResendButton;
Log.i(TAG, "onBindViewHolder: ");
checkInLastDateTime.setText(checkInList.get(listPosition).getCheckInLastDateTime());
checkInTitle.setText(checkInList.get(listPosition).getCheckInTitle());
checkInDestinationName.setText(checkInList.get(listPosition).getCheckInDestinationName());
checkInComments.setText(checkInList.get(listPosition).getCheckInComments());
holder.checkInEditButton.setImageResource(R.drawable.ic_menu_edit);
holder.checkInResendButton.setImageResource(R.drawable.ic_menu_share);
ImageButton editCheckInButton = checkInEditButton.findViewById(R.id.checkInEditButton);
ImageButton resendCheckInButton = checkInResendButton.findViewById(R.id.checkInResendButton);
editCheckInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//put in edit check in logic
}
}
);
resendCheckInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//put in resend logic
}
});
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView checkInLastDateTime;
TextView checkInTitle;
TextView checkInDestinationName;
TextView checkInComments;
ImageView checkInEditButton;
ImageView checkInResendButton;
ViewHolder(View itemView) {
super(itemView);
Log.i(TAG, "ViewHolder: ");
checkInLastDateTime = itemView.findViewById(R.id.checkInLastDateTime);
checkInTitle = itemView.findViewById(R.id.checkInTitle);
checkInDestinationName = itemView.findViewById(R.id.checkInDestinationName);
checkInComments = itemView.findViewById(R.id.checkInComments);
checkInEditButton = itemView.findViewById(R.id.checkInEditButton);
checkInResendButton = itemView.findViewById(R.id.checkInResendButton);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
}
}
Your RecyclerView's ID is check_in_recent_recycler_view. Your findViewById call is using check_in_recent_row. These need to match.

click on textview on listview on fragment

click on textview on listview on fragment
TextView On category_row.xml textViewCategoryName
onclick SetText this textViewCategoryName ok!
CategoriesFragment.java
package com.example;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.example.adapter.CategoryArrayAdapter;
import com.example.model.CategoryDataModel;
import com.example.parser.JSONParser;
import com.example.utils.Keys;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class CategoriesFragment extends Fragment {
private ListView listView;
private ArrayList<CategoryDataModel> list;
private CategoryArrayAdapter adapter;
private TextView categoryCurrent;
public CategoriesFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_categories, null);
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
/**
* Array List for Binding Data from JSON to this List
*/
list = new ArrayList<>();
adapter = new CategoryArrayAdapter(getActivity(), list);
/**
* Getting List and Setting List Adapter
*/
listView = (ListView) getActivity().findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Snackbar.make(getActivity().findViewById(R.id.parentLayout), list.get(position).getCategoryName(), Snackbar.LENGTH_LONG).show();
}
});
/**
* Check internet connection
*/
//if (InternetConnection.checkConnection(getApplicationContext())) {
new GetDataCategories().execute();
//} else {
//Snackbar.make(getActivity().findViewById(R.id.parentLayout), "اتصال به اینترنت برقرار نیست", Snackbar.LENGTH_LONG).show();
//}
}
/**
* Creating Get Data Task for Getting Data From Web
*/
class GetDataCategories extends AsyncTask<Void, Void, Void> {
ContentLoadingProgressBar progressBar;
#Override
protected void onPreExecute() {
super.onPreExecute();
/**
* Progress Bar for User Interaction
*/
progressBar = (ContentLoadingProgressBar) getActivity().findViewById(R.id.progress);
progressBar.show();
}
#Nullable
#Override
protected Void doInBackground(Void... params) {
/**
* Getting JSON Object from Web Using okHttp
*/
JSONObject jsonObject = JSONParser.getDataFromWeb("http://example.com/api-service/v1/platform_categories/");
try {
/**
* Check Whether Its NULL???
*/
if (jsonObject != null) {
/**
* Check Length...
*/
if(jsonObject.length() > 0) {
/**
* Getting Array named "Categories" From MAIN Json Object
*/
JSONArray array = jsonObject.getJSONArray(Keys.KEY_CATEGORIES);
/**
* Check Length of Array...
*/
int lenArray = array.length();
if(lenArray > 0) {
for(int jIndex = 0; jIndex < lenArray; jIndex++) {
/**
* Creating Every time New Object
* and
* Adding into List
*/
CategoryDataModel model = new CategoryDataModel();
/**
* Getting Inner Object from contacts array...
* and
* From that We will get Name of that Contact
*
*/
JSONObject innerObject = array.getJSONObject(jIndex);
String category_name = innerObject.getString(Keys.KEY_CATEGORY_NAME);
String category_link = innerObject.getString(Keys.KEY_CATEGORY_LINK);
/**
* Getting Object from Object "other"
*/
//JSONObject otherObject = innerObject.getJSONObject(Keys.KEY_NAME);
//String other = otherObject.getString(Keys.KEY_NAME_SUB);
model.setCategoryName(category_name);
model.setCategoryLink(category_link);
/**
* Adding data in List...
*/
list.add(model);
}
}
}
} else {
}
} catch (JSONException je) {
Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
/**
* Progress Bar for User Interaction
*/
progressBar.hide();
/**
* Checking if List size if more than zero then
* Update ListView
*/
if(list.size() > 0) {
adapter.notifyDataSetChanged();
} else {
Snackbar.make(getActivity().findViewById(R.id.parentLayout), "مشکلی در اتصال به سرورهای سخنک رخ داده است!", Snackbar.LENGTH_LONG).show();
}
}
}
}
CategoryArrayAdapter.java
package com.example.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.example.R;
import com.example.model.CategoryDataModel;
import java.util.List;
public class CategoryArrayAdapter extends ArrayAdapter<CategoryDataModel> {
List<CategoryDataModel> modelList;
Context context;
private LayoutInflater mInflater;
// Constructors
public CategoryArrayAdapter(Context context, List<CategoryDataModel> objects) {
super(context, 0, objects);
this.context = context;
this.mInflater = LayoutInflater.from(context);
modelList = objects;
}
#Override
public CategoryDataModel getItem(int position) {
return modelList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder vh;
if (convertView == null) {
View view = mInflater.inflate(R.layout.category_row, parent, false);
vh = ViewHolder.create((RelativeLayout) view);
view.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
CategoryDataModel item = getItem(position);
vh.textViewCategoryName.setText(item.getCategoryName());
return vh.rootView;
}
private static class ViewHolder {
public final RelativeLayout rootView;
public final TextView textViewCategoryName;
private ViewHolder(RelativeLayout rootView, TextView textViewCategoryName) {
this.rootView = rootView;
this.textViewCategoryName = textViewCategoryName;
}
public static ViewHolder create(RelativeLayout rootView) {
TextView textViewCategoryName = (TextView) rootView.findViewById(R.id.textViewCategoryName);
return new ViewHolder(rootView, textViewCategoryName);
}
}
}
fragment_categories.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:layout_width="match_parent"
android:id="#+id/parentLayout"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.v4.widget.ContentLoadingProgressBar
android:id="#+id/progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:visibility="visible" />
<ListView app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:id="#+id/listView"
android:layout_width="fill_parent"
android:layout_height="match_parent" />
</android.support.design.widget.CoordinatorLayout>
category_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_centerVertical="true"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/imageViewProfilePhoto">
<TextView
android:id="#+id/textViewCategoryName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
android:textIsSelectable="true"
tools:text="Quote Content" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</LinearLayout>
</LinearLayout>
</RelativeLayout>
You have to set an onClickListener to your TextView in your ViewHolder.
private static class ViewHolder {
public final RelativeLayout rootView;
public final TextView textViewCategoryName;
private ViewHolder(RelativeLayout rootView, TextView textViewCategoryName) {
this.rootView = rootView;
this.textViewCategoryName = textViewCategoryName;
}
public static ViewHolder create(RelativeLayout rootView) {
TextView textViewCategoryName = (TextView) rootView.findViewById(R.id.textViewCategoryName);
textViewCategoryName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Do whatever you want
}
});
return new ViewHolder(rootView, textViewCategoryName);
}
}

onPostExecute is not working in fragment activity

I want to load some data from a website using Jsoup in my fragment activity and show the output in the Textview. I am using AsyncTask to load the data from a website using Jsoup but after successfully getting the data from the website the onPostExecute method in AsyncTask is not displaying the data. I have tried to debug it and it seems like the there is a problem in onPostExecute
and I don't know why.
Here is my code..
MainActivity2.java
package com.example.ebad.bustudentprofile;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import com.example.ebad.bustudentprofile.tabs.SlidingTabLayout;
public class MainActivity2 extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
// Layout manager that allows the user to flip through the pages
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
// getSupportFragmentManager allows use to interact with the fragments
// MyFragmentPagerAdapter will return a fragment based on an index that is passed
viewPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(),
MainActivity2.this));
// Initialize the Sliding Tab Layout
SlidingTabLayout slidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
// Connect the viewPager with the sliding tab layout
slidingTabLayout.setViewPager(viewPager);
}
}
MyFragmentPagerAdapter.java
package com.example.ebad.bustudentprofile;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
private String tabTitles[] = new String[]{"Tab 1", "Tab 2", "Tab 3"};
private Context context;
public MyFragmentPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return 3;
}
// Return the correct Fragment based on index
#Override
public Fragment getItem(int position) {
if (position == 0) {
return new TabFragment1();
} else if (position == 1) {
return new TabFragment2();
} else if (position == 2) {
return new TabFragment3();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
// Return the tab title to SlidingTabLayout
return tabTitles[position];
}
}
TabFragment1.java
package com.example.ebad.bustudentprofile;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.util.HashMap;
public class TabFragment1 extends Fragment {
ProgressDialog progressDialoge;
TextView fa, na;
String urlw = "http://111.68.99.8/StudentProfile/PersonalInfo.aspx";
HashMap<String, String> hashMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
hashMap = Data.map;
//hashMap = (HashMap<String, String>) getArguments().get("hashMap");
View rootview = inflater.inflate(R.layout.tab_fragment_1, container, false);
Activity activity = getActivity();
fa = (TextView) rootview.findViewById(R.id.Fathere);
na = (TextView) rootview.findViewById(R.id.Y_Name);
new peea(activity,rootview).execute();
return inflater.inflate(R.layout.tab_fragment_1, container, false);
}
private class peea extends AsyncTask<Void, Void, Void> {
String father ;
String son ;
private Context activity;
private View rootView;
public peea(Context context, View main){
this.activity=context;
this.rootView=main;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialoge = new ProgressDialog(getActivity());
progressDialoge.setMessage("Getting into your information");
progressDialoge.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Document doce = Jsoup.connect(urlw)
.cookies(hashMap)
.get();
father = doce.select("span[id=ctl00_Body_FATHERNAME]").html();
son = doce.select("span[id=ctl00_Body_NAME]").html();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPreExecute();
TextView wa = (TextView)rootView.findViewById(R.id.Y_Name);
wa.setText(son);
/*fa.setText(father);
na.setText(son);*/
/*fa = (TextView)findViewById(R.id.das);
fa.setText(father);*/
progressDialoge.dismiss();
}
}
}
tab_fragment_1.xml
<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:id="#+id/Fathere"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Father Name"
android:textSize="25dp" />
<TextView
android:id="#+id/Y_Name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Your name"
android:textSize="30dp" />
</LinearLayout>
If you guys tell where the problem is or how to solve it, it will be very helpful to me
I don't think that your super class has an onPreExecute function, so
super.onPreExecute();
may be causing you some issues. You can try
super.onPostExecute();
That may be fix it.

How do I change my Activity's fragment container's background with a custom dialog with code?

Fairly new to Android and I am trying to do some background color changes. Basically I have a main activity that only has a FrameLayout in it's xml. When the activity is created it opens up a fragment for my program. I have a menu item that when clicked pops a dialog box with 3 seekbars(red, green, blue). I want to change the background color to whatever the seekbars position is. I have all the code finished for the seekbars and I know it works on a simple app I created. For reasons to me unknown my app fails when i try to open the dialog box. What is the proper way to set this up in the Main Activity? I want the user to be able to change the background color whenever they want. All my fragment layouts are transparent. This is the tutorial I have been working off of. http://android-er.blogspot.com/2009/08/change-background-color-by-seekbar.html Any advice would be great. I think my problem is I do not fully understand how to access my main_activity's FrameLayout from with-in my MainActivity java class.
activity_main.xml
<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"
tools:context=".MainActivity"
android:orientation="vertical"
android:background="#e3a153">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragmentView"></FrameLayout>
</LinearLayout>
Color_seekbar_selecter.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/myScreen"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Change color"
/>
<SeekBar
android:id="#+id/mySeekingBar_R"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="255"
android:progress="0"/>
<SeekBar
android:id="#+id/mySeekingBar_G"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="255"
android:progress="0"/>
<SeekBar
android:id="#+id/mySeekingBar_B"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="255"
android:progress="0"/>
</LinearLayout>
menu_main.xml
<menu 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"
tools:context=".MainActivity">
<item android:id="#+id/menu_settings"
android:title="Green" />
<item android:id="#+id/menu_red"
android:title="Red" />
<item android:id="#+id/menu_blue"
android:title="Blue" />
<item android:id="#+id/menu_tan"
android:title="Tan" />
</menu>
MainActivity.java
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Toast;
import java.util.zip.Inflater;
public class MainActivity extends ActionBarActivity {
//public CategoryFragment categoryFragment;
//public RecipeFragment recipeFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null)
{
CategoryFragment categoryFragment = new CategoryFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.fragmentView, categoryFragment, "categoryFrag")
.commit();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPostResume() {
super.onPostResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate( R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.menu_green:
}
return super.onOptionsItemSelected(item);
}
}
I have tried for hours to figure this out, but I just don't know where to put what.
This is the code from the example that I found in the link posted above.
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.SeekBar;
public class SeekColorActivity extends Activity {
private int seekR, seekG, seekB;
SeekBar redSeekBar, greenSeekBar, blueSeekBar;
LinearLayout mScreen;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mScreen = (LinearLayout) findViewById(R.id.myScreen);
redSeekBar = (SeekBar) findViewById(R.id.mySeekingBar_R);
greenSeekBar = (SeekBar) findViewById(R.id.mySeekingBar_G);
blueSeekBar = (SeekBar) findViewById(R.id.mySeekingBar_B);
updateBackground();
redSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);
greenSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);
blueSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);
}
private SeekBar.OnSeekBarChangeListener seekBarChangeListener
= new SeekBar.OnSeekBarChangeListener()
{
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
updateBackground();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
};
private void updateBackground()
{
seekR = redSeekBar.getProgress();
seekG = greenSeekBar.getProgress();
seekB = blueSeekBar.getProgress();
mScreen.setBackgroundColor(
0xff000000
+ seekR * 0x10000
+ seekG * 0x100
+ seekB
);
}
}
categoryFragment.java
package com.example.mikesgamerig.finalproject;
import android.app.AlertDialog;
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.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class CategoryFragment extends Fragment {
private ArrayList<String> categoryNameArrayList;
private ArrayAdapter<String> adapter;
private AlertDialog alertDialog;
private AlertDialog alertDialogDelete;
private EditText categoryEditText;
private String getCategoryName;
private List<Category> cats;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//create view
View rootView = inflater.inflate(R.layout.fragment_category, container, false);
//initialize all variables and widgets
inflater = getLayoutInflater(savedInstanceState);
alertDialog = new AlertDialog.Builder(getActivity()).create();
alertDialog.setView(inflater.inflate(R.layout.dialog_add_category, null));
alertDialogDelete = new AlertDialog.Builder(getActivity()).create();
alertDialogDelete.setView(inflater.inflate(R.layout.dialog_delete_category, null));
Button buttonAddCategory = (Button) rootView.findViewById(R.id.addCategoryButton);
ListView categoryListView = (ListView) rootView.findViewById(R.id.list);
//Array list to store names of categories
categoryNameArrayList = new ArrayList<String>();
//List of Category Objects
cats = Category.listAll(Category.class);
getCategoryNames();
//iterate through the CategoryList and attach to the ArrayList
//create adapter and fill the listView with all the name of categories
adapter = new ArrayAdapter<String>(getActivity(), R.layout.rowlayout, R.id.label, categoryNameArrayList);
categoryListView.setAdapter(adapter);
//set OnClick listener for the add category Button.
// This calls another method that will open a custom dialog box
buttonAddCategory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DisplayAddCategoryDialogBox();
}
});
//set an onItemLongClick listener for the ListView.
//First have to setLongClickable to true.
//the OnItemLongClick listener will call a method to open a custom Dialog to delete a category.
categoryListView.setLongClickable(true);
categoryListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
DeleteCategory(i);
return true;
}
});
//opens up a new fragment with a list of recipes for the specific category.
categoryListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = categoryNameArrayList.get(i);
RecipeFragment fragment = new RecipeFragment();
fragment.SetTitleName(name);
getFragmentManager().beginTransaction()
.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right)
.replace(R.id.fragmentView, fragment)
.addToBackStack(null).commit();
}
});
return rootView;
}
//This method will Display a custom add category Dialog Box.
public void DisplayAddCategoryDialogBox(){
//Show the Dialog box to enter a new category name.
alertDialog.show();
categoryEditText = (EditText) alertDialog.findViewById(R.id.categoryEditText);
Button saveCategoryDialogBtn = (Button) alertDialog.findViewById(R.id.saveBtn);
Button cancelDialogButton = (Button) alertDialog.findViewById(R.id.cancelBtn);
saveCategoryDialogBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getCategoryName = categoryEditText.getText().toString();
//Log.d("STRING VALUE:", getCategoryName);
Category test = new Category(getCategoryName);
test.save();
categoryNameArrayList.add(test.getName());
//Log.d("added Value: ", test.getName());
adapter.notifyDataSetChanged();
alertDialog.hide();
}
});
cancelDialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertDialog.hide();
}
});
}
//this method will display a custom Delete Category Alert Dialog box.
public void DeleteCategory(final int i)
{
alertDialogDelete.show();
Button noBtn = (Button) alertDialogDelete.findViewById(R.id.noBtn);
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertDialogDelete.hide();
}
});
Button yesBtn = (Button) alertDialogDelete.findViewById(R.id.yesBtn);
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String tempString = categoryNameArrayList.get(i);
//Log.d("VALUE OF STRING= ", tempString);
categoryNameArrayList.remove(i);
for (Category category : cats) {
String name = category.getName();
if (name.equals(tempString)) {
category.delete();
}
}
adapter.notifyDataSetChanged();
alertDialogDelete.hide();
}
});
}
//Filles the Array
public void getCategoryNames()
{
for(Category category : cats)
{
String name = category.getName();
categoryNameArrayList.add(name);
}
}
}

Actionbarsherlock crashes on screen rotation using latest version

I'm wondering if anyone can help me. I'm pretty new to programming and this is a little over my head, but once this issue is resolved I think I can complete the rest of my program with my current skill set (I hope). Anyway, I'm using Actionbarsherlock to create a swipe tab interface. The code I used was found on Youtube as an example of how to do it. The URL to download the source is: https://www.dropbox.com/s/p91dzt4dekuia3q/SwipeyTabs.zip if anyone wants to look. The sourcecode is available for download, but I'll post what I believe are the relevant parts here. Basically, whenever the device (and emulator) is rotated, the app crashes. If I start the device in landscape mode, it works until rotated into portrait, and if I start in portrait it works until rotated into landscape. I get a null pointer exception as the error and could provide the logcat output if needed.
The MainActivity.java file is:
package com.rufflez.swipeytabs;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
public class MainActivity extends SherlockFragmentActivity {
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
final ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setText("Fragment 1"), Fragment_1.class, null);
mTabsAdapter.addTab(bar.newTab().setText("Fragment 2"), Fragment_2.class, null);
mTabsAdapter.addTab(bar.newTab().setText("Fragment 3"), Fragment_3.class, null);
mTabsAdapter.addTab(bar.newTab().setText("Fragment 4"), Fragment_4.class, null);
}
}
The TabsAdapter.java file is:
package com.rufflez.swipeytabs;
import java.util.ArrayList;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockFragmentActivity;
public class TabsAdapter extends FragmentPagerAdapter implements ActionBar.TabListener , ViewPager.OnPageChangeListener{
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
private final String TAG = "21st Polling:";
static final class TabInfo{
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args){
clss = _class;
args = _args;
}
}
public TabsAdapter(SherlockFragmentActivity fa, ViewPager pager) {
super(fa.getSupportFragmentManager());
mContext = fa;
mActionBar = fa.getSupportActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args){
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
Log.v(TAG, "clicked");
Object tag = tab.getTag();
for (int i = 0; i<mTabs.size(); i++){
if (mTabs.get(i) == tag){
mViewPager.setCurrentItem(i);
}
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(mContext, "You've deselected a tab", Toast.LENGTH_SHORT).show();
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
#Override
public int getCount() {
return mTabs.size();
}
}
Each Fragment_#.java is basically this with the appropriate reference:
package com.rufflez.swipeytabs;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.app.SherlockFragment;
public class Fragment_1 extends SherlockFragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_1, container, false);
}
}
The activity_main.xml is:
<RelativeLayout 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"
tools:context=".MainActivity" >
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/pager" />
</RelativeLayout>
Each fragment_#.xml is basically this with the appropriate reference changed:
<?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="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Fragment 1"/>
</LinearLayout>
From what I could figure out, doing several hours of research, is that this used to be a bug in ABS that was addressed several versions ago and likely this issue is somehow connected to that issue. Any help would be very much appreciated. Especially if you can provide it in a teacher-student style so I can learn more effectively. :-) Thanks in advance to anyone attempting to help though!

Categories