RecyclerView fragment does not appear - java

I am trying to create an app to display data in a recyclerview. However, when I run it, the main view is blank (the toolbar and navigation drawer work fine). I have meticulously looked over my code for errors and looked at similar problems, but nothing has worked so far. I have tested the asynctasks, which work, but the info won't display.
Main Activity:
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private static ListView mDrawerList;
private static ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private static String zipCode = "<zipcode>";
private static String street = "<address>";
public static String[] officeList = null;
public static Elements positionLinks = null;
public static int positionSelected;
public CardFragment currentFragment;
public static String[] namesOfCandidates;
public static String[] partiesOfCandidates;
public static String[] occupationsOfCandidates;
public static String[] candidateLinks;
public static boolean gotCandidates = false;
public static Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
officeList = getResources().getStringArray(R.array.offices_array);
new AsyncPositions().execute();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, officeList));
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_favorite).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}else if(item.getItemId()==R.id.action_settings){
Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show();
// User chose the "Settings" item, show the app settings UI...
return true;
}else if(item.getItemId()==R.id.action_favorite){
Toast.makeText(this, "Favorited", Toast.LENGTH_SHORT).show();
// User chose the "Favorite" action, mark the current item
// as a favorite...
//remember to change this to something else - or maybe just a starred thing for elected officials
return true;
}else {
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_bar_buttons, menu);
return super.onCreateOptionsMenu(menu);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
/**
* Swaps fragments in the main content view
*/
private void selectItem(int position) {
positionSelected = position;
//try {
new AsyncCandidates().execute();
/* }
catch(InterruptedException ie){
ie.printStackTrace();
}
catch(ExecutionException ee){
ee.printStackTrace();
}*/
//change the cards to info about candidate
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(officeList[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
}
public String pollingPlaceInfo(){
//document.getElementsByClassName("PollingPlace_polling-place-content_ucq")[0].innerText;
return null;
}
//Gets the information about the specific candidate chosen by the card view
// requests position on drawer and candidate number (index) to pinpoint which candidate
// returns 2d array that contains each issue as well as info about it
public String[][] getIssues(int position, int candidate) {
return null;
}
//asynctask to pull the positions for the nav drawer
private static class AsyncPositions extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(MainActivity.context);
String[] positions;
private String zipCode;
private String street;
private String urlString = "";
private Elements positionLinks;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.setCanceledOnTouchOutside(false);
pdLoading.show();
zipCode = MainActivity.zipCode;
street = MainActivity.street;
}
#Override
protected Void doInBackground(Void... params) {
Document doc = null;
urlString = "http://votersedge.org/en/ca/search?zip="+zipCode+"&address="+street;
try {
//get initial landing page to find most recent election
doc = Jsoup.connect(urlString)
.userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36")
.timeout(12000)
.followRedirects(true)
.get();
//get the link to the most recent election page
String newLink = "";
boolean nullpe = false;
try{
doc.body().getElementsByClass("MultipleElections_upcoming-elections_3C2 col-md-12").first().child(1).attr("action");
}
catch(NullPointerException npe) {
newLink = "http://votersedge.org"+doc.body().getElementsByClass("MultipleElections_recent-elections_rsw col-md-12").first().child(1).attr("action");
nullpe = true;
}
if(!nullpe) {
newLink = "http://votersedge.org" + doc.body().getElementsByClass("MultipleElections_upcoming-elections_3C2 col-md-12").first().child(1).attr("action");
}
doc = Jsoup.connect(newLink)
.userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36")
.timeout(12000)
.followRedirects(true)
.get();
}
catch(IOException ioe){
ioe.printStackTrace();
}
Elements positionHeaders = doc.getElementsByClass("ContestsList_jurisdiction-group-label_1Kt");
positionLinks = doc.getElementsByClass("ContestsList_contest-link_W44");
//get size of positions list for easy access
int sizeOfList = positionLinks.size()/2;
//create array that will be returned
positions = new String[sizeOfList];
int l = 0;
int k=0;
int j=2;
for(int i=0; i<sizeOfList; i++){
try{
doc.getElementsByClass("ContestsList_accordion-content_1rY card-content").first().child(k).child(j);
}
catch(IndexOutOfBoundsException ibe){
k++;
j=2;
l++;
}
try{
doc.getElementsByClass("ContestsList_accordion-content_1rY card-content").first().child(k).child(j).child(0);
}
catch(IndexOutOfBoundsException ibe){
j++;
l++;
}
while(!doc.getElementsByClass("ContestsList_accordion-content_1rY card-content").first().child(k).child(j).child(0).tagName().equals("h4")){
j++;
l++;
}
positions[i] = positionHeaders.eq(l).text() + " " +doc.getElementsByClass("ContestsList_accordion-content_1rY card-content").first().child(k).child(j).child(0).child(0).child(1).text();
j++;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
MainActivity.officeList = positions;
MainActivity.mDrawerList.setAdapter(new ArrayAdapter<>(MainActivity.context,
R.layout.drawer_list_item, MainActivity.officeList));
MainActivity.positionLinks = positionLinks;
pdLoading.dismiss();
}
}
private class AsyncCandidates extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(MainActivity.context);
private Elements positionElements;
private int position;
private String[] namesOfCandidates;
private String[] partiesOfCandidates;
private String[] occupationsOfCandidates;
private String[] candidateLinks;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.setCanceledOnTouchOutside(false);
pdLoading.show();
positionElements = MainActivity.positionLinks;
position = MainActivity.positionSelected;
}
#Override
protected Void doInBackground(Void... params) {
Document doc = null;
String link = "http://votersedge.org"+ positionElements.eq(position).attr("href");
try {
doc = Jsoup.connect(link)
.userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36")
.timeout(12000)
.followRedirects(true)
.get();
}
catch(IOException ioe){
ioe.printStackTrace();
}
//getting links for reference for further information gathering
//need to create initial array to get all links (each has 1 duplicate in the array)
// and then create another array to get rid of duplicates
Elements links = doc.body().getElementsByClass("CandidateCard_candidate-link_2m1");
String[] cLinks = new String[links.size()];
for(int i=0; i<links.size(); i++) {
cLinks[i] = "http://votersedge.org" + links.eq(i).attr("href");
}
candidateLinks = new String[links.size()/2];
for(int i=0; i<links.size(); i+=2){
candidateLinks[i/2] = cLinks[i];
}
//getting names of candidates
Elements names = doc.body().getElementsByClass("CandidateCard_candidate-name_234 col-md-12 col-xs-12 col-sm-12 flush-cols");
namesOfCandidates = new String[names.size()];
for(int i=0; i<names.size(); i++){
namesOfCandidates[i] = names.eq(i).text();
}
//getting political parties of candidates
Elements attributes = doc.body().getElementsByClass("CandidateCard_candidate-attributes_3qD col-md-12 col-xs-12 col-sm-12 flush-cols");
partiesOfCandidates = new String[names.size()];
for(int i=0; i<names.size(); i++){
partiesOfCandidates[i] = attributes.eq(i).first().child(0).text()+" Candidate";
if(partiesOfCandidates[i].equals(" Candidate")) partiesOfCandidates[i] = "Candidate";
}
//getting occupations of candidates
occupationsOfCandidates = new String[names.size()];
for(int i=0; i<names.size(); i++){
occupationsOfCandidates[i] = attributes.eq(i).first().child(1).text();
}
gotCandidates = true;
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
MainActivity.namesOfCandidates = namesOfCandidates;
MainActivity.candidateLinks = candidateLinks;
MainActivity.partiesOfCandidates = partiesOfCandidates;
MainActivity.occupationsOfCandidates = occupationsOfCandidates;
Bundle bundle = new Bundle();
bundle.putStringArray("names", namesOfCandidates);
bundle.putStringArray("parties", partiesOfCandidates);
bundle.putStringArray("links", candidateLinks);
bundle.putStringArray("occupations", occupationsOfCandidates);
FragmentManager fm = getSupportFragmentManager();
MainActivity.this.currentFragment = (CardFragment) fm.findFragmentById(R.id.fragmentContainer);
if (MainActivity.this.currentFragment == null) {
MainActivity.this.currentFragment = new CardFragment();
MainActivity.this.currentFragment.setArguments(bundle);
fm.beginTransaction()
.add(R.id.fragmentContainer, MainActivity.this.currentFragment)
.addToBackStack(null)
.commit();
}else{
MainActivity.this.currentFragment = new CardFragment();
MainActivity.this.currentFragment.setArguments(bundle);
fm.beginTransaction()
.replace(R.id.fragmentContainer, MainActivity.this.currentFragment)
.addToBackStack(null)
.commit();
}
pdLoading.dismiss();
}
}
}
CardFragment.java
public class CardFragment extends Fragment {
RecyclerView MyRecyclerView;
String[] namesOfCandidates;
String[] partiesOfCandidates;
String[] occupationsOfCandidates;
String[] candidateLinks;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("test", "fragment has been created");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.getArguments();
namesOfCandidates = this.getArguments().getStringArray("names");
partiesOfCandidates = this.getArguments().getStringArray("parties");
candidateLinks = this.getArguments().getStringArray("links");
occupationsOfCandidates = this.getArguments().getStringArray("occupations");
View view = inflater.inflate(R.layout.fragment_card, container, false);
MyRecyclerView = (RecyclerView) view.findViewById(R.id.cardView);
MyRecyclerView.setHasFixedSize(true);
LinearLayoutManager MyLayoutManager = new LinearLayoutManager(getActivity());
MyLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
if (namesOfCandidates.length > 0 & MyRecyclerView != null) {
MyRecyclerView.setAdapter(new MyAdapter(namesOfCandidates));
}
MyRecyclerView.setLayoutManager(MyLayoutManager);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
private String[] list;
public MyAdapter(String[] Data) {
list = Data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
// create a new view
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycle_items, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
holder.titleTextView.setText(list[position]);
holder.mainTextView.setText(CardFragment.this.partiesOfCandidates[position]+"Candidate\n"+CardFragment.this.occupationsOfCandidates[position]);
holder.arrowImageView.setTag(R.drawable.ic_arrow_forward_black_24dp);
}
#Override
public int getItemCount() {
return list.length;
}
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView titleTextView;
ImageView arrowImageView;
TextView mainTextView;
public MyViewHolder(View v) {
super(v);
titleTextView = (TextView) v.findViewById(R.id.titleTextView);
mainTextView = (TextView) v.findViewById(R.id.mainTextView);
arrowImageView = (ImageView) v.findViewById(R.id.arrowImageView);
arrowImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = (int)arrowImageView.getTag();
if( id == R.drawable.ic_arrow_forward_black_24dp) {
//MOVE TO NEXT SCREEN
}
}
});
}
}
activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
</FrameLayout>
<!-- Action bar -->
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<!-- The navigation drawer -->
<ListView android:id="#+id/left_drawer"
android:theme="#style/ThemeOverlay.AppCompat.Light"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
fragment_card.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="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_left_margin"
android:paddingRight="#dimen/activity_right_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<android.support.v7.widget.RecyclerView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
recycle_items.xml
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
card_view:cardCornerRadius="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="#dimen/card_height"
android:orientation="vertical"
android:weightSum="4">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="left|bottom"
android:background="#android:drawable/screen_background_dark_transparent"
android:orientation="vertical">
<TextView
android:id="#+id/titleTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:textSize="#dimen/text_size"
android:textColor="#FFFFFF"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="3.2"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal">
<TextView
android:id="#+id/mainTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:textSize="#dimen/text_size2"
android:layout_gravity="center"
/>
</FrameLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="0.8"
android:gravity="center|right"
android:orientation="horizontal">
<ImageView
android:id="#+id/arrowImageView"
android:layout_width="#dimen/icon_width"
android:layout_height="#dimen/icon_height"
android:padding="#dimen/icon_padding"
android:src="#drawable/ic_arrow_forward_black_24dp" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
Any help is much appreciated!

Maybe the problem is in your conditional checking, as logical AND should be && not &.

I did some more troubleshooting, and after some tinkering I found that getting rid of the MyToolbar object and the ActionBarDrawerToggle the content showed up. Thank you for your help!

Related

Error Picasso doesn't work with RecyclerView

no image is shown from URL even if i tried one image in onCreate it actually works with the same URL but with the RecyclerView nothing is shown
my On Create Method
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NetworkUtilites ob=new NetworkUtilites();
ob.execute();
/** moviesArray contains Movies with Description **/
moviesArray=ob.getArrayMovies();
adapter = new RecyclerViewAdapter( this, moviesArray);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setAdapter(adapter);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
Here is onBindViewHolder function
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
/** MoviesArray return description of movie , getPoster_path() path return URL Of the poster film**/
String moviePosterURL= moviesArray.get(position).getPoster_path();
if(!TextUtils.isEmpty(moviePosterURL))
{
Picasso.get().load(moviePosterURL).into(holder.imageView);
}
}
Here is onCreateViewHolder function
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layoul_listitem,parent,false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
Here is ViewHolder function
public class ViewHolder extends RecyclerView.ViewHolder
{
ImageView imageView;
RelativeLayout parentlayout;
public ViewHolder(#NonNull View itemView)
{
super(itemView);
imageView=itemView.findViewById(R.id.image);
parentlayout =itemView.findViewById(R.id.parent_layout);
}
}
layout_listitem.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/parent_layout"
>
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:id="#+id/image"
/>
</RelativeLayout>
activity_main.xml with the Recycler View
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
NetworkUtilites class
public class NetworkUtilites extends AsyncTask<Void,Void,Void>
{
private static final String MoviesURL="http://api.themoviedb.org/3/movie/popular?api_key=";
private ArrayList <ListItem> arrayMovies =new ArrayList<>();
private String sent=null;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... strings)
{
try
{
URL url = new URL(MoviesURL);
HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
sent=StreamtoString(in);
in.close();
}
catch (Exception e)
{
}
return null;
}
#Override
protected void onPostExecute(Void s)
{
super.onPostExecute(s);
}
public String StreamtoString(InputStream inputStream)
{
BufferedReader bureader= new BufferedReader(new InputStreamReader(inputStream));
String line;
String Text = "";
try{
while((line=bureader.readLine())!=null)
{
Text+=line;
}
} catch (Exception e) {
}
return Text;
}
public String getSent() {
return sent;
}
public ArrayList<ListItem> getArrayMovies()
{
try {
JSONObject parentObject;
JSONArray parentArray;
if (!sent.equals(null))
{
parentObject = new JSONObject(sent);
parentArray = parentObject.getJSONArray("results");
System.out.println(parentArray.length());
for (int i = 0; i < parentArray.length(); i++)
{
JSONObject movieDetails = parentArray.getJSONObject(i);
String poster_path="http://image.tmdb.org/t/p/w342";
poster_path += movieDetails.getString("poster_path");
String original_title=movieDetails.getString("original_title");
String overview= movieDetails.getString("overview");
int vote_average=movieDetails.getInt("vote_average");
String release_date=movieDetails.getString("release_date");
ListItem ob= new ListItem(original_title,poster_path,overview,vote_average,release_date);
arrayMovies.add(ob);
}
}
}
catch (Exception e)
{
}
return arrayMovies;
}
}

multiple alert dialog with list view

hi i am trying to add a list view to an alert dialog. on click of the ok button on my first alert dialog, the program directs to the response fragment which contains a second dialog box which needs to be populated with the list view. the problem i am having is that i am getting an empty alert box with the list view showing behind it on the fragment
public class ResponseFragment extends Fragment {
ListView list;
private String urlString;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_response, container, false);
list=(ListView)v.findViewById(R.id.listviewResp);
urlString = "http://172.20.10.5:1012/easyQ.svc/rest/reasons";
new getReasons().execute(urlString);
return v;
}
private class getReasons extends AsyncTask<String, Void, String> {
protected String doInBackground(String... strings) {
String stream;
String urlString = strings[0];
HTTPDataHandler hh = new HTTPDataHandler();
stream = hh.GetHTTPData(urlString);
// Return the data from specified url
System.out.println(stream);
return stream;
}
protected void onPostExecute(String stream) {
if (stream != null)
{
try
{
JSONObject object = new JSONObject(stream);
JSONArray array = object.getJSONArray("reasonsResult");
for(int i = 0 ; i < array.length(); i++) {
JSONObject reasonObj = array.getJSONObject(i);
String ID = reasonObj.getString("reason_leaving_id");
String reason = reasonObj.getString("description");
HashMap<String, String> map = new HashMap<String, String>();
map.put("description", reason);
map.put("id", ID);
oslist.add(map);
}
for(int i = 0; i < oslist.size(); i++)
{
ListAdapter adapter = new SimpleAdapter(getActivity(), oslist,
R.layout.dialog_list,
new String[] { "description"}, new int[] {
R.id.txtResp});
// alertDialog.setView(inflater.inflate(R.layout.fragment_response,null));
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String branchId = oslist.get(+position).get("id");
final SessionV globalVariable = (SessionV) getActivity().getApplicationContext();
globalVariable.setBranchId(branchId);
Fragment fragment = null;
fragment = new HomeFragment();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container_body, fragment).commit();
}
});
}
AlertDialog alertDialog = new AlertDialog.Builder(
getActivity()).create();
alertDialog.setTitle("easyQ");
alertDialog.setMessage("reason");
LayoutInflater inflater = (getActivity()).getLayoutInflater();
final View dialogView=inflater.inflate(R.layout.fragment_response,null);
alertDialog.setView(dialogView);
alertDialog.show();
alertDialog.show();
}
catch(JSONException e)
{
e.printStackTrace();
}
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listviewResp"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingTop="15dp"
android:layout_centerVertical="true"
android:layout_alignParentStart="true" />
</LinearLayout>
<?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="horizontal" >
<TextView
android:id="#+id/txtResp"
android:layout_width="match_parent"
android:layout_height="?listPreferredItemHeightSmall"
android:checkMark="?android:attr/listChoiceIndicatorSingle"
android:gravity="center_vertical"
android:paddingLeft="?listPreferredItemPaddingLeft"
android:paddingRight="?listPreferredItemPaddingRight"
android:textAppearance="?textAppearanceListItemSmall" />
</LinearLayout>
I think you want to show a ListView inside the AlertDialog . So, You need to modify some of your code.
1st :
You inflate the listview from the fragment_response layout. Which is not necessary. In onCreateView() method just initialize a new object of ListView.
Replace :
list=(ListView)v.findViewById(R.id.listviewResp);
By
list = new ListView(getActivity());
2nd:
Change this Code :
AlertDialog alertDialog = new AlertDialog.Builder(
getActivity()).create();
alertDialog.setTitle("easyQ");
alertDialog.setMessage("reason");
LayoutInflater inflater = (getActivity()).getLayoutInflater();
final View dialogView=inflater.inflate(R.layout.fragment_response,null);
alertDialog.setView(dialogView);
alertDialog.show();
alertDialog.show();
By
AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
alertDialog.setTitle("easyQ");
alertDialog.setMessage("reason");
alertDialog.setView(listView);
alertDialog.show();
If other code is ok, then i hope it will work well.

Android: calling getview() for ListView's Adapter from Fragment in viewPager

I have ViewPager that containing 3 different Fragment. each Fragment containing A Different View and also ListView, I got a problem when I was trying to show the ListView in one of Fragment from ViewPager, it doesn't show anything. I've tried to debug my adapter and it seems my getView() method is not called. I try to call my Fragment not from ViewPager, the result is getView() is called from adapter and ListView is showing. Is there any problem to show ListView from ViewPager? I have tried this solution by calling my adapter from onViewCreated() but there's nothing change. so is there any wrong with my method? this is my code :
My Fragment Class for Managing ViewPager
public class Frag_Provider extends Fragment {
private String[] tabsTitles = {"TERDEKAT", "SEMUA", "PROVIDERKU"};
String url = "";
List<ModelProvider> list_provider;
DB_Esehat db_esehat = null;
SQLiteDatabase db = null;
ContentLoadingProgressBar progressbar;
TabLayout tabLayout;
ViewPager pager;
public Frag_Provider (){
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
((MainActivity) getActivity()).custom_toolbar("Provider", R.color.toolbar_provider, R.color.toolbar_provider_dark);
View result=inflater.inflate(R.layout.fragment_provider, container, false);
list_provider = new ArrayList<ModelProvider>();
progressbar = (ContentLoadingProgressBar)result.findViewById(R.id.progressbar);
db_esehat = new DB_Esehat(getActivity());
db = db_esehat.getWritableDatabase();
db.delete("LST_PROVIDER", null, null);
pager=(ViewPager)result.findViewById(R.id.pager);
tabLayout = (TabLayout)result.findViewById(R.id.sliding_tabs);
url = getResources().getString(R.string.url_host)+getResources().getString(R.string.url_provider);
new ProviderTask(url).execute();
pager.setAdapter(buildAdapter(tabsTitles));
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(pager);
}
});
return(result);
}
public class ProviderTask extends AsyncTask<String, Void, String> {
String url = "";
public ProviderTask(String url) {
this.url = url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressbar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
String result = "";
try {
result = Connection.get(url);
} catch (Exception e) {
result = "";
}
return result;
}
#Override
protected void onPostExecute(String result) {
progressbar.setVisibility(View.GONE);
pager.setVisibility(View.VISIBLE);
tabLayout.setVisibility(View.VISIBLE);
super.onPostExecute(result);
if (result.equals("") || result.equals(null)) {
MethodSupport.AlertDialog(getActivity());
} else {
try {
JSONArray Data = new JSONArray(result);
for (int i = 0; i < Data.length(); i++) {
String LSKA_NOTE = "";
String RSALAMAT = "";
String RSTELEPON = "";
String RSNAMA = "";
String MAPPOS = "";
int RSTYPE = 0;
int RSID = 0;
int RS_NTT = 0;
JSONObject json = Data.getJSONObject(i);
if (json.has("LSKA_NOTE")) {
LSKA_NOTE = json.getString("LSKA_NOTE");
}
if (json.has("RSALAMAT")) {
RSALAMAT = json.getString("RSALAMAT");
}
if (json.has("RSTELEPON")) {
RSTELEPON = json.getString("RSTELEPON");
}
if (json.has("RSNAMA")) {
RSNAMA = json.getString("RSNAMA");
}
if (json.has("MAPPOS")) {
MAPPOS = json.getString("MAPPOS");
}
if (json.has("RSTYPE")) {
RSTYPE = json.getInt("RSTYPE");
}
if (json.has("RSID")) {
RSID = json.getInt("RSID");
}
if (json.has("RS_NTT")) {
RS_NTT = json.getInt("RS_NTT");
}
db_esehat.InsertRS(LSKA_NOTE, RSALAMAT, RSTELEPON, RSNAMA, MAPPOS, RSTYPE, RSID, RS_NTT);
}
} catch (Exception e) {
Log.d("TES", e.getMessage());
}
}
}
}
private PagerAdapter buildAdapter(String[] tabsTitles) {
return(new FragmentStatePagerAdapter(getActivity(), getChildFragmentManager(),tabsTitles));
}
}
This is FragmentStatePagerAdapter.java
public class FragmentStatePagerAdapter extends FragmentPagerAdapter {
Context ctxt=null;
private String[] tabsTitles;
public FragmentStatePagerAdapter(Context ctxt, FragmentManager mgr, String[] tabsTitles) {
super(mgr);
this.ctxt=ctxt;
this.tabsTitles = tabsTitles;
}
#Override
public int getCount() {
return tabsTitles.length;
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0:
return Frag_Provider_Terdekat.newInstance(position);
case 1:
return Frag_Provider_Semua.newInstance(position);
case 2:
return Frag_Provider_Ku.newInstance(position);
}
return null;
}
// #Override public float getPageWidth(int position) { return(0.7f); }
#Override
public String getPageTitle(int position) {
return tabsTitles[position];
}
}
this is my Fragment_Provider.xml, Layout for managing my ViewPager
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.widget.ContentLoadingProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone"
android:indeterminate="false" />
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMaxWidth="0dp"
app:tabGravity="fill"
style="#style/MyCustomTabLayout"
app:tabMode="fixed"
android:fillViewport="true"
android:visibility="gone" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white"
android:layout_below="#id/sliding_tabs"
android:visibility="gone"/>
</RelativeLayout>
This is of my Fragment in ViewPagerthat containing ListView :
public class Frag_Provider_Terdekat extends Fragment {
private static final String KEY_POSITION="position";
private ListView list_provider;
List<ModelProviderTerdekat> list_ekamedicare;
DB_Esehat db_esehat;
SQLiteDatabase db;
ProviderTerdekatAdapter adapter;
static Frag_Provider_Terdekat newInstance(int position) {
Frag_Provider_Terdekat frag=new Frag_Provider_Terdekat();
Bundle args=new Bundle();
args.putInt(KEY_POSITION, position);
frag.setArguments(args);
return(frag);
}
static String getTitle(Context ctxt, int position) {
return("PROVIDER KU");
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View result=inflater.inflate(R.layout.fragment_child_providerterdekat, container, false);
list_provider = (ListView)result.findViewById(R.id.list_provider);
list_ekamedicare = new ArrayList<ModelProviderTerdekat>();
db_esehat = new DB_Esehat(getActivity());
list_ekamedicare = db_esehat.getProvider();
adapter = new ProviderTerdekatAdapter(getActivity().getApplicationContext(), R.layout.adapter_provider, list_ekamedicare);
list_provider.setAdapter(adapter);
return result;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
and this is Adapter for my ListView
public class ProviderTerdekatAdapter extends ArrayAdapter<ModelProviderTerdekat> {
List<ModelProviderTerdekat> data = Collections.emptyList();
private LayoutInflater inflater;
private Context context;
static class ViewHolder {
ImageView imvprov_map;
ImageView imvprov_fav;
TextView textprov_nama_rs;
TextView textprov_alamat_rs;
TextView textprov_km_rs;
}
public ProviderTerdekatAdapter (Context context, int viewResourceId, List<ModelProviderTerdekat> data) {
super(context, R.layout.adapter_provider, data);
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
#Override
public int getCount() {
return data.size();
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
view = inflater.inflate(R.layout.adapter_provider, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.imvprov_map = (ImageView) view.findViewById(R.id.imvprov_map);
viewHolder.imvprov_fav = (ImageView) view.findViewById(R.id.imvprov_fav);
viewHolder.textprov_nama_rs = (TextView) view.findViewById(R.id.textprov_nama_rs);
viewHolder.textprov_alamat_rs = (TextView) view.findViewById(R.id.textprov_alamat_rs);
viewHolder.textprov_km_rs = (TextView) view.findViewById(R.id.textprov_km_rs);
view.setTag(viewHolder);
}
ViewHolder viewHolder = (ViewHolder) view.getTag();
viewHolder.textprov_nama_rs.setText(data.get(position).getRSNAMA());
viewHolder.textprov_alamat_rs.setText(data.get(position).getRSALAMAT());
return view;
}
}
I have no Idea why my GetView() not called in my Adapter, is it because I put in ViewPager? well I hope someone understand about it and help me to solver my problem. thank you very much.
Finally.. I found a solution for my problem, it's because I put ViewPager in RelativeLayout after I change into LinearLayout all view displayed as I wanted
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.widget.ContentLoadingProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone"
android:indeterminate="false" />
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMaxWidth="0dp"
app:tabGravity="fill"
style="#style/MyCustomTabLayout"
app:tabMode="fixed"
android:fillViewport="true"
android:visibility="gone" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white"
android:layout_below="#id/sliding_tabs"
android:visibility="gone"/>
</LinearLayout>

Cannot Reach Breakpoint / Intent Will Not Launch

I'm attempting to launch an intent in my Home.java:
#Override
public void onVideoClicked(Video video) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(video.getUrl()));
startActivity(intent);
}
It should be initiated by:
package com.idg.omv.ui;
import com.idg.omv.domain.Video;
public interface VideoClickListener {
public void onVideoClicked(Video video);
}
which is initiated by listView.setOnVideoClickListener(this); in my Home.java
However I cannot seem to reach onVideoClicked when setting a breakpoint in Home.java and I'm unsure why.
FULL SOURCE:
public class Home extends YouTubeBaseActivity implements
VideoClickListener {
// A reference to our list that will hold the video details
private VideosListView listView;
private ActionBarDrawerToggle actionBarDrawerToggle;
public static final String API_KEY = "AIzaSyC0Te2pyooXzuyLaE6_SsFlITKCwjj55fI";
public static final String VIDEO_ID = "o7VVHhK9zf0";
private int mCurrentTabPosition = NO_CURRENT_POSITION;
private static final int NO_CURRENT_POSITION = -1;
private DrawerLayout drawerLayout;
private ListView drawerListView;
private String[] drawerListViewItems;
private ViewPager mPager;
ScrollView mainScrollView;
Button fav_up_btn1;
Button fav_dwn_btn1;
String TAG = "DEBUG THIS";
String PLAYLIST = "idconex";
Activity activity;
int imageArray[];
String[] stringArray;
private OnPageChangeListener mPageChangeListener;
ImagePagerAdapter adapter = new ImagePagerAdapter();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
final ActionBar actionBar = getActionBar();
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setAdapter(adapter);
actionBar.setCustomView(R.layout.actionbar_custom_view_home);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
// get list items from strings.xml
drawerListViewItems = getResources().getStringArray(R.array.items);
// get ListView defined in activity_main.xml
drawerListView = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
drawerListView.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_listview_item, drawerListViewItems));
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
drawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
//mainScrollView = (ScrollView) findViewById(R.id.groupScrollView);
listView = (VideosListView) findViewById(R.id.videosListView);
// Here we are adding this activity as a listener for when any row in
// the List is 'clicked'
// The activity will be sent back the video that has been pressed to do
// whatever it wants with
// in this case we will retrieve the URL of the video and fire off an
// intent to view it
listView.setOnVideoClickListener(this);
new GetYouTubeUserVideosTask(responseHandler, PLAYLIST).execute();
}
Handler responseHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
populateListWithVideos(msg);
};
};
private void populateListWithVideos(Message msg) {
Library lib = (Library) msg.getData().get(
GetYouTubeUserVideosTask.LIBRARY);
listView.setVideos(lib.getVideos());
}
#Override
protected void onStop() {
responseHandler = null;
super.onStop();
}
// This is the interface method that is called when a video in the listview
// is clicked!
// The interface is a contract between this activity and the listview
#Override
public void onVideoClicked(Video video) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(video.getUrl()));
startActivity(intent);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// call ActionBarDrawerToggle.onOptionsItemSelected(), if it returns
// true
// then it has handled the app icon touch event
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ImagePagerAdapter extends PagerAdapter {
public ImagePagerAdapter(Activity act, int[] mImages,
String[] stringArra) {
imageArray = mImages;
activity = act;
stringArray = stringArra;
}
// this is your constructor
public ImagePagerAdapter() {
super();
// setOnPageChangeListener(mPageChangeListener);
}
private int[] mImages = new int[] { R.drawable.selstation_up_btn,
R.drawable.classical_up_btn, R.drawable.country_up_btn,
R.drawable.dance_up_btn, R.drawable.hiphop_up_btn };
private String[] stringArray = new String[] { "vevo",
"TheMozARTGROUP‎", "TimMcGrawVEVO‎", "TiestoVEVO‎",
"EminemVEVO‎" };
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = Home.this;
ImageView imageView = new ImageView(context);
imageView.setImageResource(mImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
private final ViewPager.SimpleOnPageChangeListener mPageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(final int position) {
onTabChanged(mPager.getAdapter(), mCurrentTabPosition, position);
mCurrentTabPosition = position;
}
};
protected void onTabChanged(final PagerAdapter adapter,
final int oldPosition, final int newPosition) {
// Calc if swipe was left to right, or right to left
if (oldPosition > newPosition) {
// left to right
} else {
// right to left
View vg = findViewById(R.layout.home);
vg.invalidate();
}
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
int oldPos = viewPager.getCurrentItem();
#Override
public void onPageScrolled(int position, float arg1, int arg2) {
if (position > oldPos) {
// Moving to the right
} else if (position < oldPos) {
// Moving to the Left
View vg = findViewById(R.layout.home);
vg.invalidate();
}
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
}
});
}
}
}
VideoListView.java
public class VideosListView extends ListView implements android.widget.AdapterView.OnItemClickListener {
private List<Video> videos;
private VideoClickListener videoClickListener;
public VideosListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public VideosListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public VideosListView(Context context) {
super(context);
}
public void setVideos(List<Video> videos){
this.videos = videos;
VideosAdapter adapter = new VideosAdapter(getContext(), videos);
setAdapter(adapter);
// When the videos are set we also set an item click listener to the list
// this will callback to our custom list whenever an item it pressed
// it will tell us what position in the list is pressed
setOnItemClickListener(this);
}
// Calling this method sets a listener to the list
// Whatever class is passed in will be notified when the list is pressed
// (The class that is passed in just has to 'implement VideoClickListener'
// meaning is has the methods available we want to call)
public void setOnVideoClickListener(VideoClickListener l) {
videoClickListener = l;
}
#Override
public void setAdapter(ListAdapter adapter) {
super.setAdapter(adapter);
}
// When we receive a notification that a list item was pressed
// we check to see if a video listener has been set
// if it has we can then tell the listener 'hey a video has just been clicked' also passing the video
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
if(videoClickListener != null){
videoClickListener.onVideoClicked(videos.get(position));
}
}
}
My Source:
https://www.dropbox.com/s/irab3x18nhj4twt/idg.zip
Working Example:
http://blog.blundell-apps.com/click-item-in-a-listview-to-show-youtube-video/
If the List has clickable elements like ImageViewand Button, when you click on the list it is consumed by the ImageView and Button and your onitemClickListener is never called.
To make it work add android:clickable="false", android:focusable="false" and
android:focusableInTouchMode="false" to each of those Buttons and ImageViews in custom adapter view.
list_item_user_video.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<com.idg.omv.ui.widget.UrlImageView
android:id="#+id/userVideoThumbImageView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#android:color/black"
android:contentDescription="YouTube video thumbnail"
android:gravity="center"
android:scaleType="fitCenter"
android:src="#drawable/ic_launcher"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"/>
<View android:layout_width="match_parent"
android:layout_height="2dp"
android:visibility="invisible"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/userVideoTitleTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft = "5dip"
android:textSize="16sp"
android:text="Video Title Not Found"
android:textColor="#android:color/black" />
<TextView
android:id="#+id/userVideouploaderTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="13sp"
android:paddingLeft = "5dip"
android:layout_below="#id/userVideoTitleTextView"
android:textColor="#android:color/black" />
<Button
android:id="#+id/fav_up_btn1"
android:layout_width="27dp"
android:layout_height="27dp"
android:layout_alignParentRight="true"
android:background="#drawable/fav_up_btn1"
android:gravity="right"
android:paddingRight="5dp"
android:paddingTop="5dp"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"/>
</RelativeLayout>
<View android:layout_width="match_parent"
android:layout_height="11dp"
android:visibility="invisible"/>
</LinearLayout>
Checkout this article for more info
List view doesn't respond to click

Call NavigationDrawer in ALL Activitys

I have a NavigationDrawer and I would call it more Activity without having to copy and paste the same code in different classes. Thus, all the code that I would have to paste in the various classes, I put it in a class of its own, called NavDrawer. Here is the code.
NavDrawer
public class NavDrawer extends Activity{
ListView mDrawerList;
DrawerLayout mDrawer;
CustomActionBarDrawerToggle mDrawerToggle;
String[] menuItems;
Intent intent, intent2, intent3, intent4, intent5, intent6;
public void _initMenu() {
NsMenuAdapter mAdapter = new NsMenuAdapter(this);
// Add Header
mAdapter.addHeader(R.string.ns_menu_main_header);
// Add first block
menuItems = getResources().getStringArray(
R.array.ns_menu_items);
String[] menuItemsIcon = getResources().getStringArray(
R.array.ns_menu_items_icon);
int res = 0;
for (String item : menuItems) {
int id_title = getResources().getIdentifier(item, "string",
this.getPackageName());
int id_icon = getResources().getIdentifier(menuItemsIcon[res],
"drawable", this.getPackageName());
NsMenuItemModel mItem = new NsMenuItemModel(id_title, id_icon);
mAdapter.addItem(mItem);
res++;
}
mDrawerList = (ListView) findViewById(R.id.drawer);
if (mDrawerList != null)
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawer.isDrawerOpen(mDrawerList);
//menu.findItem(R.id.item1).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
/*
* The action bar home/up should open or close the drawer.
* ActionBarDrawerToggle will take care of this.
*/
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
private class CustomActionBarDrawerToggle extends ActionBarDrawerToggle {
public CustomActionBarDrawerToggle(Activity mActivity,DrawerLayout mDrawerLayout){
super(
mActivity,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.ns_menu_open,
R.string.ns_menu_close);
}
#Override
public void onDrawerClosed(View view) {
getActionBar().setTitle(getString(R.string.ns_menu_close));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(getString(R.string.ns_menu_open));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// Highlight the selected item, update the title, and close the drawer
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
if(position==0) {
//Open an Activity
}
if(position==1) {
//Open an Activity
}
if(position==2) {
//Open an Activity
}
//You should reset item counter
mDrawer.closeDrawer(mDrawerList);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.examplelayout);
getActionBar().setDisplayHomeAsUpEnabled(true);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawer.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
_initMenu();
mDrawerToggle = new CustomActionBarDrawerToggle(this, mDrawer);
mDrawer.setDrawerListener(mDrawerToggle);
_initMenu();
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
}
}
NsMenuAdapter
public class NsMenuAdapter extends ArrayAdapter<NsMenuItemModel> {
public NsMenuAdapter(Context context) {
super(context, 0);
}
public void addHeader(int title) {
add(new NsMenuItemModel(title, -1, true));
}
public void addItem(int title, int icon) {
add(new NsMenuItemModel(title, icon, false));
}
public void addItem(NsMenuItemModel itemModel) {
add(itemModel);
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
return getItem(position).isHeader ? 0 : 1;
}
#Override
public boolean isEnabled(int position) {
return !getItem(position).isHeader;
}
public static class ViewHolder {
public final TextView textHolder;
public final ImageView imageHolder;
public final TextView textCounterHolder;
public ViewHolder(TextView text1, ImageView image1,TextView textcounter1) {
this.textHolder = text1;
this.imageHolder = image1;
this.textCounterHolder=textcounter1;
}
}
public View getView(int position, View convertView, ViewGroup parent) {
NsMenuItemModel item = getItem(position);
ViewHolder holder = null;
View view = convertView;
if (view == null) {
int layout = R.layout.ns_menu_row_counter;
if (item.isHeader)
layout = R.layout.ns_menu_row_header;
view = LayoutInflater.from(getContext()).inflate(layout, null);
TextView text1 = (TextView) view.findViewById(R.id.menurow_title);
ImageView image1 = (ImageView) view.findViewById(R.id.menurow_icon);
TextView textcounter1 = (TextView) view.findViewById(R.id.menurow_counter);
view.setTag(new ViewHolder(text1, image1,textcounter1));
}
Object tag = view.getTag();
if (tag instanceof ViewHolder) {
holder = (ViewHolder) tag;
}
if(item != null && holder != null)
{
if (holder.textHolder != null)
holder.textHolder.setText(item.title);
if (holder.textCounterHolder != null){
if (item.counter > 0){
holder.textCounterHolder.setVisibility(View.VISIBLE);
}else{
holder.textCounterHolder.setVisibility(View.GONE);
}
}
if (holder.imageHolder != null) {
if (item.iconRes > 0) {
holder.imageHolder.setVisibility(View.VISIBLE);
holder.imageHolder.setImageResource(item.iconRes);
} else {
holder.imageHolder.setVisibility(View.GONE);
}
}
}
return view;
}
}
NsMenuItemModel
public class NsMenuItemModel {
public int title;
public int iconRes;
public int counter;
public boolean isHeader;
public NsMenuItemModel(int title, int iconRes,boolean header,int counter) {
this.title = title;
this.iconRes = iconRes;
this.isHeader=header;
this.counter=counter;
}
public NsMenuItemModel(int title, int iconRes,boolean header){
this(title,iconRes,header,0);
}
public NsMenuItemModel(int title, int iconRes) {
this(title,iconRes,false);
}
}
In classes where I want to have the NavigationDrawer I do nothing but extend the class NavigationDrawer, so I have a code like this
public class ExampleClass extends NavDrawer
And when I run the application in the ActionBar visualize the image and NavigationDrawer displayed but is EMPTY. Why?
In addition, in the onCreate of the class NavDrawer I set layout as the layout of an Activity, but if I have to see it in ALL Activity, can not be linked to ONE that A specific layout specific Activity. So I thought I'd create one specifically for the NavigationDrawer, containing one and only its structure. code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- The navigation drawer -->
<ListView
android:id="#+id/drawer"
android:layout_width="250dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#F3F3F4"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" >
</ListView>
</android.support.v4.widget.DrawerLayout>
It can work or not?
The layout of the example has a structure similar to this
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
<!-- The navigation drawer -->
<ListView
android:id="#+id/drawer"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#F3F3F4"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" >
</ListView>
</android.support.v4.widget.DrawerLayout>
I hope to have answers to all these and I apologize if my questions may seem trivial but are days that I am looking desperately for a solution, but I just can not. I hope to get answers and help. Thanks in advance.

Categories

Resources