How to solve "Unreachable Statement" - java

This is my Android code.I have an error in below line Toast that say "Unreachable Statement" and I know this error come from return of my If but I don't know how solve it
Error part:
do
{
return;
if ((paramAnonymous2Int == 0) && (AndroidHTMLActivity.this.Count == 4))
{
Toast.makeText(getApplicationContext(),"نسخه رایگان",Toast.LENGTH_SHORT).show();
return;
}
}
The whole Function :
#JavascriptInterface
public void SaveDialog(final String paramString)
{
final SQLiteDatabase mydatabase = openOrCreateDatabase("CopyCollection", MODE_PRIVATE, null);
Object localObject = mydatabase.rawQuery("SELECT * FROM Details WHERE ID=" + paramString + ";", null);
if (((Cursor)localObject).moveToFirst()) {
do
{
AndroidHTMLActivity.this.appName = ((Cursor)localObject).getString(1);
AndroidHTMLActivity.this.txtClip = ((Cursor)localObject).getString(2);
AndroidHTMLActivity.this.text_Date = ((Cursor)localObject).getString(3);
} while (((Cursor)localObject).moveToNext());
}
localObject = new AlertDialog.Builder(AndroidHTMLActivity.this);
((AlertDialog.Builder)localObject).setTitle("ذخیره");
((AlertDialog.Builder)localObject).setPositiveButton("ذخیره", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
final SQLiteDatabase mydatabase1 = openOrCreateDatabase("CopyCollection", MODE_PRIVATE, null);
Cursor crs = mydatabase1.rawQuery("SELECT * FROM Groups;",null);
String[] array = new String[crs.getCount()];
int[] arrayID = new int[crs.getCount()];
Count = crs.getCount();
int i = 0;
while(crs.moveToNext()){
String uname = crs.getString(crs.getColumnIndex("GroupName"));
int id = crs.getColumnIndex("ID");
arrayID[i] = id;
array[i] = uname;
i++;
}
final AlertDialog.Builder builder = new AlertDialog.Builder(AndroidHTMLActivity.this);
builder.setTitle("گروه خود را انتخاب کنید");
builder.setItems(paramAnonymousDialogInterface, new DialogInterface.OnClickListener()
{
public void onClick(final DialogInterface paramAnonymous2DialogInterface, int paramAnonymous2Int)
{
strI = String.valueOf(paramAnonymous2Int);
String localObject1 = String.valueOf(paramAnonymous2Int);
final SQLiteDatabase mydatabase = openOrCreateDatabase("CopyCollection", MODE_PRIVATE, null);
Cursor localObject2 = mydatabase.rawQuery("SELECT * FROM Status WHERE ID=1;", null);
if ((localObject2).moveToFirst()) {
do
{
AndroidHTMLActivity.this.Trial = (localObject2).getInt(1);
} while ((localObject2).moveToNext());
}
if ((paramAnonymous2Int == 0) && (AndroidHTMLActivity.this.Count != 4))
{
final AlertDialog.Builder builder1 = new AlertDialog.Builder(AndroidHTMLActivity.this);
builder1.setTitle("درج عنوان گروه");
final EditText input = new EditText(AndroidHTMLActivity.this);
input.setInputType(1);
builder1.setView(input);
builder1.setPositiveButton("تایید", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymous3DialogInterface, int paramAnonymous3Int)
{
m_Text = input.getText().toString();
mydatabase.execSQL("INSERT INTO Groups (GroupName) VALUES('" + m_Text + "');");
Cursor c3 = mydatabase.rawQuery("SELECT * FROM Groups ORDER BY ID DESC LIMIT 1;", null);
if ((c3 != null) && (c3.moveToFirst()))
{
long l = c3.getLong(0);
LastDir = String.valueOf(l);
}
mydatabase.execSQL("INSERT INTO MainContent(AppName,Txt,GroupID,Time)VALUES('" + appName + "','" + txtClip + "','" + LastDir + "','" + text_Date + "');");
mydatabase.execSQL("DELETE FROM Details WHERE ID = " + paramString + ";");
mydatabase.close();
}
});
builder1.setNegativeButton("انصراف", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymous3DialogInterface, int paramAnonymous3Int)
{
paramAnonymous3DialogInterface.cancel();
AndroidHTMLActivity.this.myBrowser.post(new Runnable()
{
public void run()
{
myBrowser.loadUrl("javascript:fill_comment()");
}
});
}
});
builder1.show();
}
do
{
return;
if ((paramAnonymous2Int == 0) && (AndroidHTMLActivity.this.Count == 4))
{
Toast.makeText(getApplicationContext(),"نسخه رایگان",Toast.LENGTH_SHORT).show();
return;
}
}
while (paramAnonymous2Int == 0);
Cursor c2 = mydatabase.rawQuery("SELECT count(*) FROM `MainContent` WHERE `GroupID` LIKE '" + localObject1 + "'", null);
(c2).moveToFirst();
if ((c2).getInt(0) < 5)
{
mydatabase.execSQL("INSERT INTO MainContent (AppName,Txt,GroupID,Time) VALUES('" + AndroidHTMLActivity.this.appName + "','" + AndroidHTMLActivity.this.txtClip + "','" + (String)localObject1 + "','" + text_Date + "');");
mydatabase.execSQL("DELETE FROM Details WHERE ID = " + paramString + ";");
mydatabase.close();
}
Toast.makeText(getApplicationContext(),"نسخه رایگان",Toast.LENGTH_SHORT).show();
AndroidHTMLActivity.this.myBrowser.post(new Runnable()
{
public void run()
{
AndroidHTMLActivity.this.myBrowser.loadUrl("javascript:fill_comment()");
}
});
}
});
builder.create().show();
}
});
((AlertDialog.Builder)localObject).setNegativeButton("اشتراک گذاری", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
Intent intent = new Intent("android.intent.action.SEND");
intent.setType("text/plain");
String str = txtClip;
intent.putExtra("android.intent.extra.SUBJECT", "Subject");
intent.putExtra("android.intent.extra.TEXT", str);
startActivity(Intent.createChooser(intent, "Share via"));
}
});
((AlertDialog.Builder)localObject).show();
}
#JavascriptInterface
public void configuration()
{
Intent localIntent = new Intent(AndroidHTMLActivity.this, Directory.class);
AndroidHTMLActivity.this.startActivity(localIntent);
AndroidHTMLActivity.this.finish();
}

Look at this code
return;
if ((paramAnonymous2Int == 0) && (AndroidHTMLActivity.this.Count == 4))
You return right before the validation, hence will never reach it.

Simple remove the return statement at the begin of do block.
return means exit immediately so no other code after that line is reached.

Change ur do into this
do
{
if ((paramAnonymous2Int == 0) && (AndroidHTMLActivity.this.Count == 4))
{
Toast.makeText(getApplicationContext(),"نسخه رایگان",Toast.LENGTH_SHORT).show();
return;
}
}
It never reaches because u were returning on the beginning of the Do

In java when return is encountered it just exits the method at that point. Once return is executed, the rest of the code won't be executed. Java compiler detect the unreachable code and it will give error.
if(condition)
{
return;
yougetunreachableerror();//compiler gives error
}

Related

Android Studio + Database - Multiple check data to insert data if not exists

I'm having a problem with my code. I don't know how to check multiple columns in the database to insert different data on every not existing data.
For example:
1st input
Name: Raymond Jay Berin
Event: INTRAMURALS
FACILITATOR: CSG
2nd input
Name: Raymond Jay Berin
Event: LOVE SYMPOSIUM
FACILITATOR: DSSC
the thing here is that. Raymond Jay Berin already existed in the database, but I want Raymond Jay Berin will be inserted into a different event...
also, I already tried to create multiple tables but my project crashes when I click the attendance button to add data.
Code for DatabaseHelper.class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "attendance.sqlite";
public static final String TABLE_NAME = "attendance";
public static final String COL_1 = "ID";
public static final String COL_2 = "FULLNAME";
public static final String COL_EVENT_2 = "EVENT_NAME";
public static final String COL_EVENT_3 = "FACILITATOR_NAME";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
//ATTENDANCE
db.execSQL(" create table " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"FULLNAME TEXT NOT NULL, EVENT_NAME TEXT NOT NULL, FACILITATOR_NAME TEXT NOT NULL)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//ATTENDANCE
db.execSQL(" DROP TABLE IF EXISTS "+TABLE_NAME );
//recreate
onCreate(db);
}
//ATTENDANCE
public boolean insertData (String fullname, String event, String facilitator){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,fullname);
contentValues.put(COL_EVENT_2,event);
contentValues.put(COL_EVENT_3,facilitator);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
public boolean checkIfRecordExist(String nameOfTable,String columnName,String columnValue) {
SQLiteDatabase db = null;
try {
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT "+columnName+" FROM "+nameOfTable+" WHERE "+columnName+"='"+columnValue+"'",null);
if (cursor.moveToFirst()) {
db.close();
Log.d("Record Already Exists", "Table is:" + nameOfTable + " ColumnName:" + columnName);
return true;//record Exists
}
Log.d("New Record ", "Table is:" + nameOfTable + " ColumnName:" + columnName + " Column Value:" + columnValue);
db.close();
} catch (Exception errorException) {
Log.d("Exception occured", "Exception occured " + errorException);
db.close();
}
return false;
} }
Code for the Attendance.java class
public class Attendance extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
DatabaseHelper myDb;
EditText fname , eventname, faciname;
Button attendance;
Button view;
Switch lock;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance);
myDb = new DatabaseHelper(this);
fname = findViewById(R.id.txtFullname);
eventname = findViewById(R.id.eventname);
faciname = findViewById(R.id.faciname);
attendance = findViewById(R.id.btnatt);
view = findViewById(R.id.btnview);
lock = findViewById(R.id.switchLock);
viewAll();
AddData();
lock.setOnCheckedChangeListener(this);
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (lock.isChecked()){
eventname.setEnabled(false);
faciname.setEnabled(false);
}else{
eventname.setEnabled(true);
faciname.setEnabled(true);
}
}
public void viewAll() {
view.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = myDb.getAllData();
if (res.getCount() == 0) {
// show message
showMessage("Error", "Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
buffer.append("ID :" + res.getString(0) + "\n");
buffer.append("NAME :" + res.getString(1) + "\n");
buffer.append("EVENT :" + res.getString(2) + "\n");
buffer.append("FACILITATOR :" + res.getString(3) + "\n"+"\n");
}
// Show all data
showMessage("ATTENDANCE LIST", buffer.toString());
}
}
);
}
public void showMessage(String title, String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
public void AddData() {
attendance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String valInput = fname.getText().toString();
final String valInput1 = eventname.getText().toString();
final String valInput2 = faciname.getText().toString();
boolean valid = true;
if (TextUtils.isEmpty(valInput)) {
fname.setError("This Item must not be empty!");
valid = false;
}
if (TextUtils.isEmpty(valInput1)) {
eventname.setError("This Item must not be empty!");
valid = false;
}
if (TextUtils.isEmpty(valInput2)) {
faciname.setError("This Item must not be empty!");
valid = false;
}
if (valid) {
boolean isExist = myDb.checkIfRecordExist(DatabaseHelper.TABLE_NAME, DatabaseHelper.COL_1, fname.getText().toString());
if (!isExist) {
boolean isInserted = myDb.insertData(fname.getText().toString(), eventname.getText().toString(), faciname.getText().toString());
if (isInserted) {
Toast.makeText(Attendance.this, "Attendance Success", Toast.LENGTH_LONG).show();
fname.setText(null);
} else if (isInserted == false) {
Toast.makeText(Attendance.this, "Failed to Attendance", Toast.LENGTH_LONG).show();
}
}else if (isExist == true){
Toast.makeText(Attendance.this, "Failed to Attendance "+fname+" Already Existed", Toast.LENGTH_LONG).show();
}
}
}
}); }
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Handle the back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
//Ask the user if they want to quit
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.Logout)
.setMessage(R.string.really_logout)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Stop the activity
Intent intent = new Intent(Attendance.this, MainActivity.class);
startActivity(intent);
Attendance.this.finish();
}
})
.setNegativeButton(R.string.no, null)
.show();
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}}
change checkIfRecordExist method like this
public boolean checkIfRecordExist(String nameOfTable,String columnName1,String columnValue1,String columnName2,String columnValue2) {
SQLiteDatabase db = null;
try {
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM "+nameOfTable+" WHERE "+columnName1+"='"+columnValue1+"' and "+ columnName2 +"='"+columnValue2+"'",null);
.......................
change below line like this
boolean isExist = myDb.checkIfRecordExist(DatabaseHelper.TABLE_NAME, DatabaseHelper.COL_1, fname.getText().toString(),DatabaseHelper.COL_2, eventname.getText().toString())

database records not updating android studio , sql-lite

Could someone help me? my records are not updating.
I guess the edittext stay the same but not too sure.
How to change the view values that is being put in the edittext to change to the values in updating edittexts.
Would appreciate some help with this
Thank you.
DatabaseManager
public Cursor selectRow(String ID) {
String query = "Select * from " + TABLE_NAME + " where studentID = " + ID;
Cursor cursor = db.rawQuery(query, null);
return cursor;
}
public boolean updateData(String id, String fn, String ln, String ge, String cs, String a, String loc) {
ContentValues contentValues = new ContentValues();
contentValues.put("studentID", id);
contentValues.put("first_name", fn);
contentValues.put("last_name", ln);
contentValues.put("gender", ge);
contentValues.put("course_study", cs);
contentValues.put("age", a);
contentValues.put("location", loc);
db.update(TABLE_NAME, contentValues, "studentID = ?", new String[]{id});
return true;
}
The above is parts of my database that I use in this activity.
activity main.java
private void UpdateData() {
u.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
uptable.setVisibility(View.VISIBLE);
again.setVisibility(View.VISIBLE);
Cursor res = mydManager.selectRow(text);
if (res != null && res.moveToFirst()) {
String id = Integer.toString(res.getInt(0));
String nme = res.getString(1);
String lnme = res.getString(2);
String gen = res.getString(3);
String corse = res.getString(4);
String ag = Integer.toString(res.getInt(5));
String lo = res.getString(6);
studid.setText(id);
fname.setText(nme);
lname.setText(lnme);
gender.setText(gen);
course.setText(corse);
age.setText(ag);
loc.setText(lo);
}
}
}
);
}
public void UpdateData1() {
again.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
uptable.setVisibility(View.GONE);
String id = studid.getText().toString();
String nme = fname.getText().toString();
String lnme = lname.getText().toString();
String gen = gender.getText().toString();
String corse = course.getText().toString();
String ag = age.getText().toString();
String lo = loc.getText().toString();
boolean isUpdated = mydManager.updateData(id, nme , lnme, gen, corse ,ag , lo);
if (isUpdated == true)
Toast.makeText(Main4Activity.this, "Data Updated", Toast.LENGTH_LONG).show();
else
Toast.makeText(Main4Activity.this, "Data Not Updated", Toast.LENGTH_LONG).show();
}
}
);
}
I tried having a button to set the data but it still stays the same.
Sorry din't read the code, take the sample if it helps
Just the logic..
public long updateNote(NoteModel noteModel) {
if (LOG_DEBUG) UtilLogger.showLogUpdate(TAG, noteModel, noteModel.getRow_pos());
long updatedRow = 0;
try {
ContentValues contentValues = new ContentValues();
contentValues.put(DBSchema.DB_TITLE, noteModel.getTitle());
contentValues.put(DBSchema.DB_IMAGE_PATH, noteModel.getImgUriPath());
contentValues.put(DBSchema.DB_SUB_TEXT, noteModel.getSub_text());
contentValues.put(DBSchema.DB_CREATE_DATE, noteModel.getCreateDate());
contentValues.put(DBSchema.DB_UPDATE_DATE, noteModel.getUpdateDate());
contentValues.put(DBSchema.DB_SCHEDULED_TIME_LONG, noteModel.getScheduleTimeLong());
contentValues.put(DBSchema.DB_SCHEDULED_TIME_WHEN, noteModel.getScheduledWhenLong());
contentValues.put(DBSchema.DB_SCHEDULED_TITLE, noteModel.getScheduledTitle());
contentValues.put(DBSchema.DB_IS_ALARM_SCHEDULED, noteModel.getIsAlarmScheduled());
contentValues.put(DBSchema.DB_IS_TASK_DONE, noteModel.getIsTaskDone());
contentValues.put(DBSchema.DB_IS_ARCHIVED, noteModel.getIsArchived());
updatedRow = mSqLiteDatabase.updateWithOnConflict(
DBSchema.DB_TABLE_NAME,
contentValues,
DBSchema.DB_ROW_ID + " =?", new String[]{String.valueOf(noteModel.get_id())}, mSqLiteDatabase.CONFLICT_REPLACE);
return updatedRow;
} catch (SQLException e) {
e.printStackTrace();
}
return updatedRow;
}
then take the cursor
public Cursor getCursorForAlarmScheduled(String passAlarmScheduledStatus) {
if (LOG_DEBUG)
Log.w(TAG, " pick all record with alarmScheduled 1 : " + passAlarmScheduledStatus);
return mSqLiteDatabase.rawQuery(DBSchema.DB_SELECT_ALL +
" WHERE " + DBSchema.DB_IS_ALARM_SCHEDULED + " = " + passAlarmScheduledStatus, null);
}
and then extract
//common operation for all,
public static List<NoteModel> extractCommonData(Cursor cursor, List<NoteModel> noteModelList) {
noteModelList = new ArrayList<>();
if (LOG_DEBUG) Log.i(TAG, "inside extractCommonData()");
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
NoteModel noteModel = new NoteModel();
noteModel.set_id(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_ROW_ID)));
noteModel.setTitle(cursor.getString(cursor.getColumnIndex(DBSchema.DB_TITLE)));
noteModel.setImgUriPath(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IMAGE_PATH)));
noteModel.setSub_text(cursor.getString(cursor.getColumnIndex(DBSchema.DB_SUB_TEXT)));
noteModel.setCreateDate(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_CREATE_DATE)));
noteModel.setUpdateDate(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_UPDATE_DATE)));
noteModel.setScheduleTimeLong(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_SCHEDULED_TIME_LONG)));
noteModel.setScheduledWhenLong(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_SCHEDULED_TIME_WHEN)));
noteModel.setScheduledTitle(cursor.getString(cursor.getColumnIndex(DBSchema.DB_SCHEDULED_TITLE)));
noteModel.setIsAlarmScheduled(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IS_ALARM_SCHEDULED)));
noteModel.setIsTaskDone(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IS_TASK_DONE)));
noteModel.setIsArchived(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IS_ARCHIVED)));
noteModelList.add(noteModel);
} while (cursor.moveToNext());
}
cursor.close();
}
return noteModelList;
}
Again, I din't read,just copied from my old samples
Please do find the needful, cheers

How to add quantity if item already exist

I would like to check whether a record exists or not.If exist , i want to add the quantity.
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = etCode.getText().toString();
String product = etProduct.getText().toString();
String qty = etQty.getText().toString();
try {
if (isExist(code)) {
rQty = Integer.parseInt(rQty + etQty.getText().toString());
} else {
myDB.addData(code, product, Integer.parseInt(qty));
Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
}
}
});
}
public boolean isExist(String code) {
boolean result;
SQLiteDatabase db = myDB.getReadableDatabase();
try {
Cursor cursor = db.rawQuery("SELECT QTY FROM users_data WHERE CODE " + code + "'", null);
if (cursor.getCount() > 0 ){
while (cursor.moveToFirst()){
rQty = cursor.getInt(cursor.getColumnIndex("QTY"));
}
result = true;
}else {
result = false;
}
}
catch (Exception ex){
result = false;
}
return result;
}
}
Here is the code.if insert the same code of item , the data become duplicate and it not add the quantity for the same code.Please help me to solve this problem .
There are multiple errors and bugs in your code. One problem is this code
rQty = Integer.parseInt(rQty + etQty.getText().toString());
It won't add qQty with input quantity. because here strings concatenated.
You have to use
rQty += Integer.parseInt (qty);
Second one is your sqlite query is not right and it is incomplete
so change
Cursor cursor = db.rawQuery("SELECT QTY FROM users_data WHERE CODE " + code + "'", null);
to
Cursor cursor = db.rawQuery("SELECT QTY FROM users_data WHERE CODE = '" + code + "'", null);
Try below code
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = etCode.getText().toString();
String product = etProduct.getText().toString();
String qty = etQty.getText().toString();
try {
if (isExist(code)) {
rQty += Integer.parseInt (qty);
} else {
myDB.addData(code, product, Integer.parseInt(qty));
Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
}
}
});
}
public boolean isExist(String code) {
boolean result;
SQLiteDatabase db = myDB.getReadableDatabase();
try {
Cursor cursor = db.rawQuery("SELECT QTY FROM users_data WHERE CODE = '" + code + "'", null);
if (cursor.getCount() > 0 ){
while (cursor.moveToFirst()){
rQty = cursor.getInt(cursor.getColumnIndex("QTY"));
}
result = true;
}else {
result = false;
}
}
catch (Exception ex){
result = false;
}
return result;
}

Can ListView host TextView items that are also displayed in a separate TextView

I'm having a problem changing a TextView to a ListView. Originally, the app had a button that when clicked, runs tests to a bluetooth device and displays the results in a textview. I modified the app to contain two textviews that have the last text results and a separate xml file (connected with viewflipper) to go to a second textview that contains all of the test results, until the user clears the textview by clicking a button. I followed along with this example and checked what I was entering in the ArrayAdapter section of the code, and it appears to be what is required according to the developer's guide, but I still get his error:
Cannot resolve constructor 'ArrayAdapter(com.example.android.stardustscanner.ScannerFragment, int, int, java.lang.String)'
Why am I getting this error?
My .java file that I am making all the changes in is very long and contains a lot of thins that aren't relevant to this question and doesn't fit in the question box, so I'll try to only include the relevant parts. The error is towards the bottom with this line:
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.fragment_bluetooth_scanner, R.id.textView, saveData);
ScannerFragment.java
public class ScannerFragment extends Fragment implements LocationListener {
ListView mListView;
//page switching things KG 8/24/17
private ViewFlipper mViewFlipper;
private float lastX;
private Button mViewLog;
private Button mReturnFlipper;
private TextView mShowData;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.flipper_holder, container, false);//kg 8/24/17
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
SP = PreferenceManager.getDefaultSharedPreferences(getContext());
mViewFlipper = (ViewFlipper) view.findViewById(R.id.viewFlip); //KG 8/24/17
mViewLog = (Button) view.findViewById(R.id.viewLog); //kg 8/24/17
mReturnFlipper = (Button) view.findViewById(R.id.flipperReturn); //kg 8/24/17
mShowData = (TextView) view.findViewById(R.id.textView) ; //kg 8/25/2017
mShowData.setText(readFromFile()); // kg 8/25/2017
mPowerOffButton = (Button) view.findViewById(R.id.button_poweroff);
mDisconnectButton = (Button) view.findViewById(R.id.button_disconnect);
mConnectButton = (Button) view.findViewById(R.id.button_connect);
mPresence = (Button) view.findViewById(R.id.button_present);
mBattery = (ProgressBar) view.findViewById(R.id.progressBar);
mBlinkConnect = (Button) view.findViewById(R.id.button_connectionblink);
mBlinkData = (Button) view.findViewById(R.id.button_communication);
mClearLog = (Button) view.findViewById(R.id.button_clear_log);
mDeviceName = (Button) view.findViewById(R.id.button_devicename);
mDeviceSN = (Button) view.findViewById(R.id.button_devicesn);
mBatteryPerc = (TextView) view.findViewById(R.id.label_batterypct);
mListView = (ListView) view.findViewById(R.id.scanLogView); //kg 8/28/17
// mReadingLog = (TextView) view.findViewById(R.id.scanLogView);
mReadingLog.setMovementMethod(new ScrollingMovementMethod());
mReadingLog.setText(readFromFile());
telephonyManager = (TelephonyManager)getContext().getSystemService(Context.TELEPHONY_SERVICE);
initLocationService(this.getContext());
final ActionBar actionBar = getActivity().getActionBar();
if (null == actionBar) {
return;
}
final Drawable D = getResources().getDrawable(R.drawable.stardust2);
actionBar.setBackgroundDrawable(D);
actionBar.setTitle("");
//KG 8/24/17
mViewLog.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
mViewFlipper.showNext();
}
});
mReturnFlipper.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
mViewFlipper.showPrevious();
}
});
}
private void setupScanner() {
Log.d(TAG, "setupScanner()");
// Initialize the send button with a listener that for click events
mPowerOffButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(isIris) {
publishMessage(Constants.COMMAND_POWEROFF_IRIS);
} else {
publishMessage(Constants.COMMAND_POWEROFF);
}
mScannerService.stop();
}
});
// Initialize the send button with a listener that for click events
mDisconnectButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
publishMessage(Constants.COMMAND_DISCONNECT);
mScannerService.stop();
}
});
// Initialize the send button with a listener that for click events
mConnectButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
publishMessage(Constants.COMMAND_ON_CONNECT);
}
});
mClearLog.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
mReadingLog.setText("");
if(SP.getBoolean("writeToFile", true)) {
writeToFile("", "", false);
}
}
});
// Initialize the ScannerService to perform bluetooth connections
mScannerService = new ScannerService(getActivity(), mHandler);
}
private TextView.OnEditorActionListener mWriteListener
= new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
// If the action is a key-up event on the return key, send the message
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
String message = view.getText().toString();
publishMessage(message);
}
return true;
}
};
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
FragmentActivity activity = getActivity();
switch (msg.what) {
case Constants.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case ScannerService.STATE_CONNECTED:
setStatus(mConnectedDeviceName);
if(mConnectedDeviceName.substring(0, 4).toLowerCase().equals("iris") || mConnectedDeviceName.substring(0, 8).toLowerCase().equals("stardust")) {
isIris = true;
mPresence.setClickable(true);
mPresence.setText("Click to detect taggant");
mPresence.setBackgroundColor(Color.parseColor("#0061ff"));
mPresence.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
readoutStarted = true;
publishMessage(Constants.COMMAND_RUN_IRIS);
}
});
mPowerOffButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
publishMessage(Constants.COMMAND_POWEROFF_IRIS);
mScannerService.stop();
}
});
} else {
isIris = false;
}
if(!isIris) {
mPresence.setClickable(false);
mPresence.setText("NO TAGGANT DETECTED");
mPresence.setBackgroundColor(Color.parseColor("#ffc4ab"));
publishMessage(Constants.COMMAND_ON_CONNECT);
timer = new Timer();
timerStarted = true;
timer.scheduleAtFixedRate(new TimerTask() {
synchronized public void run() {
publishMessage(Constants.COMMAND_READDATA);
}
}, 1000, 1000);
} else {
if(timerStarted) {
timer.cancel();
timer.purge();
timerStarted = false;
}
}
mBlinkConnect.setBackgroundColor(Color.parseColor("#11D901"));
break;
case ScannerService.STATE_CONNECTING:
setStatus("C");
break;
case ScannerService.STATE_LISTEN:
case ScannerService.STATE_NONE:
mBlinkConnect.setBackgroundColor(Color.parseColor("#ff2b0f"));
mBlinkData.setBackgroundColor(Color.parseColor("#CCCCCC"));
if(timerStarted) {
timer.cancel();
timer.purge();
timerStarted = false;
}
setStatus("D");
break;
}
break;
case Constants.MESSAGE_WRITE:
mBlinkData.setBackgroundColor(Color.parseColor("#CCCCCC"));
break;
case Constants.MESSAGE_READ:
mBlinkData.setBackgroundColor(Color.parseColor("#0091FA"));
String readMessage = (String)msg.obj;
if(isIris) {
readIris(readMessage);
} else {
readNormal(readMessage);
}
break;
case Constants.MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
if (null != activity) {
Toast.makeText(activity, "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
}
break;
case Constants.MESSAGE_TOAST:
if (null != activity) {
Toast.makeText(activity, msg.getData().getString(Constants.TOAST),
Toast.LENGTH_SHORT).show();
}
break;
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, true);
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a session
setupScanner();
} else {
// User did not enable Bluetooth or an error occurred
Log.d(TAG, "BT not enabled");
Toast.makeText(getActivity(), R.string.bt_not_enabled_leaving,
Toast.LENGTH_SHORT).show();
getActivity().finish();
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.secure_connect_scan: {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
return true;
}
/*case R.id.insecure_connect_scan: {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
return true;
}*/
case R.id.settings_button: {
Intent serverIntent = new Intent(getActivity(), SettingsActivity.class);
startActivityForResult(serverIntent, REQUEST_SHOW_SETTINGS);
return true;
}
}
return false;
}
/**
*
* #param data String
* #param append boolean
*/
private void writeToFile(String data, String uploadData, boolean append) {
String root = Environment
.getExternalStorageDirectory().toString();
File myDir = new File(root);
String fname = "starDust.txt";
String fname2 = "starDust.csv";
File file = new File (myDir, fname);
File file2 = new File (myDir, fname2);
//if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file, append);
out.write(data.getBytes(), 0, data.getBytes().length);
out.flush();
out.close();
FileOutputStream out2 = new FileOutputStream(file2, append);
out2.write(uploadData.getBytes(), 0, uploadData.getBytes().length);
out2.flush();
out2.close();
if(mConnectedDeviceName != null) {
Log.d(TAG, "Connecting " + SP.getString("server_ip", "") + SP.getString("server_username", "") + SP.getString("server_password", ""));
new FTPUploadTask().execute(mConnectedDeviceName, SP.getString("server_ip", ""), SP.getString("server_username", "") , SP.getString("server_password", ""));
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
*/
private String readFromFile() {
String root = Environment
.getExternalStorageDirectory().toString();
File myDir = new File(root);
String fname = "starDust.txt";
File file = new File (myDir, fname);
StringBuilder text = new StringBuilder();
if (file.exists ()) {
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.insert(0, line + System.getProperty("line.separator"));
}
br.close();
} catch (Exception e) {
}
}
return text.toString();
}
private void readNormal(String readMessage) {
String parsedData[];
if(readMessage.contains(";")) {
if(readMessage.equals(";")) {
parsedData = bufferedMessage.trim().split(",");
bufferedMessage = "";
} else {
String partialMessage[] = readMessage.split(";");
bufferedMessage += partialMessage[0];
parsedData = bufferedMessage.trim().split(",");
if (partialMessage.length > 1) {
bufferedMessage = partialMessage[1];
} else {
bufferedMessage = "";
}
}
} else {
bufferedMessage += readMessage.trim();
return;
}
if(parsedData.length == RESPONSE_SIZE && parsedData[0].equals("U")) {
if(parsedData[1].matches("[-+]?\\d*\\.?\\d+")) {
if(Integer.parseInt(parsedData[1]) > maxU1 || hitTrigger) {
maxU1 = Integer.parseInt(parsedData[1]);
}
}
if(parsedData[2].matches("[-+]?\\d*\\.?\\d+")) {
if(Integer.parseInt(parsedData[2]) > maxU2 || hitTrigger) {
maxU2 = Integer.parseInt(parsedData[2]);
}
}
if(parsedData[3].matches("[-+]?\\d*\\.?\\d+")) {
if(Integer.parseInt(parsedData[3]) > maxU3 || hitTrigger) {
maxU3 = Integer.parseInt(parsedData[3]);
}
}
double u1val = Double.parseDouble(parsedData[1]);
double u2val = Double.parseDouble(parsedData[2]);
double u1u2div = 0;
if(u2val > 0) {
u1u2div = ((u1val / u2val) * KFactor);
}
if(parsedData[4].matches("[-+]?\\d*\\.?\\d+")) {
mBatteryPerc.setText(parsedData[4] + "%");
mBattery.setProgress(Integer.parseInt(parsedData[4]));
}
}
taggantType = 0;
if(maxU1 > Integer.parseInt(SP.getString("maxThreshold", Integer.toString(MAX_TRIGGER)))) {
taggantType += 4;
} else {
taggantType += 0;
}
if(maxU2 > Integer.parseInt(SP.getString("maxThreshold", Integer.toString(MAX_TRIGGER)))) {
taggantType += 2;
} else {
taggantType += 0;
}
if(maxU3 > Integer.parseInt(SP.getString("maxThreshold", Integer.toString(MAX_TRIGGER)))) {
taggantType += 1;
} else {
taggantType += 0;
}
Log.d(TAG, Integer.toString(taggantType));
Log.d(TAG, Boolean.toString(hitTrigger));
Log.d(TAG, bufferedMessage);
// Check if hit threshold, if so hitTrigger is enabled.
if(taggantType > 0) {
savedTaggantType = taggantType;
hitTrigger = true;
mPresence.setText("VALID TAGGANT DETECTED");
mPresence.setBackgroundColor(Color.parseColor("#11D901"));
} else if(taggantType == 0 && hitTrigger) {
hitTrigger = false;
mPresence.setText("NO TAGGANT DETECTED");
mPresence.setBackgroundColor(Color.parseColor("#ffc4ab"));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
String saveData =
"Device: " + mConnectedDeviceName +
System.getProperty("line.separator") +
"Timestamp: " + currentDateandTime +
System.getProperty("line.separator") +
"Location: " + latitude + " (lat) / " + longitude + " (lon)" +
System.getProperty("line.separator") +
"Taggan Type: N" + Integer.toString(savedTaggantType) +
System.getProperty("line.separator") +
"Phone id: " + telephonyManager.getDeviceId() +
System.getProperty("line.separator") +
"=========================" +
System.getProperty("line.separator");
String csvData = mConnectedDeviceName + "," +
currentDateandTime + "," +
"\"http://maps.google.com/?q=" + latitude + "," + longitude + "\"," +
"N" + Integer.toString(savedTaggantType) + "," +
"\"" + telephonyManager.getDeviceId() + "\"" +
System.getProperty("line.separator");
mReadingLog.setText(saveData + mReadingLog.getText());
mShowData.setText(saveData); //kg 8/25/17
maxU1 = 0;
maxU2 = 0;
maxU3 = 0;
savedTaggantType = 0;
if(SP.getBoolean("writeToFile", true)) {
writeToFile(saveData, csvData, true);
}
}
}
/**
* #param readMessage String
*/
public void readIris(String readMessage) {
if(!readoutStarted) {
return;
}
String parsedData[];
if(readMessage.contains(";")) {
readoutStarted = false;
if(readMessage.equals(";")) {
parsedData = bufferedMessage.replaceAll("\n", "").replaceAll(" +", " ").trim().split("\\*");
bufferedMessage = "";
} else {
String partialMessage[] = readMessage.replaceAll("\n", "").replaceAll(" +", " ").trim().split(";");
bufferedMessage += partialMessage[0].trim();
parsedData = bufferedMessage.replaceAll("\n", "").replaceAll(" +", " ").trim().split("\\*");
bufferedMessage = "";
}
} else {
bufferedMessage += readMessage.trim().replaceAll("\n", "").replaceAll(" +", " ");
return;
}
Log.d(TAG, Arrays.toString(parsedData));
boolean passed = false;
int v1 = 0;
int v2 = 0;
if(parsedData[3].equals("S")) {
passed = true;
String values[] = parsedData[7].split("\\s+");
v1 = Integer.parseInt(values[0].replaceAll("[\\D]", ""));
v2 = Integer.parseInt(values[values.length-1]);
} else {
Log.d(TAG, Arrays.toString(parsedData));
String values[] = parsedData[5].split("\\s+");
v1 = Integer.parseInt(values[0].replaceAll("[\\D]", ""));
v2 = Integer.parseInt(values[values.length-1]);
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
String saveData =
"Device: " + mConnectedDeviceName +
System.getProperty("line.separator") +
"Timestamp: " + currentDateandTime +
System.getProperty("line.separator") +
"Location: " + latitude + " (lat) / " + longitude + " (lon)" +
System.getProperty("line.separator") +
"Phone id: " + telephonyManager.getDeviceId() +
System.getProperty("line.separator") +
"Valid:" + (passed ? "YES" : "NO") +
System.getProperty("line.separator") +
"Values: " + "T" + v1 + " / " + v2 +
System.getProperty("line.separator") +
"=========================" +
System.getProperty("line.separator");
String csvData = mConnectedDeviceName + "," +
currentDateandTime + "," +
"\"http://maps.google.com/?q=" + latitude + "," + longitude + "\"," +
"Valid: " + (passed ? "YES" : "NO") + " - " + "T" + v1 + " / " + v2 + Integer.toString(savedTaggantType) + "," +
"\"" + telephonyManager.getDeviceId() + "\"" +
System.getProperty("line.separator");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.fragment_bluetooth_scanner, R.id.textView, saveData);
mListView.setAdapter(arrayAdapter);
mReadingLog.setText(saveData + mReadingLog.getText());
mShowData.setText(saveData); //kg 8/25/17
if(SP.getBoolean("writeToFile", true)) {
writeToFile(saveData, csvData, true);
}
}
}
I have three xml files associated with this problem, but because of space I'll only include the one that contains the ListView and remove the other buttons.
view_list.xml contains the ListView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="#+id/viewList"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal"
android:paddingLeft="4dp"
android:paddingRight="4dp"
android:visibility="visible">
<LinearLayout
android:layout_width="match_parent"
android:id="#+id/listview_holder"
android:layout_alignParentTop="true"
android:layout_alignTop="#id/button_holder"
android:layout_weight=".1"
android:layout_height="wrap_content">
<ListView
android:id="#+id/scanLogView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:maxLines="4096"
android:scrollbars="vertical"
android:text="#string/app_name"
android:textAppearance="?android:attr/textAppearanceSmall"/>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
The error was with ArrayAdapter. I changed the decloration from
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
R.layout.fragment_bluetooth_scanner, R.id.textView, saveData);
to
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, listItems);
It now builds the project and displays the listview.

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