Android custom compound component's contents won't appear - java

I'm trying to create a custom view, a calendar. The views inside this component are inflated from a xml layout. I have studied several tutorials and three or four similar (or even identical) questions on stack overflow but nothing seems to work. I'd appreciate it if you could point out the problem. Thanks in advance and here are the codes.
kcalendar_view.xml // the layout for the custom view
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center" >
<Button
android:id="#+id/btnKCalendarNavLeft"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="5dp"
android:background="#drawable/kcalendar_nav_button_bg"
android:text="<" />
<TextView
android:id="#+id/txvKCalendarNavTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/btnKCalendarNavRight"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="5dp"
android:background="#drawable/kcalendar_nav_button_bg"
android:text=">" />
</LinearLayout>
<GridView
android:id="#+id/gridViewKCalendar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="7" >
</GridView>
</merge>
KCalendarView.java // the custom view's class
package ir.kcoder.KCalendarView;
import ir.kcoder.persiancalendarweather.R;
import java.util.Calendar;
import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import com.samanpr.jalalicalendar.JalaliCalendar;
import com.samanpr.jalalicalendar.JalaliCalendar.YearMonthDate;
public class KCalendarView extends LinearLayout {
private YearMonthDate currentJalaliDate;
private int parentWidth, parentHeight;
private Button leftButton, rightButton;
private GridView gridView;
private KCalendarAdapter calendarAdapter;
private Context context;
private View inflated;
public KCalendarView(Context context) {
super(context);
}
public KCalendarView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
setOrientation(LinearLayout.VERTICAL);
setGravity(Gravity.CENTER);
setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflated = inflater.inflate(R.layout.kcalendar_view, this, true);
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
init(getContext());
}
private void init(Context context) {
Calendar c = Calendar.getInstance();
YearMonthDate currentGregDate = new YearMonthDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE));
currentJalaliDate = JalaliCalendar.gregorianToJalali(currentGregDate);
leftButton = (Button)findViewById(R.id.btnKCalendarNavLeft);
rightButton = (Button)findViewById(R.id.btnKCalendarNavRight);
gridView = (GridView)findViewById(R.id.gridViewKCalendar);
if(gridView != null) {
calendarAdapter = new KCalendarAdapter(context, currentJalaliDate.getYear(),
currentJalaliDate.getMonth());
gridView.setAdapter(calendarAdapter);
}
}
public void nextMonth() {
}
public void prevMonth() {
}
// #Override
// protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// parentWidth = MeasureSpec.getSize(widthMeasureSpec);
// parentHeight = MeasureSpec.getSize(heightMeasureSpec);
// this.setMeasuredDimension(parentWidth, parentHeight);
// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// }
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// TODO Auto-generated method stub
}
}
activity_main.xml // I use this tag to include the custom view in my app
<ir.kcoder.KCalendarView.KCalendarView
android:id="#+id/kCalendarView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
</ir.kcoder.KCalendarView.KCalendarView>

Updated
Try this I think it should work
public class KCalendarView extends LinearLayout {
private YearMonthDate currentJalaliDate;
private int parentWidth, parentHeight;
private Button leftButton, rightButton;
private GridView gridView;
private KCalendarAdapter calendarAdapter;
public KCalendarView(Context context, AttributeSet attrs) {
super(context, attrs);
doInflate();
}
private void doInflate() {
setOrientation(LinearLayout.VERTICAL);
setGravity(Gravity.CENTER);
setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
inflate(getContext(), R.layout.kcalendar_view, this);
leftButton = (Button)findViewById(R.id.btnKCalendarNavLeft);
rightButton = (Button)findViewById(R.id.btnKCalendarNavRight);
gridView = (GridView)findViewById(R.id.gridViewKCalendar);
init();
}
private void init() {
Calendar c = Calendar.getInstance();
YearMonthDate currentGregDate = new YearMonthDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE));
currentJalaliDate = JalaliCalendar.gregorianToJalali(currentGregDate);
calendarAdapter = new KCalendarAdapter(context, currentJalaliDate.getYear(), currentJalaliDate.getMonth());
gridView.setAdapter(calendarAdapter);
}
public void nextMonth() {
}
public void prevMonth() {
}
}

Related

An unordered RecycleView list after scrolling

If I scroll this list RecycleView with the mouse wheel my items in the list look like unordered.
I do not understand , why?
An incorrect clicked item in the new activity from RecycleView
I have tried to create the separate class CrimeAdapter extends RecyclerView.Adapter<CrimeAdapter.CrimeHolder> and
class CrimeHolder extends RecyclerView.ViewHolder implements View.OnClickListener in the separate file, but I couldn't do it right.
Unfornuntely, I do not have enough experience for this.
I do not know how to write the correct code in the method public void onClick(View v)
Crime.java
package com.bignerdranch.android.criminalintent;
import java.util.Date;
import java.util.UUID;
public class Crime{
private UUID mId;
private String mTitle;
private Date mDate;
private boolean mSolved;
private boolean mRequiresPolice;
public Crime() {
// Generate unique identifier
this(UUID.randomUUID());
}
public Crime(UUID id) {
mId = id;
mDate = new Date();
}
public UUID getId() {
return mId;
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
mTitle = title;
}
public Date getDate() {
return mDate;
}
public void setDate(Date date) {
mDate = date;
}
public boolean isSolved() {
return mSolved;
}
public void setSolved(boolean solved) {
mSolved = solved;
}
public boolean isRequiresPolice() {
return mRequiresPolice;
}
public void setRequiresPolice(boolean requiresPolice) {
mRequiresPolice = requiresPolice;
}
}
CrimeLab.java
package com.bignerdranch.android.criminalintent;
import android.content.Context;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
public class CrimeLab {
private static CrimeLab sCrimeLab;
private List<Crime> mCrimes;
public static CrimeLab get(Context context) {
if (sCrimeLab == null) {
sCrimeLab = new CrimeLab(context);
}
return sCrimeLab;
}
private CrimeLab(Context context){
mCrimes = new ArrayList<>();
for (int i = 0; i < 100; i++) {
Crime crime = new Crime();
crime.setTitle("Crime #" + i);
crime.setSolved(i % 2 == 0);
if (i % 4 == 0 ) {crime.setRequiresPolice(true);}
else {crime.setRequiresPolice(false);}
mCrimes.add(crime);
}
}
public List<Crime> getCrimes() {
return mCrimes;
}
public Crime getCrime(UUID id){
for (Crime crime : mCrimes){
int rez = id.compareTo(crime.getId());
if (crime.getId().equals(id)){
return crime;
}
}
return null;
}
}
CrimeListFragment.java
package com.bignerdranch.android.criminalintent;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.LayoutRes;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.Date;
import java.util.List;
public class CrimeListFragment extends Fragment {
private static final int REQUEST_CRIME = 1;
private static final int NOT_REQUIRES_POLICE = 0;
private static final int REQUIRES_POLICE = 1;
private RecyclerView mCrimeRecyclerView;
private CrimeAdapter mAdapter;
private TextView mTitleTextView;
private TextView mDateTextView;
private ImageView mSolvedImageView;
private Button mButtonCallPolice;
private Crime mCrime;
private CharSequence mDateFormat;
private int layout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_crime_list, container,
false);
mCrimeRecyclerView = (RecyclerView) view
.findViewById(R.id.crime_recycler_view);
mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
updateUI();
return view;
}
private class CrimeHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public CrimeHolder(int layout, LayoutInflater inflater, ViewGroup parent ) {
super(inflater.inflate(layout, parent, false));
mTitleTextView = (TextView) itemView.findViewById(R.id.crime_title);
mDateTextView = (TextView) itemView.findViewById(R.id.crime_date);
mSolvedImageView = (ImageView) itemView.findViewById(R.id.crime_solved);
if (itemView.findViewById(R.id.call_police)!=null) {
mButtonCallPolice = (Button) itemView.findViewById(R.id.call_police);
}
itemView.setOnClickListener(this);
}
public void bind(Crime crime) {
mCrime = crime;
mTitleTextView.setText(mCrime.getTitle());
mDateFormat = DateFormat.format("EEE, MMM dd, yyyy", mCrime.getDate());
mDateTextView.setText(mDateFormat);
mSolvedImageView.setVisibility(mCrime.isSolved() ? View.VISIBLE :
View.GONE);
if(mCrime.isRequiresPolice()){
mButtonCallPolice.setEnabled(true);
}
}
#Override
public void onClick(View view) {
Intent intent = CrimePagerActivity.newIntent(getActivity(),
CrimeLab.get(requireActivity()).getCrimes().get((getAdapterPosition())).getId());
startActivityForResult(intent, REQUEST_CRIME);
}
}
private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder> {
private List<Crime> mCrimes;
public CrimeAdapter(List<Crime> crimes) {
mCrimes = crimes;
}
#Override
public CrimeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
if (viewType==1) { layout = R.layout.list_item_crime_police;}
else { layout = R.layout.list_item_crime; }
return new CrimeHolder (layout, layoutInflater, parent);
}
#Override
public void onBindViewHolder(CrimeHolder holder, int position) {
Crime crime = mCrimes.get(position);
holder.bind(crime);
}
#Override
public int getItemCount() {
return mCrimes.size();
}
public int getItemViewType(int position) {
Crime crime = mCrimes.get(position);
return (crime.isRequiresPolice()) ? 1 : 0;
}
}
#Override
public void onResume() {
super.onResume();
updateUI();
}
private void updateUI() {
CrimeLab crimeLab = CrimeLab.get(getActivity());
List<Crime> crimes = crimeLab.getCrimes();
if (mAdapter == null) {
mAdapter = new CrimeAdapter(crimes);
mCrimeRecyclerView.setAdapter(mAdapter);
} else {
mAdapter.notifyDataSetChanged();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CRIME) {
// Обработка результата
}
}
public void returnResult() {
getActivity().setResult(Activity.RESULT_OK, null);
}
}
CrimePagerActivity.java
package com.bignerdranch.android.criminalintent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;
import java.util.List;
import java.util.UUID;
public class CrimePagerActivity extends AppCompatActivity {
private static final String EXTRA_CRIME_ID = "com.bignerdranch.android.criminalintent.crime_id";
private ViewPager mViewPager;
private List<Crime> mCrimes;
MyAdapter mAdapter;
public static Intent newIntent(Context packageContext, UUID crimeId) {
Intent intent = new Intent(packageContext, CrimePagerActivity.class);
intent.putExtra(EXTRA_CRIME_ID, crimeId);
return intent;
}
#Override
protected void onCreate( Bundle savedInstanceState ) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime_pager);
UUID crimeId = (UUID) getIntent().getSerializableExtra(EXTRA_CRIME_ID);
mViewPager = (ViewPager) findViewById(R.id.crime_view_pager);
mCrimes = CrimeLab.get(this).getCrimes();
mAdapter = new MyAdapter(getSupportFragmentManager(),mCrimes);
mViewPager.setAdapter(mAdapter);
for (int i = 0; i < mCrimes.size(); i++) {
if (mCrimes.get(i).getId().equals(crimeId)) {
mViewPager.setCurrentItem(i);
break;
}
}
}
public static class MyAdapter extends FragmentStatePagerAdapter {
private List<Crime> mCrimesCopy;
public MyAdapter(FragmentManager fm, List<Crime> mCrimesParametr) {
//super(fm);
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
this.mCrimesCopy = mCrimesParametr;
}
#Override
public int getCount() {
return mCrimesCopy.size();
}
#Override
public Fragment getItem(int position) {
Crime crime = mCrimesCopy.get(position);
return CrimeFragment.newInstance(crime.getId());
}
}
}
fragment_crime_list.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/crime_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
fragment_crime.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:layout_margin="16dp"
android:orientation="vertical">
<TextView
style="?android:listSeparatorTextViewStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_title_label"/>
<EditText
android:id="#+id/crime_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/crime_title_hint"
android:inputType=""
android:autofillHints="" />
<TextView
style="?android:listSeparatorTextViewStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_details_label"/>
<Button
android:id="#+id/crime_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<CheckBox
android:id="#+id/crime_solved"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_solved_label"/>
</LinearLayout>
list_item_crime_police.xml
<?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/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/crime_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:text="#string/crime_title"
android:textColor="#android:color/black"
android:textSize="18sp"
app:layout_constraintEnd_toStartOf="#+id/crime_solved"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/crime_date"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:text="#string/crime_date"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/crime_solved" />
<Button
android:id="#+id/call_police"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:text="#string/call_police"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/crime_date" />
<ImageView
android:id="#+id/crime_solved"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="16dp"
android:contentDescription="#string/todo"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_solved" />
</androidx.constraintlayout.widget.ConstraintLayout>
list_item_crime.xml
<?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/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/crime_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:text="#string/crime_title"
android:textColor="#android:color/black"
android:textSize="18sp"
app:layout_constraintEnd_toStartOf="#+id/crime_solved"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/crime_date"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:text="#string/crime_date"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/crime_solved" />
<ImageView
android:id="#+id/crime_solved"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_solved"
android:contentDescription="#string/todo" />
</androidx.constraintlayout.widget.ConstraintLayout>
activity_crime_pager.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.viewpager.widget.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/crime_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.viewpager.widget.ViewPager>
activity_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
I think the items in the RecyclerView are unordered because the references for views which are present in your list_item_crime_police.xml or list_item_crime.xml layout file is declared as class members of CrimeListFragment and not inside CrimeHolder class as :
public class CrimeListFragment extends Fragment {
// your other views and variables related declarations
// these are problematic declaration that keeps on being reused
private TextView mTitleTextView;
private TextView mDateTextView;
private ImageView mSolvedImageView;
private Button mButtonCallPolice;
// your other declarations
// your other code
}
That's why, the same view instances such as mTitleTextView, mDateTextView, mSolvedImageView, mButtonCallPolice, etc. are being reused for every CrimeHolder instances causing the unordering of the items in the list. Now, in order to fix this problem, you can simply move these lines to code to CrimeHolder class as class variable which would ensures that every new CrimeHolder instance will have separate instances of above-mentioned views as :
private class CrimeHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
// declare all of them here so there will be unique instances of these views for unique viewholder
private TextView mTitleTextView;
private TextView mDateTextView;
private ImageView mSolvedImageView;
private Button mButtonCallPolice;
public CrimeHolder(int layout, LayoutInflater inflater, ViewGroup parent ) {
View itemView = inflater.inflate(layout, parent, false));
super(itemView);
mTitleTextView = (TextView) itemView.findViewById(R.id.crime_title);
mDateTextView = (TextView) itemView.findViewById(R.id.crime_date);
mSolvedImageView = (ImageView) itemView.findViewById(R.id.crime_solved);
if (itemView.findViewById(R.id.call_police)!=null) {
mButtonCallPolice = (Button) itemView.findViewById(R.id.call_police);
}
itemView.setOnClickListener(this);
}
public void bind(Crime crime) {
mCrime = crime;
mTitleTextView.setText(mCrime.getTitle());
mDateFormat = DateFormat.format("EEE, MMM dd, yyyy", mCrime.getDate());
mDateTextView.setText(mDateFormat);
mSolvedImageView.setVisibility(mCrime.isSolved() ? View.VISIBLE :
View.GONE);
if(mCrime.isRequiresPolice()){
mButtonCallPolice.setEnabled(true);
}
}
#Override
public void onClick(View view) {
Intent intent = CrimePagerActivity.newIntent(getActivity(),
CrimeLab.get(requireActivity()).getCrimes().get((getAdapterPosition())).getId());
startActivityForResult(intent, REQUEST_CRIME);
}
}
It fixed my problem and I hope it will fix yours too.

show data from sqlite to recyclerview using recyclerview adapter

i am making an application where data is being saved in the database.i am lacking in displaying the data in the recyclerview using recyclerview adapter.don't know what code should be written. please check.
here is my files: MainActivity.java
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView applist;
ArrayList<Guides> guides;
GuideAdapter adapter;
GuideDB guideDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
guideDB = new GuideDB(this);
guides = new ArrayList<>();
applist = (RecyclerView) findViewById(R.id.app_list);
applist.setHasFixedSize(true);
applist.setLayoutManager(new LinearLayoutManager(this));
adapter = new GuideAdapter(this,guides);
applist.setAdapter(adapter);
try {
Cursor cursor = guideDB.getGuides("SELECT * FROM GUIDE_LIST");
while (cursor.moveToNext()){
int guide_id = cursor.getInt(0);
String post_tile = cursor.getString(1);
String post_desc = cursor.getString(2);
String post_address = cursor.getString(3);
byte [] post_image = cursor.getBlob(4);
Guides g = new Guides(guide_id,post_tile,post_desc,post_address,post_image);
guides.add(g);}
}catch (Exception e){e.printStackTrace();}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.action_add){
startActivity(new Intent(MainActivity.this,PostActivity.class));
}
return super.onOptionsItemSelected(item);
}
}
PostActivity.java
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class PostActivity extends AppCompatActivity {
public ImageButton mSelectImage;
public EditText mPostTitle;
public EditText mPostDesc;
public EditText mPostAddress;
public Button mSubmitbtn;
private static final int GALLERY_REQUEST= 1;
GuideDB guideDB;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
guideDB = new GuideDB(this);
mSelectImage = (ImageButton) findViewById(R.id.imageSelect);
mPostTitle = (EditText) findViewById(R.id.titleField);
mPostDesc = (EditText) findViewById(R.id.descField);
mPostAddress = (EditText) findViewById(R.id.addressField);
mSubmitbtn = (Button) findViewById(R.id.submitButton);
mSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,GALLERY_REQUEST);
}
});
mSubmitbtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
if(!mPostTitle.getText().toString().isEmpty() && !mPostDesc.getText().toString().isEmpty() && !mPostAddress.getText().toString().isEmpty())
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,50,outputStream);
byte[] byteArray = outputStream.toByteArray();
try {
guideDB.addGuide(mPostTitle.getText().toString(),
mPostDesc.getText().toString(),
mPostAddress.getText().toString(),byteArray
);
Toast.makeText(getApplicationContext(),"Added successfully!",Toast.LENGTH_LONG).show();
}catch (Exception e){e.printStackTrace();}
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_REQUEST && resultCode == RESULT_OK) {
Uri mimageUri = data.getData();
try {
InputStream inputstream = getContentResolver().openInputStream(mimageUri);
bitmap = BitmapFactory.decodeStream(inputstream);
mSelectImage.setImageBitmap(bitmap);
}catch (FileNotFoundException e){e.printStackTrace();}
}
}
}
GuideDB.java
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
/**
* Created by 291 on 14.12.2017.
*/
public class GuideDB extends SQLiteOpenHelper {
private static final int DATABASE_VERSION= 1;
private static final String DATABASE_NAME= "guide_db";
private static final String TABLE_NAME = "GUIDE_LIST";
private static String GUIDE_ID = "guide_id";
private static String GUIDE_TITLE = "guide_title";
private static String GUIDE_DESC = "guide_desc";
private static String GUIDE_ADDRESS = "guide_address";
private static String GUIDE_IMG = "guides_image";
public GuideDB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE" + TABLE_NAME + "("
+ GUIDE_ID + "INTEGER PRIMARY KEY AUTOINCREMENT"
+ GUIDE_TITLE + "TEXT"
+ GUIDE_DESC + "TEXT"
+ GUIDE_ADDRESS + "TEXT"
+ GUIDE_IMG + "BLOB" + ")";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
onCreate(db);
}
public void addGuide (String title,String desc,String address,byte[] image){
SQLiteDatabase gdb = getWritableDatabase();
try
{
String sql = "INSERT INTO GUIDE_LIST VALUES(NULL,?,?,?)";
SQLiteStatement statement = gdb.compileStatement(sql);
statement.clearBindings();
statement.bindString(1,title);
statement.bindString(2,desc);
statement.bindString(3,address);
statement.bindBlob(4,image);
statement.execute();
}catch (Exception e){e.printStackTrace();}
}
public Cursor getGuides(String sql){
SQLiteDatabase gdb = getReadableDatabase();
return gdb.rawQuery(sql,null);
}
}
GuideAdapter.java
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by 291 on 14.12.2017.
*/
public class GuideAdapter extends RecyclerView.Adapter<GuideAdapter.ViewHolder> {
private Context ctx;
private ArrayList<Guides> guidelist;
public GuideAdapter(Context ctx, ArrayList<Guides> guidelist) {
this.ctx = ctx;
this.guidelist = guidelist;
}
#Override
public GuideAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.guide_row,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(GuideAdapter.ViewHolder holder, int position) {
Guides guides = guidelist.get(position);
holder.psttitle.setText(guides.getPost_title());
holder.pstdesc.setText(guides.getPost_desc());
holder.pstaddres.setText(guides.getPost_address());
byte [] postimg = guides.getPost_image();
Bitmap bitmap = BitmapFactory.decodeByteArray(postimg,0,postimg.length);
holder.pstimg.setImageBitmap(bitmap);
}
#Override
public int getItemCount() {
return guidelist.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public ImageView pstimg;
public TextView psttitle;
public TextView pstdesc;
public TextView pstaddres;
public int id;
public ViewHolder(View itemView) {
super(itemView);
pstimg = (ImageView) itemView.findViewById(R.id.post_image);
psttitle = (TextView) itemView.findViewById(R.id.post_title);
pstdesc = (TextView) itemView.findViewById(R.id.post_title);
pstaddres = (TextView) itemView.findViewById(R.id.post_address);
}
}
}
Guides.java
public class Guides {
private int guide_id;
private String post_title,post_desc,post_address;
private byte [] post_image;
public Guides(int guide_id, String post_title, String post_desc, String post_address, byte [] post_image) {
this.guide_id = guide_id;
this.post_title = post_title;
this.post_desc = post_desc;
this.post_address = post_address;
this.post_image = post_image;
}
public int getGuide_id() {
return guide_id;
}
public void setGuide_id(int guide_id) {
this.guide_id = guide_id;
}
public String getPost_title() {
return post_title;
}
public void setPost_title(String post_title) {
this.post_title = post_title;
}
public String getPost_desc() {
return post_desc;
}
public void setPost_desc(String post_desc) {
this.post_desc = post_desc;
}
public String getPost_address() {
return post_address;
}
public void setPost_address(String post_address) {
this.post_address = post_address;
}
public byte[] getPost_image() {
return post_image;
}
public void setPost_image(byte[] post_image) {
this.post_image = post_image;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ugurcangursen.guideappsqlite.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/app_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:padding="10dp"></android.support.v7.widget.RecyclerView>
</RelativeLayout>
activity_post.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ugurcangursen.guideappsqlite.PostActivity">
<ImageButton
android:id="#+id/imageSelect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:adjustViewBounds="true"
android:background="#00ffffff"
android:scaleType="centerCrop"
app:srcCompat="#drawable/add_btn" />
<EditText
android:id="#+id/titleField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/imageSelect"
android:layout_centerHorizontal="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:background="#drawable/input_outline"
android:hint="Post Title..."
android:inputType="textPersonName"
android:padding="10dp"
android:singleLine="true" />
<EditText
android:id="#+id/descField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/titleField"
android:layout_centerHorizontal="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:background="#drawable/input_outline"
android:hint="Post Description..."
android:inputType="textMultiLine"
android:padding="10dp" />
<EditText
android:id="#+id/addressField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/descField"
android:layout_centerHorizontal="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:background="#drawable/input_outline"
android:hint="Adres..."
android:inputType="textMultiLine"
android:padding="10dp" />
<Button
android:id="#+id/submitButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#color/colorPrimary"
android:text="SUBMIT POST"
android:textColor="#android:color/white" />
</RelativeLayout>
guide_row.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/post_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
app:srcCompat="#drawable/add_btn" />
<TextView
android:id="#+id/post_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:textSize="16dp"
android:textStyle="bold"
tools:text="Başlık" />
<TextView
android:id="#+id/post_desc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
tools:text="Açıklama" />
<TextView
android:id="#+id/post_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
tools:text="Adres" />
</LinearLayout>
</android.support.v7.widget.CardView>
I'm not reviewing all the code you have posted. However, it does appear that you are setting the adpater with an empty source (guides), so it would then display nothing.
The following version of the onCreate method may result in the data being displayed
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
guideDB = new GuideDB(this);
guides = new ArrayList<>();
applist = (RecyclerView) findViewById(R.id.app_list);
applist.setHasFixedSize(true);
applist.setLayoutManager(new LinearLayoutManager(this));
//adapter = new GuideAdapter(this,guides); //<<<< MOVED
//applist.setAdapter(adapter); //<<<< MOVED
try {
Cursor cursor = guideDB.getGuides("SELECT * FROM GUIDE_LIST");
while (cursor.moveToNext()){
int guide_id = cursor.getInt(0);
String post_tile = cursor.getString(1);
String post_desc = cursor.getString(2);
String post_address = cursor.getString(3);
byte [] post_image = cursor.getBlob(4);
Guides g = new Guides(guide_id,post_tile,post_desc,post_address,post_image);
guides.add(g);}
}catch (Exception e){e.printStackTrace();}
adapter = new GuideAdapter(this,guides); //<<<< MOVED
applist.setAdapter(adapter); //<<<< MOVED
}

Move views up when SnackBar appears in CoordinatorLayout

I have a TextView at the bottom of the CoordinatorLayout.
But when I show a SnackBar , it will cover the TextView.
I know I have to customize a Behavior for the TextView and override layoutDependsOn and onDependentViewChanged,but it doesn't fix very well.
Could you give me some advice if you know? Thanks.
If the TextView is a direct child of a CoordinatorLayout, just add
app:layout_dodgeInsetEdges="bottom"
in the TextView attributes.
Magic!
You need to add a behavior to your LinearLayout and embed it in a CoordinatorLayout.
Here is how you do that.
MoveUpwardBehavior.class
import android.os.Build;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.view.View;
public class MoveUpwardBehavior extends CoordinatorLayout.Behavior<View> {
private static final boolean SNACKBAR_BEHAVIOR_ENABLED;
#Override
public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) {
return SNACKBAR_BEHAVIOR_ENABLED && dependency instanceof Snackbar.SnackbarLayout;
}
#Override
public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {
float translationY = Math.min(0, dependency.getTranslationY() - dependency.getHeight());
child.setTranslationY(translationY);
return true;
}
static {
SNACKBAR_BEHAVIOR_ENABLED = Build.VERSION.SDK_INT >= 11;
}
}
CustomLinearLayout.class
import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.util.AttributeSet;
import android.widget.LinearLayout;
#CoordinatorLayout.DefaultBehavior(MoveUpwardBehavior.class)
public class CustomLinearLayout extends LinearLayout {
public CustomLinearLayout(Context context) {
super(context);
}
public CustomLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
Sample xml->activity_home
Here user.example.charu.its2017huree is my package name replace it with yours!
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:fitsSystemWindows="true"
android:layout_height="match_parent">
<user.example.charu.its2017huree.CustomLinearLayout
android:background="#098"
android:gravity="bottom"
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello world" />
</user.example.charu.its2017huree.CustomLinearLayout>
Finally in my Activity called HomeActivity
public class HomeActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
CustomLinearLayout customLinearLayout = (CustomLinearLayout) findViewById(R.id.linearLayout);
Snackbar.make(customLinearLayout, "Text to display", Snackbar.LENGTH_LONG).show();
}
}
Source is from this example.

Loading images from URLs into gridview

I have a gridview which is supposed to contain an image and a text below it. I am using Picasso to load the images but when I run the app, nothing appears in the imageviews!
Below is my MainActivity.java code:
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
GridView gv;
Context context;
ArrayList prgmName;
public static String [] prgmNameList={"C++","VB.NET","JAVA", "JavaScript", "MySQL", "PHP"};
public static String [] prgmImgFiles = {"cpp.png", "vb.net.png", "java.png", "js.png", "mysql.png", "php.png"};
public static Integer [] prgmImages={R.mipmap.img_0, R.mipmap.img_1, R.mipmap.img_2};
public ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(prgmNameList));
public ArrayList<Integer> arrayList2 = new ArrayList<Integer>(Arrays.asList(prgmImages));
public ArrayList<String> arrayList3 = new ArrayList<String>(Arrays.asList(prgmImgFiles));
public static GridViewAdapter gvd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onLoadClick(View v)
{
gv=(GridView) findViewById(R.id.gridView2);
gvd = new GridViewAdapter(this, arrayList, arrayList3);
gv.setAdapter(gvd);
ImageView iv2 = (ImageView)findViewById(R.id.imageViewTest);
// addItem("JavaScript", "http://10.0.2.2/picgal/images/js.png");
Picasso.with(this).load("http://10.0.2.2/picgal/images/java.png").into(iv2);
}
public void addItem(String txt, String ImgID)
{
arrayList.add(txt);
arrayList3.add(ImgID);
gvd.notifyDataSetChanged();
}
}
Below is my GridViewAdapter.java code:
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
/**
* Created by ITM on 7/4/2016.
*/
public class GridViewAdapter extends BaseAdapter {
ArrayList<String> result;
Context context;
ArrayList<String> imageId;
private static LayoutInflater inflater=null;
public static final String server = "http://10.0.2.2/picgal/images/";
public Holder holder=new Holder();
public GridViewAdapter(MainActivity mainActivity, ArrayList<String> prgmNameList, ArrayList<String> prgmImages) {
// TODO Auto-generated constructor stub
result=prgmNameList;
context=mainActivity;
imageId=prgmImages;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
public TextView tv;
public ImageView img;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View rowView;
rowView = inflater.inflate(R.layout.img_layout, null);
holder.tv=(TextView) rowView.findViewById(R.id.txt);
holder.img=(ImageView) rowView.findViewById(R.id.img);
holder.tv.setText(result.get(position));
Log.i("getView", imageId.get(position));
Picasso.with(context).load(imageId.get(position)).into(holder.img);
// holder.img.setImageResource(imageId.get(position));
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "You Clicked " + result.get(position) +"\n"+getCount(), Toast.LENGTH_LONG).show();
}
});
return rowView;
}
}
The activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.badihbarakat.gridviewapp.MainActivity">
<GridView
android:layout_width="wrap_content"
android:layout_height="250dp"
android:id="#+id/gridView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#ffe5e5"
android:columnWidth="100dp"
android:drawSelectorOnTop="true"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="spacingWidthUniform"
android:verticalSpacing="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:scrollIndicators="left" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load"
android:id="#+id/btnLoad"
android:layout_below="#+id/gridView2"
android:layout_centerHorizontal="true"
android:onClick="onLoadClick" />
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/imageViewTest"
android:layout_below="#+id/btnLoad"
android:layout_centerHorizontal="true" />
</RelativeLayout>
The img_layout.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:orientation="vertical">
<FrameLayout
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true">
<ImageView
android:id="#+id/img"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/frame" />
</FrameLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txt"
android:textAlignment="center"/>
</LinearLayout>
I have added a test ImageView below the button to test the Picasso object working. It is working fine. Can any one help please.
Thanks
1.You are passing wrong arguments in the gridView's constructor.
gvd = new GridViewAdapter(this, arrayList, arrayList3);
should be
gvd = new GridViewAdapter(this, arrayList, arrayList2);
as stated in your code, arrayList2 consists of Images.
2.In adapter, change the second argument in constructor:
from ArrayList<String> to ArrayList<Integer>
public GridViewAdapter(MainActivity mainActivity, ArrayList<String> prgmNameList, ArrayList<Integer> prgmImages) {
//...
}
After this, try passing it to Picasso.
New :
Can you try the following code :
//server url
String imageURL = ""
//array of images passed in constructor to append with url
String arrayOfImages[] = imageId;
String completeImageURL = server + arrayOfImages[position];
Picasso.with(context)
.load(completeImageURL)
.into(holder.img);
Best ever I used , ImageLoader Library
https://github.com/nostra13/Android-Universal-Image-Loader
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(imageUri, imageView);
Thanks for all of you who assisted in this question.
Actually, after revising the Picasso code, I discovered that the path to the image file was missing!
What I have put was:
Picasso.with(context).load(imageId.get(position)).into(holder.img);
As imageId.get(position) contains only the file name and not the full path on the server, the Picasso was not able to find the file!
The correct code is:
Picasso.with(context).load(server+imageId.get(position)).into(holder.img);
Where server is a String containing the full path of the images folder.
Thanks again to all of you.

How to set this listview when you clicked/tapped opens into a different activity/intent

See this site: http://www.androidbegin.com/tutorial/android-search-filter-listview-images-and-texts-tutorial/
How do I set it to open into different activity/intent.
MainActivity.java
package com.androidbegin.filterlistviewimg;
import java.util.ArrayList;
import java.util.Locale;
import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity {
// Declare Variables
ListView list;
ListViewAdapter adapter;
EditText editsearch;
String[] rank;
String[] country;
String[] population;
int[] flag;
ArrayList<WorldPopulation> arraylist = new ArrayList<WorldPopulation>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_main);
// Generate sample data
rank = new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
country = new String[] { "China", "India", "United States",
"Indonesia", "Brazil", "Pakistan", "Nigeria", "Bangladesh",
"Russia", "Japan" };
population = new String[] { "1,354,040,000", "1,210,193,422",
"315,761,000", "237,641,326", "193,946,886", "182,912,000",
"170,901,000", "152,518,015", "143,369,806", "127,360,000" };
flag = new int[] { R.drawable.china, R.drawable.india,
R.drawable.unitedstates, R.drawable.indonesia,
R.drawable.brazil, R.drawable.pakistan, R.drawable.nigeria,
R.drawable.bangladesh, R.drawable.russia, R.drawable.japan };
// Locate the ListView in listview_main.xml
list = (ListView) findViewById(R.id.listview);
for (int i = 0; i < rank.length; i++)
{
WorldPopulation wp = new WorldPopulation(rank[i], country[i],
population[i], flag[i]);
// Binds all strings into an array
arraylist.add(wp);
}
// Pass results to ListViewAdapter Class
adapter = new ListViewAdapter(this, arraylist);
// Binds the Adapter to the ListView
list.setAdapter(adapter);
// Locate the EditText in listview_main.xml
editsearch = (EditText) findViewById(R.id.search);
// Capture Text in EditText
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
}
}
WorldPopulation.java
package com.androidbegin.filterlistviewimg;
public class WorldPopulation {
private String rank;
private String country;
private String population;
private int flag;
public WorldPopulation(String rank, String country, String population,
int flag) {
this.rank = rank;
this.country = country;
this.population = population;
this.flag = flag;
}
public String getRank() {
return this.rank;
}
public String getCountry() {
return this.country;
}
public String getPopulation() {
return this.population;
}
public int getFlag() {
return this.flag;
}
}
listview_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<EditText
android:id="#+id/search"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<requestFocus />
</EditText>
<ListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/search" />
</RelativeLayout>
ListViewAdapter.java
package com.androidbegin.filterlistviewimg;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<WorldPopulation> worldpopulationlist = null;
private ArrayList<WorldPopulation> arraylist;
public ListViewAdapter(Context context,
List<WorldPopulation> worldpopulationlist) {
mContext = context;
this.worldpopulationlist = worldpopulationlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<WorldPopulation>();
this.arraylist.addAll(worldpopulationlist);
}
public class ViewHolder {
TextView rank;
TextView country;
TextView population;
ImageView flag;
}
#Override
public int getCount() {
return worldpopulationlist.size();
}
#Override
public WorldPopulation getItem(int position) {
return worldpopulationlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.rank = (TextView) view.findViewById(R.id.rank);
holder.country = (TextView) view.findViewById(R.id.country);
holder.population = (TextView) view.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
holder.flag = (ImageView) view.findViewById(R.id.flag);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.rank.setText(worldpopulationlist.get(position).getRank());
holder.country.setText(worldpopulationlist.get(position).getCountry());
holder.population.setText(worldpopulationlist.get(position)
.getPopulation());
// Set the results into ImageView
holder.flag.setImageResource(worldpopulationlist.get(position)
.getFlag());
// Listen for ListView Item Click
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(mContext, SingleItemView.class);
// Pass all data rank
intent.putExtra("rank",
(worldpopulationlist.get(position).getRank()));
// Pass all data country
intent.putExtra("country",
(worldpopulationlist.get(position).getCountry()));
// Pass all data population
intent.putExtra("population",
(worldpopulationlist.get(position).getPopulation()));
// Pass all data flag
intent.putExtra("flag",
(worldpopulationlist.get(position).getFlag()));
// Start SingleItemView Class
mContext.startActivity(intent);
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
} else {
for (WorldPopulation wp : arraylist) {
if (wp.getCountry().toLowerCase(Locale.getDefault())
.contains(charText)) {
worldpopulationlist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
listview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/ranklabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/ranklabel" />
<TextView
android:id="#+id/rank"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/ranklabel" />
<TextView
android:id="#+id/countrylabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/ranklabel"
android:text="#string/countrylabel" />
<TextView
android:id="#+id/country"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/rank"
android:layout_toRightOf="#+id/countrylabel" />
<TextView
android:id="#+id/populationlabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/countrylabel"
android:text="#string/populationlabel" />
<TextView
android:id="#+id/population"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/country"
android:layout_toRightOf="#+id/populationlabel" />
<ImageView
android:id="#+id/flag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="#000000"
android:padding="1dp" />
</RelativeLayout>
SingleItemView.java
package com.androidbegin.filterlistviewimg;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
public class SingleItemView extends Activity {
// Declare Variables
TextView txtrank;
TextView txtcountry;
TextView txtpopulation;
ImageView imgflag;
String rank;
String country;
String population;
int flag;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.singleitemview);
// Get the intent from ListViewAdapter
Intent i = getIntent();
// Get the results of rank
rank = i.getStringExtra("rank");
// Get the results of country
country = i.getStringExtra("country");
// Get the results of population
population = i.getStringExtra("population");
// Get the results of flag
flag = i.getIntExtra("flag", flag);
// Locate the TextViews in singleitemview.xml
txtrank = (TextView) findViewById(R.id.rank);
txtcountry = (TextView) findViewById(R.id.country);
txtpopulation = (TextView) findViewById(R.id.population);
// Locate the ImageView in singleitemview.xml
imgflag = (ImageView) findViewById(R.id.flag);
// Load the results into the TextViews
txtrank.setText(rank);
txtcountry.setText(country);
txtpopulation.setText(population);
// Load the image into the ImageView
imgflag.setImageResource(flag);
}
}
singleitemview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/ranklabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/ranklabel" />
<TextView
android:id="#+id/rank"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/ranklabel" />
<TextView
android:id="#+id/countrylabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/ranklabel"
android:text="#string/countrylabel" />
<TextView
android:id="#+id/country"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/rank"
android:layout_toRightOf="#+id/countrylabel" />
<TextView
android:id="#+id/populationlabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/countrylabel"
android:text="#string/populationlabel" />
<TextView
android:id="#+id/population"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/country"
android:layout_toRightOf="#+id/populationlabel" />
<ImageView
android:id="#+id/flag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="#000000"
android:padding="1dp" />
</RelativeLayout>

Categories