update textview in oncreate android - android

hi frnds i have a button and a textview in a whole view,when i click the button then all contact are sved in csv file but i wnt when these contact are going to csv file it update text as "exporting 3 (this count is changingmeans 1 2 3 4 5....till total no of contacts) contcts " means text view is changing when i click button then how to do it
the code for getting total no. of contacts in phone is below...
update:
#Override
protected Boolean doInBackground(String... args) {
int count;
CSVWriter writer = null;
try
{
writer = new CSVWriter(new FileWriter(Environment.getExternalStorageDirectory().getAbsolutePath() + "/my_test_contact.csv"));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String displayName;
String number;
String emailid;
long _id;
String columns[] = new String[]{ ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
writer.writeColumnNames(); // Write column header
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
columns,
null,
null,
ContactsContract.Data.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
startManagingCursor(cursor);
if(cursor.moveToFirst()) {
do {
_id = Long.parseLong(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)));
displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)).trim();
number = getPrimaryNumber(_id);
emailid=getEmailid(_id);
writer.writeNext((displayName + "/" + number+ "/" + emailid).split("/"));
}
while(cursor.moveToNext());
csv_status = true;
} else {
csv_status = false;
}
try {
if(writer != null)
writer.close();
} catch (IOException e)
{
Log.w("Test", e.toString());
}
return null;
}

insert this code anywhere in activity
doInBackground :
Runnable myRun = new Runnable(){
public void run(){
int count;
CSVWriter writer = null;
try
{
writer = new CSVWriter(new FileWriter(Environment.getExternalStorageDirectory().getAbsolutePath() + "/my_test_contact.csv"));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String displayName;
String number;
String emailid;
long _id;
String columns[] = new String[]{ ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
writer.writeColumnNames(); // Write column header
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
columns,
null,
null,
ContactsContract.Data.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
startManagingCursor(cursor);
int i = 1;
if(cursor.moveToFirst()) {
do {
publishProgress() //<<<< DO THIS
_id = Long.parseLong(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)));
displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)).trim();
number = getPrimaryNumber(_id);
emailid=getEmailid(_id);
writer.writeNext((displayName + "/" + number+ "/" + emailid).split("/"));
}
while(cursor.moveToNext());
csv_status = true;
} else {
csv_status = false;
}
try {
if(writer != null)
writer.close();
} catch (IOException e)
{
Log.w("Test", e.toString());
}
////////////////// end loop
}
}
onProgressUpdate()
runOnUiThread(new Runnable() {
public void run(){
TEXTVIEW.setText("GETTING contact"+integer);//update text! /// here
}
});

Related

Create gmail contact group in android

In my android application i have try to create a gmail group but not able to create
the way i have tried is below
ArrayList<ContentProviderOperation> opsGroup = new ArrayList<ContentProviderOperation>();
opsGroup.add(ContentProviderOperation
.newInsert(ContactsContract.Groups.CONTENT_URI)
.withValue(ContactsContract.Groups.TITLE, GroupTitle)
.withValue(ContactsContract.Groups.GROUP_VISIBLE, 1)
.withValue(ContactsContract.Groups.ACCOUNT_NAME, "sarobrindha")//my gmail name
.withValue(ContactsContract.Groups.ACCOUNT_TYPE,
"gmail.com")
.withValue(ContactsContract.Groups.SHOULD_SYNC, true)
.build());
try {
con.getContentResolver().applyBatch(ContactsContract.AUTHORITY,
opsGroup);
} catch (Exception e) {
e.printStackTrace();
}
What mistake i have done.
Kindly help me to figure out
Thanks
You may simply make DB Queries to do so.
make a look into this method:
private Boolean createGrp(String GroupName) {
// TODO Auto-generated method stub
String s = "";
for (int i = 0; i < InteractiveArrayAdapter.list.size(); i++) {
if (InteractiveArrayAdapter.list.get(i).isSelected()) {
s = s + i + " ";
}
}
String s1 = null;
s1 = editText.getText().toString();
// Check the edittext is empty or not
if (s1.equals("")) {
Toast.makeText(getActivity(), "Please Enter Any Text", Toast.LENGTH_SHORT).show();
return false;
}
// Check the Group is available or not
Cursor groupCursor = null;
String[] GROUP_PROJECTION = new String[] {
ContactsContract.Groups._ID, ContactsContract.Groups.TITLE
};
groupCursor = getActivity().managedQuery(ContactsContract.Groups.CONTENT_URI, GROUP_PROJECTION, ContactsContract.Groups.TITLE + "=?", new String[] {s1}, ContactsContract.Groups.TITLE + " ASC");
Log.d("*** Here Counts: ", "** " + groupCursor.getCount());
if (groupCursor.getCount() > 0) {
Toast.makeText(getActivity(), "Group is already available", Toast.LENGTH_SHORT).show();
return false;
} else {
// Toast.makeText(Create_Group_Main_Page.this, "Not available", Toast.LENGTH_SHORT).show();
// Here we create a new Group
try {
ContentValues groupValues = null;
ContentResolver cr = getActivity().getContentResolver();
groupValues = new ContentValues();
groupValues.put(ContactsContract.Groups.TITLE, s1);
cr.insert(ContactsContract.Groups.CONTENT_URI, groupValues);
Log.d("########### Group Creation Finished :", "###### Success");
} catch (Exception e) {
Log.d("########### Exception :", "" + e.getMessage());
return false;
}
}
groupCursor.close();
groupCursor = null;
Log.d(" **** Contacts add to Groups...", "**** Fine");
String groupID = null;
Cursor getGroupID_Cursor = null;
getGroupID_Cursor = getActivity().managedQuery(ContactsContract.Groups.CONTENT_URI, GROUP_PROJECTION, ContactsContract.Groups.TITLE + "=?", new String[] {s1}, null);
Log.d("**** Now Empty Cursor size:", "** " + getGroupID_Cursor.getCount());
getGroupID_Cursor.moveToFirst();
groupID = (getGroupID_Cursor.getString(getGroupID_Cursor.getColumnIndex("_id")));
Log.d(" **** Group ID is: ", "** " + groupID);
getGroupID_Cursor.close();
getGroupID_Cursor = null;
for (int i = 0; i < InteractiveArrayAdapter.list.size(); i++) {
if (InteractiveArrayAdapter.list.get(i).isSelected()) {
cursor.moveToPosition(i);
String contactID = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
long contact = Long.parseLong(contactID);
long group = Long.parseLong(groupID);
addToGroup(contact, group);
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
Log.d(" **** Contact Added: ", "* :" + name);
}
}
return true;
}

Getting a unique row in SQLite

I am trying to search an item in sqlite by using String, & trying to return description contained in that row. items are stored in the table named Articles with column name A_name, Description column name is AS_name
This is my code, the cursor is not null, but the while loop is not getting executed once
public String searchData(String text)
{
Cursor cursor = sdb.query("Articles", new String[] {"A_name","AS_name"}, " A_name=?",new String[]{text}, null, null, null);
Log.e("running", "cursor run");
String temp = null,temp2 = null;
if(cursor!=null)
{
Log.e("running", "curosr is not null");
while(cursor.moveToFirst())
{
Log.e("running", "curosr while loop enter");
temp = (cursor.getString(cursor.getColumnIndex("A_name")));
//temp2 =(cursor.getString(cursor.getColumnIndex("AS_name")));
Log.e("running", "id email" +temp+ " name"+temp2);
}
}
return temp;
}
I want to return the corresponding element of AS_name, also I am confused what should I wrote in while loop ?
Can anyone please identify my mistake, Thanks in advance...
UPDATE DBAdapter.java
public class DBAdapter extends SQLiteOpenHelper
{
//CustomAdapter adapter;
static String name = "law6.sqlite";
static String path = "";
static ArrayList<GS> gs;
static SQLiteDatabase sdb;
#Override
public void onCreate(SQLiteDatabase db)
{
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
}
private DBAdapter(Context v)
{
super(v, name, null, 1);
path = "/data/data/" + v.getApplicationContext().getPackageName() + "/databases";
}
public boolean checkDatabase()
{
SQLiteDatabase db = null;
try
{
db = SQLiteDatabase.openDatabase(path + "/" + name, null, SQLiteDatabase.OPEN_READONLY);
} catch (Exception e)
{
e.printStackTrace();
}
if (db == null)
{
return false;
}
else
{
db.close();
return true;
}
}
public static synchronized DBAdapter getDBAdapter(Context v)
{
return (new DBAdapter(v));
}
public void createDatabase(Context v)
{
this.getReadableDatabase();
try
{
InputStream myInput = v.getAssets().open(name);
// Path to the just created empty db
String outFileName = path +"/"+ name;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0)
{
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
/*
InputStream is = v.getAssets().open("quiz.sqlite");
// System.out.println(is.available());
System.out.println(new File(path + "/" + name).getAbsolutePath());
FileOutputStream fos = new FileOutputStream(path + "/" + name);
int num = 0;
while ((num = is.read()) > 0) {
fos.write((byte) num);
}
fos.close();
is.close();*/
} catch (IOException e)
{
System.out.println(e);
}
}
public void openDatabase()
{
try
{
sdb = SQLiteDatabase.openDatabase(path + "/" + name, null,
SQLiteDatabase.OPEN_READWRITE);
} catch (Exception e)
{
System.out.println(e);
}
}
public ArrayList<GS> getData()
{
try{
Cursor c1 = sdb.rawQuery("SELECT DISTINCT * FROM Articles", null);
gs = new ArrayList<GS>();
while (c1.moveToNext())
{
GS q1 = new GS();
q1.setId(c1.getString(0));
q1.setA_id(c1.getString(1));
q1.setA_name(c1.getString(2));
q1.setAS_name(c1.getString(3));
q1.setDesc_art(c1.getString(4));
// q1.setAct(c1.getString(5));
q1.setExtra(c1.getString(6));
q1.setPart(c1.getString(7));
q1.setItalic(c1.getString(8));
Log.v("AS_name",q1.AS_name);
gs.add(q1);
}
}
catch (Exception e) {
e.printStackTrace();
}
return gs;
}
public String searchData(String text)
{
Cursor cursor = sdb.query("Articles", new String[] {"A_name","AS_name"}, " A_name=?",new String[]{text}, null, null, null);
Log.e("running", "cursor run");
String temp = null,temp2 = null;
if(cursor!=null)
{
Log.e("running", "curosr is not null");
Log.v("", ""+cursor.getCount());
while(cursor.moveToNext())
{
Log.e("running", "curosr while loop enter");
temp = (cursor.getString(cursor.getColumnIndex("AS_name")));
// temp2 =(cursor.getString(cursor.getColumnIndex(name)));
Log.e("running", "desc" +temp);
}
}
return temp;
}
}
UPDATE after implementing rajaji answer, I got this error :
try this it will help you
create the raw query for getting the data
public String searchData(String text)
{
String strvalue=null;
SQliteDatabase db=this.getwritabledatabase();
Cursor cur=null;
String strquery="select * from youurtablename where A_name="+text;
cur=db.rawQuery(strquery,null);
if(cur!=null&&cur.moveToFirst())
{
do
{
strvalue=cur.getString(0);
}
while(cur.moveToNext());
}
}
let me inform once you complete
Is your Uri correct??
create Uri depends on your package name and table name, like the code below :
private static final String AUTHORITY = "com.sample.test_db_provider";
private static final String BASE_PATH = "Tables";
private static final Uri Sample_URI = Uri.parse("content://" + AUTHORITY
+ "/" + BASE_PATH
+ "/SampleTable");
Then in your get Method, query the db like the below code with Uri
cur = m_Resolver.query(Sample_URI, new String[] {"A_name","AS_name"},
"SampleTable.A_name = " + text, null, null);
if(cur != null && cur.moveToFirst())
{
do
{
...
}
while(cur.moveToNext());
}
cur.close();
I use the inline where clause but you can do it your way with a parameter. Is this what you are looking for?

Is there any solution to load phone messages in an activity?

I'd like to load messages from phone in my activity. I search for solution, but I can`t find any.
Use this :
private String SmsDetails(Application mContext) {
// TODO Auto-generated method stub
smsInbox = new ArrayList<Entry>();
final Uri SMS_Inbox = Uri.parse("content://sms/inbox");
String smsHistory = "";
try {
String sDirection = "1";
String sMessageType = "0";
String SMS_READ_COLUMN = "read";
String SORT_ORDER = " _id ASC";
int count = 0;
Cursor cursor;
int iLastIDRun = 0;
// "address = '+9180009'"
cursor = mContext.getContentResolver().query(
SMS_Inbox,
new String[] { "_id", "thread_id", "address", "person",
"date", "body" },
" _id > " + String.valueOf(iLastIDRun), null,
SORT_ORDER);
sMessageType = "1";
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
do {
String address = cursor.getString(2);
long timestamp = cursor.getLong(4);
String sBody = cursor.getString(5);
if (address.startsWith("1")) {
address = address.substring(1);
}
//store the required details
} while (cursor.moveToNext());
}
} catch (Exception e) {
e.printStackTrace();
}
cursor.close();
}
doCheckSmsHistory();
} catch (Exception e) {
e.printStackTrace();
}
return smsHistory;
}

MediaStore doesn't give me size, resolution, duration, and date of video files

I'm trying to retrieve info about user videos stored in sdcard, and I've this method:
protected void addVideo () {
cursor = cr.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
mediaColumns, null, null, null);
if (cursor.moveToFirst()) {
int i = 1;
do {
VideoItem newVVI = new VideoItem();
int id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Video.Media._ID));
newVVI.idthumb = cursor.getString(cursor
.getColumnIndex(MediaStore.Video.Thumbnails._ID));
Cursor thumbCursor = cr.query(
MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
thumbColumns, MediaStore.Video.Thumbnails.VIDEO_ID
+ "=" + id, null, null);
if (thumbCursor.moveToFirst()) {
newVVI.thumbPath = thumbCursor.getString(thumbCursor
.getColumnIndex(MediaStore.Video.Thumbnails.DATA));
}
newVVI.filePath = cursor.getString(cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
newVVI.title = cursor.getString(cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));
try {
newVVI.date = cursor.getString(cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DATE_TAKEN));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
newVVI.date = "0";
}
try {
newVVI.duration = cursor.getString(cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
newVVI.duration = "0";
}
try {
newVVI.size = cursor.getString(cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
newVVI.size = "0";
}
try {
newVVI.resolution = cursor.getString(cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.RESOLUTION));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
newVVI.resolution = "0";
}
newVVI.mimeType = cursor
.getString(cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE));
newVVI.id = Integer.toString(i);
ITEMS.add(newVVI);
ITEM_MAP.put(newVVI.id, newVVI);
i++;
} while (cursor.moveToNext());
cursor.close();
} else {
Log.d("TEST", ": else);
}
}
The problem is that for MediaStore.Video.Media.DATE_TAKEN, MediaStore.Video.Media.DURATION,MediaStore.Video.Media.SIZE, and MediaStore.Video.Media.RESOLUTION I got always "0" because for these I always catch the IllegalArgumentException.
Why?
The values are 0 because that is the default and they were never set to be anything else.
The MediaStore does not automatically calculate these values when a video is copied to sdcard.
For duration you could try using MediaPlayer to load the video and then call getDuration.
this code return info from one special audio.but it worked truely.
you can change it acording to my main Question whit while statement for get all audios or videos.
you must change MediaStore.audio in my response to Mediastore.Video.
String name="";
String duration="";
String path="";
Log.d("Loading file: " + filepath,"");
// This returns us content://media/external/videos/media (or something like that)
// I pass in "external" because that's the MediaStore's name for the external
// storage on my device (the other possibility is "internal")
Uri audiosUri = MediaStore.Audio.Media.getContentUri("external");
Log.d("audiosUri = " + audiosUri.toString(),"");
String[] projection = {MediaStore.Audio.AudioColumns.DATA,MediaStore.Audio.AudioColumns.DISPLAY_NAME,MediaStore.Audio.AudioColumns.DURATION};
// TODO This will break if we have no matching item in the MediaStore.
Cursor cursor = managedQuery(audiosUri, projection, MediaStore.Audio.AudioColumns.DATA + " LIKE ?", new String[] { filepath }, null);
cursor.moveToFirst();
path =cursor.getString( cursor.getColumnIndex(projection[0]));
name=cursor.getString( cursor.getColumnIndex(projection[1]));
int iduration = cursor.getColumnIndex(projection[2]);
duration=CalTotalTime(Integer.valueOf(iduration));
Log.d("pathhhhhhhhhhhhhhhhhh", path);
Log.d("nameeeeeeeeeeeeeeeeeeeeeee", name);
Log.d("duration", duration);
cursor.close();
see this link too:
get your info from files by mediastore

adding custom type of number to a contact [Android]

I been working on an app that helps sending sms to your contacts. Everything is great, except that I'm supposed to add a "custom field number" to a contact such as "Work" or "Private". I'd search the web for answers and the ones that are useful for evryone, aren't for me. This is my code:
private void AddCtxtAttribute(int contactID, String contactNumber) {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder = ContentProviderOperation
.newInsert(Data.CONTENT_URI);
builder.withValue(Data.RAW_CONTACT_ID, contactID);
builder.withValue(ContactsContract.Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
builder.withValue(ContactsContract.Data.DATA1, contactNumber);
builder.withValue(ContactsContract.Data.DATA2, Phone.TYPE_CUSTOM);
builder.withValue(ContactsContract.Data.DATA3, "My Custom Label");
ops.add(builder.build());
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
Log.e("RESULT", "Success! " + contactID + " - "
+ contactNumber);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("ERROR", "error : " + e.toString());
} catch (OperationApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("ERROR", "error : " + e.toString());
}
}
And it's called:
AddCtxtAttribute(contacto_id, contacto_numero);
where contacto_id and contacto_numero are a int and a String respectively.
The problem is that when I pressed the button, I have the ID (contacto_id) of that contact but it updates other contact. (like the id's don't match) but i've debug it and the id doesn't change.
Can anyone help me with this?
I figured it out!
the problem was that i was using diferent column names and uris in reading the contacts and inserting a new contact number.
I did this:
to query all contacts:
private void llenar_contactos() {
ProgressDialog progress;
lista_contactos_cel_sobrantes = null;
sobrantes = false;
lista_contactos_cel = new ArrayList<HashMap<String, Object>>();
progress = ProgressDialog.show(contactsActivity.this, "",
"Cargando Contactos. Porfavor espere...");
String[] projection = new String[] { Data.RAW_CONTACT_ID,
Phone.DISPLAY_NAME, Phone.NUMBER, Phone.LABEL };
String selection = Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'";
// ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER + "='1'";
String sort_order = "display_name ASC";
Uri mContacts = Data.CONTENT_URI;
// ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
Cursor contacts = getContentResolver().query(mContacts, // Contact URI
projection, // Which columns to return
selection, // Which rows to return
null, // Where clause parameters
sort_order // Order by clause
);
total_contactos = contacts.getCount();
if (total_contactos > 0) {
int i = 0;
int multiplo = 0;
int indice_total = 0;
int temp_registros = 0;
String contact_id = "";
String name = "";
String phoneNo = "";
String label = "";
sobrantes = false;
int nameFieldColumnIndex = 0;
while (contacts.moveToNext()) {
nameFieldColumnIndex = contacts.getColumnIndex(Data.RAW_CONTACT_ID);
if (nameFieldColumnIndex > -1) {
contact_id = contacts.getString(nameFieldColumnIndex);
}
nameFieldColumnIndex = contacts.getColumnIndex(Phone.DISPLAY_NAME);
if (nameFieldColumnIndex > -1) {
name = contacts.getString(nameFieldColumnIndex);
}
nameFieldColumnIndex = contacts.getColumnIndex(Phone.NUMBER);
if (nameFieldColumnIndex > -1) {
phoneNo = contacts.getString(nameFieldColumnIndex);
}
nameFieldColumnIndex = contacts.getColumnIndex(Phone.LABEL);
if (nameFieldColumnIndex > -1) {
label = contacts.getString(nameFieldColumnIndex);
}
if(label != null){
Log.i("CONTACTO", "id: " + contact_id + " -> name: " + name
+ " ->number: " + phoneNo + " ->label: " + label);
} else {
Log.d("CONTACTO", "id: " + contact_id + " -> name: " + name
+ " ->number: " + phoneNo + " ->label: " + label);
}
}
contacts.close();
}
}
And to insert a new custom label:
private void AddCtxtAttribute(int contactID, String contactNumber) {
if (contactID != 0 && contactNumber != null) {
ArrayList<ContentProviderOperation> ops =
new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValue(Data.RAW_CONTACT_ID, contactID)
.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, contactNumber)
.withValue(Phone.TYPE, Phone.TYPE_CUSTOM)
.withValue(Phone.LABEL, "My Custom Label")
.build());
try{
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OperationApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Categories

Resources