Gridview using custom adapter not displaying all results - android

firstly a big thanks to all the experts that answer questions and provide insight into challenges. Your work is appreciated.
Now, i'm a newbie and just started using java and Android....but i'm loving it.
secondly,
do forgive my code. its my very first Android app...moving from 13yrs of vb and vba :) and much of it is modified from user questions here on stackoverflow.
Background:
I have a gridview that i want to display contact data (name and number) from the Call Log.
In order to eliminate duplicate numbers, i loop through the cursor and compare phone numbers after of course, sorting the incoming cursor data by CallLog.Calls.NUMBER + " ASC";
i have also created my own class (ContactObj) that holds the name,number and ID of a contact and i pass this class to an ArrayList. eventually i pass this ArrayList to a custom adapter which uses layout inflater to populate the grid.
The issue:
For some reason, the program runs fine but the first ten contacts are repeated over and over. ie. the total contacts on my phone log are 113 unique. however the grid displays only the first 10 over and over for the total 113.
The question:
perhaps the "old hands" at this could point me on where i'm going wrong? i'm guessing is something to do with my implementation of the custom adapter that feeds the gridview.
as i debug, noticed that the value of mChildrenCount is fixed at 11 which is the count of the cells in the gridview in design mode. for some reason whenever this number is reached the gridview starts from 0 again and that repeats the data. it seems i'm missing some setting to allow the grid to go beyond the cells shown during design. ...any ideas anyone?
Thanks.
here's the code for the main activity
public class CallLogActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview);
final Context myContext = CallLogActivity.this;
final CustomAdapter mAdapter;
ArrayList<ContactObj> arrToPassToGrid = new ArrayList<ContactObj>();
String strNameHolder = "";
String strCurrentName;
String strNumber;
String strCallDate;
String ID;
int i = 0;
int ComparisonResult;
// first find the grid
GridView callLogGrid = (GridView) findViewById(R.id.callLogGrid);
// next get the contents to display
Long yourDateMillis = System.currentTimeMillis()- (30 * 24 * 60 * 60 * ' `1000);
Time yourDate = new Time();
yourDate.set(yourDate);
String[] YourDateMillistring = {String.valueOf(yourDateMillis)};
String formattedDate = yourDate.format("%Y-%m-%d %H:%M:%S");
Time tempDate;
Cursor Tempcursor;
Cursor cursor;
cursor = getContentResolver().query(CallLog.Calls.CONTENT_URI,
new String[]{CallLog.Calls._ID,
CallLog.Calls.CACHED_NAME,
CallLog.Calls.NUMBER,
CallLog.Calls.DATE},
null,
null,
CallLog.Calls.NUMBER + " ASC");
startManagingCursor(cursor);
// intialize nameholder ----will be used to remove duplicate names in
strNameHolder = "";
if (cursor.moveToFirst()) {
while (cursor.moveToNext()) {
// place contents in variables for easier reading later on;
strCurrentName =
cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
strNumber = cursor.getString(
cursor.getColumnIndex(CallLog.Calls.NUMBER)).trim();
strCallDate = cursor.getString(cursor.getColumnIndex(CallLog.Calls.DATE));
ID = cursor.getString(cursor.getColumnIndex(CallLog.Calls._ID));
if (strCurrentName == null && strNumber == null) {
ComparisonResult = 0;
} else {
ComparisonResult = strNameHolder
.compareToIgnoreCase(strNumber);
}
if (ComparisonResult != 0) {
ContactObj contList = new ContactObj();
contList.setIndex(i);
contList.setContactName(strCurrentName);
contList.setContactDialledNumber(strNumber);
contList.setContact_ID(ID);
contList.setCallDate(strCallDate);
arrToPassToGrid.add(i, contList);
i++;
}
strNameHolder = cursor.getString(
cursor.getColumnIndex(CallLog.Calls.NUMBER)).trim();
};
};
try {
// Collections.sort(arrToPassToGrid)
mAdapter = new CustomAdapter(this, arrToPassToGrid);
callLogGrid.setAdapter(mAdapter);
} catch (Exception e)
{
Log.d("Kush", e.getMessage());
e.printStackTrace();
}
}
This code is my custom adapter
public class CustomAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<ContactObj> mItems;
public CustomAdapter(Context c, ArrayList<ContactObj> items)
{
mContext = c;
mItems = items;
}
public int getCount()
{
return mItems.size();
}
public Object getItem(int position)
{
return mItems.get(position);
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater li = (LayoutInflater)
mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.calllog_layout, null);
Log.d("Kush",String.valueOf(getCount()));
TextView txtContactName = (TextView)v.findViewById(R.id.txtContactName);
txtContactName.setText(mItems.get(position).getContactName() );
TextView txtNumber = (TextView)v.findViewById(R.id.txtContactNumber);
txtNumber.setText(mItems.get(position).getContactDialledNumber());
TextView txtDate = (TextView)v.findViewById(R.id.txtCallDate);
txtNumber.setText(String.valueOf(position) );
}
return v;
}
public static String getDate(long milliSeconds, String dateFormat)
{
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
return formatter.format(calendar.getTime());
}
}
This is the object holding the contact details
public class ContactObj {
private String ContactName;
private String ContactDialledNumber;
private String Contact_ID;
private String CallDate;
public final String getCallDate()
{
return CallDate;
}
public final void setCallDate(String callDate)
{
CallDate = callDate;
}
private int index;
// #return the contactName
public final String getContactName()
{
return ContactName;
}
// #param contactName the contactName to set
public final void setContactName(String contactName)
{
ContactName = contactName;
}
//#return the contactDialledNumber
public final String getContactDialledNumber()
{
return ContactDialledNumber;
}
//#param contactDialledNumber the contactDialledNumber to set
public final void setContactDialledNumber(String contactDialledNumber)
{
ContactDialledNumber = contactDialledNumber;
}
//#return the contact_ID
public final String getContact_ID()
{
return Contact_ID;
}
// #param contact_ID the contact_ID to set
public final void setContact_ID(String contact_ID)
{
Contact_ID = contact_ID;
}
//#return the index
public final int getIndex()
{
return index;
}
//#param index the index to set
public final void setIndex(int index)
{
this.index = index;
}
}
Finally the gridview and layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center_horizontal"
android:id="#+id/GridItem"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/grid_item_image"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:scaleType="centerCrop" />
<TextView
android:gravity="center_horizontal"
android:id="#+id/txtContactName"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/contactName"
android:textColor="#000000" />
<TextView
android:gravity="center_horizontal"
android:id="#+id/txtContactNumber"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/contactNumber"
android:textColor="#000000" />
<TextView
android:gravity="center_horizontal"
android:id="#+id/txtCallDate"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/CallDate"
android:textColor="#000000" />
</LinearLayout>
and Gridview

txtContactName.setText(mItems.get(position).getContactName() );
These statements should be outside the if condition. Also check the viewholder usageonce.
Probably you will get the solution.

Related

Put data in Gson and display it in a listview

It's my first time face to face with Gson. My question will be a long one, hope you'll understand and I there are more problems wich got me stuck for about 1 week.
So, I have a ListView where I get selected items from another Activtity. Under this ListView I have a Button where the seller save items to FireBase, bought by customer.
Now the problem is, each time when seller save bought items to FireBase I want to enumerate(like an increment) each customer and give a customer number. And show the number of customer in TextView in top of the page where number 1 is in the picture. But next day enumeration have to starts from 1. So every day has to starts from 1.
In this ListView, I am counting selected items and calculate sum of prices.
But second problem is I have no idea how to send customer number, counted items and sum of items to another ListView with a card view. I want to put it inside of Gson. I tried something, but I'm completely lost. And my code looks really messy in this moment. Hope you'll understand.
Here is the code where I get selected items and display counted items and sum of items with Toast :
int totalPrice = 0;
for(VanzatorProduse v : Util.getInstance().getVanzatorProduse())
{
int vPrice = Integer.parseInt(v.getPret());
totalPrice = totalPrice + vPrice;
}
Toast.makeText(getApplicationContext(), "Selected products : " + listaProdusePreview.getAdapter().getCount() +"\n"+"Total sum : " + totalPrice , Toast.LENGTH_LONG).show();
Intent sumaProduse = new Intent(FormCumparareActivity.this, VanzatorActivity.class);
sumaProduse.putExtra("sumaProduse", totalPrice);
startActivity(sumaProduse);
String produseSelectate = String.valueOf(listaProdusePreview.getAdapter().getCount());
Intent intent = new Intent(FormCumparareActivity.this, VanzatorActivity.class);
intent.putExtra("produseSelectate", produseSelectate);
startActivity(intent);
Util.getInstance().getVanzatorProduse().removeAll(Util.getInstance().getVanzatorProduse());
Object class for customer number, counted items and sum of items :
public class Card {
private Integer numarCumparator;
private String listaProduse;
private Integer sumaProduse;
public Card(Integer numarCumparator, String listaProduse, Integer sumaProduse) {
this.numarCumparator = numarCumparator;
this.listaProduse = listaProduse;
this.sumaProduse = sumaProduse;
}
public Integer getNumarCumparator() {
return numarCumparator;
}
public void setNumarCumparator(Integer numarCumparator) {
this.numarCumparator = numarCumparator;
}
public String getListaProduse() {
return listaProduse;
}
public void setListaProduse(String listaProduse) {
this.listaProduse = listaProduse;
}
public Integer getSumaProduse() {
return sumaProduse;
}
public void setSumaProduse(Integer sumaProduse) {
this.sumaProduse = sumaProduse;
}
Here is code for listview adapter :
public class CardArrayAdapter extends ArrayAdapter<Card> {
private static final String TAG = "CardArrayAdapter";
private List<Card> cardList = new ArrayList<Card>();
static class CardViewHolder {
TextView line1;
TextView line2;
TextView line3;
}
public CardArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public void add(Card object) {
cardList.add(object);
super.add(object);
}
#Override
public int getCount() {
return this.cardList.size();
}
#Override
public Card getItem(int index) {
return this.cardList.get(index);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CardViewHolder viewHolder;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.list_item_card, parent, false);
viewHolder = new CardViewHolder();
viewHolder.line1 = (TextView) row.findViewById(R.id.txtViewNumarCumparator);
viewHolder.line2 = (TextView) row.findViewById(R.id.listaProduse);
viewHolder.line3 = (TextView) row.findViewById(R.id.sumaProduse);
row.setTag(viewHolder);
} else {
viewHolder = (CardViewHolder)row.getTag();
}
Card card = getItem(position);
viewHolder.line1.setText(card.getNumarCumparator());
viewHolder.line2.setText(card.getListaProduse());
viewHolder.line3.setText(card.getSumaProduse());
return row;
}
Layout for card view :
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:descendantFocusability="afterDescendants"
android:orientation="vertical"
android:paddingBottom="15dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="15dp">
<TextView
android:id="#+id/txtViewNumarCumparator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="NumarCumparator" />
<TextView
android:id="#+id/listaProduse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/txtViewNumarCumparator"
android:layout_marginTop="10dp"
android:text="NumarProduse" />
<TextView
android:id="#+id/sumaProduse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:text="SumaProdsue" />
Here, is my attempt for Gson, I put it in a JSONManager class :
public class JSONManager {
private static JSONManager instance = null;
protected JSONManager() {
// Exists only to defeat instantiation.
}
public static JSONManager getInstance() {
if (instance == null) {
instance = new JSONManager();
}
return instance;
}
//Create list of Cards because we need to show list for date selected
public List<Card> readJSON(String dateFromCalendar) throws JSONException {
String JSON = SharedPreference.getString(Util.get(), SharedPreference.APP_DATA, SharedPreference.JSON_DATA, "");
String numeVanzator = SharedPreference.getString(Util.get(), SharedPreference.USER_DATA, SharedPreference.NUME_VANZATOR,"");
JSONObject jsonObj = new JSONObject(JSON);
JSONArray contacts = jsonObj.getJSONArray("jsonData");
List<Card> listCard = null;
Card card = null;
listCard = new ArrayList<>();
for (int i =0; i< contacts.length();i++) {
JSONObject c = contacts.getJSONObject(i);
String data = c.getString("data");
if (data.equals(dateFromCalendar)){
String numeVanzato = c.getString("numeVanzator");
if (numeVanzato.equals(numeVanzator)){
Integer numarClient = c.getInt("numarClient");
JSONObject detaliiCos = c.getJSONObject("detaliiCos");
Integer sumaProduse = detaliiCos.getInt("sumaProduse");
String produseselectate = c.getString("produseSelectate");
card = new Card(numarClient, produseselectate, sumaProduse);
listCard.add(card);
}
}
}
return listCard;
} }
Code for activity where i tried to get data inside from Gson.
#Override
protected void onResume() {
super.onResume();
c = Calendar.getInstance();
String numeVanzator = SharedPreference.getString(this, SharedPreference.USER_DATA, SharedPreference.NUME_VANZATOR, "");
if (!numeVanzator.equals("")) {
textViewNumeVanzator.setText(numeVanzator);
}
String jsonData = SharedPreference.getString(getApplicationContext(), SharedPreference.APP_DATA, SharedPreference.JSON_DATA, "");
System.out.println("JSON data" + jsonData);
textViewDataCurenta.setText(getDate(c.getTimeInMillis()));
cardArrayAdapter = new CardArrayAdapter(this, R.layout.list_item_card);
Card card = null;
List<Card> listCard = new ArrayList<Card>();
c = Calendar.getInstance();
try {
String date = getDate(c.getTimeInMillis());
listCard = JSONManager.getInstance().readJSON(date);
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i <= listCard.size()-1; i++) {
card = listCard.get(i);
cardArrayAdapter.add(card);
}
listViewVanzatorActivity.setAdapter(cardArrayAdapter);
}
Right now, everything is working perfectly but when click on save Button nothing appears in next activity and no errors.
Hope, you understand my question, I really need your help. Thank you !!
In your code you created two times Intent for call activity that is not good way.
just remove second intent from this
Intent sumaProduse = new Intent(FormCumparareActivity.this, VanzatorActivity.class);
sumaProduse.putExtra("sumaProduse", totalPrice);
startActivity(sumaProduse);
Intent intent = new Intent(FormCumparareActivity.this, VanzatorActivity.class);
intent.putExtra("produseSelectate", produseSelectate);
startActivity(intent);
now create new bundle and add pass to this with key like this:
Intent intent = new Intent(FormCumparareActivity.this, VanzatorActivity.class);
Bundle bundle = new Bundle();
bundle.put("key",totalPrice);
bundle.put("key",produseSelectate);
intent .putExtras(bundle)
startActivity(intent);
you are getting list from JSON which are not store in shared preferences.
hope you are get it my point.

SQLite- heading above ListView (source same as ListView source)

Im busy with a Bible app, I use an SQLite db from my assets folder to retrieve the data, I use 3 listviews, each in its own activity, it goes like this:
DB column names: Book name, book id, chapter number, chapter id, verse text, verse id
1st activity, user selects a book, Genesis, Exodus, Leviticus, etc... and 2nd activity starts
2nd activity, db gets filtered so user can select chapters under that book...and 3rd activity starts
3rd activity, db gets filtered and shows all the verses under that chapter...
What I want is to put a text view at the top of the 2nd list view and then after the user selected from the 1st listview and the 2nd activity starts to show all chapters, it should show the book name that was selected from the 1st activity. And in the 3rd list view it should show the book name and chapter number that was selected from the previous two activities, I've tried using the intend, but I get errors.
Adapter:
public class customAdapterHoofstuk extends BaseAdapter {
private Context mContext;
private List<defineBybeldbAlles> defineBybeldbAlles;
public customAdapterHoofstuk(Context mContext, List<defineBybeldbAlles> defineBybelDBList) {
this.mContext = mContext;
this.defineBybeldbAlles = defineBybelDBList;
}
#Override
public int getCount() {
return defineBybeldbAlles.size();
}
#Override
public Object getItem(int position) {
return defineBybeldbAlles.get(position);
}
#Override
public long getItemId(int position) {
return (defineBybeldbAlles.get(position).getHoofstuk_id());
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = View.inflate(mContext, R.layout.custom_row_hoofstuk, null);
//this works->
TextView hoofstuknommer = (TextView)v.findViewById(R.id.custom_row_hoofstuktext);
hoofstuknommer.setText (defineBybeldbAlles.get(position).getHoofstuk_nommer());
//this works-->
TextView hoofstukid = (TextView)v.findViewById(R.id.hoofstuk_id);
hoofstukid.setText(String.valueOf(defineBybeldbAlles.get(position).getHoofstuk_id()));
//this doesnt work->
TextView boeknaambyhoofstuk = (TextView)v.findViewById(R.id.boeknaambyhoofstuklys);
boeknaambyhoofstuk.setText(defineBybeldbAlles.get(position).get_hebreeus());
return v;
}
}
Activity where it should be shown:
public class BybelActivityHoofstuk extends Activity {
private ListView listviewHoofstuk;
private customAdapterHoofstuk adapter_customAdapterHoofstuk;
private List<defineBybeldbAlles> defineBybeldbAllesList;
private DBHandlerHoofstuk DBHandlerHoofstuk;
ArrayList<HashMap<String, String>> HoofstukList;
//Boek id
String boek_id_na_hoofstuk;
#Override
public void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bybel_hoofstuk);
listviewHoofstuk = (ListView) findViewById(R.id.BybelHoofstukListView);
DBHandlerHoofstuk = new DBHandlerHoofstuk(this);
//Check exists database
File Database = getApplicationContext().getDatabasePath(DBHandlerHoofstuk.DBNAME);
if(false == Database.exists()){
DBHandlerHoofstuk.getReadableDatabase();}
//Get boek id
Intent boekIntent = getIntent();
boek_id_na_hoofstuk = boekIntent.getStringExtra("boek_id");
//hashmap for listview
HoofstukList = new ArrayList<HashMap<String, String>>();
//Get bybel list in db when db exists
defineBybeldbAllesList = DBHandlerHoofstuk.getListHoofstuk(boek_id_na_hoofstuk);
//Init adapter
adapter_customAdapterHoofstuk = new customAdapterHoofstuk(this,defineBybeldbAllesList);
//Set adapter for listview
listviewHoofstuk.setAdapter(adapter_customAdapterHoofstuk);
//Listview item click listener
//BybelActivityVers will be launched by passing hoofstuk_id
listviewHoofstuk.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick (AdapterView<?> arg0, View view, int arg2, long arg3){
//on selecting a hoofstk
//BybelActivityVers will be launched to show verse inside
Intent hoofstukIntent = new Intent(BybelActivityHoofstuk.this,BybelActivityVers.class);
//send hoofstuk_id to VersActivity to get verse under that book
String hoofstuk_id_na_vers = ((TextView)view.findViewById(R.id.hoofstuk_id)).getText().toString();
hoofstukIntent.putExtra("hoofstuk_id", hoofstuk_id_na_vers);
startActivity(hoofstukIntent);
}
});
}
}
DBHandler:
public class DBHandlerHoofstuk extends SQLiteOpenHelper{
public static final int DATABASE_VERSION = 1;
public static final String DBNAME = "pwl14082016-5.db";
public static final String DBLOCATION = "location goes here";
private Context mContext;
private SQLiteDatabase mDatabase;
public static final String COLUMN_BOEK_ID = "boek_id";
public static final String COLUMN_HEBREEUS = "_hebreeus";
public static final String COLUMN_AFRIKAANS = "_afrikaans";
public static final String COLUMN_HOOFSTUK_ID = "hoofstuk_id";
public static final String COLUMN_HOOFSTUK_NOMMER = "hoofstuk_nommer";
public static final String COLUMN_VERS_ID = "vers_id";
public static final String COLUMN_VERS_NOMMER = "vers_nommer";
public static final String COLUMN_VERS_TEXT = "vers_text";
public DBHandlerHoofstuk(Context context) {
super(context, DBNAME, null, DATABASE_VERSION);
this.mContext = context;
}
//Blank want db bestaan klaar
#Override
public void onCreate(SQLiteDatabase db) {
}
//blank want db word ekstern geupgrade
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
//maak db oop
public void opendatabase(){
String dbPath = mContext.getDatabasePath(DBNAME).getPath();
if (mDatabase !=null && mDatabase.isOpen()) {
return;
}
//verander dalk na 'mDatabase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);' as OPEN_READONLY nie werk nie
mDatabase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
//maak db toe
public void closeDatabase(){
if (mDatabase!=null) {
mDatabase.close();
}
}
public List<defineBybeldbAlles> getListHoofstuk(String boek_id_na_hoofstuk){
defineBybeldbAlles defineBybeldbHoofstuk = null;
List<defineBybeldbAlles> defineBybeldbAllesList = new ArrayList<>();
opendatabase();
Cursor cursor = mDatabase.rawQuery("SELECT * FROM PWLBybel WHERE " + COLUMN_BOEK_ID + " = '" + boek_id_na_hoofstuk + "'GROUP BY hoofstuk_id ORDER BY hoofstuk_id * 1 ASC", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
defineBybeldbHoofstuk = new defineBybeldbAlles(cursor.getInt(0), cursor.getString(1),cursor.getString(2),cursor.getInt(3),cursor.getString(4),cursor.getInt(5),cursor.getString(6),cursor.getString(7));
defineBybeldbAllesList.add(defineBybeldbHoofstuk);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return defineBybeldbAllesList;
}
}
XML where it gets displayed:
<?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"
tools:context=".defineBybeldbAlles">
<ListView
android:id="#+id/BybelHoofstukListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#ff303030"
android:dividerHeight="1dp"
android:layout_marginTop="21dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Boek naam:"
android:id="#+id/boeknaambyhoofstuklys"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textColor="#000063"
android:textSize="20dp" />
</RelativeLayout>
You can send the string through intent using
String KEY = "PUT_ANY_KEY_HERE";
String VALUE = "BOOK_NAME/CHAPTER_NAME";
Intent i = new Intent(FROM_CLASS.this, TO_CLASS.class);
i.putExtra(KEY,VALUE);
startActivity(i);
and get the string in the 2nd activity using
Intent intent = getIntent();
if(intent!=null)
String VALUE = intent.getExtras().getString(KEY);
now set the VALUE string in your textview. Also you need to put the chapterName textview above your listview or add the VALUE string as your 1st entry in the arraylist that you might be using to populate listview in 2nd and 3rd activity.
If someone might come across this, I wasn't able to pass the book and chapter name to the heading or bar, but I was able to figure out to set a title.
In your manifest under each activity, just put in android:label="title here"
to at least get a heading or title you want.

Gridview items changes order using a RecyclerView

The gridview items change order randomly sometimes when i click on items and mostly when scrolling. I have searched all over the internet but couldn't find a solution which works for recyclerview.
This is my layout adapter class
public class LayoutAdapter extends RecyclerView.Adapter<LayoutAdapter.SimpleViewHolder>{
private static final int COUNT = 100;
private static final String TAG = "LayoutAdapter";
private final Context mContext;
private final TwoWayView mRecyclerView;
private final int mLayoutId;
private int mCurrentItemId = 0;
private FileManager file_manager;
private ArrayList<Integer> positions;
private static LayoutInflater inflator = null;
private TextView folder_name;
private Context c;
ArrayList<String> mDataSource, mMultiSelectData;
private File file, files;
private File[] list2;
public boolean multi_select_flag = false;
public class SimpleViewHolder extends RecyclerView.ViewHolder {
public SimpleViewHolder(View view) {
super(view);
thumbnail = (ImageView) view.findViewById(R.id.ivFolderThumbnail);
folder_name = (TextView) view.findViewById(R.id.tvFolderTitle);
}
}
//In logcat I see this constructor is being called again and again and again!
public LayoutAdapter(Context context, TwoWayView recyclerView, int layoutId, FileManager filemanager, String file_path) {
mContext = context;
file_manager = filemanager;
c = context;
mDataSource = new ArrayList<String>(file_manager.setHomeDir
(Environment.getExternalStorageDirectory().getPath()));
mRecyclerView = recyclerView;
mLayoutId = layoutId;
String root_sd = Environment.getExternalStorageDirectory().toString();
if (file_path == null) {
file = new File(root_sd);
} else {
file = new File(root_sd + "/" + file_path);
}
Log.d(TAG, "GOT ALL FILES >>>>>>" + root_sd);
list2 = file.listFiles();
}
public String getName(int position) {
String name = list2[position].getName();
return name;
}
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;
}
#Override
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(mContext).inflate(R.layout.grid_item, parent, false);
return new SimpleViewHolder(view);
}
public String getData(int position) {
if (position > mDataSource.size() - 1 || position < 0)
return null;
return mDataSource.get(position);
}
#Override
public void onBindViewHolder(SimpleViewHolder holder, int position) {
// boolean isVertical = (mRecyclerView.getOrientation() ==TwoWayLayoutManager.Orientation.VERTICAL);
final View itemView = holder.itemView;
int num_items = 0;
String temp = file_manager.getCurrentDir();
File file = new File(temp + "/" + mDataSource.get(position));
String[] list = file.list();
if (list != null)
num_items = list.length;
Log.d(TAG, ">>>>>>>>>>>>> " + String.valueOf(file.length()));
folder_name.setText(file.getName());
}
}
#Override
public int getItemCount() {
return mDataSource.size();
}
}
This is the layout file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="105dp"
android:layout_height="105dp"
android:orientation="vertical" >
<com.filemanager.android.SquareImageView
android:id="#+id/ivFolderThumbnail"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_marginLeft="15dp"
android:scaleType="centerCrop"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/tvFolderTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/ivFolderThumbnail"
android:text="Medium Text"
android:textColor="#android:color/black"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageView
android:id="#+id/ivMultiSelect"
android:layout_width="50dp "
android:layout_height="50dp"
android:layout_above="#+id/tvFolderTitle"
android:layout_toRightOf="#+id/ivFolderThumbnail"
android:src="#drawable/ic_action_new" />
</RelativeLayout>
Could you please post the layout definitions as well? We already know that if the items do not have fixed or pre-defined dimensions, then the items may shift order in case of TwoWay/Recycler Views.
This happens because in recycler view older item views are reused when we scroll down and older item dimensions may differ from the new item dimensions. Hence they may reorder.
In that case setting fixed dimensions for your ImageView and TextView would solve the issue or determine the dimension of the ImageView before inflating.
I ran in the same problem, which is/was really annoying. I tested several things and one of them did the trick: I dont know why but you have to set the item animator explicitly to null for the recycler view with [RecyclerView].setItemAnimator(null); ... Especially the first items reordered when scrolling up again in my staggered layout. Now it is gone. Hope this helps you as well.
Issue # GitHub
Yes, it is very annoying; the solution which I have realized is in adapter just clear all the conditions like for every if condition there will also be else with valid body.
Try this approach you will get rid of this issue.

Populate ListView from ArrayList is showing database row references instead of row data

I get rows from a db as an ArrayList. I want to use data that is in two of the columns to populate a list view.
What I have done so far only shows the ?row reference? (com.app.Poster#2349049)
ListView listView = (ListView) findViewById(R.id.poster_list_view);
MySQLiteHelper db = new MySQLiteHelper(this);
List<Poster> posters = db.getAllPosters();
ArrayAdapter<Poster> listAdapter = new ArrayAdapter<Poster>(this, android.R.layout.simple_list_item_1, posters);
listView.setAdapter(listAdapter);
I thought maybe I am suppose to loop the ArrayList and add each row to the adapter
for (Poster p : posters){
listAdapter.add(p.getPosterTitle());
}
Apparently the adapter only wants an object I think. Should I be customizing an adapter for this? I thought it would be a lot easier.
This is my Poster Class
public class Poster {
private int posterId;
private int categoryId;
private int eventId;
private String presenterFname;
private String presenterLname;
private String posterTitle;
private String posterSynopsis;
private String posterFilename;
private String posterRemoteLocation;
public Poster(int pid, int cid, int eid, String prf, String prl, String pt, String ps, String pfn, String fl){
posterId = pid;
categoryId = cid;
eventId = eid;
presenterFname = prf;
presenterLname = prl;
posterTitle = pt;
posterSynopsis = ps;
posterFilename = pfn;
posterRemoteLocation = fl;
}
public int getPosterID(){
return this.posterId;
}
public int getCatID(){
return this.categoryId;
}
public int getEventId(){
return this.eventId;
}
public String getPresenterFname(){
return this.presenterFname;
}
public String getPresenterLname(){
return this.presenterLname;
}
public String getPosterTitle(){
return this.posterTitle;
}
public String getPosterSynopsis(){
return this.posterSynopsis;
}
public String getPosterFilename(){
return this.posterFilename;
}
public String getPosterRemote(){
return this.posterRemoteLocation;
}
}
You can find the class for a custom adapter to vaguely fit your needs below. This will work in pretty much the same way that you are trying to use the general one in your code sample.
This method will give you more flexibility in the way your information is displayed.
You can set the custom layout in the getView method. As well as set the values in the view from the item number passed in.
public class PosterListAdapter extends BaseAdapter {
private final ArrayList<Poster> listItems;
private final LayoutInflater inflater;
public PosterListAdapter(ArrayList<Poster> listItems, LayoutInflater inflater) {
this.listItems = listItems;
this.inflater = inflater;
}
#Override
public int getCount() {
return this.listItems.size();
}
#Override
public Film getItem(int i) {
return this.listItems.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
view = inflater.inflate(R.layout.poster_layout, viewGroup, false);
}
Poster item = this.listItems.get(i);
TextView posterTitle = ((TextView) view.findViewById(R.id.poster_layout_title));
posterTitle.setText(item.getTitle());
ImageView posterImage = ((ImageView) view.findViewById(R.id.poster_layout_image));
posterImage.setImageResource(R.drawable.apple);
return view;
}
}
Below you will find a simple layout that can be used with the above array adapter for a list view item.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="vertical">
<ImageView
android:id="#+id/poster_layout_image"
android:layout_width="50dp"
android:layout_height="75dp"
android:layout_centerVertical="true"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/poster_layout_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/poster_layout_image"
android:textColor="#color/text"
android:textSize="20sp" />
</RelativeLayout>

Get tags from Radiobuttons in ListView Android

I have a custom listView built with ArrayAdapter. In ListView each item contents a TextView and a RadioGroup (with 4 RadioButton). I can choose one RadioButton to be selected for each list item. On the bottom of ListView i have a footer with button. What i want is to get all data when i click on button like this:
name1 - 1
name2 - 3
name3 - 2
name4 - 3
...
First column - Text from TextView
Second column - Tag of selected RadioButton
Atcivity with view:
public class MarksAdd extends ListActivity {
ArrayList<String> itemlist = new ArrayList<String>();
private Context context = null;
private ListView listView;
private Button BtnDone;
#Override
public void onCreate(Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
setContentView(R.layout.marks_add);
Intent intent = getIntent();
int day = intent.getIntExtra("day", 0);
int month = intent.getIntExtra("month", 0);
int year = intent.getIntExtra("year", 0);
String dayStr = String.valueOf(day);
String monthStr = String.valueOf(month);
String yearStr = String.valueOf(year);
if (day != 0) {
if(dayStr.length()==1){
dayStr = "0"+dayStr;
}
if(monthStr.length()==1){
monthStr = "0"+monthStr;
}
yearStr = yearStr.substring(2);
String date = dayStr+"."+monthStr+"."+yearStr;
Toast.makeText(this, date, Toast.LENGTH_SHORT).show();
}
final ArrayAdapter<Model> adapter = new InteractiveArrayAdapter(this,
getModel());
listView = getListView();
LayoutInflater inflater = getLayoutInflater();
listView.addFooterView(inflater.inflate(R.layout.list_footer, null), null, false);
setListAdapter(adapter);
BtnDone = (Button) findViewById(R.id.markListBtn);
BtnDone.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
//get Values ?????
}
});
}
private List<Model> getModel() {
List<Model> list = new ArrayList<Model>();
dbHelper sql = new dbHelper(this);
SQLiteDatabase db = sql.getWritableDatabase();
Cursor cursor = db.query(
PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("group", ""), new String[]{
"Id", "Name"},
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
"Name ASC" // The sort order
);
while (cursor.moveToNext()) {
// GET COLUMN INDICES + VALUES OF THOSE COLUMNS
int id = cursor.getInt(cursor.getColumnIndex("Id"));
String name = cursor.getString(cursor
.getColumnIndex("Name"));
list.add(get(name));
}
cursor.close();
// Initially select one of the items
return list;
}
private Model get(String question) {
return new Model(question);
}
}
ArrayAdapter:
public class InteractiveArrayAdapter extends ArrayAdapter<Model> {
private final List<Model> list;
private final Activity context;
public InteractiveArrayAdapter(Activity context, List<Model> list) {
super(context, R.layout.simple_list_item1_marks, list);
this.context = context;
this.list = list;
}
class ViewHolder {
TextView t = null;
RadioGroup group;
ViewHolder(View v) {
t = (TextView) v.findViewById(R.id.personName);
group = (RadioGroup) v.findViewById(R.id.myRgroup);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder = null;
if (v == null) {
LayoutInflater inflater = context.getLayoutInflater();
v = inflater.inflate(R.layout.simple_list_item1_marks, parent, false);
holder = new ViewHolder(v);
v.setTag(holder);
final View finalV = v;
holder.group
.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group,
int checkedId) {
Integer pos = (Integer) group.getTag(); // To identify the Model object i get from the RadioGroup with getTag()
// an integer representing the actual position
Model element = list.get(pos);
switch (checkedId) { //set the Model to hold the answer the user picked
case R.id.rb1:
element.current = Model.ANSWER_ONE_SELECTED;
break;
case R.id.rb2:
element.current = Model.ANSWER_TWO_SELECTED;
break;
case R.id.rb3:
element.current = Model.ANSWER_THREE_SELECTED;
break;
case R.id.rb4:
element.current = Model.ANSWER_FOUR_SELECTED;
break;
default:
element.current = Model.NONE; // Something was wrong set to the default
}
}
});
} else {
holder = (ViewHolder) v.getTag();
}
holder.group.setTag(position); // I passed the current position as a tag
holder.t.setText(list.get(position).question); // Set the question body
if (list.get(position).current != Model.NONE) {
RadioButton r = (RadioButton) holder.group.getChildAt(list
.get(position).current);
r.setChecked(true);
} else {
holder.group.clearCheck(); // This is required because although the Model could have the current
// position to NONE you could be dealing with a previous row where
// the user already picked an answer.
}
return v;
}
}
Model:
public class Model {
String question; // hold the question
int current = NONE; // hold the answer picked by the user, initial is NONE(see below)
public static final int NONE = 1000; // No answer selected
public static final int ANSWER_ONE_SELECTED = 0; // first answer selected
public static final int ANSWER_TWO_SELECTED = 1; // second answer selected
public static final int ANSWER_THREE_SELECTED = 2; // third answer selected
public static final int ANSWER_FOUR_SELECTED = 3; // forth answer selected
public Model(String question) {
this.question = question;
}
}
I was doing this according to that tutorial with some changes. Actualy i'm realy newbie in development, so im asking you to help me. Sorry if my question is not correct, my english is not realy good.
Well be very thankfull for any help here.
The first thought would be to iterate over the ListView and get the checked button in each row. This won't actually work because ListView does not contain all of its children all of the time.
Instead, you should store the checked item when the user actually makes a selection. Then when you press the button, you already have all the data stored and don't have to iterate over the ListView. Also, having the current selections saved this way will be useful if you scroll back up the list because you can set the current checked radio button for previous items in getView().
Let's assume the row layout has this in it:
<RadioGroup android:id="#+id/radio_group" ... >
<RadioButton android:id="#+id/radio_button_1" ... />
<RadioButton android:id="#+id/radio_button_2" ... />
<RadioButton android:id="#+id/radio_button_3" ... />
<RadioButton android:id="#+id/radio_button_4" ... />
</RadioGroup>
In your adapter's getView(), give the RadioGroup an OnCheckedChangedListener defined in the adapter itself (so you have one OnCheckedChangedListener instead of one per row). Tag the RadioGroup with the position of the list item so that you can differentiate it in the callback.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
...
Model model = getItem(position);
int checkedId = ... //figure out checked id from model
viewHolder.group.check(checkedId);
viewHolder.group.setTag(position);
viewHolder.group.setOnCheckedChangedListener(checkChangedListener);
...
}
private OnCheckedChangedListener checkChangedListener = new OnCheckedChangedListener() {
#Override
public void onCheckChanged(RadioGroup group, int checkId) {
Object tag = group.getTag();
if (!(tag instanceof Integer)) {
// you have a bug. Fix it!
return;
}
int position = (Integer) tag;
Model model = getItem(position);
switch(checkedId) {
case R.id.radio_button_1:
model.setCurrent(Model.ANSWER_ONE_SELECTED); break;
case R.id.radio_button_1:
model.setCurrent(Model.ANSWER_TWO_SELECTED); break;
case R.id.radio_button_1:
model.setCurrent(Model.ANSWER_THREE_SELECTED); break;
case R.id.radio_button_1:
model.setCurrent(Model.ANSWER_FOUR_SELECTED); break;
}
}
};
Now you just need to get your list of Models from the adapter.

Categories

Resources