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
Related
I am attempting to use the Swipecards library (https://github.com/Diolor/Swipecards) to build a tinder-esqe application. I am using a BaseAdapter to populate a layout with two text views and an image view that will be provided to the main SwipeFlingAdapterView. While both of the text fields are populated, I cannot get the image to appear on the cards. I have tried this implementation with both an ArrayAdapter and a BaseAdapter and the results are the same.
The activity layout (deal_page_layout)
<FrameLayout
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_height="match_parent"
android:layout_width="match_parent">
<com.lorentzos.flingswipe.SwipeFlingAdapterView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/swipe_fling_view"
app:rotation_degrees="10"
tools:context=".DealPage"
android:alpha="1.0"
app:max_visible="2"
app:min_adapter_stack="5"/>
</FrameLayout>
The layout being populated by the BaseAdapter (deal_card)
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="#+id/deal_card_image">
</ImageView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/deal_card_title"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_margin="15dp"
android:gravity="center"
android:textSize="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/deal_card_description"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_margin="15dp"
android:gravity="center"
android:textSize="20dp"/>
</RelativeLayout>
BaseAdapter class
public class DealBaseAdapter extends BaseAdapter {
private Context context;
private List<GrubbyDeal> dealList;
private LayoutInflater li;
public DealBaseAdapter(Context context, LayoutInflater li, ArrayList<GrubbyDeal> dealList){
this.context = context;
this.dealList = dealList;
this.li = li;
}
#Override
public int getCount(){
return dealList.size();
}
#Override
public Object getItem(int position){
return dealList.get(position);
}
#Override
public long getItemId(int position){
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder viewHolder;
//resuse a view if possible
if(convertView == null){
convertView = li.inflate(R.layout.deal_card,parent,false);
viewHolder = new ViewHolder();
viewHolder.img = (ImageView) convertView.findViewById(R.id.deal_card_image);
viewHolder.title = (TextView) convertView.findViewById(R.id.deal_card_title);
viewHolder.desc = (TextView) convertView.findViewById(R.id.deal_card_description);
convertView.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) convertView.getTag();
}
GrubbyDeal curDeal = dealList.get(position);
viewHolder.img.setImageURI(curDeal.getImageUri());
viewHolder.title.setText(curDeal.getTitle());
viewHolder.desc.setText(curDeal.getDescription());
return convertView;
}
//view holder class to hold cached findViewByID results
private static class ViewHolder {
public ImageView img;
public TextView title;
public TextView desc;
}
And the main activity (DealPage)
public class DealPage extends Activity {
private ArrayList<GrubbyDeal> dealList;
private DealBaseAdapter dealAdapter;
SwipeFlingAdapterView flingContainer;
#Override
public void onCreate(Bundle sis){
super.onCreate(sis);
setContentView(R.layout.deal_page_layout);
//add some awesome cat deals to the adapter
dealList = new ArrayList<>();
for(int i=0; i < 5; i++){
GrubbyDeal tmp = new GrubbyDeal(i);
dealList.add(tmp);
}
//add another type of cat deal to the list
dealList.add(new GrubbyDeal());
dealAdapter = new DealBaseAdapter(this, getLayoutInflater(), dealList);
flingContainer = (SwipeFlingAdapterView) findViewById(R.id.swipe_fling_view);
flingContainer.setAdapter(dealAdapter);
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
GrubbyDeal popped = dealList.remove(0);
dealList.add(popped);
dealAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
makeToast(DealPage.this, "Left!");
}
#Override
public void onRightCardExit(Object dataObject) {
makeToast(DealPage.this, "Right!");
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
dealList.add(new GrubbyDeal());
dealAdapter.notifyDataSetChanged();
Log.d("LIST", "notified");
}
#Override
public void onScroll(float scrollProgressPercent) {
View view = flingContainer.getSelectedView();
}
});
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
makeToast(DealPage.this, "Clicked!");
}
});
}
}
Am I missing something obvious? Is there some vastly superior library that I should be using? Thanks,
Ian
I would recommend using Picasso to load images into your imageview.
Picasso.with(context).load(imgurl).into(viewHolder.img);
The problem was formatting. I was attempting to use
Uri.parse("android.resource://com.thepackage.theapp/R.drawable.cat4.jpg");
but wasn't getting a valid Uri back. So instead I am using resource ids with picasso and the card works great!
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.
we're currently working on a project and can't get through this weird NullPointerException. We have to cast a specific EditText into a TextView to get our GridView to work. Problem right now is that all tutorials seem to use an Activity, while we're using a Fragment. Our "MainActivity" is just here to initilize some starter things (Splash Screen, Intro Slider etc.). All the other stuff happens in our "HomeFragment". The goal is to capture a picture, write a title and some content, and then save it into a SQLite Database, which can be used to show it in a GridView later on.
We used this guys(github) template to create our own db (and rewrote some stuff because we're using Fragments, of course).
Bear with us while reading the code, it is not finalized yet. Tons of junk code still inside.
FragmentHome.class
public class FragmentHome extends Fragment {
private ImageButton mUnicornButton;
private ImageButton mBaseballbatButton;
private ImageButton mExplosionButton;
private ImageButton mCowButton;
private ImageButton mShitButton;
private ImageButton mPenguinButton;
private final int REQUEST_GALLERY_CODE = 999;
EditText edtTitle, edtContent;
Button btnAdd, btnChoose;
private ImageView mImageView;
protected View mView;
private static final int CAMERA_REQUEST = 1888;
public FragmentHome() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
public static SQLiteHelper sqLiteHelper;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home, container, false);
this.mView = v;
initUI(v);
sqLiteHelper = new SQLiteHelper(getActivity().getApplicationContext(), "ListDB.sqlite",null,1);
sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS DBLIST(Id INTEGER PRIMARY KEY AUTOINCREMENT, title VARCHAR, content VARCHAR, image BLOB)");
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},REQUEST_GALLERY_CODE);
}
});
Button photoButton = v.findViewById(R.id.add_foto);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
sqLiteHelper.insertData(
edtTitle.getText().toString().trim(),
edtContent.getText().toString().trim(),
imageViewToByte(mImageView)
);
Toast.makeText(getActivity().getApplicationContext(),"Added",Toast.LENGTH_SHORT).show();
edtTitle.setText("");
edtContent.setText("");
mImageView.setImageResource(R.mipmap.ic_launcher_round);
} catch(Exception e){
e.printStackTrace();
}
}
});
return v;
}
private byte[] imageViewToByte(ImageView image) {
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,0,stream);
byte[] byteArray = stream.toByteArray();
return byteArray;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults){
if(requestCode == REQUEST_GALLERY_CODE){
if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_GALLERY_CODE);
}
else {
Toast.makeText(getActivity().getApplicationContext(),"No Permissions",Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode,permissions,grantResults);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == CAMERA_REQUEST){
if(resultCode == Activity.RESULT_OK){
Bitmap bmp = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray,0,byteArray.length);
mImageView.setImageBitmap(bitmap);
}
}
}
private void initUI(View v) {
[...] //initializes everything using findViewById()
}
}
DBListAdapter.class (our custom adapter)
public class DBListAdapter extends BaseAdapter{
private Context context;
private int layout;
private ArrayList<DBList> dblistsList;
public DBListAdapter(Context context, int layout, ArrayList<DBList> dblistsList) {
this.context = context;
this.layout = layout;
this.dblistsList = dblistsList;
}
#Override
public int getCount() {
return dblistsList.size();
}
#Override
public Object getItem(int position) {
return dblistsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder{
ImageView imageView;
TextView txtTitle, txtContent;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
View row = view;
ViewHolder holder = new ViewHolder();
if(row==null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(layout, null);
holder.txtTitle = row.findViewById(R.id.input_title);
holder.txtContent = row.findViewById(R.id.input_content);
holder.imageView = row.findViewById(R.id.fotoView);
row.setTag(holder);
}
else{
holder = (ViewHolder) row.getTag();
}
DBList dbList = dblistsList.get(position);
holder.txtTitle.setText(dbList.getTitle());
holder.txtContent.setText(dbList.getContent());
byte[] dblistImage = dbList.getImage();
Bitmap bitmap = BitmapFactory.decodeByteArray(dblistImage, 0, dblistImage.length);
holder.imageView.setImageBitmap(bitmap);
return row;
}
}
The problem is in this Adapter.
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at s***.d***.u***.th***ive.DBListAdapter.getView(DBListAdapter.java:78)
We can't figure out how to cast the EditText from the fragment_home.xml into a TextView, which is needed for the ViewHolder.
fragment_home.xml
[...]
<ImageView
android:id="#+id/fotoView"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="#color/Gainsboro"
app:srcCompat="#android:drawable/ic_menu_camera" />
<EditText
android:id="#+id/input_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Title"
android:inputType="text"
android:maxLines="1"
android:textAlignment="center"
android:layout_above="#+id/input_content"
android:layout_alignParentStart="true" />
<EditText
android:id="#+id/input_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/hint_what"
android:inputType="textMultiLine"
android:textAlignment="center"
android:layout_above="#+id/linearLayout"
android:layout_alignParentStart="true"
android:layout_marginBottom="33dp" /> [...]
Any help would be appreciated, my mind is burning right now, I certaintly have no clue how to solve this. If you need more, just ask me. Kinda tired right now, so probably gonna replay late.
okey .. Firstly you need to create new xml file and name it as you want ... let assume that it's name is list_reycle_view then transfer those views to it
<ImageView
android:id="#+id/fotoView"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="#color/Gainsboro"
app:srcCompat="#android:drawable/ic_menu_camera" />
<EditText
android:id="#+id/input_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Title"
android:inputType="text"
android:maxLines="1"
android:textAlignment="center"
android:layout_above="#+id/input_content"
android:layout_alignParentStart="true" />
<EditText
android:id="#+id/input_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/hint_what"
android:inputType="textMultiLine"
android:textAlignment="center"
android:layout_above="#+id/linearLayout"
android:layout_alignParentStart="true"
android:layout_marginBottom="33dp" />
then .. replace these lines
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(layout, null);
with this line
row= LayoutInflater.from(context).inflate(R.layout.list_recycle_view,viewGroup,false);
and run your program
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(layout, null);
holder = new ViewHolder();
holder.txtTitle = row.findViewById(R.id.input_title);
holder.txtContent = row.findViewById(R.id.input_content);
holder.imageView = row.findViewById(R.id.fotoView);
row.setTag(holder);
}
I have a RecyclerView which has CardView as its list items. The CardView have only 2 TextView and one ImageView.
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_marginTop="2dp"
android:layout_marginBottom="2dp"
android:id="#+id/dcCardView">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#drawable/detail_coast_cardview_bg">
<ImageView
android:id="#+id/dcImage"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginStart="8dp"
android:src="#drawable/radiation"
android:layout_gravity="center_vertical" />
<LinearLayout
android:layout_gravity="center_vertical"
android:layout_marginStart="16dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/dcName"
android:textColor="#fff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="212"
android:textSize="18dp" />
<TextView
android:textColor="#fff"
android:id="#+id/dcValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="renu asdasasd"
android:textSize="18dp" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
The class that goes in it is this
public class DetailedCoastRecyclerView {
//region fields
private String name;
private String value;
private int imageName;
//end region fields
//constructor
public DetailedCoastRecyclerView() {}
public DetailedCoastRecyclerView(String name, String value, int image) {
this.name = name;
this.value = value;
this.imageName = image;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
public int getImageName() {
return imageName;
}
}
And my CoastDetailsActivity2
public class CoastDetailsActivity2 extends AppCompatActivity {
private Context context;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
private int coastId;
private String jsonCoastDetailsString = "";
private RecyclerView recyclerView;
private DetailedCoastAdapter detailedCoastAdapter;
private ImageView btnBlueFlag;
private ImageView btnHandycapFriendly;
private ImageView btnFavorite;
private ImageView btnWaze;
private LinearLayout mainLayout;
private Beach mBeach;
private TextView tvBeachName;
private DetailedCoastWithForcast detailedCoastWithForcast;
private DetailedBeachMetadata detailedBeachMetadata;
private DetailedBeachHourlyForecast dbhfToday;
private List<DetailedCoastRecyclerView> detailedCoastRecyclerViewList = new ArrayList<>();
private Map<String, String> windBearing = new HashMap<>();
private Map<String, String> jellyType = new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_coast_details2);
setPointer();
}
private void setPointer() {
this.context = this;
mainLayout = (LinearLayout) findViewById(R.id.mainLayout);
sharedPreferences = context.getSharedPreferences(sharedPreferencesName, MODE_PRIVATE);
editor = sharedPreferences.edit();
tvBeachName = (TextView) findViewById(R.id.tvBeachName);
//start the forecast activity
tvBeachName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ForecastActivity.class);
intent.putExtra("coastId", coastId);
startActivity(intent);
}
});
AndroidNetworking.initialize(context);
//get the coastId
Bundle extras = getIntent().getExtras();
if (extras == null) {
//TODO add snackbar for error
} else {
coastId = extras.getInt("coastId");
}
getBeachDetails();
recyclerView = (RecyclerView) findViewById(R.id.dcRecyclerView);
detailedCoastAdapter = new DetailedCoastAdapter(detailedCoastRecyclerViewList, context);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(detailedCoastAdapter);
}
}
And the adapter
public class ForecastAdapter extends RecyclerView.Adapter<ForecastAdapter.myViewHolder> {
Context context;
private List<DetailedCoastRecyclerView> dbhf0;
public ForecastAdapter(Context context, List<DetailedCoastRecyclerView> dbhf0) {
this.context = context;
this.dbhf0 = dbhf0;
}
#Override
public myViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.detailed_coast_card, parent, false);
return new myViewHolder(view);
}
#Override
public void onBindViewHolder(myViewHolder holder, int position) {
DetailedCoastRecyclerView dcrv = dbhf0.get(position);
holder.tvName.setText(dcrv.getName());
holder.tvValue.setText(dcrv.getValue());
//holder.ivImage.setImageResource(dcrv.getImageName());
Glide.with(context).load(dcrv.getImageName()).into(holder.ivImage);
}
#Override
public int getItemCount() {
return dbhf0.size();
}
public class myViewHolder extends RecyclerView.ViewHolder {
ImageView ivImage;
TextView tvName;
TextView tvValue;
public myViewHolder(View itemView) {
super(itemView);
ivImage = (ImageView) itemView.findViewById(R.id.dcImage);
tvName = (TextView) itemView.findViewById(R.id.dcName);
tvValue = (TextView) itemView.findViewById(R.id.dcValue);
}
}
}
When I run it, the getBeachDetails() method gets all the info from the server, add it to an ArrayList and calls notifyDataSetChanged() on the adapter.
I know its working because I see the name and value for every card but the images which are stored locally are not displayed.
I use the same adapter inside a ViewPager with 3 fragments and there everything is ok.
Any ideas?
You provided code of ForecastAdapter, but actually you are using DetailedCoastAdapter. Make sure whether they are the same.
Check whether you have a valid url/resource in dcrv.getImageName()
I guess your image resolution is too high that android buffer cant handle and throws exception while rendering your image, so as I know you have to decrease your image quality when loading it on ImageView.
In Picasso this is done like this by calling resize(width,height) method.
Picasso.with(context)
.load(res)
.resize(width,height)
.placeholder(placeHolder)
.into(view);
I guess it is done in the same way with Glide.
I am building a sudoku in android ,so how do i register all the textviews
for e.g :
button1=(Button)findViewByid(R.id.btn1)
Do i need to write 81 such statements to register every TextView
you can add the views in java code when app running.
you can write your textview's xml statement in an xml file alone, and then inflate it.
In this way, you don't need the view id, because you already have its reference.
grid.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
...
/>
MyActivity.java
ArrayList<TextView> list = new ArrayList<>();
for (int i = 0; i < 81; i++) {
TextView view = (TextView)LayoutInflater.from(ItemDragAndSwipeUseActivity.this).inflate(R.layout.grid, null);
list.add(view);
}
// then attach these views to the layout with addView()
you can use grid view with an adapter instead of text views
grid item
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="13sp"
android:text="#string/country_name"
android:textColor="#color/accent_color"
android:gravity="center"
android:paddingBottom="8dp"
android:paddingTop="8dp"
android:background="#color/color_primary_dark"/>
</RelativeLayout>
Adapter class
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolders> {
private List<ItemObject> itemList;
private Context context;
public RecyclerViewAdapter(Context context, List<ItemObject> itemList) {
this.itemList = itemList;
this.context = context;
}
#Override
public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, null);
RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView);
return rcv;
}
#Override
public void onBindViewHolder(RecyclerViewHolders holder, int position) {
holder.textView.setText(itemList.get(position).getName());
}
#Override
public int getItemCount() {
return this.itemList.size();
}
public class RecyclerViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView textView;
public RecyclerViewHolders(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
textView = (TextView)itemView.findViewById(R.id.textView);
}
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Clicked Position = " + getPosition(), Toast.LENGTH_SHORT).show();
}
}
}
Activity class
public class MainActivity extends ActionBarActivity {
private GridLayoutManager lLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle(null);
Toolbar topToolBar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(topToolBar);
topToolBar.setLogo(R.drawable.logo);
topToolBar.setLogoDescription(getResources().getString(R.string.logo_desc));
List<ItemObject> rowListItem = getAllItemList();
lLayout = new GridLayoutManager(MainActivity.this, 4);
RecyclerView rView = (RecyclerView)findViewById(R.id.recycler_view);
rView.setHasFixedSize(true);
rView.setLayoutManager(lLayout);
RecyclerViewAdapter rcAdapter = new RecyclerViewAdapter(MainActivity.this, rowListItem);
rView.setAdapter(rcAdapter);
}
private List<ItemObject> getAllItemList(){
List<ItemObject> allItems = new ArrayList<ItemObject>();
allItems.add(new ItemObject("1");
allItems.add(new ItemObject("2");
allItems.add(new ItemObject("3");
return allItems;
}
}
You don't have to use IDs for this. You can just create a View (Container) in XML and fill it using a for loop completely without using IDs. You can access them afterwards via their index in the Container.
I hope this helped.