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
Related
I have worked with the concept of filter that have to filter the job from job list based on skills and some list or there.
https://postimg.org/image/g3p1z6lbd/ - DashBoard Fragment.
About DashBoardFragment:
Contains job list view.
Dash Filter Button. - which redirect to the Filter screen.
public class DashBoardRefactor extends Fragment {
public static ProgressDialog progress;
public static List<DashListModel> dashRowList1 = new ArrayList<DashListModel>();
public static View footerView;
// #Bind(R.id.dashListView)
public static ListView dashListView;
int preCount = 2, scroll_Inc = 10, lastCount;
boolean flag = true;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dashboard_fragment, container, false);
ButterKnife.bind(this, v);
setHasOptionsMenu(true);
progress = new ProgressDialog(getActivity());
dashListView = (ListView) v.findViewById(R.id.dashListView);
footerView = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.dashboard_list_footer, null, false);
dashListView.addFooterView(footerView);
footerView.setVisibility(View.GONE);
dashRowList1.clear();
dashboardViewTask();
dashListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("onItemClick", "onItemClick <---- ");
Intent toPositionDetail = new Intent(getActivity(), PositionDetailScreenRefactor.class);
toPositionDetail.putExtra("id", dashRowList1.get(position).getDashId());
startActivity(toPositionDetail);
getActivity().overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
}
});
final int totalJobCount = SessionStores.gettotalJobList(getActivity());
Log.e("totalJobCount", "totalJobCount----" + totalJobCount);
dashListView.setOnScrollListener(new EndlessScrollListener(getActivity(), dashListView, footerView));
return v;
}
public void dashboardViewTask() {
progress.setMessage("Please Wait. It is Loading..job orders....");
progress.setCanceledOnTouchOutside(false);
progress.setCancelable(false);
progress.show();
// footerView.setVisibility(View.VISIBLE);
Map<String, String> params = new HashMap<String, String>();
Log.e("candidate_id", "candidate_id---->" + SessionStores.getBullHornId(getActivity()));
params.put("candidate_id", SessionStores.getBullHornId(getActivity()));
params.put("page", "1");
new DashBoardTask(getActivity(), params, dashListView, footerView);
// progress.dismiss();
}
#Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
if (menu != null) {
menu.removeItem(R.id.menu_notify);
}
inflater.inflate(R.menu.menu_options, menu);
MenuItem item = menu.findItem(R.id.menu_filter);
item.setVisible(true);
getActivity().invalidateOptionsMenu();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.his__menu_accept:
Toast.makeText(getActivity(), "clicked dashboard menu accept", Toast.LENGTH_LONG).show();
return true;
case R.id.menu_filter:
// click evnt for filter
Toast.makeText(getActivity(), "clicked dashboard filter", Toast.LENGTH_LONG).show();
Intent filter_intent = new Intent(getActivity(), DashBoardFilterScreen.class);
startActivity(filter_intent);
getActivity().overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onPause() {
super.onPause();
// dashboardViewTask();
}}
DashBoardTask:
public class DashBoardTask {
public DashBoardTask(Context context, Map<String, String> params, ListView dashListView, View footerView) {
this.context = context;
Log.e("context ", "DashBoardTask: " + context);
this.dashListView = dashListView;
this.params = params;
this.footerView = footerView;
ResponseTask();
}
private void ResponseTask() {
new ServerResponse(ApiClass.getApiUrl(Constants.DASHBOARD_VIEW)).getJSONObjectfromURL(ServerResponse.RequestType.POST, params, authorizationKey, context, "", new VolleyResponseListener() {
#Override
public void onError(String message) {
if (DashBoardRefactor.progress.isShowing()) {
DashBoardRefactor.progress.dismiss();
}
}
#Override
public void onResponse(String response) {
//Getting Response and Assign into model Class
int currentPosition = dashListView.getFirstVisiblePosition();
dashListAdapter = new DashListAdapter(context, DashBoardRefactor.dashRowList1, dashListView);
dashListView.setAdapter(dashListAdapter);
((BaseAdapter) dashListAdapter).notifyDataSetChanged();
if (currentPosition != 0) {
// Setting new scroll position
dashListView.setSelectionFromTop(currentPosition + 1, 0);
}
if (footerView.isShown()) {
footerView.setVisibility(View.GONE);
}
//progress.dismiss();
if (DashBoardRefactor.progress.isShowing()) {
try {
DashBoardRefactor.progress.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
DashListAdapter:
________________
public class DashListAdapter extends BaseAdapter {
public static ListView dashListView;
Context c;
private LayoutInflater inflater;
private List<DashListModel> dashRowList;
public DashListAdapter(Context c, List<DashListModel> dashRowList, ListView dashListView) {
this.c = c;
this.dashListView = dashListView;
this.dashRowList = dashRowList;
}
#Override
public int getCount() {
return this.dashRowList.size();
}
#Override
public Object getItem(int position) {
return dashRowList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder dashHolder;
if (inflater == null)
inflater = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.dashboard_jobdetails_list, null);
Log.e("get pos", "get pooooossss---->" + dashRowList.get(position));
final DashListModel dashModel = dashRowList.get(position);
dashHolder = new ViewHolder(convertView);
//Assign the value into screen
dashHolder.dash_company_name.setText(dashModel.getDashCompanyName());
}
the above code for displaying dashboard fragment list.
https://postimg.org/image/nqvp1dud9/ - This link is FilterScreen
By using this image if i filter the job based on the designed UI detail. That should replace into the DashboadFragment list The result should display into the DashBoard Fragment. How can I add pagination on Filter screen the same which have in DashBoardFragment.
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();
}
});
I'm trying to create base adapter for Favorites.class so I can display items in it.
The getView method is not being called and the Activity won't show any view.
BaseAdapter:
public class fYtAdapter extends BaseAdapter {
private List<SearchResult> mfVideoList = null;
private LayoutInflater mfLayoutInflater = null;
private Favorites fActivity = null;
public fYtAdapter(Favorites iActivity){
fActivity = iActivity;
mfLayoutInflater = LayoutInflater.from(fActivity);
}
public void setmVideoList(List<SearchResult> mVideoList){
this.mfVideoList = mVideoList;
}
#Override
public int getCount() {
return (mfVideoList == null)? (0):(mfVideoList.size());
}
#Override
public Object getItem(int position) {
return (mfVideoList != null && mfVideoList.size()>position)? (mfVideoList.get(position)):(null);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder mHolder;
if(convertView != null){
mHolder = (ViewHolder)convertView.getTag();
}else{
mHolder = new ViewHolder();
convertView = mfLayoutInflater.inflate(R.layout.view_video_item,null);
mHolder.mVideoThumbnail = (ImageView)convertView.findViewById(R.id.video_thumbnail);
mHolder.mVideoTitle = (TextView)convertView.findViewById(R.id.video_title);
convertView.setTag(mHolder);
}
//Setting the data
final SearchResult result = mfVideoList.get(position);
mHolder.mVideoTitle.setText(result.getSnippet().getTitle());
//Loading the image
Picasso.with(fActivity).load(result.getSnippet().getThumbnails().getMedium().getUrl()).into(mHolder.mVideoThumbnail);
return convertView;
}
private class ViewHolder{
private TextView mVideoTitle = null;
private ImageView mVideoThumbnail = null;
}
}
Favorites.class
public class Favorites extends ActionBarActivity
implements View.OnClickListener, AdapterView.OnItemClickListener, ServerResponseListener{
private LayoutInflater mLayoutInflater = null;
private ProgressDialog mLoadingDialog = null;
private fYtAdapter mYtadapter = null;
String vidID = null, vidTitle = null, vidThumbnail = null;
ListView mFavLsv;
Bundle extras;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorites_layout);
getSupportActionBar().setTitle("Favorites");
initializeViews();
extras = getIntent().getExtras();
this.vidID = extras.getString("id");
this.vidTitle = extras.getString("title");
this.vidThumbnail = extras.getString("thumbnail");
}
public void initializeViews(){
mLayoutInflater = LayoutInflater.from(this);
mFavLsv = (ListView)findViewById(R.id.yt_fav_lst);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
//Not needed in this Activity
#Override
public void onClick(View v) {
}
//To start video
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent videoIntent = YouTubeStandalonePlayer.createVideoIntent(this, AppConstants.KEY, vidID);
startActivity(videoIntent);
}
#Override
public void prepareRequest(Object... objects) {
//Parse the response based on type of request
Integer reqCode = (Integer) objects[0];
if(reqCode == null || reqCode == 0)
throw new NullPointerException("Request Code's value is Invalid.");
String dialogMsg = null;
switch(reqCode){
case SEARCH_VIDEO:
dialogMsg = SEARCH_VIDEO_MSG;
break;
}
if(mLoadingDialog != null && !mLoadingDialog.isShowing())
mLoadingDialog = ProgressDialog.show(this, DIALOG_TITLE, dialogMsg, true, true);
}
#Override
public void goBackground(Object... objects) {
}
#Override
public void completedRequest(Object... objects) {
//Dismiss the dialog
if(mLoadingDialog != null && mLoadingDialog.isShowing())
mLoadingDialog.dismiss();
//Parse the response based on type of request
Integer reqCode = (Integer) objects[0];
if(reqCode == null || reqCode == 0)
throw new NullPointerException("Request Code's value is Invalid.");
switch (reqCode){
case SEARCH_VIDEO:
if(mYtadapter == null){
mYtadapter = new fYtAdapter(this);
mYtadapter.setmVideoList((List<SearchResult>)objects[1]);
mFavLsv.setAdapter(mYtadapter);
}else{
mYtadapter.setmVideoList((List<SearchResult>) objects[1]);
mYtadapter.notifyDataSetChanged();
}
break;
}
}
}
I got another base adapter for another Activity and it is working fine.
I can't figure out why this is not working in here.
I need to display the view (with thumbnail(vidThumbnail) and title(vidTitle) in Favorites.class
*It seems that it won't got into "completedRequest" at all.
I faced this same issue. And I got the solution from here.. Link
Solution:
The only reasons getView() is not called are:
1) getCount() returns 0
2) You forget to call setListAdapter on the ListView.
3) If the ListView's visibility (or its container's visibility) is GONE.
Initialize your adapter and then set it to your ListView inside your initializeViews() method using mFavLsv.setAdapter(youradapter);
you have to add one more line -
mFavLsv.setAdapter(mYtadapter );
You missed set adapter in listview.
I have created a custom lisview with images and text by using an array adapter. I would like to highlight one of the row manually, but I cannot seem to do this. I have tried using setItemChecked and setSelection(1);. I have made sure to disable touch events by calling listView.setEnabled(false);, as I read that manual selection might not work if touch events are enabled. Any insight into this matter would be greatly appreciated. I have included my source code below.
Main Activity
public class MainActivity extends Activity
{
// GUI
int Update_Frequency = 1000;
double ack = 0;
// Sensor Constants
public static String temperature = "--";
public static String humidity = "--";
public static String lpg = "--";
public static String alcohol = "--";
// Layout
ListView listView;
ItemAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initialize Interface
Model.LoadModel();
listView = (ListView) findViewById(R.id.listView);
String[] ids = new String[Model.Items.size()];
for (int i= 0; i < ids.length; i++)
{ids[i] = Integer.toString(i+1);}
this.adapter = new ItemAdapter(this,R.layout.row, ids);
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setEnabled(false);
listView.setItemChecked(1, true);
listView.setSelection(1);
Model.LoadModel();
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
GUI_Management();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.action_connect:
break;
case R.id.action_disconnect:
break;
case R.id.action_settings:
break;
case R.id.action_about:
break;
case R.id.action_exit:
break;
default:
break;
}
return true;
}
private void GUI_Management()
{
new Thread()
{
public void run()
{
//Replace with a changeable variable
while (true)
{
try
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Model.LoadModel();
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
});
Thread.sleep(Update_Frequency);
}
catch (InterruptedException e)
{
}
}
}
}.start();
}
}
Array Adapter
public class Model extends MainActivity
{
public static ArrayList<Item> Items;
public static void LoadModel()
{
Items = new ArrayList<Item>();
Items.add(new Item(1, "temperature_icon.png", "Temperature/Humidity " + temperature + "°F / " + humidity + "%"));
Items.add(new Item(2, "gas_icon.png", "LPG " + lpg +" ppm"));
Items.add(new Item(3, "alcohol_icon.png", "Alcohol " + alcohol + " ppm"));
}
public static Item GetbyId(int id)
{
for(Item item : Items)
{
if (item.Id == id)
{
return item;
}
}
return null;
}
}
class Item
{
public int Id;
public String IconFile;
public String Name;
public Item(int id, String iconFile, String name)
{
Id = id;
IconFile = iconFile;
Name = name;
}
}
class ItemAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] Ids;
private final int rowResourceId;
public ItemAdapter(Context context, int textViewResourceId, String[] objects) {
super(context, textViewResourceId, objects);
this.context = context;
this.Ids = objects;
this.rowResourceId = textViewResourceId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(rowResourceId, parent, false);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imageView);
TextView textView = (TextView) rowView.findViewById(R.id.textView);
int id = Integer.parseInt(Ids[position]);
String imageFile = Model.GetbyId(id).IconFile;
textView.setText(Model.GetbyId(id).Name);
// get input stream
InputStream ims = null;
try {
ims = context.getAssets().open(imageFile);
} catch (IOException e) {
e.printStackTrace();
}
// load image as Drawable
Drawable d = Drawable.createFromStream(ims, null);
// set image to ImageView
imageView.setImageDrawable(d);
return rowView;
}
}
put setonclick listener in rootview object which are inflate by you in getview method this will solve your issue and on click event you can change the background of rootview and many more you can do with it.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(rowResourceId, parent, false);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imageView);
TextView textView = (TextView) rowView.findViewById(R.id.textView);
int id = Integer.parseInt(Ids[position]);
String imageFile = Model.GetbyId(id).IconFile;
textView.setText(Model.GetbyId(id).Name);
if (position == selectedItem)
{
rootView /*or you can use any viewgroup*/
.setBackgroundResource(R.drawable.background_dark_blue);
}
else
{
rootView
.setBackgroundResource(R.drawable.border02);
}
return rowView;
}
private int selectedItem;
public void setSelectedItem(int position) {
selectedItem = position;
}
i know this is not good solutionbut might this help you out you can use setSelectedItem method to highlight row
and please use static placeholder class for efficiency and use position field in static placeholder class to get position of selected row
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.