the code idea is originally like this , i want to add the persons from android contacts
public final class People{
public static Person[] PEOPLE = {
new Person(1, R.drawable.person1, "Betty Boo", "is having her hair cut at 6pm"),
new Person(1, R.drawable.person2, "Lisa James", "is going to Avicii live ft.. event"),
};
}
in activity
ViewGroup people = (ViewGroup) findViewById(R.id.people);
for(int i = 0; i < People.PEOPLE.length; i++){
people.addView(People.inflatePersonView(this, people, People.PEOPLE[i]));
}
i want to put the items into array from the query , my attempts were as follows
public final class People{
public static Person[] PEOPLE(ContentResolver cr) {
Person[] PEOPLE = {};
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, "starred=?",
new String[] {"1"}, null);
int i=0;
int contactID;
String contactName;
while (cursor.moveToNext()) {
contactID = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
PEOPLE[i] = new Person(contactID, R.drawable.person1, contactName, contactName);
i++;
}
cursor.close();
return PEOPLE;
}
}
thanks !
An array isn't the most appropriate data structure for this, as it cannot be resized to add new elements (well, it can, but you actually need to create a new array and copy the contents -- definitely not suitable for adding items one by one).
I would suggest using a List<Person> instead (using ArrayList or LinkedList as the actual class). More or less like this:
public static List<Person> PEOPLE(ContentResolver cr) {
ArrayList<Person> people = new ArrayList<Person>();
...
while (cursor.moveToNext()) {
...
people.add(new Person(...);
}
return people;
}
To iterate over a List, you can use a for loop:
for (Person person : People.PEOPLE(cr)) {
... person
or, if you prefer, a more traditional
List<Person> people = People.PEOPLE(cr);
for (int i = 0; i < people.size(); i++) {
Person person = people.get(i);
...
Related
I have class called unviersityClient and method name `getallstudent,but how to include them in cursor to get results displayed
this is in mainactivity
public class MainActivity extends ActionBarActivity {
private TextView tv;
private Button bt;
private Context mycontext;
Cursor c;
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.textView1);
bt=(Button)findViewById(R.id.button1);
mycontext=this.getApplication();
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// universityClient.addStudents(mycontext, "christy");
// universityClient.addStudents(mycontext, "joe");
universityClient.getAllStudents(mycontext);
c.moveToFirst();
while(!c.isAfterLast()){
String dir =c.getString(c.getColumnIndex("name"));
tv.setText("Name : "+dir);
c.moveToNext();
}
and this is in .java created by json. it's already created the db
public static Cursor getAllStudents(Context c) {
ContentResolver cr = c.getContentResolver();
String[] result_columns = new String[]{
universityDB.STUDENTS__ID_COLUMN,
universityDB.STUDENTS_NAME_COLUMN,
};
String where = null;
String whereArgs[] = null;
String order = null;
Cursor resultCursor = cr.query(university.STUDENTS_URI, result_columns, where, whereArgs, order);
return resultCursor;
}
if you have all the students in a database you can use this to get all the names and then send them to a variable
String SELECT_QUERY = "SELECT * FROM Tutores t1 INNER JOIN Tutorados t2 ON t1._id = t2.id_tutor and t1._id = " + ET1.getText().toString().trim();
cursor = db.rawQuery(SELECT_QUERY, null);
if (cursor.getCount() != 0) {
if (cursor.moveToFirst()) {
do {
C1 = cursor.getString(cursor
.getColumnIndex("_id"));
C2 = cursor.getString(cursor
.getColumnIndex("name"));
Fin += C1 + "-" + C2 + "\n";
} while (cursor.moveToNext());
}
}
cursor.close();
Fin is a String and you can get all the names or whatever you want from the columns with the getColumnIndex("nameOfTheColumn") and send "Fin" to a textview or something like that
hope that helps!, see ya
Cant understand why you want to put json data in cursor while json parsing is the best way to do the same. If your priority is to bring data somewhere else and fetch one by one using loop, you can use arraylist/hashmap like collection objects. If you have many fields in one json object, you can create a class having those fields and make an arraylist of that having type of class and store data in that. Like this:
1. Fetch single json object at a time, fetch values of fields.
2. create class object by passing those values in constructor.
3. Create arraylist of that class type.
4. put class objects in that arraylist one by one and fetch as well.
ArrayList<Person> person = new ArrayList<Person>();
Person newPerson = new Person("balvier", "27", "Male");
person.add(newPerson);
Person newPersonAnother = new Person("Adel", "20", "FeMale");
person.add(newPersonAnother);
am developing a application which fetches some data from Database..but it shows this error
private void add() {
db = (new DbHelper(this)).getReadableDatabase();
String query = "select * from stock where product = ?";
String list_data;
Cursor c = db.rawQuery(query, new String[] { list_data });
c.moveToFirst();
final CharSequence[] items = new CharSequence[list_data.length()];
for (int i = 0; i < list_data.length(); i++) {
items[i] = list_data[i];//here is the error
}
Try this
db = (new DbHelper(this)).getReadableDatabase();
String query = "select * from stock where product = ?";
String list_data;
Cursor c = db.rawQuery(query, new String[] { list_data });
c.moveToFirst();
final CharSequence[] items = new CharSequence[list_data.length()];
for (int i = 0; i < list_data.length(); i++) {
items[i] = list_data.charAt(i);
}
You can get char from String using charAt(int index) method
Your variable, list_data by virtue of being a String variable cannot be used like an array. When I say it cannot be used as an array, I'm specifically talking about the square brackets you used for referencing individual characters within the string.
items[i] = list_data[i];
As Aniruddh correctly pointed out, you must use the built in charAt() method which is defined under the String class.
items[i] = list_data.charAt(i);
Refer the definition for details-
https://developer.android.com/reference/java/lang/String.html#charAt%28int%29
Cheers.
How to return a list in a column e.g like all emails in column...here my code
public String reTurn() throws SQLException
{
String emails=null;
Cursor mCursor = db.rawQuery("SELECT EmailNO FROM Details_Customer " ,null);
mCursor.moveToFirst();
if(mCursor.getCount() > 0){
emails= mCursor.getString(mCursor.getColumnIndex(DBAdapter.COLUMN_EMAIL));
//password = mCursor.getString(11);
}
return emails;
}
But it only returning one email, I want it to return all the emails in a database
Try this:
public List<String> reTurn() throws SQLException
{
List<String> emails = new ArrayList<String>();
Cursor mCursor = db.rawQuery("SELECT EmailNO FROM Details_Customer ", null);
int index = mCursor.getColumnIndex(DBAdapter.COLUMN_EMAIL);
while(mCursor.moveToNext()) {
emails.add(mCursor.getString(index));
//password = mCursor.getString(11);
}
return emails;
}
Added from comment
From this:
email.putExtra(Intent.EXTRA_EMAIL, new String[]{ dbUser.reTurned});
I guess that your are trying to put the array of email addresses into an Intent called email. Here is a better approach:
public String[] reTurn() throws SQLException
{
Cursor mCursor = db.rawQuery("SELECT EmailNO FROM Details_Customer ", null);
String[] emails = new String[mCursor.getCount()];
int i = 0;
int index = mCursor.getColumnIndex(DBAdapter.COLUMN_EMAIL);
while(mCursor.moveToNext()) {
emails[i++] = mCursor.getString(index);
//password = mCursor.getString(11);
}
return emails;
}
And to put this in an Intent:
email.putExtra(Intent.EXTRA_EMAIL, dbUser.reTurned());
Lastly, in your new Activity read the email array with:
String[] emails = getIntent().getStringArrayExtra(Intent.EXTRA_EMAIL);
Hope that helps.
The problem with your code is inside the if statement.
emails = mCursor.getString(...);
That statement is only being executed once, so you only get one email.
Instead try something like:
String[] emails = new String[mCursor.getCount()];
for(int i=0; i<emails.length; i++){
emails[i] = mCursor.getString(...);
mCursor.moveToNext();
}
You can use the code as follow to get all mail address :
mCursor.moveToFirst();
ArrayList<String> mails = new ArrayList<String>();
if(mCursor.getCount() > 0){
while(!mCursor.isAfterLast()){
mails.add(mCursor.getString(mCursor.getColumnIndex(DBAdapter.COLUMN_EMAIL)));
mCursor.moveToNext();
}
}
They're all available through the Cursor because it's essentially an iterator. See the Cursor API. So you can pass the cursor as you would an array and iterate over it as needed.
If truly necessary you can copy the results into an array:
int n = mCursor.getCount();
String [] emails = new String[n];
int emailColIndex = mCursor.getColumnIndex(DBAdapter.COLUMN_EMAIL);
mCursor.moveToFirst();
for (int i = 0; i < n; i++) {
emails[i] = mCursor.getString(emailColIndex);
mCursor.moveToNext();
}
// A good place to close the cursor.
I'm trying to write an activity that shows the DisplayNames of contacts evolved in SMS conversations.
Unfortunately:
The SMS database doesn't contain the DisplayName
so I used a function that uses the address "phone number" to get the DisplayName
I don't know how to query unique addresses from the SMS database
so I used sorted query, used a loop to find unique DisplayNames, and then put them in an array
If not, is it better to run this process in the background? but how will the activity open if the list is not prepared yet?!
Finally, I used this array in an ArrayAdapter to populate my ListView (pretty much trying to mimic the native Messaging app)
The activity turned out to take a lot of time to open up (around 2-3 seconds, and I don't have much messages)
Is there a way to solve any or both of my problems efficiently?
Here's my code
public class MessagesPicker extends Activity {
Cursor myCursor;
ListView pickerListView;
public static final String MessageAddress = address;
public static final String MessageID = _id;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.picker);
ContentResolver cr = getContentResolver();
myCursor = cr.query(Uri.parse(contentsms), null, null, null, MessageAddress + ASC); //getting sorted data to easy finding uniqueness
/**setting up unique DisplayNames array**/
int allCount = myCursor.getCount(), uniqueCount = 0;
String[] uniqueNames = new String[allCount];
String temp1,temp2;
myCursor.moveToFirst();
temp1 = getContactDiplayNameByAddr();
uniqueNames[uniqueCount++] = temp1;
do {
temp2 = getContactDiplayNameByAddr();
if (temp1.compareTo(temp2) != 0){
uniqueNames[uniqueCount++] = temp2;
temp1 = temp2;
}
}while(myCursor.moveToNext());
String [] valuesArray = new String[uniqueCount]; //filling the array
for (int i = 0 ; i uniqueCount ; i++)
valuesArray[i] = uniqueNames[i];
/**setting up the ListView**/
ArrayAdapterString adapter = new ArrayAdapterString(this, android.R.layout.simple_list_item_multiple_choice, valuesArray);
pickerListView = (ListView)findViewById(R.id.PickerLV); //linking the object to the interface
pickerListView.setAdapter(adapter); //setting the adapter
pickerListView.setItemsCanFocus(false); //allowing to check the checkbox
pickerListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); //allowing multiple choices
}
String getContactDiplayNameByAddr() { //this function returns DisplayName, or if not available, returns the address
String Address = myCursor.getString(myCursor.getColumnIndex(address));
Uri personUri = Uri.withAppendedPath( ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Address);
Cursor cur = getContentResolver().query(personUri,
new String[] {PhoneLookup.DISPLAY_NAME},
null, null, null );
if( cur.moveToFirst() ) {
String DisplayName = cur.getString(cur.getColumnIndex(PhoneLookup.DISPLAY_NAME));
cur.close();
return DisplayName;
}
return Address;
}
}
I have an application where I want to use the values returned from an SQL query against a database in my application. I want to use attach these values to a uri that links to a script on remote host. I am doing a call to the method to retrieve the values, after which I will now extract them. The issue is that I am facing a challenge in going about this. I know a bit of php and what I want in android is done like this in php:
....(preceding code)...$row['email'];
and I can now assign a variable e.g. $email=$row['email'];
How can I do this in android?
I don't want a cursor returned, just the values of the columns as strings.
Below is my code (I will need help to retrieve the password column)
public String[] selectAll()
{
Cursor cursor = db.query(DB_TABLE_NAME, new String[] { "email","password"},null, null, null, null,null);
if(cursor.getCount() >0)
{
String[] str = new String[cursor.getCount()];
int i = 0;
while (cursor.moveToNext())
{
str[i] = cursor.getString(cursor.getColumnIndex("email"));
i++;
}
return str;
}
else
{
return new String[] {};
}
}
I need help on inserting the "password" column so that it will be returned with the email.
try this way
String[][] str = new String[cursor.getCount()][cursor.getColumnCount()];
while (cursor.moveToNext())
{
for(int j=0;j<cursor.getColumnCount();j++)
str[i][j] = cursor.getString(j); /// may be this column start with the 1 not with the 0
i++;
}
you need to store this in two dimenstion array for row wise and column wise
but if this will give only one result everytime
String[] str = new String[cursor.getColumnCount()]; // here you have pass the total column value
while (cursor.moveToNext())
{
str[0] = cursor.getString(cursor.getColumnIndex("email"));
str[1] = cursor.getString(cursor.getColumnIndex("password"));
}
You should change your design like this
public Cursor selectAll() {
Cursor cursor = db.query(DB_TABLE_NAME, new String[] { "email","password"},null, null, null, null,null);
return cursor;
}
and use the selectAll function like this
Cursor cursor=selectAll();
String[] mail = new String[cursor.getCount()];
String[] pass = new String[cursor.getCount()];
int i=0;
while (cursor.moveToNext())
{
mail[i] = cursor.getString(cursor.getColumnIndex("email"));
pass[i] = cursor.getString(cursor.getColumnIndex("password"));
i++;
}