Retrieving global search results in the code from android global searchable dialog - Java for Android App Development

I am trying to develop a web crawler to using Android searchable following this guide:
Creating a Search Interface | Android Developers
So far, the search results display a new browser screen to display the google results. The guide says that I can get the results in a ListActivity using a ListAdapter. All examples I have seen describe how to create this Adapter for q query from database or contacts on phone, such as:
Code:
public class MyListAdapter extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
// We'll define a custom screen layout here (the one shown above), but
// typically, you could just use the standard ListActivity layout.
setContentView(R.layout.custom_list_activity_view);
// Query for all people contacts using the Contacts.People convenience class.
// Put a managed wrapper around the retrieved cursor so we don't have to worry about
// requerying or closing it as the activity changes state.
mCursor = this.getContentResolver().query(People.CONTENT_URI, null, null, null, null);
startManagingCursor(mCursor);
// Now create a new list adapter bound to the cursor.
// SimpleListAdapter is designed for binding to a Cursor.
ListAdapter adapter = new SimpleCursorAdapter(
this, // Context.
android.R.layout.two_line_list_item, // Specify the row template to use (here, two columns bound to the two retrieved cursor
rows).
mCursor, // Pass in the cursor to bind to.
new String[] {People.NAME, People.COMPANY}, // Array of cursor columns to bind to.
new int[] {android.R.id.text1, android.R.id.text2}); // Parallel array of which template objects to bind to those columns.
// Bind to our new adapter.
setListAdapter(adapter);
}
}
I couldn't find anything to declare a cursor to read from the global search results. I appreciate any help I can get to retrieve the global search results programatically to be able to process it and produce a report about the results, not just the mere listings.

Related

A question about list

Hi.
I am building an app that has a list. All of the clicks on list items result in one activity, like XActivity. XActivity contains a text view. I want that when I click on ListItem1 the text view shows a string forexample string1, then onClickListItem2 it shows string2, onListItemClicX it shows stringX. If it's confusing let me know.
How can I handle it ?
Thanks in advance.
torpedo mohammadi said:
Hi.
I am building an app that has a list. All of the clicks on list items result in one activity, like XActivity. XActivity contains a text view. I want that when I click on ListItem1 the text view shows a string forexample string1, then onClickListItem2 it shows string2, onListItemClicX it shows stringX. If it's confusing let me know.
How can I handle it ?
Thanks in advance.
Click to expand...
Click to collapse
I'm assuming you're using an ArrayAdapter - it would be helpful if you posted some code.
You have to setup an OnItemClickListener for your ListView. In the OnItemClick method, you will have to get the data from the adapter using the position that was clicked. Then create an intent to ActivityX and pass the clicked data.
Code:
[B]ArrayAdapter adapter = new ArrayAdapter();[/B]
listView.setClickable(true);
//Setup the on item click listener for the listview
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Create an intent pointing to XActivity
Intent intent = new Intent(this, XActivity.class);
//Add the clicked string as an extra
intent.putExtra("KEY_CLICKEDSTRING", adapter.getItem(position - 1));
//Start the activity
this.startActivity(intent);
}
});
In ActivityX, simply retrieve the data and set it in the textview:
Code:
@Override
public void onCreate(Bundle savedInstanceState) {
... Activity setup code
TextView textView = findViewById(R.id.yourtextview);
//Get the intent data
String strClicked = getIntent().getStringExtra("KEY_CLICKEDSTRING");
textView.setText(strClicked);
}
Thank you.
But I don't know what value does the "int position" give me ? Forexample does it give the value of "1" or .... ?
I want to know that in order to know which item was clicked and now what to do .
Can anybody help me ?
Thanks in advance.
Like previously mentioned. Post your code and we can help you out better.
not complex, First I make a new ArrayAdapter<string> add adapt it to my listView. Up to know no problem. But in the continue :
// usual codes to answer a click onItemClick(AdapterView<?> av, View v, int position, long id) {
//create a intent as Alkonic said
//My problem }
...
@My problem I want to use a set of codes and understand which item was clicked. I have 41 items and my idea is this :
// getting the text of the clicked item String title = ((TextView)v).getText().toString();
If (title=getString(R.string.theTextIHadAddedToArrayAdapterForItem1)) {
// so item 1 was clicked
//Change the text of thesecond TextView in the second activity ( wich I wrote intent for)
// rewrite the if order 41 times for 41 items
...
But this doesn't work. Can anybody help me ?
@Alconic :
I don't understand the method you wrote for retrieving intent data ( I mean
//Get the intent data String strClicked = getIntent().getStringExtra("KEY_CLICKEDSTRING");
) because the "Key_CLICKEDSTRING" is always constant and one thing. How can I cange it for 41 items ?
Thank you guys anyway.
not complex, First I make a new ArrayAdapter<string> add adapt it to my listView. Up to know no problem. But in the continue :
// usual codes to answer a click onItemClick(AdapterView<?> av, View v, int position, long id) {
//create a intent as Alkonic said
//My problem }
...
@My problem I want to use a set of codes and understand which item was clicked. I have 41 items and my idea is this :
// getting the text of the clicked item String title = ((TextView)v).getText().toString();
If (title=getString(R.string.theTextIHadAddedToArrayAdapterForItem1)) {
// so item 1 was clicked
//Change the text of thesecond TextView in the second activity ( wich I wrote intent for)
// rewrite the if order 41 times for 41 items
...
But this doesn't work. Can anybody help me ?
@Alconic :
I don't understand the method you wrote for retrieving intent data ( I mean
//Get the intent data String strClicked = getIntent().getStringExtra("KEY_CLICKEDSTRING");
) because the "Key_CLICKEDSTRING" is always constant and one thing. How can I cange it for 41 items ?
Thank you guys anyway.
You should post your onItemClick routine. But for going at it blind on our side this is what I would do:
Code:
public void onItemClick(AdapterView<?> av, View v, int pos, long id) {
//Get text from a textview that is on your listview
TextView textView2 = (TextView) v.findViewById(R.id.myTextView);
String txtMytext = textView2.getText().toString();
//Create an intent pointing to XActivity
Intent intent = new Intent(this, XActivity.class);
//Add the clicked string as an extra
intent.putExtra("KEY_CLICKEDSTRING", txtMytext);
//Start the activity
this.startActivity(intent);
}
Without your code, I don't understand what you are comparing with the if statement you posted. Use this along with @Alkonic 's code should get you in the right direction. If it doesn't, we need more code to help better.
torpedo mohammadi said:
not complex, First I make a new ArrayAdapter<string> add adapt it to my listView. Up to know no problem. But in the continue :
// usual codes to answer a click onItemClick(AdapterView<?> av, View v, int position, long id) {
//create a intent as Alkonic said
//My problem }
...
@My problem I want to use a set of codes and understand which item was clicked. I have 41 items and my idea is this :
// getting the text of the clicked item String title = ((TextView)v).getText().toString();
If (title=getString(R.string.theTextIHadAddedToArrayAdapterForItem1)) {
// so item 1 was clicked
//Change the text of thesecond TextView in the second activity ( wich I wrote intent for)
// rewrite the if order 41 times for 41 items
...
But this doesn't work. Can anybody help me ?
@Alconic :
I don't understand the method you wrote for retrieving intent data ( I mean
//Get the intent data String strClicked = getIntent().getStringExtra("KEY_CLICKEDSTRING");
) because the "Key_CLICKEDSTRING" is always constant and one thing. How can I cange it for 41 items ?
Thank you guys anyway.
Click to expand...
Click to collapse
Handling Clicks:
The int position refers to the position of the item that was clicked in the arrayadapter.
Instead of this:
Code:
String title = ((TextView)v).getText().toString();
you can use
Code:
String title = adapter.getItem(position);
That code will take the clicked position and get the clicked string from the adapter.
Intent Data
When you send data with an intent, it has two parts: the Name and Value.
The following code sets the name to a constant "Key_CLICKEDSTRING" and the Value is variable, depending on what was clicked.
Code:
intent.putExtra("KEY_CLICKEDSTRING", adapter.getItem(position));
When you want to access the VALUE, you have to provide the constant name:
Code:
String strClicked = getIntent().getStringExtra("KEY_CLICKEDSTRING");
Hope that helped!

[Q] Issues with adding objects to a photo taken by the user

I've been trying to learn to program for Android lately by simply coming up with ideas and implementing them. It started out easy enough with pulling information from an online RSS feed and showing this in a nice environment. But the current idea has me stumped.
I'd like the following to happen:
Take a picture using intent
Entire picture is shown in a new activity
Zoom in on a certain spot
Add predefined items to the picture
Press next which connects the items from left to right
Add some more items
Press next to connect the new items
Zoom out
Save the image
First taking a picture, this wasn't too hard using the camera intent:
Code:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
I can then extract the absolute path from fileUri with the following line:
Code:
String path = new File(fileUri.getPath()).getAbsolutePath();
This path can be put in a bundle which can be put in an intent which is then used to start the activity that should show the image.
Code:
public class TestActivity extends Activity implements SurfaceHolder.Callback {
private static final String TAG = TestActivity.class.getSimpleName();
private String path = "";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SurfaceView view = new SurfaceView(this);
setContentView(view);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
path = bundle.getString("path");
view.getHolder().addCallback(this);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Canvas canvas = holder.lockCanvas();
if (canvas == null) {
Log.d(TAG,"Can't draw because canvas is null");
}
else {
Bitmap bitmap = BitmapFactory.decodeFile(path);
Paint paint = new Paint();
if(bitmap == null) {
Log.d(TAG,"Can't draw because bitmap is null");
}
else {
canvas.drawBitmap(bitmap,0,0,paint);
}
holder.unlockCanvasAndPost(canvas);
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int frmt, int w, int h) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
}
The first issue here is that it of course doesn't show the entire photo. Not that surprising considering it's larger than the view. Ideally I'd like to zoom out to show the entire photograph. Once I've zoomed one way I'd assume that zooming in on the part that you want should also be possible.
Next is adding the objects. My idea was simply catching any touch events and adding a new object once the finger is released. This way I'd end up with a list of items with each having a draw function which can be called through the surfaceview when it is redrawn.
Connecting these items could simply be done by creating a line object and going through the list of all items and using their locations for the begin and endpoints of the lines
One of the big issues here is that the x and y locations would be relative to the screen, not to the photo. Which would mean that when you zoom back out the entire background would change but the actual items would remain at the same spot and in the same size.
I've been searching and searching for any tutorial or other question about the same issue, but either I've had no luck or I've been using the wrong keywords. And for all I know everything I have up till now could be wrong.
If anyone could give some pointers, or maybe knows a guide or tutorial somewhere or some better keywords I could use for searching I'd really appreciate it.
Xylon- said:
One of the big issues here is that the x and y locations would be relative to the screen, not to the photo. Which would mean that when you zoom back out the entire background would change but the actual items would remain at the same spot and in the same size.
Click to expand...
Click to collapse
would you just not need to either control or track the sample/scale if the image so that you know the 1st pixel displayed (top left) and the scale factor, then the eventX/Y can be processed to be relative to what you want ?

ListView in Fragment not displaying

Hello, I am hoping someone can point out anything I might be doing wrong that is causing my issue. (seems hard to find "best practice" type of advise for newer android features)
My problem is that a ListView which is inside a fragment, controlled by a ViewPager does not get displayed on the screen if I swipe to the next fragment. (but a TextView inside the same fragment shows up fine on all fragment instances),
To set the scene, I have only one fragment class out of which I instantiate all the fragments used by the ViewPager.
Inside the fragments onActivityCreated I create a cursor loader and a custom cursor adapter and on the loaders onLoadFinished I swap the cursor as its supposed to be. Naturally the customCursorAdapter that I created handles the inflation of the listView row in the newView method and binds the data from the cursor in the bindView method.
Does this sound right? I mean I did it this way with the intent of not having tight coupling, having the fragment be independent. So why won't it draw out the listview for subsequent pages? From what I have seen in the logs, all methods get called for all fragments, including getItem, newView, bindView etc.
Final quirk is that the "previous" fragmet's listView does get drawn. Meaning I start on Fragment 1 - listView is there. Move to fragment 2 - listview not there, move to fragment 3 list view not there, move back to fragment 2 list view IS there now, and back to fragment 1 it is NOT there anymore.
I don't have time to post code right now but will as soon as I get a chance.
Thank you all.
Code:
//main activity which creates the view pager and adapter and starts the process
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG,"onCreate begin");
super.onCreate(savedInstanceState);
setContentView(R.layout.pager_task_tracking);
viewPager = (ViewPager) findViewById(R.id.pager);
FragmentManager fragmentManager = getSupportFragmentManager();
MyPagerAdapter myPagerAdapter = new MyPagerAdapter(fragmentManager);
viewPager.setOffscreenPageLimit(0); // trying to force drawing of fragments
viewPager.setAdapter(myPagerAdapter);
Log.d(TAG,"onCreate viewPager done");
//MyPagerAdapter getItem (extends FregmentSatePagerAdapter
public Fragment getItem(int i) {
Log.d(TAG,"getItem called with item:"+i);
return TaskListFragment.newInstance(i);
}
//fragment onActivityCreated , this fragment instanciated in getView of viewPager
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d(TAG, "onActivityCreated with datePointer:"+datePointer);
TextView textViewFragmentTitle = (TextView) getView().findViewById(R.id.fragmentTitle);
textViewFragmentTitle.setText("DATE:"+datePointer);
loaderManager = getLoaderManager();
list = (ListView) getActivity().findViewById(R.id.TaskListView);
customAdapter = new CustomCursorAdapter(getActivity(), null, 1 , datePointer);
list.setAdapter(customAdapter);
loaderID = datePointer; //attempt to get fragment listview to draw - not working
loaderManager.initLoader(loaderID, null, this);
}
///cursor loader onFinish
public void onLoadFinished(android.support.v4.content.Loader<Cursor> loader,
Cursor newCursor) {
Log.d(TAG, "onLoadFinished:"+datePointer);
if (customAdapter != null && newCursor != null ){
Log.d(TAG, "onLoadFinished swapCursor:"+datePointer);
customAdapter.swapCursor(newCursor);
//doesnt help customAdapter.notifyDataSetChanged();
} else {
Log.v(TAG,"OnLoadFinished: mAdapter is null");
}
}
//MyCustomCursorAdapter (used by the listview inside the fragment above)
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View retView = inflater.inflate(R.layout.task_list_item_layout, null);
RelativeLayout.LayoutParams relativeLayoutParameters;
Log.d(TAG,"newView layout inflated:"+datePointer);
return retView;
}
///bindView of same MyCustomCursorAdapter
public void bindView(View view, Context context, Cursor cursor) {
Log.d(TAG,"bindView:"+datePointer);
TextView tvName = (TextView) view.findViewById(R.id.textviewItemName);
tvName.setText(cursor.getString(cursor.getColumnIndex(DBHelper.C_TASK_NAME))+" ["+datePointer+"]");
}
Also check out the LogCat logs with description of the action in the name corresponding to the log statements in the code above.
I noticed more detail about what happens (if you look at the logcat you will see also)
When the screen is displayed the first fragment has the listview present, but the fragment has the id/datePointer (same thing) of "0" BUT the listview items have an id/datePointer of "1"
If you look at the initial logcat you will see "newView layout inflated:1" but no "newView layout inflated:0" how this is being skipped I have no idea. And how the id's can be mix-matched between fragment instances baffles me.
And lastly, after scrolling right twice (to the 0,1, 2nd fragment) it did not have the listview as reported, but scrolling BACK ONE the listview shows up in the 1st fragment ... but even more baffling with lisvtView items that report being part of the "0" fragment .... whaaaat?
Why are you using a listview inside fragment when you have listfragment available?
EatHeat said:
Why are you using a listview inside fragment when you have listfragment available?
Click to expand...
Click to collapse
EatHeat, I am doing this for the sake of flexibility for adding additional controls/views to the fragment besides just a list view (Example I envision adding several buttons to the bottom of the fragment/screen which will be "outside" the listview.
Does it make more sense what I am doing now? That is exactly one of the questions I have, its so hard to find advise on what makes more sense when it comes to these complex combinations of viewPager+fragments+custom listViews+loaders
So my current flow is:
1--Activity (creates ViewPager with myPagerAdapter)
2----ViewPager in itst getItem method instantiates a fragment from class TaskListFragment
3-------The fragment in it's onActivityCreated instantiates a CustomCursorAdapter (with null cursor) and initializes a loader
4-------The loader swaps the cursor in it's onLoadFinished (and this is supposed to populate the listview)
Items 2-4 repeat for every "swipe" or every fragment instantiated.
-The listView control XML is defined in an XML file which is used by the fragment's setContentView
-The lisView row layout XML is defined in a separate XML file inflated by the customCursorAdapter's newView method.
SOLVED: (after literally one week of headache and rewriting the code in every way I know)
the fragments onCreateView I had it getting the listview with getActivity() .. but I should have done it with getView()
the solution was replacing this line
Code:
list = (ListView) getActivity().findViewById(R.id.TaskListView);
with this line
Code:
list = (ListView) getView().findViewById(R.id.TaskListView);
That was it!!! all the headache!!
I don't particularly understand what getView does as opposed to getActivity .. but right now I am pleased it works.
Hi Can u please provide me the code .. I an working on same thing .. bt my getView Function is not called ..
Email : [email protected]
Make sure you custom pager adapter returns all pages as per count.
Use recyclerview in fragments
Sent from my Lenovo A6000 using Tapatalk
The offscreen page limit is by default 1. It is useless to set the limit lesser equals as 1.
Code:
viewPager.setOffscreenPageLimit(0);

Dynamically refresh ListView with CursorAdapter

Hi everyone,
First of all, I'd like to apologize if I'm posting this in a wrong place... This is my first post, I'm still getting familiar with this forum.
I would also like to apologize for the lengthy post.
The title, to a certain extent, reflects what my problem is, but to clarify:
I'm learning Android, so I'm making a simple SMS app for practice.
In it, I have a database which has tables for sent messages, received messages and contacts. I have 3 separate activities (which do NOT extend ListActivity) which show lists for sent messages, received messages and contacts, respectively. The lists are populated through CursorAdapter.
Let's consider the activity for contacts...
In it I have list (ListView) which displays contacts (each list element displays name and phone number). Below the list I have a "Add Contact" button. When I click the button a dialog pops up and shows the form for adding new contact. The buttons in the dialog preform all the database operations.
Similarly, when I click some item in the ListView, another dialog pops up. That dialog has buttons for "Send SMS", "Edit" and "Delete" contact. Again, the buttons do all the work with the database.
The trouble:
My trouble is... When I add a new contact, or delete one (after both operations their dialogs dismiss), the ListView is not refreshed.
In order to see the refreshed list I need to close the activity and start it again.
I googled and googled this for 3 days now, and all the answers I found say that I need to call
Code:
adapter.notifyDataSetChanged
and
Code:
adapter.changeCursor
but that doesn't do the trick.
I'll now post the relevant code with the two methods mentioned above. I placed them where i thought they should be, but this doesn't work.
So, I humbly beg someone to guide me through this ordeal.
Many thanks in advanced!
Here comes the code:
The Adapter:
Code:
public class AdapterContactListView extends CursorAdapter {
private MyDatabaseHelper mdbh;
private LayoutInflater myLayoutInflater;
public AdapterContactListView(Context context, Cursor c, int flags) {
super(context, c, flags);
mdbh = MyDatabaseHelper.getMyDatabaseHelper(context);
myLayoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// TODO Auto-generated method stub
TextView fullNameTV = (TextView)view.findViewById(R.id.contactElementNameTV);
TextView phoneNumberTV = (TextView)view.findViewById(R.id.contactElementNumberTV);
String fullName = cursor.getString(cursor.getColumnIndex(mdbh.getContactFirstName()));
fullName = fullName.concat(" ");
fullName = fullName.concat(cursor.getString(cursor.getColumnIndex(mdbh.getContactLastName())));
String phoneNumber = cursor.getString(cursor.getColumnIndex(mdbh.getContactPhoneNumber()));
fullNameTV.setText(fullName);
phoneNumberTV.setText(phoneNumber);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
return myLayoutInflater.inflate(R.layout.contact_element, parent, false);
}
}
And the Activity:
Code:
public class ContactsActivity extends Activity {
private MyUtilities myUtilities;
private MyDatabaseHelper mdbh;
private AdapterContactListView contactsAdapter;
private ListView contactsListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
mdbh = MyDatabaseHelper.getMyDatabaseHelper(this);
myUtilities = new MyUtilities(this);
contactsAdapter = new AdapterContactListView(this,mdbh.getContactsCursor(),CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
contactsListView = (ListView)findViewById(R.id.contactActivityLV);
contactsListView.setAdapter(contactsAdapter);
contactsListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
TextView phoneNumberTV = (TextView)view.findViewById(R.id.contactElementNumberTV);
String phoneNumber = phoneNumberTV.getText().toString();
Contact contact = mdbh.getContactFromPhoneNumber(phoneNumber);
Dialog d = myUtilities.createSelectedContactOptionsDialog(contact);
d.show();
contactsAdapter.changeCursor(mdbh.getContactsCursor());
contactsAdapter.notifyDataSetChanged();
}
});
}
public void addContact(View view) {
Dialog d = myUtilities.createAddContactDialog();
d.show();
contactsAdapter.changeCursor(mdbh.getContactsCursor());
contactsAdapter.notifyDataSetChanged();
}
}
djolec987 said:
Hi everyone,
Click to expand...
Click to collapse
Well notifyDatasetChanged only informs the adapter that the backing interface has new data... but your backing it with a cursor... so in your case it would just cause getView/bindView to be called for all current visible items, thus fire a query at the cursor. I think the cursor will cache the data so it's really a reload on the cursor data and then an adapter notify call you want... If you use loader (depending on target api version) then it should do most of this for you. As it stands if you want to do it manually make sure the cursor is a new cursor of the database that has changed.
(typed in a rush)

[Q] Updating Image in list adapter

I have the following code that successfully updates parts of my layout from values in an SQLite table
Code:
helper = new TaskDBHelper(Overview.this);
SQLiteDatabase sqlDB = helper.getReadableDatabase();
Cursor cursor = sqlDB.query(TaskContract.TABLE,
new String[]{TaskContract.Columns._ID, TaskContract.Columns.TASK, TaskContract.Columns.BAL, TaskContract.Columns.IP, TaskContract.Columns.STATUS},
null, null, null, null, null);
listAdapter = new SimpleCursorAdapter(
this,
R.layout.sum_view,
cursor,
new String[]{TaskContract.Columns.TASK, TaskContract.Columns.BAL, TaskContract.Columns.IP, TaskContract.Columns.STATUS},
new int[]{R.id.taskTextView, R.id.txtData, R.id.txtIP, R.id.txtStatus},
0
);
this.setListAdapter(listAdapter);
I am trying to set an image based on the value of one of the fields. The status column will return 1, 2 or 3 and I have 3 images that correspond, to display. Can anyone help me and explain how I can fit this into what I am already doing please?
calnaughtonjnr said:
I have the following code that successfully updates parts of my layout from values in an SQLite table
Code:
helper = new TaskDBHelper(Overview.this);
SQLiteDatabase sqlDB = helper.getReadableDatabase();
Cursor cursor = sqlDB.query(TaskContract.TABLE,
new String[]{TaskContract.Columns._ID, TaskContract.Columns.TASK, TaskContract.Columns.BAL, TaskContract.Columns.IP, TaskContract.Columns.STATUS},
null, null, null, null, null);
listAdapter = new SimpleCursorAdapter(
this,
R.layout.sum_view,
cursor,
new String[]{TaskContract.Columns.TASK, TaskContract.Columns.BAL, TaskContract.Columns.IP, TaskContract.Columns.STATUS},
new int[]{R.id.taskTextView, R.id.txtData, R.id.txtIP, R.id.txtStatus},
0
);
this.setListAdapter(listAdapter);
I am trying to set an image based on the value of one of the fields. The status column will return 1, 2 or 3 and I have 3 images that correspond, to display. Can anyone help me and explain how I can fit this into what I am already doing please?
Click to expand...
Click to collapse
can u explain more .
but what i understand is , u need to implement custom adapter so it will be good to set
hisee said:
can u explain more .
but what i understand is , u need to implement custom adapter so it will be good to set
Click to expand...
Click to collapse
The code I used works great and one of the textboxes it fills will be a number. 1, 2 or 3. I want to display an image in the row also. I have 3 images in my drawables folder (one.png, two.png, three.png). I want to display the correct one depending on the number that was returned to R.id.txtStatus
What i would do is as follows:
Create a new class named Item for example which contains five attributes: four strings which contain the texts for the four textviews and one int where you save the image number.
Then you need a custom implementation of ArrayAdapter, using an arraylist of Items (or however you name your holder class).
In the adapter you can then assign the textviews their corresponding contents by using item.getStatus etc and you check the int that contains the image number and assign the imageview the correct image.
Edit:
Here is the implementation i am using in my app with "Row" as my custom holder class, i don't use an imageview but you can easily add this:
package com.masrepus.vplanapp;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.io.Serializable;
import java.util.ArrayList;
/**
* Created by samuel on 27.07.14.
*/
public class MySimpleArrayAdapter extends ArrayAdapter implements Serializable {
private final ArrayList<Row> list;
/**
* Constructor for the custom arrayadapter
*
* @param activity used for method-calls that require a context parameter
* @param list a Row ArrayList that has to be parsed into a listview
*/
public MySimpleArrayAdapter(Activity activity, ArrayList<Row> list) {
super(activity, R.layout.vplan_list, list);
this.list = list;
}
/**
* Puts the klasse, stunde and status attributes of a row object into the right textviews in a listview item
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
ViewHolder view;
if (rowView == null) {
//get a new instance of the row layout view
rowView = View.inflate(getContext(), R.layout.vplanlist_element, null);
//hold the view objects in an object, that way they don't need to be "re- found"
view = new ViewHolder();
view.klasseView = (TextView) rowView.findViewById(R.id.grade);
view.stundeView = (TextView) rowView.findViewById(R.id.stunde);
view.statusView = (TextView) rowView.findViewById(R.id.status);
rowView.setTag(view);
} else {
view = (ViewHolder) rowView.getTag();
}
//put data to the views
Row item = list.get(position);
view.klasseView.setText(item.getKlasse());
view.stundeView.setText(item.getStunde());
view.statusView.setText(item.getStatus());
return rowView;
}
/**
* Used to distribute klasse, stunde, status to the right textviews
*/
protected static class ViewHolder {
protected TextView klasseView;
protected TextView stundeView;
protected TextView statusView;
}
}
Click to expand...
Click to collapse
--------------------
Phone: Nexus 4
OS: rooted Lollipop LRX21T
Bootloader: unlocked
Recovery: TWRP 2.8.2.0

Categories

Resources