I have a ListView and I want to display the selected list content in a popup when I click on it in the view. How can I do this?
Here's my code:
public class EventbyDate extends ListActivity {
Context cont;
private Runnable DateEventListThread;
public String DateEventListThreadResponse;
private ProgressDialog m_ProgDialog = null;
public DateEventListAdapter DateEventList_adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.eventsbydate);
GetDateEventList();
this.DateEventList_adapter = new DateEventListAdapter(this,R.layout.eventsbydate_list,
RoamMeo_Config.DateEventList);
setListAdapter(this.DateEventList_adapter);
}
#Override
public void onPause() {
super.onPause();
this.finish();
}
void GetDateEventList() {
m_ProgDialog = ProgressDialog.show(EventbyDate.this, " Please wait",
"Collecting Data..", true);
DateEventListThread = new Runnable() {
#Override
public void run() {
DateEventListThread = null;
try {
} catch (Exception e) {
e.printStackTrace();
}
runOnUiThread(returnResponse);
}
};
Thread thread = new Thread(null, DateEventListThread, "DateEventListThread");
thread.start();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
LayoutInflater inflater = (LayoutInflater) EventbyDate.
this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
PopupWindow pw = new PopupWindow(inflater.inflate(R.layout.popup,null,
false),300,400,true);
pw.showAtLocation(findViewById(R.id.txt_start_date),
Gravity.CENTER, 0,0);
}
private Runnable returnResponse = new Runnable() {
#Override
public void run() {
try {
if (DateEventListThreadResponse != null&&
DateEventListThreadResponse.length() > 0) {
boolean check =
XMLParsing.EventDate_List_Response(DateEventListThreadResponse);
if(check) {
DateEventList_adapter.notifyDataSetChanged();
} else {
Toast msg =
Toast.makeText(EventbyDate.this,"No list... ",Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER,
msg.getXOffset() / 2,msg.getYOffset() / 2);
msg.show();
}
}
if (m_ProgDialog != null)
m_ProgDialog.dismiss();
m_ProgDialog = null;
} catch (Exception e) {
if (m_ProgDialog != null)
m_ProgDialog.dismiss();
m_ProgDialog = null;
}
}
};
class DateEventListAdapter extends ArrayAdapter<SaveDateEventList> {
ArrayList<SaveDateEventList> items;
public DateEventListAdapter(Context context, int
textViewResourceId,
ArrayList<SaveDateEventList> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup
parent) {
View v = convertView;
final SaveDateEventList d = items.get(position);
if (v == null) {
LayoutInflater vi = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.eventsbydate_list, null);
}
if (!items.isEmpty()) {
if (d != null) {
TextView start_date = (TextView)
v.findViewById(R.id.txt_start_date);
start_date.setText(d.ev_start_date);
TextView start_time = (TextView)
v.findViewById(R.id.txt_start_time);
start_time.setText(d.ev_start_time);
TextView poptext = (TextView)
v.findViewById(R.id.poptext);
poptext.setText(d.ev_start_time);
}
}
return v;
}
}
}
You can do something like this, protected void onListItemClick(ListView l, View v, int position, long id) {YourObject o = l.getItemAtPosition(position);}. After that you have to set what ever you need to display in your pop-up screen via this obtained object.
Related
Hello to all android folks over there!!
I want to get list of objects from web service and want to display them in list view.Now i am able to fetch those values and collected them in arraylist.But i am facing problem to display them in list view.below is my code.
Using everyones suggestion ,i solved my problem.Thats the spirit of android buddies.I am pasting my answer in UPDATED block.Hope it will be helpful in future.
UPDATED
public class TabFragment2 extends android.support.v4.app.Fragment {
ListView FacultyList;
View rootView;
LinearLayout courseEmptyLayout;
FacultyListAdapter facultyListAdapter;
String feedbackresult,programtype,programname;
Boolean FeedBackResponse;
String FacultiesList[];
public ArrayList<Faculty> facultylist = new ArrayList<Faculty>();
SharedPreferences pref;
FacultyListAdapter adapter;
SessionSetting session;
public TabFragment2(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = getActivity().getSharedPreferences("prefbook", getActivity().MODE_PRIVATE);
programtype = pref.getString("programtype", "NOTHINGpref");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_studenttab2, container, false);
session = new SessionSetting(getActivity());
new FacultySyncerBg().execute("");
courseEmptyLayout = (LinearLayout) rootView.findViewById(R.id.feedback_empty_layout);
FacultyList = (ListView) rootView.findViewById(R.id.feedback_list);
facultyListAdapter = new FacultyListAdapter(getActivity());
FacultyList.setEmptyView(rootView.findViewById(R.id.feedback_list));
FacultyList.setAdapter(facultyListAdapter);
return rootView;
}
public class FacultyListAdapter extends BaseAdapter {
private final Context context;
public FacultyListAdapter(Context context) {
this.context = context;
if (!facultylist.isEmpty())
courseEmptyLayout.setVisibility(LinearLayout.GONE);
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final ViewHolder TabviewHolder;
if (convertView == null) {
TabviewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_feedback,
parent, false);
TabviewHolder.FacultyName = (TextView) convertView.findViewById(R.id.FacultyName);//facultyname
TabviewHolder.rating = (RatingBar) convertView.findViewById(R.id.rating);//rating starts
TabviewHolder.Submit = (Button) convertView.findViewById(R.id.btnSubmit);
// Save the holder with the view
convertView.setTag(TabviewHolder);
} else {
TabviewHolder = (ViewHolder) convertView.getTag();
}
final Faculty mFac = facultylist.get(position);//*****************************NOTICE
TabviewHolder.FacultyName.setText(mFac.getEmployeename());
// TabviewHolder.ModuleName.setText(mFac.getSubject());
TabviewHolder.rating.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
feedbackresult =String.valueOf(rating);
}
});
return convertView;
}
#Override
public int getCount() {
return facultylist.size();
}
#Override
public Object getItem(int position) {return facultylist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
static class ViewHolder {
TextView FacultyName;
RatingBar rating;
Button Submit;
}
private class FacultySyncerBg extends AsyncTask<String, Integer, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog= ProgressDialog.show(getActivity(), "Faculty Feedback!","Fetching Faculty List", true);
}
#Override
protected Void doInBackground(String... params) {
//CALLING WEBSERVICE
Faculty(programtype);
return null;
}
#Override
protected void onPostExecute(Void result) {
/*if (FacultyList.getAdapter() != null) {
if (FacultyList.getAdapter().getCount() == 0) {
FacultyList.setAdapter(facultyListAdapter);
} else
{
facultyListAdapter.notifyDataSetChanged();
}
} else {
FacultyList.setAdapter(facultyListAdapter);
}
progressDialog.dismiss();*/
if (!facultylist.isEmpty()) {
// FacultyList.setVisibiltity(View.VISIBLE) ;
courseEmptyLayout.setVisibility(LinearLayout.GONE);
if (FacultyList.getAdapter() != null)
{
if (FacultyList.getAdapter().getCount() == 0)
{
FacultyList.setAdapter(facultyListAdapter);
}
else
{
facultyListAdapter.notifyDataSetChanged();
}
}
else
{
FacultyList.setAdapter(facultyListAdapter);
}
}else
{
courseEmptyLayout.setVisibility(LinearLayout.VISIBLE);
// FacultyList.setVisibiltity(View.GONE) ;
}
progressDialog.dismiss();
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && isResumed()) {
new FacultySyncerBg().execute("");
}
}//end*
//**************************WEBSERVICE CODE***********************************
public void Faculty(String programtype)
{
String URL ="http://detelearning.cloudapp.net/det_skill_webservice/service.php?wsdl";
String METHOD_NAMEFACULTY = "getUserInfo";
String NAMESPACEFAC="http://localhost", SOAPACTIONFAC="http://detelearning.cloudapp.net/det_skill_webservice/service.php/getUserInfo";
String faculty[]=new String[4];//changeit
String webprogramtype="flag";
String programname="DESHPANDE SUSANDHI ELECTRICIAN FELLOWSHIP";
// Create request
SoapObject request = new SoapObject(NAMESPACEFAC, METHOD_NAMEFACULTY);
request.addProperty("fellowshipname", programname);
// Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
// Set output SOAP object
envelope.setOutputSoapObject(request);
// Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
//my code Calling Soap Action
androidHttpTransport.call(SOAPACTIONFAC, envelope);
// ArrayList<Faculty> facultylist = new ArrayList<Faculty>();
java.util.Vector<SoapObject> rs = (java.util.Vector<SoapObject>) envelope.getResponse();
if (rs != null)
{
for (SoapObject cs : rs)
{
Faculty rp = new Faculty();
rp.setEmployeename(cs.getProperty(0).toString());//program name
rp.setEmployeeid(cs.getProperty(1).toString());//employee name
facultylist.add(rp);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
if (lstView.getAdapter() != null) {
if (lstView.getAdapter().getCount() == 0) {
lstView.setAdapter(finalAdapter);
} else {
finalAdapter.notifyDataSetChanged();
}
} else {
lstView.setAdapter(finalAdapter);
}
and setVisibiltity(View.VISIBLE)for listview
Put this code here
#Override
protected void onPostExecute(Void result) {
if (!facultylist.isEmpty()) {
FacultyList.setVisibiltity(View.VISIBLE) ;
courseEmptyLayout.setVisibility(LinearLayout.GONE);
if (FacultyList.getAdapter() != null) {
if (FacultyList.getAdapter().getCount() == 0) {
FacultyList.setAdapter(facultyListAdapter);
} else {
facultyListAdapter.notifyDataSetChanged();
}
} else {
FacultyList.setAdapter(facultyListAdapter);
}
}else{
courseEmptyLayout.setVisibility(LinearLayout.VISIBLE);
FacultyList.setVisibiltity(View.GONE) ;
}
progressDialog.dismiss();
}
you can try this:
this is the adapter class code.
public class CustomTaskHistory extends ArrayAdapter<String> {
private Activity context;
ArrayList<String> listTasks = new ArrayList<String>();
String fetchRefID;
StringBuilder responseOutput;
ProgressDialog progress;
String resultOutput;
public String getFetchRefID() {
return fetchRefID;
}
public void setFetchRefID(String fetchRefID) {
this.fetchRefID = fetchRefID;
}
public CustomTaskHistory(Activity context, ArrayList<String> listTasks) {
super(context, R.layout.content_main, listTasks);
this.context = context;
this.listTasks = listTasks;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_task_history, null, true);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
LinearLayout linearLayout = (LinearLayout) listViewItem.findViewById(R.id.firstLayout);
//System.out.println("client_id" + _clientID);
//TextView textViewDesc = (TextView) listViewItem.findViewById(R.id.textViewDesc);
//ImageView image = (ImageView) listViewItem.findViewById(R.id.imageView);
if (position % 2 != 0) {
linearLayout.setBackgroundResource(R.color.sky_blue);
} else {
linearLayout.setBackgroundResource(R.color.white);
}
textViewName.setText(listTasks.get(position));
return listViewItem;
}
}
and now in the parent class you must have already added a list view in your xml file so now display code for it is below:
CustomTaskHistory customList = new CustomTaskHistory(TaskHistory.this, task_history_name);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(customList);
you can also perform any action on clicking cells of listview.If needed code for it is below add just below the above code:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent nextScreen2 = new Intent(getApplicationContext(), SubscribeProgrammes.class);
nextScreen2.putExtra("CLIENT_ID", _clientID);
nextScreen2.putExtra("REFERENCE_ID", reference_IDs.get(i));
startActivity(nextScreen2);
Toast.makeText(getApplicationContext(), "You Clicked " + task_list.get(i), Toast.LENGTH_SHORT).show();
}
});
This is my fragment where I create the listview. When the data changed the listview is not notify. How can I do this? I make the request in viewModel using volley. I receive the next error: java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. Make sure your adapter calls notifyDataSetChanged() when its content changes. [in ListView(2131558620, class android.widget.ListView) with Adapter(class pharma.com.pharmaapp.Common.EventsArrayAdapter)]
at android.widget.ListView.layoutChildren(ListView.java:1582)
public class EventesFragment extends Fragment {
private final String TAG = EventesFragment.class.getSimpleName();
private ArrayList<EvenimentType> events = new ArrayList<>();
private ListView eventsListView;
private SwipeRefreshLayout swipeContainer;
public EventsArrayAdapter eventsArrayAdapter;
private EventsFragmentViewModel eventsFragmentViewModel = new EventsFragmentViewModel();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_events, container, false);
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), SearchActivity.class);
startActivity(intent);
}
});
if(events.size() != 0) {
events.clear();
}
eventsListView = (ListView) view.findViewById(R.id.listView_events);
swipeContainer = (SwipeRefreshLayout) view.findViewById(R.id.swipeContainer);
eventsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name = ((EvenimentType) eventsListView.getAdapter().getItem(position)).getName();
Log.d(TAG, "Click " + name);
Intent intent = new Intent(getActivity(), SelectedEventActivity.class);
intent.putExtra("Parceable", events.get(position));
startActivity(intent);
}
});
eventsListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
String name = ((EvenimentType) eventsListView.getAdapter().getItem(position)).getName();
return false;
}
});
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
events.clear();
eventsFragmentViewModel.loadEvents(getActivity());
eventsFragmentViewModel.setInterface(new EventsFragmentViewModel.EventsFragmentInterface() {
#Override
public void takeData(ArrayList<EvenimentType> list) {
if(eventsArrayAdapter == null) {
eventsArrayAdapter = new EventsArrayAdapter(getActivity(), list);
eventsListView.setAdapter(eventsArrayAdapter);
swipeContainer.setRefreshing(false);
} else {
events = list;
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
eventsArrayAdapter.notifyDataSetChanged();
}
});
swipeContainer.setRefreshing(false);
}
}
});
}
});
loadEvents();
return view;
}
public void loadElementsToArrayAdapter() {
eventsArrayAdapter = new EventsArrayAdapter(getContext(), events);
// eventsArrayAdapter.notifyDataSetChanged();
swipeContainer.setRefreshing(false);
eventsListView.setAdapter(eventsArrayAdapter);
eventsFragmentViewModel.saveEvents(events, getActivity());
}
public void loadEvents() {
eventsFragmentViewModel.loadEvents(getActivity());
eventsFragmentViewModel.setInterface(new EventsFragmentViewModel.EventsFragmentInterface() {
#Override
public void takeData(ArrayList<EvenimentType> list) {
events = list;
loadElementsToArrayAdapter();
}
});
}
#Override
public void onResume() {
super.onResume();
// eventsFragmentViewModel.getUserEventsId(getActivity());
}
}
This is the Base Adapter class:
public class EventsArrayAdapter extends BaseAdapter {
private static final String TAG = EventsArrayAdapter.class.getSimpleName();
private Context context;
private List<EvenimentType> list = null;
public EventsArrayAdapter(Context context, List<EvenimentType> objects) {
this.context = context;
this.list = objects;
}
public void addAll(List<EvenimentType> objects) {
if(list == null) {
list = new ArrayList<>();
}
list.addAll(objects);
notifyDataSetChanged();
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(convertView == null) {
convertView = inflater.inflate(R.layout.item_array_adapter, null);
}
TextView title = (TextView) convertView.findViewById(R.id.text_simposion_title);
TextView date = (TextView) convertView.findViewById(R.id.text_simposion_date);
TextView location = (TextView) convertView.findViewById(R.id.text_simposion_location);
TextView price = (TextView) convertView.findViewById(R.id.text_simposion_price);
ImageView image = (ImageView) convertView.findViewById(R.id.image_event);
Log.d(TAG, "Checking: " + checkEvent(list.get(position)));
if (checkSelection(list.get(position)) == true) {
title.setText(list.get(position).getName());
date.setText(list.get(position).getDate());
location.setText(list.get(position).getLocation());
price.setText(list.get(position).getPaid());
image.setImageResource(R.drawable.ic_simposions);
} else {
title.setText(list.get(position).getName());
date.setText(list.get(position).getDate());
location.setText(list.get(position).getLocation());
price.setText(list.get(position).getPaid());
}
Log.d(TAG, "getView");
return convertView;
}
This is the viewModel where I make the request
public class EventsFragmentViewModel extends LoginViewModel {
private static final String TAG = EventsFragmentViewModel.class.getSimpleName();
private ArrayList<EvenimentType> events = new ArrayList<>();
EventsFragmentInterface listener = null;
public void loadEvents(final Context context) {
DataServices dataServices = new DataServices(context);
dataServices.getEvents();
dataServices.setCommunicationInterface(new RequestToServer.CommunicationInterface() {
#Override
public void takeResponse(JSONObject response) {
try {
Log.d(TAG, response.toString());
EvenimentType evenimentType = new EvenimentType();
JSONArray obj = response.getJSONArray("entry");
Log.d(TAG, obj.length() + "");
for (int i = 0; i < obj.length(); i++) {
events.add(evenimentType.createEvent(obj.getJSONObject(i)));
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d(TAG, "EVENTS: " + events.size());
if(listener!= null) {
listener.takeData(events);
}
}
});
}
public void saveEvents(ArrayList<EvenimentType> list, Context context) {
Preferences preferences = new Preferences(context);
preferences.saveToSharedPreferencesEvents(list);
preferences.getFromSharedPreferencesEvents();
}
public void setInterface(EventsFragmentInterface listener) {
this.listener = listener;
}
public interface EventsFragmentInterface {
public void takeData(ArrayList<EvenimentType> list);
}
}
In my app I'm showing data in listview. While scrolling through listview my app is crashing. What changes should I make?
as given in the error my RecipeListFragment.java file is:
public class RecipeListFragment extends Fragment {
MyDatabase db;
boolean isfav = false;
Context context;
ListView lvrecipe;
ArrayList<RecipePojo> recipelist = new ArrayList<RecipePojo>();
LinearLayout ll;
DisplayImageOptions options;
private ProgressDialog progress;
int position;
String recipeid;
int checkcounter = 0;
private Custom_Adapter adapter;
public RecipeListFragment() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_recipe_list_actvity, container, false);
context = getActivity();
lvrecipe = (ListView) rootView.findViewById(R.id.lvrecipe);
// adView = (MoPubView)rootView. findViewById(R.id.mopub_sample_ad);
new getrecipe().execute();
db = new MyDatabase(getActivity());
// recipelist = DataManager.recipelist;
position = DataManager.selectedposition;
adapter = new Custom_Adapter(getActivity());
adapter.notifyDataSetChanged();
lvrecipe.setAdapter(adapter);
/* if(recipeid!=null){
checkcounter = db.checkrecipefav(recipeid);
}
if (checkcounter > 0) {
isfav = true;
} else {
isfav = false;
}
db.close();*/
lvrecipe.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
DataManager.selectedposition = position;
Intent i = new Intent(getActivity(), RecipeDescription.class);
i.putExtra("cusinename", DataManager.cusinename);
startActivity(i);
getActivity().finish();
}
});
// adddisplay();
return rootView;
}
#Override
public void onResume() {
super.onResume();
}
public class Custom_Adapter extends BaseAdapter {
private LayoutInflater mInflater;
public Custom_Adapter(Context c) {
mInflater = LayoutInflater.from(c);
}
#Override
public int getCount() {
if (recipelist != null) {
return recipelist.size();
} else {
return 0;
}
}
#Override
public Object getItem(int position) {
if (recipelist != null) {
return recipelist.get(position);
} else {
return 0;
}
}
#Override
public long getItemId(int position) {
if (recipelist != null) {
return position;
} else {
return 0;
}
}
#SuppressWarnings("deprecation")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.recipelist, null);
holder = new ViewHolder();
holder.txttile = (TextView) convertView.findViewById(R.id.txttile);
holder.imgrecipe = (ImageView) convertView.findViewById(R.id.imgrecipe);
holder.fav_unfav = (ImageView) convertView.findViewById(R.id.fav_unfav);
holder.ratingbar = (RatingBar) convertView.findViewById(R.id.ratingbar);
holder.txtduration = (TextView) convertView.findViewById(R.id.txtduration);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (recipelist != null) {
recipeid = recipelist.get(position).getRecipeid();
checkcounter = db.checkrecipefav(recipeid);
}
if (checkcounter > 0) {
isfav = true;
} else {
isfav = false;
}
db.close();
if (isfav) {
holder.fav_unfav.setImageResource(R.drawable.favourite);
} else {
holder.fav_unfav.setImageResource(R.drawable.favourites);
}
Typeface face1 = Typeface.createFromAsset(getActivity().getAssets(), "sinkin_sans_300_light.ttf");
Typeface face2 = Typeface.createFromAsset(getActivity().getAssets(), "sinkin_sans_400_regular.ttf");
holder.txttile.setTypeface(face2);
holder.txtduration.setTypeface(face1);
holder.txttile.setText(recipelist.get(position).getRecipename());
try {
String[] prep = recipelist.get(position).getPrep_time().split(" ");
String[] cook = recipelist.get(position).getCooking_time().split(" ");
int totalTime = Integer.parseInt(prep[0]) + Integer.parseInt(cook[0]);
holder.txtduration.setText(""+totalTime+" min");
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
String url = DataManager.photourl + "recipe/" + recipelist.get(position).getRecipeid() + ".jpg";
try {
url = URLDecoder.decode(url, "UTF-8");
url = url.replaceAll(" ", "%20");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if (recipelist.get(position).getVideo_link().equals("none")) {
// holder.imgvideo.setVisibility(View.GONE);
}
String rating = recipelist.get(position).getRatings();
if (rating != null && rating.trim().length() > 0) {
holder.ratingbar.setRating(Float.valueOf(rating));
}
//holder.imgrecipe.setImage(url,getResources().getDrawable(R.drawable.cusine));
if (holder.imgrecipe != null) {
if (url != null && url.trim().length() > 0) {
//final ProgressBar pbar = holder.pbar;
final ImageView imageView = holder.imgrecipe;
//final RelativeLayout imgRL = holder.imageRL;
ImageLoader.getInstance().displayImage(url, holder.imgrecipe, options, new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(String imageUri,
View view, Bitmap loadedImage) {
super.onLoadingComplete(imageUri, view, loadedImage);
imageView.setAdjustViewBounds(true);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
super.onLoadingFailed(imageUri, view, failReason);
}
#Override
public void onLoadingStarted(String imageUri, View view) {
super.onLoadingStarted(imageUri, view);
}
});
} else {
}
}
return convertView;
}
class ViewHolder {
TextView txttile, txtduration;
ImageView imgrecipe;
ImageView fav_unfav;
RatingBar ratingbar;
}
}
public class getrecipe extends AsyncTask<String, Void, String> {
boolean response = false;
#Override
protected void onPreExecute() {
//progress = ProgressDialog.show(context, "Getting Data...","Please wait....");
progress = new ProgressDialog(getActivity());
progress.setMessage("Please wait....");
progress.show();
}
#Override
protected String doInBackground(String... params) {
response = APIManager.getrecipebycusine(DataManager.CUISINE_ID);
return "";
}
#Override
protected void onPostExecute(String result) {
progress.cancel();
if (response) {
if (DataManager.status.equalsIgnoreCase("1")) {
recipelist = DataManager.recipelist;
adapter.notifyDataSetChanged();
//Intent i = new Intent(getActivity(),RecipeListActvity.class);
//startActivity(i);
} else {
connectionerror();
}
} else {
connectionerror();
}
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
public void alert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("No Recipe!");
alertDialog.setMessage("No Recipe for this Cusine");
alertDialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
public void connectionerror() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Error!");
alertDialog.setMessage("Connection Lost ! Try Again");
alertDialog.setPositiveButton("Retry",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new getrecipe().execute();
}
});
alertDialog.show();
}}
The errors that are showing in Crashlytics is:
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:154)
at android.app.AlertDialog$Builder.<init>(AlertDialog.java:379)
at com.raccoonfinger.salad.RecipeListFragment.connectionerror(RecipeListFragment.java:381)
at com.raccoonfinger.salad.RecipeListFragment$getrecipe.onPostExecute(RecipeListFragment.java:335)
at com.raccoonfinger.salad.RecipeListFragment$getrecipe.onPostExecute(RecipeListFragment.java:296)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Method.java)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Please do not use getActivity() directly in Fragment because sometimes it returns null..
Always pass activity as a parameter in constructor..!!
Please use below method to create your Fragment and use activity reference instead of getActivity()..
public static AboutFragment newInstance(Activity activity) {
AboutFragment aboutFragment = new AboutFragment();
aboutFragment.mActivity = activity;
return aboutFragment;
}
Hope it will help.
Thanks ..!!
I've got a custom listview inside a fragment that inflates a PopupWindow whenever an message is clicked.
However I can't seem to figure out why the buttons in the list-view header are using a different theme/style than the normal rows in the listview. Can someone please care to explain?
List-view item:
List-view header:
This is how i inflate the toolbar:
popup = new PopupWindow(inflater.inflate(R.layout.message_tool, null, false));
popup.setWindowLayoutMode(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
popup.setOutsideTouchable(true);
Rect location = locateView(v);
popup.showAtLocation(v, Gravity.NO_GRAVITY, location.left, location.top - 200);
QuestionFragment.java
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final LinearLayout view = (LinearLayout) inflater.inflate(R.layout.fragment_question, container, false);
final ListView messages = (ListView)view.findViewById(R.id.messages);
messages.setDivider(null);
// Add question (header)
View headerView = inflater.inflate(R.layout.messages_question, null);
MessageModel messageItem = new MessageModel();
messageItem.message = question.getQuestion();
messageItem.id = question.getId();
messageItem.gender = question.getGender();
messageItem.name = question.getName();
LinearLayout messageBackground = (LinearLayout)headerView.findViewById(R.id.messageBackground);
TextView message = (TextView)headerView.findViewById(R.id.question);
int bgDrawable = (messageItem.gender > 1) ? R.drawable.bubble_red_left_states : R.drawable.bubble_blue_left_states;
messageBackground.setBackground(ContextCompat.getDrawable(getActivity().getApplicationContext(), bgDrawable));
messages.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
SingleInstancePopup.GetInstance().hidePopup();
}
});
messageBackground.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(getClass().getName(), "Clicked on question");
SingleInstancePopup popup = SingleInstancePopup.GetInstance();
if(popup.getPopup() != null) {
popup.hidePopup();
} else {
popup.showPopup(inflater, v);
}
}
});
message.setText(messageItem.message);
messages.addHeaderView(headerView, null, false);
// Add footer
View footerView = inflater.inflate(R.layout.messages_footer, null);
messages.addFooterView(footerView, null, false);
messagesAdapter = new MessagesAdapter(getActivity().getApplicationContext());
messages.setAdapter(messagesAdapter);
final Handler handler_ = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.what == UPDATE_UI) {
QuestionModel question = (QuestionModel) msg.obj;
for (AnswerModel answer : question.getAnswers()) {
MessageModel messageItem = new MessageModel();
messageItem.message = answer.getComment();
messageItem.id = answer.getId();
messageItem.gender = answer.getGender();
messageItem.name = answer.getName();
messageItem.reply = (answer.getParentId() > 0);
messagesAdapter.add(messageItem);
}
ProgressBar progress = (ProgressBar) messages.findViewById(R.id.messagesProgress);
if (progress != null) {
progress.setVisibility(View.GONE);
}
messagesAdapter.notifyDataSetChanged();
}
}
};
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
QuestionModel q = QuestionModel.getById(question.getId());
handler_.sendMessage(Message.obtain(handler_, UPDATE_UI, q));
} catch (Exception e) {
Log.d(getClass().getName(), "Failed to load question", e);
}
}
});
thread.start();
return view;
}
MessagesAdapter.java
#Override
public View getView(int position, View convertView, final ViewGroup parent) {
final LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final MessageModel messageItem = this.getItem(position);
View v;
int bgDrawable;
if(messageItem.reply) {
v = inflater.inflate(R.layout.messages_answer_reply, null, false);
bgDrawable = (messageItem.gender > 1) ? R.drawable.bubble_red_right_states : R.drawable.bubble_blue_right_states;
} else {
v = inflater.inflate(R.layout.messages_answer, null, false);
bgDrawable = (messageItem.gender > 1) ? R.drawable.bubble_red_left_states : R.drawable.bubble_blue_left_states;
}
LinearLayout messageBackground = (LinearLayout)v.findViewById(R.id.messageBackground);
TextView message = (TextView)v.findViewById(R.id.comment);
messageBackground.setBackground(ContextCompat.getDrawable(getContext(), bgDrawable));
message.setText(messageItem.message);
messageBackground.setClickable(true);
messageBackground.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(getClass().getName(), "Pressing down on message");
SingleInstancePopup popup = SingleInstancePopup.GetInstance();
if(popup.getPopup() != null) {
popup.hidePopup();
} else {
popup.showPopup(inflater, v);
}
}
});
return v;
}
Thanks!
- Simon
In MessagesAdapter.java, inflater doesn't have your activity's theme, that's why your buttons look different. Instead of getting the system inflater service, pass the activity's layout inflater to your adapter, like this:
QuestionFragment.java
messagesAdapter = new MessagesAdapter(getActivity().getApplicationContext(), getActivity().getLayoutInflater());
MessagesAdapter.java
private LayoutInflater inflater;
public MessagesAdapter(Context context, LayoutInflater inflater) {
super(context, 0);
this.inflater = inflater;
}
#Override
public View getView(int position, View convertView, final ViewGroup parent) {
final MessageModel messageItem = this.getItem(position);
View v;
int bgDrawable;
if (messageItem.reply) {
v = inflater.inflate(R.layout.messages_answer_reply, null, false);
bgDrawable = (messageItem.gender > 1) ? R.drawable.bubble_red_right_states : R.drawable.bubble_blue_right_states;
} else {
v = inflater.inflate(R.layout.messages_answer, null, false);
bgDrawable = (messageItem.gender > 1) ? R.drawable.bubble_red_left_states : R.drawable.bubble_blue_left_states;
}
// .......
return v;
}
I wish to create a tab application in Android.
I wish to basically have four tabs in my application.
Namely, Home, Compose, Inbox, Sent.
I started with a TabContainer extending TabActivity, is this a correct approach.
Since i will be having MenuItem, which i used be having multiple views for Inbox, as such List of inbox, i sud be able to read, and then delete and all.
I wish to know how do I approach?
Basically i wish to make an application similar to gmail.
Any ideas, or direction might help me
public class Inbox extends ListActivity{
private ProgressDialog progressDialog = null;
private ArrayList<EmailElement> emailElement = null;
private InboxAdapter inboxAdapter;
private CheckBoxWithInboxList newInboxAdapter;
private Runnable beforeFetchingEmail;
private TextView emailFromTextView = null;
private TextView emailSubjectTextView = null;
ListView listView;
private static int mode = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.inbox);
mode = this.getIntent().getIntExtra("EDIT_MODE", -1);
Log.i("EDITMODE", String.valueOf(mode));
emailElement = new ArrayList<EmailElement>();
if(mode ==0 || mode==-1){
this.inboxAdapter = new InboxAdapter(this, R.layout.inbox_row, emailElement);
setListAdapter(inboxAdapter);
}else{
this.newInboxAdapter = new CheckBoxWithInboxList(this, R.layout.inbox_row, emailElement);
setListAdapter(newInboxAdapter);
}
beforeFetchingEmail = new Runnable() {
#Override
public void run() {
getEmails();
}
};
Thread thread = new Thread(null, beforeFetchingEmail, "MagentoBackground");
thread.start();
progressDialog = ProgressDialog.show(Inbox.this,"Please wait...",
"Retrieving Emails ...", true);
listView = getListView();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parentView, View view,
int position, long id) {
}
});
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if(emailElement != null && emailElement.size() > 0){
if(mode==0 || mode==-1){
inboxAdapter.notifyDataSetChanged();
for(int i=0;i<emailElement.size();i++){
inboxAdapter.add(emailElement.get(i));
}
progressDialog.dismiss();
inboxAdapter.notifyDataSetChanged();
}else{
newInboxAdapter.notifyDataSetChanged();
for(int i=0;i<emailElement.size();i++){
newInboxAdapter.add(emailElement.get(i));
}
progressDialog.dismiss();
newInboxAdapter.notifyDataSetChanged();
}
}
}
};
private void getEmails(){
try{
emailElement = new ArrayList<EmailElement>();
EmailElement ee0 = new EmailElement();
ee0.setFrom("Robin Thapa");
ee0.setSubject("Urgent Meeting");
emailElement.add(ee0);
EmailElement ee1 = new EmailElement();
ee1.setFrom("Deepak Thapa");
ee1.setSubject("Staff meeting #Sunday");
emailElement.add(ee1);
Thread.sleep(5000);
}catch(Exception ex){
}
runOnUiThread(returnRes);
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.inbox_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.inboxEdit:
Intent intent = new Intent(this,EmailClient.class);
intent.putExtra("tabId", 2);
intent.putExtra("EDIT_MODE", 1);
startActivityForResult(intent, Intent.FILL_IN_DATA);
return true;
case R.id.inboxRefresh:
return true;
case R.id.inboxNext:
return true;
case R.id.inboxPrevious:
return true;
}
return false;
}
private class InboxAdapter extends ArrayAdapter<EmailElement>{
private ArrayList<EmailElement> items;
public InboxAdapter(Context context,int textViewResourceId,
ArrayList<EmailElement> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.inbox_row, null);
}
EmailElement o = items.get(position);
if (o != null) {
CheckBox emailCheckBox = (CheckBox)view.findViewById(R.id.inboxCheckBoxId);
emailCheckBox.setVisibility(View.INVISIBLE);
emailFromTextView = (TextView) view.findViewById(R.id.inboxEmailFrom);
emailSubjectTextView = (TextView) view.findViewById(R.id.inboxEmailSubject);
if (emailFromTextView != null){
emailFromTextView.setText("From: "+o.getFrom());
}
if(emailSubjectTextView != null){
emailSubjectTextView.setText("Sub: ["+ o.getSubject()+"]");
}
}
return view;
}
}
private class CheckBoxWithInboxList extends ArrayAdapter<EmailElement>{
private ArrayList<EmailElement> items;
public CheckBoxWithInboxList(Context context,int textViewResourceId,
ArrayList<EmailElement> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.inbox_row, null);
}
EmailElement o = items.get(position);
if (o != null) {
CheckBox emailCheckBox = (CheckBox)view.findViewById(R.id.inboxCheckBoxId);
emailCheckBox.setVisibility(View.VISIBLE);
emailFromTextView = (TextView) view.findViewById(R.id.inboxEmailFrom);
emailSubjectTextView = (TextView) view.findViewById(R.id.inboxEmailSubject);
if (emailFromTextView != null){
emailFromTextView.setText("From: "+o.getFrom());
}
if(emailSubjectTextView != null){
emailSubjectTextView.setText("Sub: ["+ o.getSubject()+"]");
}
}
return view;
}
}
}
For tablayout I recommend : http://developer.android.com/resources/tutorials/views/hello-tabwidget.html
you might want to read up on this Tab Layout | Android Development
it's a good starting point