how to add image for headers in navigationdrawer in android - java

Hi in the below code in my project contains navigation drawer with expandable listview.
but everything was working fine. but want to display image for headers on leftside and arrow icon should be in right side for each header.
using json am parsing the data and in the same way want to display images for headers.
can any one help me how to do that one.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
ArrayList<Model_country> al_main = new ArrayList<>();
ExpandableListView ev_list;
CountryAdapter obj_adapter;
String TAG = "MainActivity";
private DrawerLayout mDrawerLayout;
HomeFragment fragment;
TextView tv_name;
RelativeLayout rl_menu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fn_data();
init();
}
private void init() {
getSupportActionBar().hide();
ev_list = (ExpandableListView) findViewById(R.id.ev_menu);
tv_name = (TextView) findViewById(R.id.tv_name);
rl_menu = (RelativeLayout) findViewById(R.id.rl_menu);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
obj_adapter = new CountryAdapter(MainActivity.this, al_main);
ev_list.setAdapter(obj_adapter);
ev_list.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
setListViewHeight(parent, groupPosition);
return false;
}
});
setExpandableListViewHeightBasedOnChildren(ev_list);
fragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putString("name", al_main.get(0).getStr_country());
bundle.putString("des", al_main.get(0).getAl_state().get(0).getStr_description());
bundle.putString("dish", al_main.get(0).getAl_state().get(0).getStr_name());
bundle.putString("image", al_main.get(0).getAl_state().get(0).getStr_image());
tv_name.setText(al_main.get(0).getStr_country());
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment, "HomeFragment").addToBackStack("null").commit();
rl_menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDrawerLayout.openDrawer(Gravity.LEFT);
}
});
}
private void setListViewHeight(ExpandableListView listView, int group) {
ExpandableListAdapter listAdapter = (ExpandableListAdapter) listView.getExpandableListAdapter();
int totalHeight = 0;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(),
View.MeasureSpec.EXACTLY);
for (int i = 0; i < listAdapter.getGroupCount(); i++) {
View groupItem = listAdapter.getGroupView(i, false, null, listView);
groupItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += groupItem.getMeasuredHeight();
if (((listView.isGroupExpanded(i)) && (i != group))
|| ((!listView.isGroupExpanded(i)) && (i == group))) {
for (int j = 0; j < listAdapter.getChildrenCount(i); j++) {
View listItem = listAdapter.getChildView(i, j, false, null,
listView);
listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += listItem.getMeasuredHeight();
}
}
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
int height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getGroupCount() - 1));
/* if (height < 10)
height = 200;*/
params.height = height;
listView.setLayoutParams(params);
listView.requestLayout();
}
private void fn_data() {
String str_data = loadJSONFromAsset();
try {
JSONObject jsonObject_country = new JSONObject(str_data);
JSONArray jsonArray_country = jsonObject_country.getJSONArray("country");
al_main = new ArrayList<>();
for (int i = 0; i < jsonArray_country.length(); i++) {
Model_country obj_country = new Model_country();
JSONObject jsonObject = jsonArray_country.getJSONObject(i);
JSONArray jsonArray_dishes = jsonObject.getJSONArray("dishes");
ArrayList<Model_Dish> al_dishes = new ArrayList<>();
for (int j = 0; j < jsonArray_dishes.length(); j++) {
JSONObject jsonObject_dishes = jsonArray_dishes.getJSONObject(j);
Model_Dish obj_dish = new Model_Dish();
obj_dish.setStr_name(jsonObject_dishes.getString("dishname"));
obj_dish.setStr_description(jsonObject_dishes.getString("description"));
obj_dish.setStr_image(jsonObject_dishes.getString("image"));
al_dishes.add(obj_dish);
}
obj_country.setAl_state(al_dishes);
obj_country.setStr_country(jsonObject.getString("name"));
// obj_country.setStr_country (jsonObject.getString("image"));
al_main.add(obj_country);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public static void setExpandableListViewHeightBasedOnChildren(ExpandableListView expandableListView) {
CountryAdapter adapter = (CountryAdapter) expandableListView.getExpandableListAdapter();
if (adapter == null) {
return;
}
int totalHeight = expandableListView.getPaddingTop() + expandableListView.getPaddingBottom();
for (int i = 0; i < adapter.getGroupCount(); i++) {
View groupItem = adapter.getGroupView(i, false, null, expandableListView);
groupItem.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
totalHeight += groupItem.getMeasuredHeight();
if (expandableListView.isGroupExpanded(i)) {
for (int j = 0; j < adapter.getChildrenCount(i); j++) {
View listItem = adapter.getChildView(i, j, false, null, expandableListView);
listItem.setLayoutParams(new ViewGroup.LayoutParams(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED));
listItem.measure(View.MeasureSpec.makeMeasureSpec(0,
View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
totalHeight += listItem.getMeasuredHeight();
}
}
}
ViewGroup.LayoutParams params = expandableListView.getLayoutParams();
int height = totalHeight + expandableListView.getDividerHeight() * (adapter.getGroupCount() - 1);
if (height < 10)
height = 100;
params.height = height;
expandableListView.setLayoutParams(params);
expandableListView.requestLayout();
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("dishes.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
Log.e(TAG, "Json response " + json);
return json;
}
public void fn_selectedPosition(int group, int child) {
fragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putString("name", al_main.get(group).getStr_country());
bundle.putString("des", al_main.get(group).getAl_state().get(child).getStr_description());
bundle.putString("dish", al_main.get(group).getAl_state().get(child).getStr_name());
bundle.putString("image", al_main.get(group).getAl_state().get(child).getStr_image());
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment, "HomeFragment").addToBackStack("null").commit();
mDrawerLayout.closeDrawer(Gravity.LEFT);
tv_name.setText(al_main.get(group).getStr_country());
}
activity_main:
<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
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:background="#234E6F"
android:layout_height="60dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:textColor="#ffffff"
android:layout_centerInParent="true"
android:textStyle="bold"
android:id="#+id/tv_name"/>
<ImageView
android:layout_width="25dp"
android:layout_centerVertical="true"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:src="#drawable/menu_icon"/>
<RelativeLayout
android:layout_width="40dp"
android:id="#+id/rl_menu"
android:layout_height="match_parent"></RelativeLayout>
</RelativeLayout>
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#FFFFFF">
<include layout="#layout/menu_layout"></include>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>

You can use expandable listview for this. use custom adapter which will have textview and imageview. set image and text using expandable listview adapter. you can use custom adapter for child and parent both
public View getGroupView(final int i, boolean b, View view, ViewGroup viewGroup) {
if (view == null)
view = layoutInflater.inflate(R.layout.row_comment, viewGroup, false);
TextView username=(TextView) view.findViewById(R.id.userName);
((ImageView) view.findViewById(R.id.img_hifi)).setImageResource(R.drawable.high_5_icon_highlited);
}
#Override
public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
if (view == null)
view = layoutInflater.inflate(R.layout.row_comment, viewGroup, false);
view.setBackgroundColor(Color.parseColor("#FFCC00"));
((TextView) view.findViewById(R.id.userName)).setText(getChild(i, i1).getUser_name() + " ");
((TextView) view.findViewById(R.id.userName)).setTextColor(Color.BLACK);
return view;
}

Related

Last item in RecyclerView not shown

I have a recycle view that works fine but when the number of items is too big for them to fit on the screen and I scroll down, the last item is not shown. However, I can see through logging that a view holder has been created and bound successfully. Then if I add another item, the previous last item is shown at the end instead and so on. I would really appreciate it if you could help me.
public class ProdListAdapter extends RecyclerView.Adapter<ProdListItemViewHolder> implements Filterable {
public List<ProductListItem> prodListItems = null;
public List<ProductListItem> displayedProdListItems = null;
private int currListItemId;
private RecyclerView recyclerView;
private ProductsListFragment fragment;
private MainActivity activity;
public ProdListAdapter(ProductsListFragment fragment, MainActivity activity) {
System.out.println("LIST ADAPTER CONSTRUCTOR");
this.prodListItems = new ArrayList<>();
for (int i = 0; i < activity.products.size(); i++) {
Product currProd = activity.products.get(i);
System.out.println(currProd.getName() + " " + i);
//add category separator
if (i > 0 && !currProd.getCategory().equals(activity.products.get(i - 1).getCategory())) {
prodListItems.add(new ProductListCategory(currProd));
} else if (i == 0) {
prodListItems.add(new ProductListCategory(currProd));
}
prodListItems.add(new ProductListItem(currProd));
}
this.activity = activity;
this.displayedProdListItems = prodListItems;
this.currListItemId = 0;
this.fragment = fragment;
}
// Create new views (invoked by the layout manager)
#Override
public ProdListItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int idToUse = currListItemId % prodListItems.size();
boolean isCatSeparator = false;
ProductListItem currProdListItem = prodListItems.get(idToUse);
ConstraintLayout listItemView = (ConstraintLayout) LayoutInflater.from(parent.getContext())
.inflate(R.layout.product_list_item, parent, false);
if (currProdListItem.isCategorySeparator()) {
isCatSeparator = true;
}
if (!isCatSeparator) {
Product currProd = currProdListItem.getProduct();
}
System.out.println("CREATING: " + currProdListItem.getItemText());
System.out.println("idToUse: " + idToUse + " " + currProdListItem.getItemText());
ProdListItemViewHolder viewHolder = new ProdListItemViewHolder(listItemView, isCatSeparator, fragment, currProdListItem);
currListItemId++;
return viewHolder;
}
// (invoked by the layout manager)
// Replace the contents of a view by the item at index: itemIndex
#Override
public void onBindViewHolder(ProdListItemViewHolder viewHolder, int itemIndex) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
//update product item
ProductListItem newListViewItem = displayedProdListItems.get(itemIndex);
boolean newItemIsCatSeparator = newListViewItem.isCategorySeparator();
boolean oldItemIsCatSeparator = viewHolder.getProductListItem().isCategorySeparator();
if (!newItemIsCatSeparator) {
Product currProd = newListViewItem.getProduct();
}
System.out.println();
System.out.println(viewHolder.getProductListItem().getItemText() + " -> " + newListViewItem.getItemText());
System.out.println(viewHolder.getProductListItem().isCategorySeparator() + " TO " + newListViewItem.isCategorySeparator());
System.out.println("checked " + viewHolder.getProductListItem().isChecked() + " to " + newListViewItem.isChecked());
System.out.println();
if (newItemIsCatSeparator && oldItemIsCatSeparator) {
//System.out.println("1");
viewHolder.changeCategory(newListViewItem.getProduct());
} else if (!newItemIsCatSeparator && !oldItemIsCatSeparator) {
//System.out.println("2");
viewHolder.changeProduct(newListViewItem);
} else if (newItemIsCatSeparator && !oldItemIsCatSeparator) {
//System.out.println("3");
viewHolder.toCatSeparator(newListViewItem.getProduct());
} else { // !newListViewItem.isCategorySeparator() && viewHolder.getProductListItem().isCategorySeparator()
//System.out.println("4");
viewHolder.toProdItem(newListViewItem);
}
}
#Override
public int getItemCount() {
int count = 0;
if(this.displayedProdListItems != null){
count = displayedProdListItems.size();
}
return count;
}
}
public class ProductsListFragment extends Fragment {
private int numCheckedItems = 0;
private BottomSheetBehavior botSheetBehavior;
private boolean botSheetOpen = false;
private ProdListAdapter prodAdapter;
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_products_list, container, false);
//recyclerView stuff below
RecyclerView recyclerView = (RecyclerView) root.findViewById(R.id.prod_list_recycler_view);
recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
LinearLayoutManager layoutManager = new LinearLayoutManager(this.getContext());
recyclerView.setLayoutManager(layoutManager);
prodAdapter = new ProdListAdapter(this, activity);
recyclerView.setAdapter(prodAdapter);
activity.setProdListAdapter(prodAdapter);
return root;
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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:id="#+id/prodListLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<AutoCompleteTextView
android:id="#+id/searchTxtView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search"
android:drawableLeft="#drawable/ic_search"
android:drawablePadding="10dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/prod_list_recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:dividerHeight="2dp"
android:scrollbars="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/searchTxtView" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:layout_marginEnd="28dp"
android:layout_marginRight="28dp"
android:layout_marginBottom="28dp"
android:src="#drawable/ic_fab_plus_36dp"
app:backgroundTint="#aa00ff"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
add:
app:layout_constraintBottom_toBottomOf="parent"
and change height of recyclerview to 0dp

Android: I'm not able to display phone's images into my GridView

I have implemented Gridview, but the images from the phone gallery is not appearing in the particular GridView.
The scroll seems to be big enough as the scrollbar appearing on the right side scrolls along to the bottom. Then why I couldn't see the images.
GalleryGridAdapter.java
package com.test.Adapter;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import com.test.R;
public class GalleryGridAdapter extends CursorAdapter
{
private Context mContext;
private Cursor mCursor;
private int mColumnIndex;
private ImageView imageView;
#SuppressWarnings("deprecation")
public GalleryGridAdapter(Context context, Cursor c, int ci) {
super(context, c);
mContext = context;
mCursor = c;
mColumnIndex = ci;
}
#Override
public void bindView(View view, Context context, Cursor curs)
{
ImageView imageView = (ImageView) view;
int id = curs.getInt(mColumnIndex);
imageView.setImageURI( Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
String.valueOf(id)));
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
}
#Override
public View newView(Context context, Cursor curs, ViewGroup parent)
{
return new ImageView(context);
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public int mygetItemId(int position) {
return 0;
}
}
MyActivity.java
String[] projection = {MediaStore.Images.Thumbnails._ID, MediaStore.Images.Thumbnails.DATA};
final Cursor cursor = context.getContentResolver().query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection, null, null,
MediaStore.Images.Thumbnails.IMAGE_ID);
int columnIndex = 0;
if (cursor != null) {
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
GridView gridview = (GridView) findViewById(R.id.gridViewGallery);
gridview.setAdapter(new GalleryGridAdapter(getApplicationContext(), cursor, columnIndex));
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.e("selected Image",cursor.getColumnName(i)+"");
}
});
}
use xml code like :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="#drawable/bg_child">
<FrameLayout android:id="#+id/FrameLayout01"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<FrameLayout android:id="#+id/LinearLayout01"
android:layout_gravity="top" android:layout_height="50dp" android:layout_width="fill_parent">
<TextView android:id="#+id/TextView01"
android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" android:layout_gravity="center_vertical" android:layout_marginLeft="30dp" android:gravity="center_vertical" android:drawableLeft="#drawable/photo_frame" android:textColor="#color/grey" android:text="#string/photogallery_txt"></TextView>
<Button android:layout_gravity="right" android:id="#+id/btnMoreInfo" android:layout_marginRight="5dp" android:layout_marginTop="5dp" android:textStyle="bold" android:background="#drawable/my_child_button" android:layout_width="100dp" android:layout_height="40dp" android:text="#string/moreinfo_txt"></Button>
</FrameLayout>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridview" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:columnWidth="90dp"
android:numColumns="auto_fit" android:verticalSpacing="10dp"
android:horizontalSpacing="10dp" android:stretchMode="columnWidth"
android:gravity="center" android:layout_gravity="bottom"
android:layout_marginTop="50dp"/>
</FrameLayout>
use code like :
public class GalleryPage extends Activity {
private static Uri[] mUrls = null;
private static String[] strUrls = null;
private String[] mNames = null;
private GridView gridview = null;
private Cursor cc = null;
private Button btnMoreInfo = null;
private ProgressDialog myProgressDialog = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.gallery);
btnMoreInfo = (Button) findViewById(R.id.btnMoreInfo);
// It have to be matched with the directory in SDCard
cc = this.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null,
null);
if (cc != null) {
myProgressDialog = new ProgressDialog(GalleryPage.this);
myProgressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
myProgressDialog.setMessage(getResources().getString(R.string.pls_wait_txt));
myProgressDialog.show();
new Thread() {
public void run() {
try {
cc.moveToFirst();
mUrls = new Uri[cc.getCount()];
strUrls = new String[cc.getCount()];
mNames = new String[cc.getCount()];
for (int i = 0; i < cc.getCount(); i++) {
cc.moveToPosition(i);
mUrls[i] = Uri.parse(cc.getString(1));
strUrls[i] = cc.getString(1);
mNames[i] = cc.getString(3);
//Log.e("mNames[i]",mNames[i]+":"+cc.getColumnCount()+ " : " +cc.getString(3));
}
} catch (Exception e) {
}
myProgressDialog.dismiss();
}
}.start();
gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Intent i = new Intent(GalleryPage.this, BigImage.class);
Log.e("intent : ", ""+position);
i.putExtra("imgUrls", strUrls);
i.putExtra("position", position);
startActivity(i);
}
});
}
btnMoreInfo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(GalleryPage.this, ChildLogin.class);
startActivity(i);
}
});
}
/**
* This class loads the image gallery in grid view.
*
*/
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return cc.getCount();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.galchild, null);
try {
ImageView imageView = (ImageView) v.findViewById(R.id.ImageView01);
//imageView.setScaleType(ImageView.ScaleType.FIT_XY);
// imageView.setPadding(8, 8, 8, 8);
Bitmap bmp = decodeURI(mUrls[position].getPath());
//BitmapFactory.decodeFile(mUrls[position].getPath());
imageView.setImageBitmap(bmp);
//bmp.
TextView txtName = (TextView) v.findViewById(R.id.TextView01);
txtName.setText(mNames[position]);
} catch (Exception e) {
}
return v;
}
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
FlurryAgent.onStartSession(this, "***");
}
/**
* This method is to scale down the image
*/
public Bitmap decodeURI(String filePath){
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// Only scale if we need to
// (16384 buffer for img processing)
Boolean scaleByHeight = Math.abs(options.outHeight - 100) >= Math.abs(options.outWidth - 100);
if(options.outHeight * options.outWidth * 2 >= 16384){
// Load, scaling to smallest power of 2 that'll get it <= desired dimensions
double sampleSize = scaleByHeight
? options.outHeight / 100
: options.outWidth / 100;
options.inSampleSize =
(int)Math.pow(2d, Math.floor(
Math.log(sampleSize)/Math.log(2d)));
}
// Do the actual decoding
options.inJustDecodeBounds = false;
options.inTempStorage = new byte[512];
Bitmap output = BitmapFactory.decodeFile(filePath, options);
return output;
}
}

Android Recyclerview not showing any data

I took this tutorial as reference.
Despite of checking everything, no data is appearing on screen ie. main_activity. I've already referred to other pages on stackoverflow regarding this issue. Can't find a viable solution.
NOTE: There is no warning or error while I deploy app on the device.
This is the source code.
MainActivity.java:
public class MainActivity extends Activity
{
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyRecyclerViewAdapter(getDataSet());
mRecyclerView.setAdapter(mAdapter);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(this, LinearLayoutManager.VERTICAL);
mRecyclerView.addItemDecoration(itemDecoration);
// Code to Add an item with default animation
DataObject obj = new DataObject("red", "foo");
((MyRecyclerViewAdapter) mAdapter).addItem(obj, 0);
// Code to remove an item with default animation
//((MyRecyclerViewAdapter) mAdapter).deleteItem(index);
}
#Override
protected void onResume() {
super.onResume();
((MyRecyclerViewAdapter) mAdapter).setOnItemClickListener(new MyRecyclerViewAdapter.MyClickListener()
{
#Override
public void onItemClick(int position, View v) {
Toast.makeText(MainActivity.this, "Clicked item: " + position, Toast.LENGTH_SHORT).show();
}
});
}
private ArrayList<DataObject> getDataSet() {
ArrayList results = new ArrayList<DataObject>();
for (int index = 0; index < 20; index++){
DataObject obj = new DataObject("Some Primary Text " + index, "Secondary " + index);
results.add(index, obj);
}
return results;
}
}
DataObject.java:
public class DataObject {
private String mText1;
private String mText2;
DataObject (String text1, String text2){
mText1 = text1;
mText2 = text2;
}
public String getmText1() {
return mText1;
}
public void setmText1(String mText1) {
this.mText1 = mText1;
}
public String getmText2() {
return mText2;
}
public void setmText2(String mText2) {
this.mText2 = mText2;
}
}
MyRecyclerViewAdapter.java:
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.DataObjectHolder>
{
private static String LOG_TAG = "MyRecyclerViewAdapter";
private ArrayList<DataObject> mDataset;
private static MyClickListener myClickListener;
public static class DataObjectHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
TextView label;
TextView dateTime;
public DataObjectHolder(View itemView)
{
super(itemView);
label = (TextView) itemView.findViewById(R.id.textView);
dateTime = (TextView) itemView.findViewById(R.id.textView2);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getPosition(), v);
}
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
public MyRecyclerViewAdapter(ArrayList<DataObject> myDataset) {
mDataset = myDataset;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
holder.label.setText(mDataset.get(position).getmText1());
holder.dateTime.setText(mDataset.get(position).getmText2());
}
public void addItem(DataObject dataObj, int index) {
mDataset.add(dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount()
{
return mDataset.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
}
DividerIconDecoration.java
public class DividerItemDecoration extends RecyclerView.ItemDecoration{
private static final int[] ATTRS = new int[]{
android.R.attr.listDivider
};
public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;
public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;
private Drawable mDivider;
private int mOrientation;
public DividerItemDecoration(Context context, int orientation) {
final TypedArray a = context.obtainStyledAttributes(ATTRS);
mDivider = a.getDrawable(0);
a.recycle();
setOrientation(orientation);
}
public void setOrientation(int orientation) {
if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
throw new IllegalArgumentException("invalid orientation");
}
mOrientation = orientation;
}
#Override
public void onDraw(Canvas c, RecyclerView parent) {
if (mOrientation == VERTICAL_LIST) {
drawVertical(c, parent);
} else {
drawHorizontal(c, parent);
}
}
public void drawVertical(Canvas c, RecyclerView parent) {
final int left = parent.getPaddingLeft();
final int right = parent.getWidth() - parent.getPaddingRight();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int top = child.getBottom() + params.bottomMargin;
final int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
public void drawHorizontal(Canvas c, RecyclerView parent) {
final int top = parent.getPaddingTop();
final int bottom = parent.getHeight() - parent.getPaddingBottom();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int left = child.getRight() + params.rightMargin;
final int right = left + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
#Override
public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
if (mOrientation == VERTICAL_LIST) {
outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
} else {
outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
</RelativeLayout>
</ScrollView>
recyclerview_item.xml
<?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:background="?android:attr/selectableItemBackground"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingTop="5dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="5dp"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
The problem is in activity_main.xml. You should remove ScrollView and it will work (There's no reason to have one since the recyclerview has an implicit one). There is no scrollview in the tutorial either: check activity_recycler_view.xml.

VideoView unable to open content from internel storage

I have the following code:
try {
myVideoView.setMediaController(mediaControls);
File mydir = getDir("myDir", Context.MODE_PRIVATE);
myVideoView.setVideoPath(mydir.getPath()+"/fileName.3gp");
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
myVideoView.requestFocus();
myVideoView.setOnPreparedListener(new OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) {
progressDialog.dismiss();
myVideoView.seekTo(position);
if (position == 0) {
myVideoView.start();
} else {
myVideoView.pause();
}
}
});
within onCreate() method. The problem is that it throws an IOException, and says that Unable to open the content. It works perfect if I use myVideoView.setVideoURI(path/to/server) instead of myVideoView.setVideoPath(path/to/local/storage). All permissions at Manifest.xml are fine, and it does not says that the file was not found or something. It says unable to open it. It is not a video format problem either, because is the same video when I play it from server. If this is a useful info, I have another activity in background (same app), and the VideoView activity is in foreground. Thank you!
Hi use it to play Internal Video
public class MainActivity extends Activity {
private Cursor videocursor;
private int video_column_index;
ListView videolist;
int count;
String[] thumbColumns = { MediaStore.Video.Thumbnails.DATA, MediaStore.Video.Thumbnails.VIDEO_ID };
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init_phone_video_grid();
}
#SuppressWarnings("deprecation")
private void init_phone_video_grid() {
System.gc();
String[] proj = { MediaStore.Video.Media._ID, MediaStore.Video.Media.DATA, MediaStore.Video.Media.DISPLAY_NAME, MediaStore.Video.Media.SIZE };
videocursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, proj, null, null, null);
count = videocursor.getCount();
videolist = (ListView) findViewById(R.id.PhoneVideoList);
videolist.setAdapter(new VideoAdapter(getApplicationContext()));
videolist.setOnItemClickListener(videogridlistener);
}
private OnItemClickListener videogridlistener = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
System.gc();
video_column_index = videocursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
videocursor.moveToPosition(position);
String filename = videocursor.getString(video_column_index);
Intent intent = new Intent(MainActivity.this, ViewVideo.class);
intent.putExtra("videofilename", filename);
startActivity(intent);
}
};
public class VideoAdapter extends BaseAdapter {
private Context vContext;
public VideoAdapter(Context c) {
vContext = c;
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
System.gc();
ViewHolder holder;
String id = null;
convertView = null;
if (convertView == null) {
convertView = LayoutInflater.from(vContext).inflate(R.layout.listitem, parent, false);
holder = new ViewHolder();
holder.txtTitle = (TextView) convertView.findViewById(R.id.txtTitle);
holder.txtSize = (TextView) convertView.findViewById(R.id.txtSize);
holder.thumbImage = (ImageView) convertView.findViewById(R.id.imgIcon);
video_column_index = videocursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
videocursor.moveToPosition(position);
id = videocursor.getString(video_column_index);
video_column_index = videocursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);
videocursor.moveToPosition(position);
// id += " Size(KB):" +
// videocursor.getString(video_column_index);
holder.txtTitle.setText(id);
holder.txtSize.setText(" Size(KB):" + videocursor.getString(video_column_index));
String[] proj = { MediaStore.Video.Media._ID, MediaStore.Video.Media.DISPLAY_NAME, MediaStore.Video.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, proj, MediaStore.Video.Media.DISPLAY_NAME + "=?",
new String[] { id }, null);
cursor.moveToFirst();
long ids = cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media._ID));
ContentResolver crThumb = getContentResolver();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(crThumb, ids, MediaStore.Video.Thumbnails.MICRO_KIND, options);
holder.thumbImage.setImageBitmap(curThumb);
curThumb = null;
} /*
* else holder = (ViewHolder) convertView.getTag();
*/
return convertView;
}
}
static class ViewHolder {
TextView txtTitle;
TextView txtSize;
ImageView thumbImage;
}
}
and Video View Class is here
public class ViewVideo extends Activity {
private String filename;
VideoView vv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.gc();
Intent i = getIntent();
Bundle extras = i.getExtras();
filename = extras.getString("videofilename");
// vv = new VideoView(getApplicationContext());
setContentView(R.layout.activity_main);
vv = (VideoView) findViewById(R.id.videoView);
vv.setVideoPath(filename);
vv.setMediaController(new MediaController(this));
vv.requestFocus();
vv.start();
}
}
And Xml Part is Here
<?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" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:background="#242425"
android:gravity="center"
android:orientation="vertical" >
<VideoView
android:id="#+id/videoView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:background="#android:color/white"
android:gravity="center"
android:orientation="vertical" >
<ListView
android:id="#+id/PhoneVideoList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#android:color/darker_gray"
android:cacheColorHint="#00000000"
android:dividerHeight="2dp"></ListView>
</LinearLayout>
</LinearLayout>
</LinearLayout>

Adding views programmatically cause change of size in Android

I'm trying to add views programmatically but when i do, the size of a imageview is not the same (i've used it in another view and set by xml).
This is my function that i use to add programmatically views :
public void initClaps(int size, List<Clap> claps) {
LayoutParams params = new LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
//LayoutParams params2 = new LayoutParams(0, LayoutParams.WRAP_CONTENT,
// 33);
LayoutParams params3 = new LayoutParams(0,
LayoutParams.WRAP_CONTENT, 1.0f);
int position = 0;
for (int i = 0; i < size; i++) {
LinearLayout layout = new LinearLayout(getActivity());
layout.setWeightSum(3.0f);
layout.setOrientation(LinearLayout.HORIZONTAL);
if (i == 0) {
View view_add = in.inflate(R.layout.adapter_claps2, null);
layout.addView(view_add, params3);
for (int j = 0; j < 2; j++) {
View view_clap = in.inflate(R.layout.adapter_claps, null);
final Clap clap = claps.get(position);
FrameLayout fl = (FrameLayout) view_clap
.findViewById(R.id.fl_adapter_claps);
SmartImageViewRound siv = (SmartImageViewRound) view_clap
.findViewById(R.id.siv_adapter_claps);
TextView tv = (TextView) view_clap
.findViewById(R.id.tv_adapter_claps);
siv.setImageUrl(clap.getMini());
tv.setText("" + clap.getNom());
fl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(),
ClapDetail.class);
intent.putExtra(ClapDetail.INTENT_NOM,
clap.getNom());
getActivity().startActivity(intent);
}
});
layout.addView(view_clap, params3);
position++;
}
ll_container.addView(layout, params);
} else {
for (int j = 0; j < 3; j++) {
if(position != claps.size()){
final Clap clap = claps.get(position);
View view = in.inflate(R.layout.adapter_claps, null);
FrameLayout fl = (FrameLayout) view
.findViewById(R.id.fl_adapter_claps);
SmartImageViewRound siv = (SmartImageViewRound) view
.findViewById(R.id.siv_adapter_claps);
TextView tv = (TextView) view
.findViewById(R.id.tv_adapter_claps);
siv.setImageUrl(clap.getMini());
tv.setText("" + clap.getNom());
fl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(),
ClapDetail.class);
intent.putExtra(ClapDetail.INTENT_NOM,
clap.getNom());
getActivity().startActivity(intent);
}
});
layout.addView(view, params3);
position++;
}
}
ll_container.addView(layout, params);
}
}
}
This is caused because you are passing null while inflating your views.
Lets consider the following view to be inflated(From a listViews point of view):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="15dp"
android:text="Text1" />
<TextView
android:id="#+id/text2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Text2" />
</LinearLayout>
If we are adding the above xml view to a listview as such:
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflate(R.layout.item_row, null);
}
return convertView;
}
Result:
But with the right approach:
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflate(R.layout.item_row, parent, false);
}
return convertView;
}
Result:
More info can be found in this nice post by Dave Smith.
You too have to replace the null with the parent viewGroup.

Categories

Resources