Android: GridView shows all but a few images - java

I have 6 images downloaded as shown here, but the GridView in my gallery only displays 5 of those images.
I'm trying to copy how Instagram displays its gallery, with a selected image taking up 60% of the screen and the gallery images taking up the rest.
fragment_gallery.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">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/relLayoutl">
<!--toolbar-->
<include layout="#layout/snippet_top_gallerybar"/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="100"
android:layout_below="#+id/relLayoutl">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/galleryImageView"
android:scaleType="centerCrop"/>
<ProgressBar
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/progressBar"
android:layout_centerInParent="true"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40">
<GridView
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:numColumns="5"
android:verticalSpacing="1.5dp"
android:horizontalSpacing="1.5dp"
android:gravity="center"
android:layout_marginTop="1dp"
android:stretchMode="none"
android:id="#+id/gridView">
</GridView>
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
I created a square view to generate square cells
layout_grid_imageview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<com.example.sheldon.instagramclone.Util.SquareImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/gridViewImage"
android:adjustViewBounds="true"
android:scaleType="centerCrop"/>
<ProgressBar
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerInParent="true"
android:id="#+id/gridProgressBar"/>
</RelativeLayout>
GalleryFragment.java
public class GalleryFragment extends Fragment {
private static final int NUM_COLUMNS = 4;
private ImageView mExit;
private Spinner mSpinner;
private TextView mNext;
private ProgressBar mProgressBar;
private List<String> directories;
private GridView mGridView;
private ImageView mGalleryImage;
private HashMap<String, ArrayList<String>> directoryToImage;
private String append = "file:/";
private String mSelectedImage;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
mExit = (ImageView) view.findViewById(R.id.exitShare);
mSpinner = (Spinner) view.findViewById(R.id.shareSpinner);
mNext = (TextView) view.findViewById(R.id.shareNext);
mProgressBar = (ProgressBar) view.findViewById(R.id.progressBar);
mGridView = (GridView) view.findViewById(R.id.gridView);
mGalleryImage = (ImageView) view.findViewById(R.id.galleryImageView);
mExit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().finish();
}
});
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Navigating to next step in sharing photo");
Intent intent = new Intent(getActivity(), NextActivity.class);
intent.putExtra("selected_image", mSelectedImage);
startActivity(intent);
}
});
init();
return view;
}
private void init() {
ImageFinder imageFinder = new ImageFinder();
imageFinder.getImages(getActivity());
directoryToImage = imageFinder.getImageMapping();
directories = new ArrayList<>(directoryToImage.keySet());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.spinner_item, directories);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemSelected: " + directories.get(position));
setUpGridView(directories.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void setUpGridView(String directory) {
final ArrayList<String> imgURLS = directoryToImage.get(directory);
Log.d(TAG, "setUpGridView: Displaying " + directory + " with " + imgURLS.size() + " images");
int gridWidth = getResources().getDisplayMetrics().widthPixels;
int imageWidth = gridWidth / NUM_COLUMNS;
Log.d(TAG, "setUpGridView: Image Width is " + imageWidth);
mGridView.setColumnWidth(imageWidth);
GridImageAdapter adapter = new GridImageAdapter(getActivity(), R.layout.layout_grid_imageview, append, imgURLS);
mGridView.setAdapter(adapter);
UniversalImageLoader.setImage(imgURLS.get(0),mGalleryImage, mProgressBar, append);
mSelectedImage = imgURLS.get(0);
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
UniversalImageLoader.setImage(imgURLS.get(position), mGalleryImage, mProgressBar, append);
mSelectedImage = imgURLS.get(0);
}
});}
I display the images using a library called Universal Image loader
GridImageAdapter.java
public class GridImageAdapter extends ArrayAdapter<String>{
private Context mContext;
private LayoutInflater mInflater;
private int layoutResource;
private String mAppend;
private ArrayList<String> imgURLs;
public GridImageAdapter(Context context, int layoutResource, String append, ArrayList<String> imgURLs) {
super(context, layoutResource, imgURLs);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContext = context;
this.layoutResource = layoutResource;
mAppend = append;
this.imgURLs = imgURLs;
}
private static class ViewHolder{
SquareImageView image;
ProgressBar mProgressBar;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
final ViewHolder holder;
if(convertView == null){
convertView = mInflater.inflate(layoutResource, parent, false);
holder = new ViewHolder();
holder.mProgressBar = (ProgressBar) convertView.findViewById(R.id.gridProgressBar);
holder.image = (SquareImageView) convertView.findViewById(R.id.gridViewImage);
convertView.setTag(holder);
}
else{
holder = (ViewHolder) convertView.getTag();
}
String imgURL = getItem(position);
Log.d(TAG, "getView: Loading position " + position + ", displaying " + imgURL + ", with image " + holder.image);
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(mAppend + imgURL, holder.image, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.VISIBLE);
}
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.GONE);
}
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.GONE);
}
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.GONE);
}
}
});
return convertView;
}
First time posting, so I apologize if there's anything wrong with this post.

Sorry for being so general and unclear in my post, I wasn't quite sure which portion of the code was the problem area. After looking over the code again, I noticed a stupid mistake. I set GridView's numColumns attribute to 5 in fragment_gallery.xml, but calculated the column width in GalleryFragment.java using private static final int NUM_COLUMNS = 4. I assume that this caused images to be displayed in a non-existent 5th column.

Related

How can I transfer image new intent

This is my adapter and I save my image string type in Responsemodel class.
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.myviewholder>
{
List<ResponseModel> data;
private final IOtobusSaatleriInterface iOtobusSaatleriInterface;
Context context;
public MyAdapter(List<ResponseModel> data, IOtobusSaatleriInterface iOtobusSaatleriInterface, Context context) {
this.data = data;
this.iOtobusSaatleriInterface = iOtobusSaatleriInterface;
this.context = context;
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.singlerowdesign,parent,false);
return new myviewholder(view,iOtobusSaatleriInterface);
}
#Override
public void onBindViewHolder(#NonNull myviewholder holder, int position) {
holder.t1.setText(data.get(position).getName());
holder.t2.setText(data.get(position).getDesig());
Glide.with(holder.t1.getContext())
.load("http://example.site/Gurpinar/images/" +data.get(position).getImage()).into(holder.img);
}
#Override
public int getItemCount() {
return null!=data?data.size():0;
}
class myviewholder extends RecyclerView.ViewHolder{
ImageView img;
TextView t1,t2;
public myviewholder(#NonNull View itemView, IOtobusSaatleriInterface iOtobusSaatleriInterface) {
super(itemView);
img = itemView.findViewById(R.id.img);
t1 = itemView.findViewById(R.id.t1);
t2 = itemView.findViewById(R.id.t2);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (iOtobusSaatleriInterface != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION);
iOtobusSaatleriInterface.onItemClick(position);
Intent intent = new Intent(context,deneme.class);
intent.putExtra("name",data.get(position).getName());
intent.putExtra("resim","http://example.site/Gurpinar/images/");
context.startActivity(intent);
}
}
});
}
}
}
and my new empty activity
public class deneme extends AppCompatActivity {
TextView textView;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deneme);
textView = findViewById(R.id.textView);
imageView = findViewById(R.id.imageView);
Intent intent = getIntent();
String name = intent.getStringExtra("name");
String goruntu = intent.getStringExtra("resim");
String.valueOf(Glide.with(imageView).load(goruntu));
textView.setText(name);
}
}
And my new empty activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
android:orientation="vertical"
tools:context=".deneme">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#mipmap/ic_launcher" />
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5sp"
android:gravity="left"
android:text="TextView"
android:textColor="#494545"
android:textSize="25sp"
app:layout_constraintBottom_toTopOf="#+id/imageView" />
</LinearLayout>
My problem is I can access name data but image cannot be displayed.
How can I access the selected photo? I take the photos in mysql database and with the url recyclerview.
Perhaps you can pass the image as a Base64 in the Intent and create in the new Activity a Imagefile from this String.
Create as Base64 String:
How to get raw string of an image from Bitmap in android?
Create the Imagefile again from the String:
Create image file from raw string data

Stored data not appearing in GridView

GridVIew
I have implemented grid view in my application but it’s showing nothing although it’s not giving any error.
In xml layout I also couldn’t see the grid view.
Adapter
public class FoodListAdapter extends BaseAdapter {
private Context context;
private int layout;
private ArrayList<Food> foodsList;
public FoodListAdapter(Context context, int layout, ArrayList<Food> foodsList) {
this.context = context;
this.layout = layout;
this.foodsList = foodsList;
}
#Override
public int getCount() {
return foodsList.size();
}
#Override
public Object getItem(int position){
return foodsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder{
TextView Ename,E_des,E_size,E_Price;
ImageView MyPic;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
View r= view;
ViewHolder holder= new ViewHolder();
if (r==null){
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
r=inflater.inflate(layout,null);
holder.Ename=(TextView) r.findViewById(R.id.Menu_Name);
holder.E_des=(TextView) r.findViewById(R.id.Description_name);
holder.E_size=(TextView) r.findViewById(R.id.itemsSize);
holder.E_Price=(TextView) r.findViewById(R.id.Price);
holder.MyPic=(ImageView) r.findViewById(R.id.my_Imaage);
r.setTag(holder);
}
else {
holder=(ViewHolder) r.getTag();
}
Food food=foodsList.get(position);
holder.Ename.setText(food.getName());
holder.E_Price.setText(food.getPrice());
holder.E_size.setText(food.getSize());
holder.E_des.setText(food.getDescription());
byte [] foodImages=food.getPICs(); Bitmap
bitmap=BitmapFactory.decodeByteArray(foodImages,0,foodImages.length);
holder.MyPic.setImageBitmap(bitmap);
return r; }
}
XML CODE
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#id/recyclerView"
android:layout_width="match_parent"
android:layout_height="721dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<GridView
android:id="#+id/grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="10dp"
android:columnWidth="120dp"
android:gravity="center"
android:numColumns="auto_fit"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MAIN_ACTIVITY
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainpage);
GridView=(GridView) findViewById(R.id.grid);
list= new ArrayList<>();
Adapter= new
FoodListAdapter(Mainpage.this,R.layout.food_items,list);
GridView.setAdapter(Adapter);
Cursor cursor=AddMenu.sqLitHelper.GetData("SELECT * FROM FOOD");
list.clear();
while (cursor.moveToNext()){
int id = cursor.getInt(5);
String Name=cursor.getString(1);
String Description=cursor.getString(2);
String Price=cursor.getString(3);
String Size=cursor.getString(4);
byte [] Pics=cursor.getBlob(0);
list.add(new Food(Pics,Name,Description,Price,Size,id));
}
Adapter.notifyDataSetChanged();
Could someone help me !!
Please check below code
Cursor cursor=AddMenu.sqLitHelper.GetData("SELECT * FROM FOOD");
while (cursor.moveToNext()){
int id = cursor.getInt(5);
String Name=cursor.getString(1);
String Description=cursor.getString(2);
String Price=cursor.getString(3);
String Size=cursor.getString(4);
byte [] Pics=cursor.getBlob(0);
list.add(new Food(Pics,Name,Description,Price,Size,id));
}
FoodListAdapter adapter = new FoodListAdapter(Mainpage.this,R.layout.food_items,list);
GridView.setAdapter(adapter);

how save value of checkbox after close the app in android?

I want save the state of checkbox after close the app
what I should to do?
I don't know how I do that with list view and arrayadapter
how use sharedpreferences here?
in MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.word_list);
MyAdView.SetAd((AdView)findViewById(R.id.adView));
ListView list = (ListView) findViewById(R.id.list);
ArrayList<Word> worda = new ArrayList<>();
worda.add(new Word("The B",R.drawable.ic_launcher_background));
worda.add(new Word("The B",R.drawable.ic_launcher_background));
WordAdapter adapter = new WordAdapter(this, worda);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
if (position == 0) {
Intent intent = new Intent(MainActivity.this, TheBossBabyS1.class);
startActivity(intent);
}
} });
}
}
in Word.java
public class Word {
private String mConversation;
private int mImageResourceId = NO_IMAGE_PROVIDED;
public static final int NO_IMAGE_PROVIDED = -1;
public Word(String conversation){
mConversation = conversation;
}
public Word(String conversation, int imageResourceId){
mConversation = conversation;
mImageResourceId = imageResourceId;
}
public String getConversation(){
return mConversation;
}
public int getImageResourceId(){ return mImageResourceId; }
public boolean hasImage(){
return mImageResourceId != NO_IMAGE_PROVIDED;
}
}
in WordAdapter.java
public class WordAdapter extends ArrayAdapter {
private int mColorResourceId;
public WordAdapter(Context context, ArrayList<Word> worda){
super(context, 0, worda);
}
#SuppressLint("ResourceAsColor")
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null)
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
Word currentWord = (Word) getItem(position);
TextView convTextView = (TextView) listItemView.findViewById(R.id.conv_text_view);
convTextView.setText(currentWord.getConversation());
ImageView imageView = (ImageView) listItemView.findViewById(R.id.image);
if(currentWord.hasImage()) {
imageView.setImageResource(currentWord.getImageResourceId());
imageView.setVisibility(View.VISIBLE);
}
else {
imageView.setVisibility(View.GONE);
}
CheckBox checkbox = (CheckBox) listItemView.findViewById(R.id.checkBox2);
checkbox.setFocusable(false);
checkbox.setFocusableInTouchMode(false);
View textContainer = listItemView.findViewById(R.id.text_container2);
textContainer.setBackgroundColor(((position % 2) == 0) ? Color.parseColor("#B2DFDB") : Color.parseColor("#80CBC4"));
return listItemView;
}
}
in list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/tan_background"
android:orientation="horizontal"
android:id="#+id/text_container2"
>
<ImageView
android:id="#+id/image"
android:layout_width="22dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:contentDescription="#null"
tools:src="#mipmap/ic_launcher" />
<TextView
android:id="#+id/conv_text_view"
style="#style/CategoryStyle"
android:layout_width="0dp"
android:layout_weight="8"
android:layout_height="wrap_content"
tools:text="lutti" />
<CheckBox
android:id="#+id/checkBox2"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="24dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="16dp"
/>
</LinearLayout>
Use sharedpreferences to store the result.
boolean isChecked=false;
SharedPreferences pref = getSharedPreferences("prefs", MODE_PRIVATE);
Editor editor = pref.edit();
if(checkBox.isChecked()){
isChecked=true;
}
editor.putBoolean("checked", isChecked);
editor.apply()
retrieving the data from sharedPreferences.
write the below code just below setContentView();
if(prefs.getBoolean("checked","")==true){
checkBox.setChecked(true);
}

How to set up onItemClickListener

I set up a Listview in Android Studio but need help with coding a OnItemClickListner.
I have tried the code, but doesn't seem to work.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.list_view);
ArrayList<Object> list = new ArrayList<>();
list.add(new LTCItem("30.06 Sign Violations","Submit A Complaint To Texas Attorney General",R.drawable.gavel));
list.add(new LTCItem("U.S. & Texas LawShield","Legal Defense For Self Defense",R.drawable.lawshield));
listView.setAdapter(new LTCAdapter(this, list));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
});
}
}
Below is my list_view file. Where in the file do block descendantFocusability as suggested? Do I put it under listView? Sorry I am learning .
<?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:alwaysDrawnWithCache="true"
android:background="#000000"
android:padding="8dp">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:id="#+id/itemListViewImgIcon"
android:layout_width="50dp"
android:layout_height="50dp"
android:contentDescription="#+id/itemListViewImgIcon"
android:src="#mipmap/ic_launcher" />
<TextView
android:id="#+id/itemListViewTxtTopicName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
<TextView
android:id="#+id/itemListViewTxtTopicSubtitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/itemListViewTxtTopicName"
</RelativeLayout>
Ok I added the adapter code which is a Java Class item. Where do I add the code here?
public class LTCAdapter extends BaseAdapter {
ArrayList<Object> list;
private static final int LTC_Item = 0;
private static final int HEADER = 1;
private LayoutInflater inflater;
public LTCAdapter(Context context, ArrayList<Object> list) {
this.list = list;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getItemViewType(int position) {
if (list.get(position) instanceof LTCItem) {
return LTC_Item;
} else {
return HEADER;
}
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return 1;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
switch (getItemViewType(i)) {
case LTC_Item:
view = inflater.inflate(R.layout.item_list_view, null);
break;
case HEADER:
view = inflater.inflate(R.layout.item_listview_header, null);
break;
}
}
switch (getItemViewType(i)) {
case LTC_Item:
ImageView image = (ImageView) view.findViewById(R.id.itemListViewImgIcon);
TextView name = (TextView) view.findViewById(R.id.itemListViewTxtTopicName);
TextView subtitle = (TextView) view.findViewById(R.id.itemListViewTxtTopicSubtitle);
image.setImageResource(((LTCItem) list.get(i)).getImage());
name.setText(((LTCItem) list.get(i)).getName());
subtitle.setText(((LTCItem) list.get(i)).getSubtitle());
break;
case HEADER:
TextView title = (TextView) view.findViewById(R.id.itemListViewHeader);
title.setText(((String) list.get(i)));
break;
}
return view;
}
}
Your ListView element doesn't have an ID, you should add android:id="#+id/list_view" to it in the XML file.
Here is an example:
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
As your list view contains focusable elements, you need to write this piece of code in parent layout in your list view item xml file
android:descendantFocusability="blocksDescendants"

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>

Categories

Resources