duplicate contacts as vcf file android - java

I found this code around the forum for creating a vcf file with all contacts stored in the phone. well i get all contacts but duplicate does anyone know how to fix it? i am only interested in the contacts displayed in the contacts book not google contacts etc. THANKS
private void getVcardString() throws IOException {
// TODO Auto-generated method stub
//ProgressBar pro = (ProgressBar)findViewById(R.id.pb);
// ProgressBar pro = (ProgressBar) findViewById(R.id.pb1);
vCard = new ArrayList<String>(); // Its global....
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1",
null, null, null);
if (cursor != null && cursor.getCount() > 0) {
int i;
String storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(storage_path, false);
cursor.moveToFirst();
for (i = 0; i < cursor.getCount(); i++) {
get(cursor);
Log.d("TAG", "Contact " + (i + 1) + "VcF String is" + vCard.get(i));
cursor.moveToNext();
mFileOutputStream.write(vCard.get(i).toString().getBytes());
}
mFileOutputStream.close();
cursor.close();
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
tx.setText("");
pro.setVisibility(View.GONE);
btn3.setVisibility(View.VISIBLE);
tx1.setVisibility(View.VISIBLE);
Toast toast=Toast.makeText(getApplicationContext(),"בוצע גיבוי לכרטיס הזיכרון",Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0,90);
toast.show();
}
});
} else {
Log.d("TAG", "No Contacts in Your Phone");
}
}
private void get(Cursor cursor2) {
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd;
try {
fd = getContentResolver().openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
byte[] buf = new byte[(int) fd.getDeclaredLength()];
fis.read(buf);
String vcardstring = new String(buf);
vCard.add(vcardstring);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
} here

just found the solution edit query:
getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

Related

Android : Getting photos for contacts is not working

I am working on an Android application in which I am retrieving contacts for sync purposes and querying for getting the photos. Unfortunately, I am getting no photos from the method. I get the contact_id properly, but no photos. I have many contacts which have photos. Am I doing something wrong? There are no errors, just no photos.
Code :
Cursor cur = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if(cur!=null) {
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// System.out.println("Name is "+name);
if (Integer.parseInt(cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
assert pCur != null;
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
long contactId = pCur.getLong(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
// Above also tried passing CONTACT_ID instead of _ID
System.out.println("Contact id is "+contactId);
try {
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId));
if (inputStream != null) {
Bitmap photo = BitmapFactory.decodeStream(inputStream);
if(photo!=null){
System.out.println("Photo is not null");
}
// ImageView imageView = (ImageView) findViewById(R.id.img_contact);
// imageView.setImageBitmap(photo);
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
// System.out.println("Phone number is "+phoneNo);
}
pCur.close();
}
}
}
cur.close();
}
Thank you.

how to get photo_uri from photo_id

I go through the addressbook and try to get all contacts' photos which are not null.
I'm using android API8, so i cannot query for image_uri.
given photo_id (API 5), how can i get the photo bitmap?
here is my query:
public final static String[] PROJECTION2 = new String[] {
ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.PHOTO_ID
};
public static void fillAddressBookData() {
String sHash = null;
String where = ContactsContract.Contacts.IN_VISIBLE_GROUP + "= ? ";
String[] selectionArgs = new String[] {"1"};
Cursor cursor =
AppService
.getAppContext()
.getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION2, where,
selectionArgs, null);
...
try this:
private void GetImageByPhoneNumber(String number)
{
Uri uri1 = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(number));
Cursor test = getContentResolver().query(uri1,
new String[] { "photo_uri" }, null, null,
null);
if (test.getCount() > 0) {
test.moveToFirst();
Uri photoUri = Uri.parse(test.getString(test
.getColumnIndexOrThrow("photo_uri"))));
Bitmap image = getPhoto(context , photoUri);
}
test.close();
}
and getPhoto:
public static Bitmap getPhoto(Context context , Uri uri){
Bitmap bm = null;
try {
bm = BitmapFactory.decodeStream(context.getContentResolver()
.openInputStream(uri));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (bm == null) {
bm = BitmapFactory.decodeResource(context.getResources(),
R.drawable.default_user_avatar);
}
return bm;
}
Try the next code snippet, it should do the trick
public Uri getPhotoUri(long contactId) {
ContentResolver contentResolver = getContentResolver();
try {
Cursor cursor = contentResolver
.query(ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.CONTACT_ID
+ "="
+ contactId
+ " AND "
+ ContactsContract.Data.MIMETYPE
+ "='"
+ ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE
+ "'", null, null);
if (cursor != null) {
if (!cursor.moveToFirst()) {
return null; // no photo
}
} else {
return null; // error in cursor process
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
Uri person = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, contactId);
return Uri.withAppendedPath(person,
ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
}

Type mismatch: cannot convert from List<class name> to Cursor: android error

I am new to android and learning to connect sqllite database to an app. This is the main activity and getting an error in Cursor cursor = (Cursor) db.getAllQuestions(); line.
Error says Type mismatch: cannot convert from List<class name> to Cursor. please can somebody help me overcome this.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
String destPath = "/data/data/" + getPackageName()
+ "/databases/questions";
File f = new File(destPath);
if (!f.exists()) {
CopyDB(getBaseContext().getAssets().open("questions"),
new FileOutputStream(destPath));
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Error File", Toast.LENGTH_SHORT)
.show();
}
catch (IOException e1) {
e1.printStackTrace();
Toast.makeText(MainActivity.this, "Error IO", Toast.LENGTH_SHORT)
.show();
}
DatabaseHandler db = new DatabaseHandler(this);
// db.open();
long id = db.addQuestion(new addtodb(0, "Question1", "answer1"));
id = db.addQuestion(new addtodb(0, "Question2", "answer2"));
db.close();
// db.open();
Cursor cursor = (Cursor) db.getAllQuestions();
if (cursor.moveToFirst())
{
do {
DisplayRecord(cursor);
}
while(cursor.moveToNext());
}
db.close();
}
public void CopyDB(InputStream inputstream, OutputStream outputstream)
throws IOException {
byte[] buffer = new byte[1024];
int length;
while ((length = inputstream.read(buffer))>0){
outputstream.write(buffer, 0, length);
}
inputstream.close();
outputstream.close();
}
public void DisplayRecord(Cursor cursor){
Toast.makeText(this,
"id:" + cursor.getString(0) + "\n" +
"Question:" + cursor.getString(1) + "\n" +
"Answer:" + cursor.getString(2),
Toast.LENGTH_SHORT).show();
}
}
This is my getAllQuestions method.
public List<addtodb> getAllQuestions() {
List<addtodb> QuestionList = new ArrayList<addtodb>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_QUESTIONS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
addtodb question = new addtodb();
question.setID(Integer.parseInt(cursor.getString(0)));
question.setName(cursor.getString(1));
question.setPhoneNumber(cursor.getString(2));
// Adding contact to list
QuestionList.add(question);
} while (cursor.moveToNext());
}
// return contact list
return QuestionList;
}
Obviously you want to wrap your List whose length is 3 into a Cursor.
You can use MatrixCursor for this purpose. For example :
List<?> resultList = getAllQuestion();
MatrixCursor cursor = new MatrixCursor(new String[] { "0", "1", "2" });
cursor.addRow(resultList);
You need to return the cursor object instead of List. That would help.

InsertAPN() Method Does Not Write APN Settings - Android 2.3.6

I have an android application which is supposed to write new APN settings to a device however every time I run the application the new APN settings do not appear to be written to the device (the APN settings are totally blank after execution) I belive this may have something to do with a problem with InsertAPN() [shown below] however I'm unable to determine the root cause of the issue.
P.S.
Any debugging tips/questions are greatly appreciated.
SOURCE SNIPPET:
/*
* Insert a new APN entry into the system APN table Require an apn name, and
* the apn address. More can be added. Return an id (_id) that is
* automatically generated for the new apn entry.
*/
public int InsertAPN() throws SecurityException {
int id = -1;
for (i = 0; i < count; i++) {
ContentValues values2 = new ContentValues();
// values2 = values1;
values2 = getValues();
ContentResolver resolver = getContentResolver();
Cursor c = null;
try {
Uri newRow = resolver.insert(APN_TABLE_URI, values2);
// System.out.println("values in insertAPN" + values1);
if (newRow != null) {
c = resolver.query(newRow, null, null, null, null);
Log.d(TAG, "Newly added APN:");
// TF Settings have been inserted
// Obtain the apn id
int idindex = c.getColumnIndex("_id");
c.moveToFirst();
id = c.getShort(idindex);
Log.d(TAG, "New ID: " + id
+ ": Inserting new APN succeeded!");
}
} catch (SQLException e) {
Log.d(TAG, e.getMessage());
}
if (c != null)
c.close();
}
return id;
}
FULL SOURCE:
public class ConfigFinalActivity extends Activity implements OnClickListener {
private static final String TAG = "ConfigActivity";
TelephonyManager tm;
AlertDialog mErrorAlert = null;
private Notification mNotification = null;
private Button mXButton = null;
private Button mAssistUpdateButton = null;
private Button mAssistInstrButton = null;
private Button mReadAgainButton = null;
private int mInstructionNumber = 0;
public static ArrayList<String> NameArr = new ArrayList<String>();
public static ArrayList<String> ValueArr = new ArrayList<String>();
public static ArrayList<String> nameArr = new ArrayList<String>();
public static ArrayList<String> ApnArr = new ArrayList<String>();
public static ArrayList<String> mmscArr = new ArrayList<String>();
public static ArrayList<String> mmsportArr = new ArrayList<String>();
public static ArrayList<String> mmsproxyArr = new ArrayList<String>();
public static ArrayList<String> portArr = new ArrayList<String>();
public static ArrayList<String> proxyArr = new ArrayList<String>();
public static int count;
public static int TotalSteps = 8;
int i, g = 0, result = 0;
public static ContentValues Values = new ContentValues();
XmlParserHandlerFinal handler;
public static final Uri APN_TABLE_URI = Uri
.parse("content://telephony/carriers");
public static final String Base_URL = "https://wapgate.example.com/REST/phoneSettings";
public static InputStream stream = null;
UpdateActivity update;
public static String status, queryResult = "";
/** Called when the activity is first created. */
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int version = android.os.Build.VERSION.SDK_INT;
tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
update = new UpdateActivity();
handler = new XmlParserHandlerFinal();
handler.setContext(this.getBaseContext());
getArrayLists();
/*
* boolean deleted = deleteFile("settings.xml");if(deleted){
* Log.v("settings.xml","deleted"); }else
* Log.v("settings.xml","failed to delete the file");
*/
if (ApnArr.isEmpty() || mmscArr.isEmpty()) {
tryagain();
} else if (version < VERSION_CODES.ICE_CREAM_SANDWICH) {
// Update APN table
try {
result = updateTable();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}// Settings updated with this atomic call
catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (result != -1) {
status = "success";
} else {
status = "failure";
}
if (status.equals("success")) {
completeUpdate();
} else if (status.equals("failure")) {
tryagain();
// showAlert(getString(R.string.unchanged_dialog));
}
} else {// ICS and later versions
// Reduce number of steps to 6
TotalSteps = 6;
setContentView(R.layout.assist_instructions);
String assistUpdate = getString(R.string.instructions_1);
CharSequence styledText = Html.fromHtml(assistUpdate);
TextView assistText = (TextView) findViewById(R.id.apn_app_text_cta2);
assistText.setText(styledText);
mAssistUpdateButton = (Button) findViewById(R.id.assist_update_btn);
mAssistUpdateButton.setOnClickListener(this);
}
}
private void getArrayLists() {
nameArr = update.getnameArr();
ApnArr = update.getApnArr();
mmscArr = update.getMMSCArr();
mmsproxyArr = update.getMmscProxyArr();
mmsportArr = update.getMmsPortArr();
proxyArr = update.getProxyArr();
portArr = update.getPortArr();
count = update.getCount();
queryResult = update.getResult();
}
public void onClick(View v) {
if (v == mAssistUpdateButton) {
// Update button for ICS and up is selected
// Get the TextView in the Assist Update UI
TextView tv = (TextView) findViewById(R.id.apn_app_text_cta2);
String text = "";
CharSequence styledText = text;
switch (mInstructionNumber) {
case 0:
// Retrieve the instruction string resource corresponding the
// 2nd set of instructions
text = String.format(getString(R.string.apn_app_text_instr),
TotalSteps);
styledText = Html.fromHtml(text);
// Update the TextView with the correct set of instructions
tv.setText(styledText);
// Increment instruction number so the correct instructions
// string resource can be retrieve the next time the update
// button is pressed
mInstructionNumber++;
break;
case 1:
text = getString(R.string.apn_app_text_instr2);
styledText = Html.fromHtml(text);
tv.setText(styledText);
// Increment instruction number so the correct instructions
// string resource can be retrieve the next time the update
// button is pressed
mInstructionNumber++;
break;
case 2:
// Final set of instructions-Change to the corresponding layout
setContentView(R.layout.assist_instructions);
String assistUpdateInstr = String.format(
getString(R.string.apn_app_text_instr3), TotalSteps);
styledText = Html.fromHtml(assistUpdateInstr);
TextView assistInstrText = (TextView) findViewById(R.id.updated_text);
assistInstrText.setText(styledText);
mAssistInstrButton = (Button) findViewById(R.id.assist_instr_btn);
mAssistInstrButton.setOnClickListener(this);
}
} else if (v == mAssistInstrButton) {
// "LET'S DO THIS" Button in final instructions screen for ICS and
// up is selected
Values = getValues();
startActivity(new Intent(Settings.ACTION_APN_SETTINGS));
try {
showNotification();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finish();
} else if (v == mAssistInstrButton) {
startActivity(new Intent(Settings.ACTION_APN_SETTINGS));
try {
showNotification();
} catch (SAXException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ParserConfigurationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
showNotification();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finish();
}
}
/*
* Insert a new APN entry into the system APN table Require an apn name, and
* the apn address. More can be added. Return an id (_id) that is
* automatically generated for the new apn entry.
*/
public int InsertAPN() throws SecurityException {
int id = -1;
for (i = 0; i < count; i++) {
ContentValues values2 = new ContentValues();
// values2 = values1;
values2 = getValues();
ContentResolver resolver = getContentResolver();
Cursor c = null;
try {
Uri newRow = resolver.insert(APN_TABLE_URI, values2);
// System.out.println("values in insertAPN" + values1);
if (newRow != null) {
c = resolver.query(newRow, null, null, null, null);
Log.d(TAG, "Newly added APN:");
// TF Settings have been inserted
// Obtain the apn id
int idindex = c.getColumnIndex("_id");
c.moveToFirst();
id = c.getShort(idindex);
Log.d(TAG, "New ID: " + id
+ ": Inserting new APN succeeded!");
}
} catch (SQLException e) {
Log.d(TAG, e.getMessage());
}
if (c != null)
c.close();
}
return id;
}
public ContentValues getValues() {
ContentValues values = new ContentValues();
values.put("name", nameArr.get(i));
values.put("apn", ApnArr.get(i));
values.put("mmsc", mmscArr.get(i));
//values.put("mmsproxy", mmsproxyArr.get(i));
//values.put("mmsport", mmsportArr.get(i));
// values.put("proxy", proxyArr.get(i));
values.put("port", portArr.get(i));
values.put("mcc", (getString(R.string.mcc)));
if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))) {
values.put("numeric", getString(R.string.numeric_tmo));
values.put("mnc", (getString(R.string.mnc_tmo)));
} else if ((tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
values.put("numeric", getString(R.string.numeric_att));
values.put("mnc", (getString(R.string.mnc_att)));
}
return values;
}
/*
* Delete APN data where the indicated field has the values Entire table is
* deleted if both field and value are null
*/
private void DeleteAPNs(String field, String[] values)
throws SecurityException {
int c = 0;
c = getContentResolver().delete(APN_TABLE_URI, null, null);
if (c != 0) {
String s = "APNs Deleted:\n";
Log.d(TAG, s);
}
}
/*
* Return all column names stored in the string array
*/
private String getAllColumnNames(String[] columnNames) {
String s = "Column Names:\n";
for (String t : columnNames) {
s += t + ":\t";
}
return s + "\n";
}
/*
* Copy all data associated with the 1st record Cursor c. Return a
* ContentValues that contains all record data.
*/
private ContentValues copyRecordFields(Cursor c) {
if (c == null)
return null;
int row_cnt = c.getCount();
Log.d(TAG, "Total # of records: " + row_cnt);
ContentValues values = new ContentValues();//
if (c.moveToFirst()) {
String[] columnNames = c.getColumnNames();
Log.d(TAG, getAllColumnNames(columnNames));
String row = "";
for (String columnIndex : columnNames) {
int i = c.getColumnIndex(columnIndex);
row += c.getString(i) + ":\t";
// if (i>0)//Avoid copying the id field
// id to be auto-generated upon record insertion
values.put(columnIndex, c.getString(i));
}
row += "\n";
Log.d(TAG, row);
Log.d(TAG, "End Of Records");
}
return values;
}
// showAlert displays the text contained in message as an alert
public void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ConfigFinalActivity.this.finish();
}
});
mErrorAlert = builder.create();
mErrorAlert.show();
}
// showErrorAlert displays an alert with layout and a title
private void showErrorAlert(int layoutRes, String title) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Get the layout inflater
LayoutInflater inflater = ConfigFinalActivity.this.getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setTitle(title)
.setView(inflater.inflate(layoutRes, null))
.setPositiveButton(getString(R.string.assisted_button),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(
Settings.ACTION_APN_SETTINGS));
try {
showNotification();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
mErrorAlert = builder.create();
mErrorAlert.show();
}
// showNotification starts the process of sending notifications to the bar
// to assist the user in updating the data settings on ICS and later
// versions of Android
#SuppressWarnings("deprecation")
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void showNotification() throws SAXException, ParserConfigurationException {
String field = getString(R.string.config_name_label);
String value = Values.get("name").toString();
int mId = 1;
String title = "1 of " + UpdateActivity.TotalSteps + " (Update "
+ field + ":)";
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notifications_icon)
.setContentTitle(title).setContentText(value);
Intent resultIntent = new Intent(this,
NotificationActivityForMultiProf.class);
resultIntent.putExtra(field, value);
PendingIntent resultPendingIntent = PendingIntent.getActivity(
getApplicationContext(), 0, resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotification = mBuilder.getNotification();
mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(mId, mNotification);
finish();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
if (mNotification != null) {
outState.putString("NOTIFICATIONB", mNotification.toString());
}
}
#Override
protected void onRestart() {
super.onRestart();
if (mErrorAlert != null)
mErrorAlert.dismiss();
}
private int updateTable() throws IOException, SAXException,
ParserConfigurationException {
int insertResult = -1;
// returned value if table is not properly updated
try {
ContentValues values = new ContentValues();
// Query the carrier table for the current data settings
Cursor c = getContentResolver().query(APN_TABLE_URI, null,
"current=?", new String[] { "1" }, null);
values = copyRecordFields(c);
// Copy the settings into values
// Replace T-Mo/ATT Data settings if there is no SIM or
// NET10/T-Mo/ATT SIM is
// present
if (tm.getSimState() == TelephonyManager.SIM_STATE_ABSENT
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_tmo))) {
// delete all APNs before adding new APNs
DeleteAPNs("numeric=?",
new String[] { getString(R.string.numeric_tmo) });
// Insert Data Settings into Carrier table
insertResult = InsertAPN();
} else if (tm.getSimState() == TelephonyManager.SIM_STATE_ABSENT
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
// Delete all APNs before adding new APNs
DeleteAPNs("numeric=?",
new String[] { getString(R.string.numeric_att) });
// Insert Data Settings into Carrier table
insertResult = InsertAPN();
} else
// non NET10/ non T-Mo SIM/non ATT SIM
showAlert(getString(R.string.insert_sm_dialog));
} catch (SecurityException e) {
showErrorAlert(R.layout.assisted_setting,
getString(R.string.assited_title));
Log.d(TAG, e.getMessage());
}
return insertResult;
}
private void completeUpdate() {
// Displaying final layout after pre-ICS automatic settings update
setContentView(R.layout.completion);
TextView mCompleted = (TextView) findViewById(R.id.done_text);
String mDoneText = String.format(getString(R.string.done_text));
CharSequence styledText = Html.fromHtml(mDoneText);
mCompleted.setText(styledText);
mXButton = (Button) findViewById(R.id.x_button);
mXButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
public void tryagain() {
// Displaying final layout after failure of pre-ICS automatic settings
// update
setContentView(R.layout.tryagain);
String tryAgainText = "";
CharSequence styledTryAgainText;
tryAgainText = String.format(getString(R.string.tryagain_text1),
TotalSteps);
styledTryAgainText = Html.fromHtml(tryAgainText);
TextView tryAgain1 = (TextView) findViewById(R.id.tryagain_text1);
tryAgain1.setText(styledTryAgainText);
tryAgainText = String.format(getString(R.string.tryagain_text2),
TotalSteps);
styledTryAgainText = Html.fromHtml(tryAgainText);
TextView tryAgain2 = (TextView) findViewById(R.id.tryagain_text2);
tryAgain2.setText(styledTryAgainText);
tryAgainText = String.format(getString(R.string.tryagain_text3),
TotalSteps);
styledTryAgainText = Html.fromHtml(tryAgainText);
TextView tryAgain3 = (TextView) findViewById(R.id.tryagain_text3);
tryAgain3.setText(styledTryAgainText);
}
// This function return a cursor to the table holding the
// the APN configurations (Carrier table)
public Cursor getConfigTableCursor() {
return getContentResolver()
.query(APN_TABLE_URI, null, null, null, null);
}
}
You can no longer programatically change APN settings on Android 4.0 and up. So if you're debugging on Android 4.0 or higher, that is where your issue is.

Android UI not updating

I am currently creating a program that recursively searches through the SD card of the videos on an android phone, and then produces as hash for each of the videos.
Everything works fine, but when I try and create a progress bar, the progress bar doesn't update, until the end.
So essentially progress bar's progress appears to go from 0 to the max, but I can tell from log output that values are being sent to the progress bar to update it, the progress bar just isn't upating.
My code is below:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progress = (ProgressBar) findViewById(R.id.progressBar1);
text = (TextView) findViewById(R.id.tv1);
Button btnStart = (Button) findViewById(R.id.btnStart);
btnStart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
recursiveVideoFinder(new File("/sdcard"));
String strDB3File = getFilesDir().getPath()
+ "/VideoHashes.db3";
sql3 = SQLiteDatabase.openDatabase(strDB3File, null,
SQLiteDatabase.CREATE_IF_NECESSARY);
try {
String mysql = "CREATE TABLE videohashes (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, path TEXT NOT NULL, hash TEXT NOT NULL, date TEXT NOT NULL, size INTEGER)";
sql3.execSQL(mysql);
} catch (SQLiteException e) {
// TODO: handle exception
}
progress.setProgress(0);
progress.setMax(myFiles.size());
for (String path : myFiles) {
try {
String hash = getMD5Checksum(path);
ContentValues myInsertData = new ContentValues();
myInsertData.put("path", path);
myInsertData.put("hash", hash);
Date date = new Date();
myInsertData.put("date", dateFormat.format(date));
myInsertData.put("size", getFileSize(path));
sql3.insert("videohashes", null, myInsertData);
currVid++;
updateProgress();
Log.i("Progress", "CurrVid:" + currVid + " Max:"
+ progress.getMax());
text.append(currVid + " ");
} catch (Exception e) {
Log.i("File", "File not Found");
}
}
Cursor cur = sql3.query("videohashes", null, null, null, null,
null, null);
cur.moveToFirst();
while (!cur.isAfterLast()) {
/*
* ((TextView) findViewById(R.id.tv1)).append("\n" +
* cur.getString(1) + "\n" + cur.getString(2) + "\n" +
* cur.getString(3) + "\n" + cur.getString(4) + "\n");
*/
cur.moveToNext();
}
cur.close();
}
});
}
public long getFileSize(String path) {
File file = new File(path);
return file.length();
}
private void recursiveVideoFinder(File _dir) {
File[] files = _dir.listFiles();
if (files == null) {
return;
}
for (File currentFile : files) {
if (currentFile.isDirectory()) {
recursiveVideoFinder(currentFile);
continue;
} else {
for (String aEnd : getResources().getStringArray(
R.array.VideoExtensions)) {
if (currentFile.getName().endsWith(aEnd)) {
Log.d("PS:", currentFile.getPath().toString());
String videoFileName = currentFile.getPath().toString();
myFiles.add(videoFileName);
}
}
}
}
}
// Code based off this example:
// http://stackoverflow.com/questions/304268/getting-a-files-md5-checksum-in-java
public static byte[] createCheckSum(String filename) throws Exception {
InputStream fis = new FileInputStream(filename);
byte[] buffer = new byte[1024];
MessageDigest complete = MessageDigest.getInstance("MD5");
int numRead;
do {
numRead = fis.read(buffer);
if (numRead > 0) {
complete.update(buffer, 0, numRead);
}
} while (numRead != -1);
fis.close();
// Return MD5 Hash
return complete.digest();
}
public String getMD5Checksum(String filename) throws Exception {
byte[] b = createCheckSum(filename);
String result = "";
for (int i = 0; i < b.length; i++) {
result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
}
return result;
}
public void updateProgress() {
progress.setProgress(currVid);
progress.invalidate();
Log.i("Updating", "Updating Progress Bar");
}
}
Why do you keep all the processing code in Onclick(). That is not a good approach. Create an AsyncTask and use publishProgress to update your progressbar.
Put your updating task by overriding onResume(). Start a new timer thread there and keep calling your function. When you click back, finish that thread too by saying timer.cancel(). SO whenever you go that activity, only then the timer starts and exits on hitting back. Check this for more info

Categories

Resources