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

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.

Related

Sharing Intent Not working Properly

I have one quote application. I have implemented share and copy function in it. I am facing issue is that I am not getting shared first time sharing quote. Means if there 50 quote in list and if I try to share any quote from list than it is not sharing anything. after that if I move on another quote and try to sharing than its working fine. I have same issue in copy function also. I also face some time issue like if I share quote number 50 than its sharing another number quote. Please help me for solve the bug. Thanks
My Activity for it is like below.
public class QuoteDialogActivity extends Activity {
DAO db;
static final String KEY_ID = "_quid";
static final String KEY_TEXT = "qu_text";
static final String KEY_AUTHOR = "au_name";
static final String KEY_PICTURE = "au_picture";
static final String KEY_PICTURE_SDCARD = "au_picture_sdcard";
static final String KEY_FAVORITE = "qu_favorite";
static final String KEY_WEB_ID = "au_web_id";
ArrayList<HashMap<String, String>> quotesList;
HashMap<String, String> map;
ImageButton btnnext,btnprev,star,copy;
int pos,lstcount = 0;
ScrollView ll_quote;
String quote_id;
TextView text;
String quText, quAuthor, quPicture, quFavorite,quoteShare;
int auPictureSDCard;
String isFavorite;
String auPictureDir;
String siteUrl;
private ImageLoader imgLoader;
/**
* Register your here app https://dev.twitter.com/apps/new and get your
* consumer key and secret
* */
String TWITTER_CONSUMER_KEY;
String TWITTER_CONSUMER_SECRET;
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_FACEBOOK_LOGIN = "isFacebookLogedIn";
Typeface tf;
// Internet Connection detector
private ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
String quote;
ProgressDialog pDialog;
private SharedPreferences mSharedPreferences;
private static SharedPreferences facebookPreferences, twitterPreferences;
Cursor c, c2;
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
//private UiLifecycleHelper uiHelper;
// ==============================================================================
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imgLoader = new ImageLoader(this);
//TWITTER_CONSUMER_KEY = getResources().getString(R.string.TWITTER_CONSUMER_KEY);
//TWITTER_CONSUMER_SECRET = getResources().getString(R.string.TWITTER_CONSUMER_SECRET);
// uiHelper = new UiLifecycleHelper(this, callback);
//uiHelper.onCreate(savedInstanceState);
mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
//facebookPreferences = getApplicationContext().getSharedPreferences("facebookPref", 0);
//twitterPreferences = getApplicationContext().getSharedPreferences("twitterPref", 0);
db = new DAO(this);
db.open();
c2 = db.getSettings();
if (getIntent().getIntExtra("isQOTD", 0) == 1) {
c = db.getOneQuote(mSharedPreferences.getString("QOTD", ""));
} else {
c = db.getOneQuote(getIntent().getStringExtra("QuoteId"));
}
// if (c.getCount() != 0) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.quote_dialog);
// ============================ check if user want to display
// ============================ background image for quote
if (c2.getString(c2.getColumnIndex("background")).equals("1")) {
Random random = new Random();
int idNumber = random.nextInt(20 - 1 + 1) + 1;
RelativeLayout layout = (RelativeLayout) findViewById(R.id.RelativeLayout1);
Drawable d = null;
try {
View topShadow = (View) findViewById(R.id.topShadow);
View bottomShadow = (View) findViewById(R.id.bottomShadow);
topShadow.setVisibility(View.INVISIBLE);
bottomShadow.setVisibility(View.INVISIBLE);
d = Drawable.createFromStream(getAssets().open("backgrounds/" + String.valueOf(idNumber) + ".jpg"),
null);
layout.setBackgroundDrawable(d);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
// ===========================================================================================
quText = c.getString(c.getColumnIndex(KEY_TEXT));
quAuthor = c.getString(c.getColumnIndex(KEY_AUTHOR));
quPicture = c.getString(c.getColumnIndex(KEY_PICTURE));
auPictureSDCard = c.getInt(c.getColumnIndex(KEY_PICTURE_SDCARD));
quFavorite = c.getString(c.getColumnIndex(KEY_FAVORITE));
text = (TextView) findViewById(R.id.text); // title
// tf = Typeface.createFromAsset(getAssets(), "fonts/devnew.ttf");
//text.setTypeface(tf);
// author = (TextView) findViewById(R.id.author); // author
// picture = (ImageView) findViewById(R.id.picture); // thumb
text.setText(quText);
// author.setText("- " + quAuthor.trim());
// if (auPictureSDCard == 0) {
// AssetManager assetManager = getAssets();
// InputStream istr = null;
// try {
// istr = assetManager.open("authors_pics/" + quPicture);
// } catch (IOException e) {
// Log.e("assets", assetManager.toString());
// e.printStackTrace();
// }
// Bitmap bmp = BitmapFactory.decodeStream(istr);
// picture.setImageBitmap(bmp);
// } else {
// siteUrl = getResources().getString(R.string.siteUrl);
//
// auPictureDir = siteUrl + "global/uploads/authors/";
// imgLoader.DisplayImage(
// auPictureDir + quPicture, picture);
// }
AssetManager assetManager = getAssets();
InputStream istr = null;
try {
istr = assetManager.open("authors_pics/" + quPicture);
} catch (IOException e) {
Log.e("assets", assetManager.toString());
e.printStackTrace();
}
// Bitmap bmp = BitmapFactory.decodeStream(istr);
// picture.setImageBitmap(bmp);
final ImageButton dismiss = (ImageButton) findViewById(R.id.close);
dismiss.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
//=============================Next Button and Prev Button
star = (ImageButton) findViewById(R.id.star);
btnnext = (ImageButton)findViewById(R.id.nextButton);
btnprev = (ImageButton)findViewById(R.id.PrevioustButton);
pos= getIntent().getIntExtra("Pos",0);
quote_id = getIntent().getStringExtra("QuoteId");
lstcount = getIntent().getIntExtra("LstCount",0);
#SuppressWarnings("unchecked")
final ArrayList<HashMap<String, String>> quotesList =(ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("Quotes");
btnnext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(pos == lstcount)
{
Toast.makeText(getApplicationContext(), "End of List", Toast.LENGTH_SHORT).show();
}
else
{
int p = pos+1;
text.setText(quotesList.get(pos).get(KEY_TEXT));
quFavorite = quotesList.get(pos).get(KEY_FAVORITE);
quoteShare = quotesList.get(pos).get(KEY_TEXT);
Log.e("ErrorMsg", "quoteShare is: " + quoteShare);
quote_id = quotesList.get(pos).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
pos = p;
FirstFav();//new
Log.i("quote is",quote_id);
}
}
});
btnprev.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(pos == 1 ||pos == 0)
{
Toast.makeText(getApplicationContext(), "Start of List",Toast.LENGTH_SHORT).show();
}
else
{
int p = pos-1;
text.setText(quotesList.get(p-1).get(KEY_TEXT));
quFavorite = quotesList.get(p-1).get(KEY_FAVORITE);
quote_id = quotesList.get(p-1).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
pos = p;
FirstFav();
}
}
});
//======================================================= Swipe
ll_quote = (ScrollView)findViewById(R.id.scrollView1);
ll_quote.setOnTouchListener(new OnTouchListener() {
int downX, upX;
#Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_DOWN) {
downX = (int) event.getX();
Log.i("event.getX()", " downX " + downX);
return true;
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
upX = (int) event.getX();
Log.i("event.getX()", " upX " + downX);
if (upX - downX > 100) {
if(pos == 0 || pos == 1)
{
Toast.makeText(getApplicationContext(), "Start of List",Toast.LENGTH_SHORT).show();
}
else
{
int p = pos-1;
quFavorite = quotesList.get(p-1).get(KEY_FAVORITE);
quote_id = quotesList.get(p-1).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
text.setText(quotesList.get(p-1).get(KEY_TEXT));
pos = p;
FirstFav();
}
}
else if (downX - upX > -100) {
if(pos == lstcount)
{
Toast.makeText(getApplicationContext(), "End of List", Toast.LENGTH_SHORT).show();
}
else
{
int p = pos+1;
quFavorite = quotesList.get(pos).get(KEY_FAVORITE);
quote_id = quotesList.get(pos).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
text.setText(quotesList.get(pos).get(KEY_TEXT));
pos = p;
FirstFav();
}
}
return true;
}
return false;
}
});
// ========================== share button
final ImageButton share = (ImageButton) findViewById(R.id.share);
share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT,pos);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
});
//copy button
final ImageButton copyy = (ImageButton) findViewById(R.id.copy);
copyy.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("simple text",quoteShare);
clipboard.setPrimaryClip(clip);
Toast.makeText(getApplicationContext(), "Status Copied",
Toast.LENGTH_LONG).show();
}
});
// ========================== set as favorite and unfavorite
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
star.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (isFavorite.equals("0")) {
isFavorite = "1";
star.setImageResource(R.drawable.star_on);
} else {
isFavorite = "0";
star.setImageResource(R.drawable.star_off);
}
if (getIntent().getIntExtra("isQOTD", 0) == 1) {
db.addOrRemoveFavorites(mSharedPreferences.getString("QOTD", ""), isFavorite);
} else {
// Log.i("quotes",quotesList.get(pos).get(String.valueOf(KEY_WEB_ID))+"POS"+pos+"quid"+quotesList.get(pos).get(KEY_ID));
db.addOrRemoveFavorites(quote_id, isFavorite);
// db.addOrRemoveFavorites(getIntent().getStringExtra("QuoteId"), isFavorite);
if (getIntent().getIntExtra("quotesType", 0) == 2 && isFavorite.equals("0")) {
Intent i = new Intent(QuoteDialogActivity.this, QuotesActivity.class);
i.putExtra("quotesType", 2);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(i);
}
}
}
});
// }
}
// ==============================================================================
public void FirstFav()
{
String Image_id=quote_id;
quFavorite = db.getFavQuotes(quote_id);
if(quFavorite.length()>0)
isFavorite = quFavorite;
else
isFavorite = "0";
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
}
//===================================================================================
}
Thanks

How can i get checked checkboxes values from checkbox when checkbox made programmatically in android

I am making check-boxes programmatically. and I want to get value of checked check-boxes when click on button... how can i do this....
I am getting value of checkboxes from database.
Here is my working code..
public class Loyaltyprogram extends Activity {
SessionManager session;
EditText mpv, discount;
Button save;
String finalresult, getFlag, statusEmp, accessName, emp_id, bus_id,
preferences, bus_type_id, emp_access_name, responseString, success,
name, id, pref, per_amout, percentage, datediff, dateNo, minpvalue , discountonit;
Toast tag;
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
ProgressDialog pDialog;
int a;
String[] idsplit, namesplit, prefsplit;
List<String> testArrayList;
LinearLayout llmain;
LinearLayout[] lLayout;
Integer count1 = 0;
Context mContext;
TextView tvo;
CheckBox cb;
StringBuffer result = new StringBuffer();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.loyaltyprogram);
tvo = (TextView) findViewById(R.id.tvother);
mpv = (EditText) findViewById(R.id.et_minpurchase);
discount = (EditText) findViewById(R.id.et_discount);
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
new Homedatanew().execute();
llmain = (LinearLayout) findViewById(R.id.linearLayoutMain);
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"Check your internet connection", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
save = (Button) findViewById(R.id.button);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
minpvalue = mpv.getText().toString();
discountonit = discount.getText().toString();
for(int t = 0; t<idsplit.length; t++)
{
if(cb.isChecked())
{
System.out.println(idsplit[t]);
}
}
}
});
}
class Homedatanew extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Loyaltyprogram.this);
pDialog.setMessage("loading data..");
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://10.0.2.2/amardeep/android_api/checkbox.php");
try {
session = new SessionManager(getApplicationContext());
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// id
bus_id = user.get(SessionManager.KEY_B_ID);
bus_type_id = user.get(SessionManager.KEY_B_TYPE_ID);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("bus_type_id",
"BT101"));
nameValuePairs.add(new BasicNameValuePair("bus_id", "B101"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
response.getStatusLine().getStatusCode();
HttpEntity getResponseEntity = response.getEntity();
responseString = EntityUtils.toString(getResponseEntity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return responseString;
}
#SuppressLint("NewApi")
protected void onPostExecute(String resultStr) {
try {
JSONObject json = new JSONObject(responseString);
JSONArray jArray = json.getJSONArray("customer");
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
success = json_data.getString("success");
id = json_data.getString("id");
name = json_data.getString("name");
pref = json_data.getString("pref");
per_amout = json_data.getString("per_amount");
percentage = json_data.getString("percentage");
datediff = json_data.getString("dateDiff");
dateNo = json_data.getString("dateNo");
if (percentage.equals("null")) {
percentage = "";
}
if (per_amout.equals("null")) {
per_amout = "";
}
if((datediff.equals("No"))&&(dateNo.equals("No")))
{
count1 = 1;
}
else if((datediff.equals("YES"))&&(dateNo.equals("No")))
{
count1 = 2;
}
else
{
count1 = 0;
}
idsplit = id.split(",");
a = idsplit.length;
namesplit = name.split(",");
prefsplit = pref.split(",");
testArrayList = new ArrayList<String>(
Arrays.asList(prefsplit));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (success.equals("1")) {
mpv.setText(per_amout);
discount.setText(percentage);
if ((count1.equals(1)) || (count1.equals(2))) {
mpv.setEnabled(true);
discount.setEnabled(true);
} else {
mpv.setEnabled(false);
discount.setEnabled(false);
save.setEnabled(false);
}
int b = (a / 5);
int c = (a % 5);
if (c != 0) {
b = b + 1;
}
lLayout = new LinearLayout[b];
for (int j = 0; j < b; j++) {
int x = 0;
x = x + (j * 5);
lLayout[j] = new LinearLayout(Loyaltyprogram.this);
lLayout[j].setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
lLayout[j].setOrientation(LinearLayout.VERTICAL);
llmain.addView(lLayout[j]);
for (int i = x; i < x + 5; i++) {
if (x > a) {
break;
} else {
if (testArrayList.contains(idsplit[i])) {
cb = new CheckBox(Loyaltyprogram.this);
cb.setText(namesplit[i] + (i + 1));
cb.setId(i + 1);
cb.setChecked(true);
cb.setTextColor(Color.BLACK);
cb.setTextSize(12f);
cb.setButtonDrawable(R.drawable.checkbox);
cb.setPadding(35, 5, 25, 5);
if (count1.equals(1)) {
cb.setEnabled(true);
} else {
cb.setEnabled(false);
}
lLayout[j].addView(cb);
} else {
cb = new CheckBox(Loyaltyprogram.this);
cb.setText(namesplit[i] + (i + 1));
cb.setId(i + 1);
cb.setTextColor(Color.BLACK);
cb.setTextSize(12f);
cb.setButtonDrawable(R.drawable.checkbox);
cb.setPadding(35, 5, 25, 5);
if (count1.equals(1)) {
cb.setEnabled(true);
} else {
cb.setEnabled(false);
}
lLayout[j].addView(cb);
}
}
}
}
} else {
Toast.makeText(getApplicationContext(), "data empty",
Toast.LENGTH_LONG).show();
mpv.setEnabled(true);
discount.setEnabled(true);
}
pDialog.dismiss();
}
}
}
Just do this inside the loop and if , else condition
cb.setTag(i+99); // set the tag values so that you can refer to them later.
cb.setOnCheckedChangeListener(handleCheck(cb)); // here pass the checkbox object.
Then this is handleCheck method
private OnCheckedChangeListener handleCheck (final CheckBox chk)
{
return new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(!isChecked){
Toast.makeText(getApplicationContext(), "You unchecked " + chk.getTag(),
Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "You checked " + chk.getTag(),
Toast.LENGTH_LONG).show();
}
}
};
}
Hope this gives you some idea. Happy coding :)

Android Animation Sequence Loads Slowly - Appears To Hang [duplicate]

I have an android Animation which loads a series of sequential dots (publishProgress) however there is a 10+ second delay before they start because I have them as a part of my AsyncTask which loads once the data is processing (technically - the two should be related - but it visually causes there to be a delay) how can I call this animation when the class first starts instead? I need to remove this visual animation delay.
SOURCE:
public class UpdateActivity extends Activity implements OnClickListener {
private TelephonyManager tm;
AlertDialog mConfirmAlert = null;
NetworkTask task;
ImageView image, text;
AlertDialog mErrorAlert = null;
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>();
private ImageView mProgressImageview1;
private ImageView mProgressImageview2;
private ImageView mProgressImageview3;
private ImageView mProgressImageview4;
private ImageView mProgressImageview5;
private Button mUpdateButton = null;
private Button mAssistUpdateButton = null;
private Button mAssistInstrButton = null;
private TextView mReadAgainButton = null;
public static int count;
public AnimationDrawable mTextAnimation = null;
private Button assist_update_btn = null;
TextView mUpdatetext;
public static InputStream stream = null;
int version;
public static BigInteger iD1, iD2, mdN1, mdN2;
BigInteger[] id, mdnId;
public static String ICCID, MDN;
private int mInstructionNumber = 0;
public static String caR, result;
private static final String LOG_TAG = "DataSettings";
public static final String Base_URL = "https://apps.example.com/REST/phoneSettings";
public static XmlParserHandlerFinal handler;
public static int TotalSteps = 8;
public FileInputStream fis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// instance for xml parser class
handler = new XmlParserHandlerFinal();
handler.setContext(this.getBaseContext());
tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
int networkType = tm.getNetworkType();
int phoneType = tm.getPhoneType();
version = android.os.Build.VERSION.SDK_INT;
// to get MDN(MCC+MNC) of the provider of the SIM and ICCID (Serial
// number of the SIM)
// and to check for the Carrier type
getImpVariablesForQuery();
task = new NetworkTask();
if (phoneType == TelephonyManager.PHONE_TYPE_CDMA
|| (phoneType != TelephonyManager.PHONE_TYPE_GSM
&& networkType != TelephonyManager.NETWORK_TYPE_GPRS
&& networkType != TelephonyManager.NETWORK_TYPE_EDGE
&& networkType != TelephonyManager.NETWORK_TYPE_HSDPA
&& networkType != TelephonyManager.NETWORK_TYPE_HSPA
&& networkType != TelephonyManager.NETWORK_TYPE_HSPAP
&& networkType != TelephonyManager.NETWORK_TYPE_HSUPA
&& networkType != TelephonyManager.NETWORK_TYPE_UMTS && networkType != TelephonyManager.NETWORK_TYPE_LTE)) {
// If the phone type is CDMA or
// the phone phone type is not GSM and the network type is none of
// the network types indicated in the statement
// Display incompatibility message
showAlert(getString(R.string.incomp_sm_dialog));
// Network type is looked because some tablets have no phone type.
// We rely on network type in such cases
} else if (!(tm.getSimState() == TelephonyManager.SIM_STATE_ABSENT
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_tmo)) || (tm
.getSimOperator()).equals(getString(R.string.numeric_att)))) {
// if SIM is present and is NOT a T-Mo or ATT network SIM,
// display Error message alert indicating to use SM SIM
showAlert(getString(R.string.insert_sm_dialog));
}// No SIM or SIM with T-Mo & ATT MNC MCC present
else if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
// Device has T-Mo or ATT network SIM card MCC and MNC correctly
// populated
TotalSteps = 6;
setContentView(R.layout.updating);
// AsyncTask to call the web service
task = new NetworkTask();
task.execute("");
}
}
public void onClick(View v) {
if (v == mUpdateButton) {
// Update button for versions lower than ICS is selected
onClickMethod(v);
Intent i = new Intent(this, ConfigFinalActivity.class);
startActivity(i);
finish();
} else
if (v.getId() == R.id.assist_update_btn) {
// 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);
mReadAgainButton = (TextView) findViewById(R.id.read_again_btn);
mAssistInstrButton.setOnClickListener(this);
mReadAgainButton.setOnClickListener(this);
}
} else if (v == mAssistInstrButton) {
// "LET'S DO THIS" Button in final instructions screen for ICS and
// up is selected
// Create ConfigActivity Intent
Intent i = new Intent(this, ConfigFinalActivity.class);
// Invoke ConfigActivity Intent to start the assisted update
startActivity(i);
startActivity(new Intent(Settings.ACTION_APN_SETTINGS));
} else if (v == mReadAgainButton) {
// go back to 1st set of instructions if read again is selected
mInstructionNumber = 0;
setContentView(R.layout.assist_update);
String assistUpdate = getString(R.string.apn_app_text_cta2);
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);
}
}
public void onClickMethod(View v) {
mUpdateButton = (Button) findViewById(R.drawable.btn_update_active_hdpi);
}
private 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) {
UpdateActivity.this.finish();
}
});
mConfirmAlert = builder.create();
mConfirmAlert.show();
}
private void getImpVariablesForQuery() {
long d = 1234;
BigInteger divisor = BigInteger.valueOf(d);
// to get MDN
// MDN = tm.getLine1Number();
MDN = "3055861092";
if (MDN.equals("")) {
mdN1 = null;
mdN2 = null;
} else {
Log.d("MDN", MDN);
BigInteger bInt = new BigInteger(MDN);
mdnId = bInt.divideAndRemainder(divisor);
// to retrieve ICCID number of the SIM
mdN1 = mdnId[1];
System.out.println("MDN%1234 = " + mdN1);
mdN2 = mdnId[0];
System.out.println("MDN/1234 = " + mdN2);
}
ICCID = tm.getSimSerialNumber();
if (ICCID.equals("")) {
iD1 = null;
iD2 = null;
} else {
Log.d("ICCID", ICCID);
BigInteger bInteger = new BigInteger(ICCID);
id = bInteger.divideAndRemainder(divisor);
iD1 = id[1];
System.out.println("ICCID%1234 = " + iD1);
iD2 = id[0];
System.out.println("ICCID/1234 = " + iD2);
}
// Check for the Carrier Type
if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))) {
caR = "TMO";
} else if ((tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
caR = "ATT";
}
}
// method to save the ArrayLists from parser
public static void setArrayList() {
nameArr = handler.getnameArr();
ApnArr = handler.getApnArr();
mmscArr = handler.getMMSCArr();
mmsproxyArr = handler.getMmscProxyArr();
mmsportArr = handler.getMmsPortArr();
proxyArr = handler.getProxyArr();
portArr = handler.getPortArr();
count = handler.getCount();
result = handler.getResult();
}
public ArrayList<String> getnameArr() {
return nameArr;
}
public ArrayList<String> getApnArr() {
return ApnArr;
}
public ArrayList<String> getMMSCArr() {
return mmscArr;
}
public ArrayList<String> getMmscProxyArr() {
return mmsproxyArr;
}
public ArrayList<String> getMmsPortArr() {
return mmsportArr;
}
public int getCount() {
return count;
}
public ArrayList<String> getProxyArr() {
return proxyArr;
}
public ArrayList<String> getPortArr() {
return portArr;
}
// AsyncTask to call web service
public class NetworkTask extends AsyncTask<String, Integer, InputStream> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//
}
#Override
protected InputStream doInBackground(String... params) {
int result = 0;
{
Log.i("url...", Base_URL);
try {
stream = getQueryResults(Base_URL);
} catch (SocketTimeoutException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SSLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SAXException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// The code below plays a ST Promo animation
// prior to displaying update success or failure message
for (int incr = 0; incr < 2; incr++) {
// Sleep for 1/2 second
// Invoke UI to change updating text to show 1 dot
// And Increasing the level to reduce the amount of clipping
// and
// slowly reveals the hand image
publishProgress(R.drawable.loading_full,
R.drawable.loading_empty, R.drawable.loading_empty,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_empty,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full);
// Sleep for 1/2 second
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
}
return stream;
}
}
/*
* Sends a query to server and gets back the parsed results in a bundle
* urlQueryString - URL for calling the webservice
*/
protected synchronized InputStream getQueryResults(String urlQueryString)
throws IOException, SAXException, SSLException,
SocketTimeoutException, Exception {
try {
// HttpsURLConnection https = null;
String uri = urlQueryString;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
BasicNameValuePair mdn1, mdn2,id1,id2;
if (MDN.equals("")) {
mdn1 = new BasicNameValuePair("mdn1", null);
mdn2 = new BasicNameValuePair("mdn2", null);
} else {
mdn1 = new BasicNameValuePair("mdn1", mdN1.toString());
mdn2 = new BasicNameValuePair("mdn2", mdN2.toString());
}
BasicNameValuePair car = new BasicNameValuePair("car", caR);
if (ICCID.equals("")) {
id1 = new BasicNameValuePair("id1", null);
id2 = new BasicNameValuePair("id2", null);
} else {
id1 = new BasicNameValuePair("id1",
iD1.toString());
id2 = new BasicNameValuePair("id2",
iD2.toString());
}
nameValuePairs.add(mdn1);
nameValuePairs.add(mdn2);
nameValuePairs.add(car);
nameValuePairs.add(id1);
nameValuePairs.add(id2);
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(
nameValuePairs, "ISO-8859-1");
KeyStore trustStore = KeyStore.getInstance(KeyStore
.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(
params, registry);
HttpClient httpClient = new DefaultHttpClient(ccm, params);
params = httpClient.getParams();
HttpClientParams.setRedirecting(params, true);
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader("Authorization",
getB64Auth("nmundru", "abc123"));
httpPost.setHeader("Content-Type", "text/plain; charset=utf-8");
Log.v("httpPost", httpPost.toString());
httpPost.setEntity(urlEncodedFormEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println("response...." + httpResponse.toString());
Log.v("response...", httpResponse.toString());
stream = httpResponse.getEntity().getContent();
// save the InputStream in a file
try {
FileOutputStream fOut = openFileOutput("settings.xml",
Context.MODE_WORLD_READABLE);
DataInputStream in = new DataInputStream(stream);
BufferedReader br = new BufferedReader(
new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println(strLine); //to print the response
// in logcat
fOut.write(strLine.getBytes());
}
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
fis = openFileInput("settings.xml");
} catch (Exception e) {
Log.e(LOG_TAG, e.toString());
// tryagain();
} finally {
// https.disconnect();
}
return stream;
}
private String getB64Auth(String login, String pass) {
String source = login + ":" + pass;
String ret = "Basic "
+ Base64.encodeToString(source.getBytes(), Base64.URL_SAFE
| Base64.NO_WRAP);
return ret;
}
#Override
protected void onPostExecute(InputStream stream) {
super.onPostExecute(stream);
// This method is called to parse the response and save the
// ArrayLists
success();
}
public void success() {
// to parse the response
try {
handler.getQueryResponse(fis);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// set method to save the ArryaLists from the parser
setArrayList();
Intent i = new Intent(UpdateActivity.this, ConfigFinalActivity.class);
startActivity(i);
finish();
}
// Framework UI thread method corresponding to publishProgress call in
// worker thread
protected void onProgressUpdate(Integer... progress) {
// Call function to update image view
setProgressImgView(progress[0], progress[1], progress[2],
progress[3], progress[4]);
}
}
private void setProgressImgView(Integer imgViewId1, Integer imgViewId2,
Integer imgViewId3, Integer imgViewId4, Integer imgViewId5) {
// update image view with the updating dots
// Reset view layout in case orientation while updating
setContentView(R.layout.updating);
mProgressImageview1 = (ImageView) findViewById(R.id.loading_empty1);
mProgressImageview2 = (ImageView) findViewById(R.id.loading_empty2);
mProgressImageview3 = (ImageView) findViewById(R.id.loading_empty3);
mProgressImageview4 = (ImageView) findViewById(R.id.loading_empty4);
mProgressImageview5 = (ImageView) findViewById(R.id.loading_empty5);
mProgressImageview1.setImageResource(imgViewId1);
mProgressImageview2.setImageResource(imgViewId2);
mProgressImageview3.setImageResource(imgViewId3);
mProgressImageview4.setImageResource(imgViewId4);
mProgressImageview5.setImageResource(imgViewId5);
}
#Override
protected void onRestart() {
super.onRestart();
if (mErrorAlert != null)
mErrorAlert.dismiss();
}
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);
}
private void assistUpdate() {
// Displaying final layout after pre-ICS automatic settings update
setContentView(R.layout.assist_update);
assist_update_btn = (Button) findViewById(R.id.assist_update_btn);
assist_update_btn.setOnClickListener((OnClickListener) this);
}
public void success() {
// to parse the response
try {
handler.getQueryResponse(fis);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// set method to save the ArryaLists from the parser
setArrayList();
Intent i = new Intent(this, ConfigFinalActivity.class);
startActivity(i);
finish();
}
public String getResult() {
return result;
}
}
You can use onPreExecute() and onPostExecute() methods from the AsyncTask to set the loading before/ remove it after the work is done.
try:
protected void onPreExecute() {
setProgressImgView(R.drawable.loading_full,
R.drawable.loading_empty, R.drawable.loading_empty,
R.drawable.loading_empty, R.drawable.loading_empty);
}
protected void onPostExecute(InputStream stream) {
setProgressImgView(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full);
// This method is called to parse the response and save the
// ArrayLists
success();
}

android dropbox authentication and upload in different activities

I am trying to upload a file from dropbox in another activity from where i autenticate to dropbox. I have this RegisterActivity.java where the user registers and then later when the registration is completed the webbrowser comes up and the user has to allow the dropbox authentication.
later in my app on another activity the user is going to upload a video to dropbox. the upload is made by ASyncTask and works well. The problem is now that i dont want to reauthenticate again. How do i fix that? Is it on the same session or do i start a new session? Now Iam trying to use the sam mDBApi form RegisterAcitivity but i think that is wrong. The keys are stored in the storeKeys() method and saves them in SharedPreferences.
Thank you very much in advance
Here is my RegisterActivity in pastebin which works. http://pastebin.com/K06JUWXv
Here is the activity that where i call my ASyncTask UploadFile:
public class ShowVideo extends Activity{
final static private String ACCOUNT_PREFS_NAME = "prefs";
final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";
private DropboxAPI<AndroidAuthSession> mDBApi = RegisterActivity.mDBApi;
private String[] storedKeys = getKeys();
UploadFile upload;
public static String path = "";
public static String fileName;
private VideoView ww;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //Forces landscape orientation which is what the camera uses.
setContentView(R.layout.showvideo);
Button yesButton = (Button) findViewById(R.id.yesButton);
Button noButton = (Button) findViewById(R.id.NoButton);
Button dbButton = (Button) findViewById(R.id.dropboxButton);
dbButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
if(v.getId() == R.id.dropboxButton){
if (mDBApi.getSession().isLinked() == true){
Log.d("ShowVideo", "TRUE");
}
if (mDBApi.getSession().isLinked() == false){
Log.d("ShowVideo", "FALSE");
}
}
}
});
yesButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(v.getId() == R.id.yesButton){
UploadFile upload = new UploadFile(ShowVideo.this,mDBApi,path);
upload.execute();
}
}
});
noButton.setOnClickListener(new OnClickListener() {
public void onClick(View w) {
File file = new File(path);
boolean deleted = false;
deleted = file.delete();
Log.e("TAG", Boolean.toString(deleted));
Intent intent = new Intent(ShowVideo.this, CaptureVideo.class);
startActivity(intent);
}
});
ww = (VideoView) findViewById(R.id.satisfiedVideoView);
path = getRealPathFromURI(CaptureVideo.uriVideo);
fileName = getFileNameFromUrl(path);
//AndroidAuthSession session = new AndroidAuthSession(new AppKeyPair(ret[0], ret[1]), AccessType.APP_FOLDER);
//mDBApi = new DropboxAPI<AndroidAuthSession>(session);
}
private void playVideo(){
ww.setVideoURI(CaptureVideo.uriVideo);
ww.setMediaController(new MediaController(this));
ww.start();
ww.requestFocus();
}
public static String getFileNameFromUrl(String path) {
String[] pathArray = path.split("/");
return pathArray[pathArray.length - 1];
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
/**DROPBOX-METHOD------------------------------------------*/
private String[] getKeys() {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
String key = prefs.getString(ACCESS_KEY_NAME, null);
String secret = prefs.getString(ACCESS_SECRET_NAME, null);
if (key != null && secret != null) {
String[] ret = new String[2];
ret[0] = key;
ret[1] = secret;
return ret;
} else {
return null;
}
}
}
Here is my ASyncTask if you would take a look at that. Shouldn't be needed.
public class UploadFile extends AsyncTask<Void, Long, Boolean> {
DropboxAPI<AndroidAuthSession> dDBApi;
Context dContext;
private String SAVE_PATH;
public UploadFile(Context context,DropboxAPI<AndroidAuthSession> mDBApi, String path) {
dContext = context.getApplicationContext();
dDBApi = mDBApi;
SAVE_PATH = path;
}
#Override
protected Boolean doInBackground(Void... params) {
FileInputStream inputStream = null;
try {
File file = new File(SAVE_PATH);
inputStream = new FileInputStream(file);
Entry newEntry = dDBApi.putFileOverwrite("/GAMES/GAME_BETWEEN_USER_A_USER_B/" + "PresentVideo.mp4", inputStream, file.length(), null);
}
catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while uploading.");
} catch (FileNotFoundException e) {
Log.e("DbExampleLog", "File not found.");
} catch (IOException e) {
Log.e("DbExampleLog", "Another Exception:" + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
Log.e("DbExampleLog", "Another Exception:" + e.getMessage());
e.printStackTrace();
}
finally {
if (inputStream != null) {
try {
inputStream.close();
}
catch (IOException e) {
}
}
}
return null;
}
}

Content Resolver pointing to wrong table with correct URI

I am having a problem on the line where I call the query to PostCategoryContent Provider
I get an error stating:
11-13 10:23:40.674: E/AndroidRuntime(26012): android.database.sqlite.SQLiteException: no such column: category_id (code 1): , while compiling: SELECT * FROM post WHERE (category_id=39)
Even though the URI points to another Table postCategory
Can anyone guide me on what I'm doing wrong?
public class PostFragment extends SherlockListFragment implements LoaderCallbacks<Cursor> {
private SimpleCursorAdapter adapter;
private boolean dataRetrieved;
private SlidingArea parent;
PullToRefreshListView pullToRefreshView;
EditText searchBox;
Bundle args = new Bundle();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
parent = (SlidingArea) getActivity();
setHasOptionsMenu(true);
fillData(false);
}
#Override
public void onResume() {
super.onResume();
parent.getSupportActionBar().setCustomView(R.layout.kpmg_actionbar_list_view);
parent.getSupportActionBar().setDisplayShowCustomEnabled(true);
parent.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final ImageView searchButton = (ImageView) parent.findViewById(R.id.kpmg_actionbar_image_search_list);
searchButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (searchBox.getVisibility() == View.GONE)
{
searchBox.setVisibility(View.VISIBLE);
searchBox.requestFocus();
InputMethodManager imm = (InputMethodManager) parent.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(searchBox, InputMethodManager.SHOW_IMPLICIT);
} else {
searchBox.setVisibility(View.GONE);
searchBox.clearFocus();
hideKeyboard(v);
}
}
});
final ImageView refreshButton = (ImageView) parent.findViewById(R.id.kpmg_actionbar_image_refresh_list);
refreshButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getData(getString(R.string.kpmg_json_get_articles), true);
refreshButton.setImageResource(R.drawable.kpmg_actionbar_refresh_dark);
fillData(true);
}
});
searchBox.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
filterData(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
//Constant used as key for ID being passed in the bundle between fragments
public static final String NEWS_ID = "newsID";
private void getData(String url, boolean showProgressDialog) {
new Request(showProgressDialog).execute(new String[] {url});
}
public class Request extends AsyncTask<String, Void, String> {
ProgressDialog dialog;
/* This is the only file that needs to be edited */
private GetResponse response = null;
private boolean showProgressDialog = true;
public Request(boolean showProgressDialog)
{
super();
this.showProgressDialog = showProgressDialog;
response = new GetResponse();
}
#Override
protected void onPreExecute() {
if (showProgressDialog) {
dialog = new ProgressDialog(parent);
dialog.setMessage("Retrieving latest information...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
}
//This method must return the type specified in the constructor
#Override
protected String doInBackground(String... url) {
response.setUrl(url[0]);
String res = response.execute();
// When it returns the "res" it will call onPostExecute
return res;
}
#Override
protected void onPostExecute(String result) {
// Here we have response from server
if ( isNetworkAvailable() ){
try {
JSONObject json = new JSONObject(result);
JSONArray arr = json.getJSONArray("posts");
for (int i = arr.length() - 1; i >= 0; --i) {
JSONObject row = arr.getJSONObject(i);
JSONArray arrCategories = row.getJSONArray("categories");
int Created = 0;
int Updated = 0;
for (int j = arrCategories.length() -1; j >= 0; --j){
JSONObject rowCategory = arrCategories.getJSONObject(j);
ContentValues categoryValues = new ContentValues();
categoryValues.put(PostCategoryTable.CATEGORY_ID, rowCategory.getInt("id"));
Cursor categoryCursor = parent.getContentResolver().query(PostCategoryContentProvider.CONTENT_URI, null, PostCategoryTable.CATEGORY_ID + "=" + categoryValues.getAsString(PostCategoryTable.CATEGORY_ID), null, null);
int categoryCount = categoryCursor.getCount();
if (categoryCount == 0) {
categoryValues.put(PostCategoryTable.ICON_NAME, rowCategory.getString("slug"));
categoryValues.put(PostCategoryTable.CATEGORY_NAME, rowCategory.getString("title"));
categoryValues.put(PostCategoryTable.PARENT_ID, rowCategory.getInt("parent"));
parent.getContentResolver().insert(PostCategoryContentProvider.CONTENT_URI, categoryValues);
Created++;
}
else {
categoryCursor.moveToFirst();
categoryValues.put(PostCategoryTable.ICON_NAME, rowCategory.getString("slug"));
categoryValues.put(PostCategoryTable.CATEGORY_NAME, rowCategory.getString("title"));
categoryValues.put(PostCategoryTable.PARENT_ID, rowCategory.getInt("parent"));
parent.getContentResolver().update(PostCategoryContentProvider.CONTENT_URI, categoryValues, PostCategoryTable.CATEGORY_ID + "=" + categoryValues.getAsString(PostCategoryTable.CATEGORY_ID), null);
Updated++;
}
categoryCursor.close();
}
Toast.makeText(parent,"Created : " + "" + Created + " | Updated : " + "" + Updated, Toast.LENGTH_SHORT).show();
if (row.getString("status").equals("publish")) {
ContentValues values = new ContentValues();
values.put(PostTable.POST_ID, row.getString("id"));
values.put(PostTable.CONTENT, Html.fromHtml(row.getString(PostTable.CONTENT)).toString());
values.put(PostTable.EXCERPT, Html.fromHtml(row.getString(PostTable.EXCERPT)).toString());
//image
//imageurl
values.put(PostTable.DATE_MODIFIED, row.getString(PostTable.DATE_MODIFIED));
values.put(PostTable.DATE_PUBLISHED, row.getString(PostTable.DATE_PUBLISHED));
//thumbnail
//thumbnailurl
values.put(PostTable.TITLE, row.getString(PostTable.TITLE));
values.put(PostTable.URL, row.getString("online-url"));
values.put(PostTable.VIDEO_URL, row.getString("video-url"));
//Check for new Categories
//getThumbnail
// byte[] image = AppHelper.getBlobFromURL(row.getString(BlogTable.THUMBNAIL));
// if (image != null) {
//
// values.put(BlogTable.THUMBNAIL, image);
//
// }
Cursor c = parent.getContentResolver().query(PostContentProvider.CONTENT_URI, null, PostTable.POST_ID + "=" + values.getAsString(PostTable.POST_ID), null, null);
int count = c.getCount();
if (count == 0) {
parent.getContentResolver().insert(PostContentProvider.CONTENT_URI, values);
}
else {
c.moveToFirst();
if (!(c.getString(c.getColumnIndex(PostTable.DATE_MODIFIED)).equalsIgnoreCase(values.getAsString(PostTable.DATE_MODIFIED)))) {
//
//
// if (c.getString(c.getColumnIndex(BlogTable.THUMBNAIL)) != values.get(BlogTable.THUMBNAIL)){
// //reset image
// }
//
parent.getContentResolver().update(PostContentProvider.CONTENT_URI, values, PostTable.POST_ID + "=" + values.getAsString(PostTable.POST_ID), null);
}
}
c.close();
//Here we should last retrieved time and used as part of the condition before retrieving data
}
else {
String currentID = row.getString("id");
// Delete unpublished fields
parent.getContentResolver().delete(PostContentProvider.CONTENT_URI, "_id = " + currentID, null);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else {
Toast toast = Toast.makeText( parent , "You are not connected to the internet. Please check your connection, or try again later",
Toast.LENGTH_SHORT);
toast.show();
}
// Call onRefreshComplete when the list has been refreshed.
pullToRefreshView.onRefreshComplete();
super.onPostExecute(result);
ImageView refreshButton = (ImageView) parent.findViewById(R.id.kpmg_actionbar_image_refresh_list);
refreshButton.setImageResource(R.drawable.kpmg_actionbar_refresh);
if (showProgressDialog) {
dialog.dismiss();
}
}
}
private void fillData(boolean isRefresh){
//_id is expected from this method that is why we used it earlier
String[] from = new String[] { PostTable.TITLE, PostTable.DATE_PUBLISHED, PostTable.EXCERPT};
int[] to = new int[] { R.id.kpmg_text_news_title, R.id.kpmg_text_news_date, R.id.kpmg_text_news_excerpt};
//initialize loader to call this class with a callback
if (!isRefresh){
getLoaderManager().initLoader(0, null, this);
}
else {
if (searchBox.getText().length() == 0) {
getLoaderManager().restartLoader(0, null, this);
}
else {
getLoaderManager().restartLoader(0, args, this);
}
}
//We create adapter to fill list with data, but we don't provide any data as it will be done by loader
adapter = new SimpleCursorAdapter(parent, R.layout.kpmg_list_view, null, from, to, 0);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int column) {
if( column == cursor.getColumnIndex(PostTable.DATE_PUBLISHED) ){ // let's suppose that the column 0 is the date
TextView textDate = (TextView) view.findViewById(R.id.kpmg_text_news_date);
String dateStr = cursor.getString(cursor.getColumnIndex(PostTable.DATE_PUBLISHED));
String formattedDate = AppHelper.calculateRelativeDate(dateStr);
textDate.setText( "Posted - " + formattedDate);
return true;
}
return false;
}
});
setListAdapter(adapter);
}
private void filterData(CharSequence cs){
args.putString("Selection", cs.toString());
getLoaderManager().restartLoader(0, args, this /*LoaderCallbacks<Cursor>*/);
}
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle args) {
String[] projection = new String[] { PostTable.TITLE, PostTable.DATE_PUBLISHED, PostTable.EXCERPT, PostTable.ID };
CursorLoader loader;
if (args == null) {
Log.i("Arguments","None");
loader = new CursorLoader(parent, PostContentProvider.CONTENT_URI, projection, null, null, PostTable.DATE_PUBLISHED + " DESC");
}
else {
Log.i("Arguments","Full");
String selectionKeyword = args.getString("Selection");
String selection = PostTable.TITLE + " LIKE ? OR " + PostTable.CONTENT + " LIKE ? OR " + PostTable.EXCERPT + " LIKE ?";
String[] selectionArgs = new String[] {"%" + selectionKeyword + "%","%" + selectionKeyword + "%","%" + selectionKeyword + "%"};
loader = new CursorLoader(parent, PostContentProvider.CONTENT_URI, projection, selection, selectionArgs, PostTable.DATE_PUBLISHED + " DESC");
}
return loader;
}
public void onLoadFinished(Loader<Cursor> arg0, Cursor data) {
adapter.swapCursor(data);
}
public void onLoaderReset(Loader<Cursor> arg0) {
adapter.swapCursor(null);
}
}
On which line is the exception thrown? The problem is more likely an issue with your SQLite syntax than with anything having to do with Loaders or Cursors. Make sure your table is getting initialized as you require. Do a DatabaseUtils.dumpCursor(cursor) to analyze the contents of the Cursor between the exception is thrown. Also, I would look into your use of LIKE... I have seen people having issues with that keyword before.

Categories

Resources