Gallery, sqlite android? - android

I am now stuck at a point and can't find any solution.
Description : I have a sqlite database having a table(channel table) which have 4 column
uid channel_name cid(country id) rating
uid is Unique channel id.
I have three images with star rating if star is yellow then channel have either 4 or 5 rating
if star is half yellow then channel rating is 2 or 3. if star is white then rating 1 will be considered.
I am showing these three images from gallery widgets in android. ant the channel name below star images. according to channel rating.
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
View view = null;
Cursor mCursor=db.dataChannelsName();
mCursor.moveToFirst();
String [] channels_name = new String[mCursor.getCount()];
for(int icount=0; icount<mCursor.getCount();icount++) {
channels_name[icount] = mCursor.getString(mCursor.getColumnIndex("name"));
mCursor.moveToNext();
}
if(paramView == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
view = inflater.inflate(R.layout.items1, null);
ImageView image1 = (ImageView) view.findViewById(R.id.image1);
TextView description = (TextView) view.findViewById(R.id.description);
image1.setImageResource(mImageIds[paramInt]);
description.setTextColor(0xffffffff);
description.setText(channels_name[paramInt]);
} else {
view = paramView;
}
return view;
Question 1:
How will i show only these three images for all channel with different channels name.?
Question 2:
It can be possible to have same name channel in database
I am using sql queries and cursor for retrieving data.
Now my problem is when user will select the particular channel from the gallery then there is a possibility that there can be more than one channel with same name.
I just want to store the uid when user click on the channel name from the gallery??
EDIT I just solved the second question but i am stuck at question 1
any help would be appreciated.

Lets begin fixing some things, shall we?
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
View view = null;
Cursor mCursor=db.dataChannelsName();
mCursor.moveToFirst();
String [] channels_name = new String[mCursor.getCount()];
for(int icount=0; icount<mCursor.getCount();icount++) {
channels_name[icount] = mCursor.getString(mCursor.getColumnIndex("name"));
mCursor.moveToNext();
}
Now the getView Function is called everytime a listView displays a new Row (even when scrolling!!)...I'm assuming db.dataChannelName() fires a query SELECT * from channel (or worse, you might be opening and closing the database)....This is a very expensive operation, you should query it once in the constructor, store the array of channel names as a member variable and use it for the rest of the adapter.
Here's a concise way..
public View getView(int paramInt, View view, ViewGroup paramViewGroup) {
if(view== null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
view = inflater.inflate(R.layout.items1, null);
}
ImageView image1 = (ImageView) view.findViewById(R.id.image1);
TextView description = (TextView) view.findViewById(R.id.description);
image1.setImageResource(mImageIds[paramInt]); // i'm assuming 0 - 0 star, 1 - 1 star, etc...
description.setTextColor(0xffffffff);
description.setText(channels_name[paramInt]); //remember channel_name was obtained in the constructor.
return view
}

Related

How to change color of textView in android listView on comparing JSON data?

I am fetching JSON Data to listView successfully, but i want to change the color of the textView in that listView by comparing JSON data.
For ex-
if in JSON {"status":"approved"} - green color
else if {"status" : "disapproved"} - red color
I'm able to change it using getView in SimpleAdapter but not able to compare strings there.
when i print the status, its is only showing "approved".
i can't filter "disapproved" in else if condition.
SimpleAdapter adapter = new SimpleAdapter(getActivity(), mylist, R.layout.list_leave_approval,
new String[]{
TAG_STATUS
},
new int[]{
R.id.status}) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//return super.getView(position, convertView, parent);
View v = convertView;
if (v == null) {
// View v = convertView;
LayoutInflater vi = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_leave_approval, null);
TextView test = (TextView) v.findViewById(R.id.status);
// String str = jsonObject.getString("status");
Log.d("Day", "get view STATUS: " + strStatus);
// jsonObject = jsonArray.getJSONObject(i);
if (strStatus.equals(" Approved ")) {
test.setBackgroundColor(getResources().getColor(R.color.green));
// txtStatus.setText("DEC");
} else if (strStatus.equals(" Disapproved ")) {
test.setBackgroundColor(getResources().getColor(android.R.color.holo_red_light));
}
}
return super.
getView(position, v, parent);
}
};
list.setAdapter(adapter);
You can do like this.
Here string will be your parsed json string.
JSONObject jObj = new JSONObject(String);
if (jObj.getString("status").equalsIgnoreCase("approved")) {
textView1.setTextColor(Color.GREEN)
} else {
textView1.setTextColor(Color.RED)
}
I advise you to read about MVC design pattern
You should keep your JSON in a data object (model in MVC) for example Status object and put all the needed data from json to this object
When filling the listView adjust the view according to the statuses:
if(items[index].getStatus.equals("approved"))
textView.setTextColor(ContextCompat.getColor(context, R.color.green));
else if(items[index].getStatus.equals("disapproved"))
textView.setTextColor(ContextCompat.getColor(context, R.color.red));
You will need to override a more complex type of Adapter in order to do what you want, SimpleAdapter only allows setting the text in a very simple way as a String.
Something like ArrayAdapter might be a better fit, in that case you could use the code Michael A has shown in the getView method of ArrayAdapter to change the display of the text.
You might also look into SpannableString which allows adding color to text, but this would require being able to provide code to determine the status of the item.

Set onclick to item that isn't visible

So I have been looking around for about 4 hours now and maybe I just don't know how to word my search, but I am not finding out what I need.
I am using a custom adapter to setup my listview from items I have stored into an sqlite database. My cursor sends id, name, product_id, data, datetime to my adapter. But my adapter is set to only display the name, data & datetime.
I need to be able to click on the name, but have it go to my next activity and display the information from the product_id that was sent to the adapter. Example I click on Apples, but it would actually be product_id 505 in my database. Unless I set the product_id to a textview, when I click on my item, it does not bring up the correct listing and searches for Apples.
If this is not clear, please let me know and I will to explain it better.
** EDIT **
So my database is like this
_ID | PRODUCT_NAME | PRODUCT_ID | PRODUCT_DATA | DATE
1 Apples 505 Fresh Apples 123456
2 Oranges 506 Fresh Orange 123456
3 Kiwi 507 Fresh kiwi 123456
4 Nuts 508 Fresh Nuts 123456
My ListView shows this:
Apples- FRESH APPLES - DATE
Oranges - FRESH ORANGE - DATE
Kiwi- FRESH KIWI - DATE
Nuts - FRESH NUTS - DATE
When I click on Apples, I want it to return PRODUCT_ID to me, not _ID, so I can pass that product_id onto my next intent.
My Display listing
public void displayListView()
{
DatabaseOperations db = new DatabaseOperations(this);
Cursor cursor = db.getProducts();
dataAdapter = new MainActivityAdapter(
this,
cursor,
0);
ListView listView = (ListView) findViewById(R.id.product_list);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
// listening to single list item on click
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,
int position, long ID)
{
TextView listText = (TextView) view.findViewById(R.id.name);
String product_name = listText.getText().toString();
Intent i = new Intent(MainActivity.this, product_detail.class);
i.putExtra("productName", product_name);
MainActivity.this.startActivity(i);
}
});
db.close();
}
My Adapter
public class MainActivityAdapter extends CursorAdapter
{
private LayoutInflater cursorInflater;
private Context c;
// Default constructor
public MainActivityAdapter(Context context, Cursor cursor, int flags)
{
super(context, cursor, flags);
cursorInflater = (LayoutInflater) context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
c = context;
// Log.i("Custom-Adapter", "Starting up");
}
public void bindView(View view, Context context, Cursor list)
{
TextView PN = (TextView) view.findViewById(R.id.product_name);
TextView PI = (TextView) view.findViewById(R.id.product_data);
TextView date = (TextView) view.findViewById(R.id.date);
// SET OUR DATA FROM OUR CURSOR
String pn = list.getString( list.getColumnIndex("pn"));
String pi = list.getString( list.getColumnIndex("pi"));;
// NEED TO RECONVERT DATE THEN SHOW IT
Long millidate = list.getLong(list.getColumnIndex("dateTime"));
Date myDateNew = new Date(millidate);
String Sdate = getDate(millidate);
PN.setText(pn);
PI.setText(pi);
date.setText(Sdate);
}
public static String getDate(long milliSeconds)
{
Calendar cl = Calendar.getInstance();
cl.setTimeInMillis(milliSeconds); //here your time in miliseconds
String date = "" + cl.get(Calendar.DAY_OF_MONTH) + ":" + cl.get(Calendar.MONTH) + ":" + cl.get(Calendar.YEAR);
String time = "" + cl.get(Calendar.HOUR_OF_DAY) + ":" + cl.get(Calendar.MINUTE) + ":" + cl.get(Calendar.SECOND);
return date;
}
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
//Log.i("Custom-Adapter", "newView Started");
// R.layout.list_row is your xml layout for each row
return cursorInflater.inflate(R.layout.activity_list, parent, false);
}
I want to get the product_id when I click on the name Apples.
We can achieve it in multiple ways but most common ways are :
Option 1:
Use setTag method for saving id of product with name in TextView :
PN.setText(pn);
PN.setTag((list.getInt(list.getColumnIndex("product_id"))).toString());
Now use getTag method to get clicked product product_id in onItemClick :
String product_name = listText.getText().toString();
int product_id = Integer.parseInt(listText.getTag().toString());
Option 2:
Instead of getting product name from TextView, get clicked row cursor using Adapter in onItemClick :
Cursor cursor = (Cursor) dataAdapter.getItem(position);
String product_name = cursor.getString(cursor.getColumnIndex("pn"));
int product_id = cursor.getInt(cursor.getColumnIndex("product_id"));
....
A good option is to create an array and store product_ids for all the names.
Goto Res->Strings create an array of strings .
then fetch from the array the relevant product_id for the name.

Picasso Only Loading 5 Images until re-using ones in cache

I'm fairly new to android programming. I've run into some issues loading images (bitmaps) into a ListView. It works flawlessly until I have around 5 images loaded, then it reuses the first image I loaded (assuming from cache). I've tried a lot of solutions and bitmap samplings but, still no luck. Here is my code:
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
view = getLayoutInflater().inflate(R.layout.listview_item, parent, false);
Contact currentContact = Contacts.get(position);
TextView name = (TextView) view.findViewById(R.id.contactName);
name.setText(currentContact.getName());
TextView phone = (TextView) view.findViewById(R.id.phoneNumber);
phone.setText(currentContact.getPhone());
TextView email = (TextView) view.findViewById(R.id.email);
email.setText(currentContact.getEmail());
TextView address = (TextView) view.findViewById(R.id.cAddress);
address.setText(currentContact.getAddress());
Context mContext = getApplicationContext();
File file = mContext.getDir("imageDir", Context.MODE_PRIVATE);
String path = "file:" + file.getPath() + "/" + currentContact.getImage() + ".png";
ImageView contactListImage = (ImageView) view.findViewById(R.id.contactListImage);
Picasso.with(getApplicationContext())
.load(path)
.centerInside()
.fit()
.error(R.drawable.user_2)
.into(contactListImage)
}
return view;
}
I did try using
recycleMemoryCache()
Thank in you advance!
You're not using the recycled view correctly.
The view parameter you have there is either null, which means you have to inflate a new one, or not null, which means you should re-use it - assign new values to all the fields etc.
You simply need to move the closing curly-brace above return view; to just after your view inflation:
if (view == null) {
view = getLayoutInflater().inflate(R.layout.listview_item, parent, false);
}
As an aside, I'd look up the viewholder pattern - or just start using RecyclerView, as that enforces it (and is the way of the future for lists on Android).

Android ListView: load items only on scroll

I have a custom adapter for a list view. It has 3 fields: a thumbnail and two text fields.
Once the layout is inflated, the thumbnails are downloaded from an external server.
How do i change the functionality so that the images are downloaded only when the user scrolls down.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Inflate the layout
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_single, parent, false);
ImageView image = (ImageView) rowView.findViewById(R.id.picture);
TextView firstline = (TextView) rowView.findViewById(R.id.firstline);
TextView secondline = (TextView) rowView.findViewById(R.id.secondline);
// Get information about the report
AnimalLocationLog current = objects.get(position);
// Get all the important information
String species = current.getSpecies();
String sanitizedSpecies = MiscHelpers.sanitizeString(species);
int reportId = objects.get(position).getTrackerId();
// Construct the URL to the image
String imageLocation = websiteUrl + sanitizedSpecies + separator + reportId + extension;
// Display user report
downloader.download(imageLocation, image);
firstline.setText(species);
secondline.setText("Spotted " + current.getDateTime().toString("yyyy-MM-dd H:m"));
return rowView;
}
Add an OnScrollListener to your ListView with ListView.setOnScrollListener() and do the download in the ScrollListener.onScroll() method. You can use the ListView.getLastVisiblePosition() to figure out what list items are visible and which aren't.

How to store images in sqlite database and display them?

In my application I need to display questions along with images in Android. I have stored questions in sqlite db and displaying them. I have created a folder DBimages in assets folder. Now all my images are there in DBimages folder.
I have created two classes. I am able to display the question and options from local sqlite db but I am unable to display the image which is stored in assets\DBimages\abc.png.
The names of all the images are stored in pictures column in sqlite db table. But how to display the image related to that particular question. Please help me regarding this.
UserBO.java
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getImage() {
return pictures;
}
public void setImage(String pictures) {
this.pictures = pictures;
}
Select.java
ArrayList<UserBO> usersList = new ArrayList<UserBO>();
for (int i = 0; i < stringList.size(); i++) {
ArrayList<String> list = stringList.get(i);
UserBO user = new UserBO();
try {
user.id = Integer.parseInt(list.get(0));
user.name = list.get(2);
user.question = list.get(3);
user.option1 = list.get(4);
user.option2 = list.get(5);
user.option3 = list.get(6);
user.option4 = list.get(7);
user.option5 = list.get(8);
user.pictures = list.get(9);
user.answer = (list.get(10));
}
catch (Exception e){}
public View getView(int position, View convertView, ViewGroup parent){
View view = convertView;
try{
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.list_item, null);
}
final UserBO listItem = mList.get(position);
if (listItem != null) {
( (TextView) view.findViewById(R.id.tv_question) ).setText( listItem.getQuestion()+"");
((ImageView) view.findViewById(R.id.imageView1)).setImageResource(R.drawable.f);
( (RadioButton) view.findViewById(R.id.option1) ).setText( listItem.getOption1() );
( (RadioButton) view.findViewById(R.id.option2) ).setText( listItem.getOption2()+"" );
( (RadioButton) view.findViewById(R.id.option3) ).setText( listItem.getOption3()+"" );
( (RadioButton) view.findViewById(R.id.option4) ).setText( listItem.getOption4()+"" );
( (RadioButton) view.findViewById(R.id.option5) ).setText( listItem.getOption5()+"" );
}}catch(Exception e){}
return view;
}
}
Some ugly way, to store images in SQLite database. Just store images in sdcard and save the relevant path of those images in SQLite database.
In your need, put the images in either drawable folder or in asset folder then store its
name(with question ID or number also) in SQLite and use it in application.
I had the same problem and i want first to clarify this, storing image path or uri from gallery as string might not give good results when populating or display the data to listview specific the images. You need to store your images on sqlite database as BLOB data types and you need to insert the image to the DB as bytes.
In my case, i tried working with image path from gallery but never worked from me.
Image path is suitable when only your are using urls from a website
You can see an example from this link

Categories

Resources