Passing object to CursorAdapter getting null - android

I am getting a callback in my main activity that is passing an object of values from a ListView click. If I throw a toast the toast is displaying the key, value pairs. I want to take that and add it to the TopListCursorAdapter to populate a new row. I am getting null on the topAdapter.notifyDataSetChanged();
Not sure how to add mEmployee to the adapter, I have tried to
#Override
public void onBottomListClick(Employee e) {
mEmployee.add(e);
dbHandler.addEmployee(e);
SQLiteDatabase db = dbHandler.getWritableDatabase();
final Cursor clickedEmployee = db.rawQuery("SELECT * FROM " + "employees" + " WHERE " +
"Employee_number" + "=" + e.getEmployee_number(), null);
// change the adapter's Cursor
topAdapter.changeCursor(clickedEmployee);
}
But I do not want to pass a cursor and the TopListCursorAdapter wants one. I just want to add mEmployee to the existing List in TopListCursorAdapter.
public class MainActivity extends FragmentActivity implements BottomListViewAdapter.BottomListClickListener {
private ProgressBar mProgressBar;
EmployeeDBHandler dbHandler;
private TopListCursorAdapter topAdapter;
private BottomListViewAdapter bottomAdapter;
private ArrayList mEmployee;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
dbHandler = new EmployeeDBHandler(getApplicationContext());
mProgressBar.setVisibility(View.VISIBLE);
getXMLData();
//GUI for seeing android SQLite Database in Chrome Dev Tools
Stetho.InitializerBuilder inBuilder = Stetho.newInitializerBuilder(this);
inBuilder.enableWebKitInspector(Stetho.defaultInspectorModulesProvider(this));
Stetho.Initializer in = inBuilder.build();
Stetho.initialize(in);
}
public void getXMLData() {
OkHttpClient client = getUnsafeOkHttpClient();
Request request = new Request.Builder()
.url(getString(R.string.API_FULL_URL))
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
final String responseData = response.body().string();
final InputStream stream = new ByteArrayInputStream(responseData.getBytes());
final XMLPullParserHandler parserHandler = new XMLPullParserHandler();
final ArrayList<Employee> employees = (ArrayList<Employee>) parserHandler.parse(stream);
for (Employee e : employees) {
dbHandler.addEmployee(e);
}
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressBar.setVisibility(View.GONE);
displayTopList();
displayBottomList();
}
});
}
});
}
public void displayTopList() {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.topFragment, new TopFragment());
fragmentTransaction.commit();
}
public void displayBottomList() {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.bottomFragment, new BottomFragment());
fragmentTransaction.commit();
}
#Override
public void onBottomListClick(Employee e) {
mEmployee.add(e);
dbHandler.addEmployee(e);
SQLiteDatabase db = dbHandler.getWritableDatabase();
final Cursor clickedEmployee = db.rawQuery("SELECT * FROM " + "employees" + " WHERE " +
"Employee_number" + "=" + e.getEmployee_number(), null);
// change the adapter's Cursor
topAdapter.changeCursor(clickedEmployee);
}
}
TopListCursorAdapter
public class TopListCursorAdapter extends CursorAdapter {
private EmployeeDBHandler dbHandler;
private Activity activityRef;
public TopListCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
activityRef = (Activity) context;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.contact_cardview_layout, parent, false);
}
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
dbHandler = new EmployeeDBHandler(context);
ViewHolder holder;
holder = new ViewHolder();
holder.tvFirstName = (TextView) view.findViewById(R.id.personFirstName);
holder.tvLastName = (TextView) view.findViewById(R.id.personLastName);
holder.tvTitle = (TextView) view.findViewById(R.id.personTitle);
holder.mPeepPic = (ImageView) view.findViewById(R.id.person_photo);
holder.mDetailsButton = (ImageButton) view.findViewById(R.id.fullDetailButton);
holder.mCardView = (CardView) view.findViewById(R.id.home_screen_cardView);
String mFirstName = cursor.getString(cursor.getColumnIndexOrThrow("First_name"));
String mLastName = cursor.getString(cursor.getColumnIndexOrThrow("Last_name"));
String mPayrollTitle = cursor.getString(cursor.getColumnIndexOrThrow("Payroll_title"));
String mThumbnail = cursor.getString(cursor.getColumnIndexOrThrow("ThumbnailData"));
holder.tvFirstName.setText(mFirstName);
holder.tvLastName.setText(mLastName);
holder.tvTitle.setText(mPayrollTitle);
if (mThumbnail != null) {
byte[] imageAsBytes = Base64.decode(mThumbnail.getBytes(), Base64.DEFAULT);
Bitmap parsedImage = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
holder.mPeepPic.setImageBitmap(parsedImage);
} else {
holder.mPeepPic.setImageResource(R.drawable.img_place_holder_adapter);
}
activityRef.runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
final int position = cursor.getPosition();
holder.mDetailsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cursor.moveToPosition(position);
String mEmployeeNumber = cursor.getString(1);
String mEmail = cursor.getString(8);
String mFirstName = cursor.getString(2);
String mLastName = cursor.getString(3);
String mPhoneMobile = cursor.getString(4);
String mPhoneOffice = cursor.getString(5);
String mCostCenter = cursor.getString(10);
String mHasDirectReports = cursor.getString(7);
String mTitle = cursor.getString(6);
String mPic = cursor.getString(9);
Intent mIntent = new Intent(context, EmployeeFullInfo.class);
mIntent.putExtra("Employee_number", mEmployeeNumber);
mIntent.putExtra("Email", mEmail);
mIntent.putExtra("First_name", mFirstName);
mIntent.putExtra("Last_name", mLastName);
mIntent.putExtra("Phone_mobile", mPhoneMobile);
mIntent.putExtra("Phone_office", mPhoneOffice);
mIntent.putExtra("Cost_center_id", mCostCenter);
mIntent.putExtra("Has_direct_reports", mHasDirectReports);
mIntent.putExtra("Payroll_title", mTitle);
mIntent.putExtra("ThumbnailData", mPic);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(mIntent);
}
});
}
public static class ViewHolder {
TextView tvFirstName;
TextView tvLastName;
TextView tvTitle;
ImageView mPeepPic;
ImageButton mDetailsButton;
CardView mCardView;
}
}

I do not want to pass a cursor and the TopListCursorAdapter wants one
Sure. You have a DBHandler which can give you a Cursor.
dbHandler = new EmployeeDBHandler(getApplicationContext());
And you have an addEmployee method.
dbHandler.addEmployee(e);
So the question is - how did you create the TopListCursorAdapter without already having a Cursor since it is required??
Anyways, you should not stick a EmployeeDBHandler in the adapter.
It only wants a Cursor. Plus, you never seem to use that class in there.
public class TopListCursorAdapter extends CursorAdapter {
// private EmployeeDBHandler dbHandler; // ** Not needed
private Context mContext; // Don't need an Activity
public TopListCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
mContext = context; // Just a Context, no Activity
}
And you should never need to create a new TopListAdapter after the first creation of one, you can call changeCursor directly on the existing adapter.
#Override
public void onBottomListClick(Employee e) {
mEmployee.add(e);
dbHandler.addEmployee(e);
// topAdapter = new TopListCursorAdapter(); // ** Nope
Cursor newCursor = dbHandler.getEmployees(); // TODO: Implement this
topAdapter.changeCursor(newCursor); // Updates the UI itself
Intent employeeDetail = new Intent(MainActivity.this, EmployeeFullInfo.class);
employeeDetail.putExtra("Employee_number", e.getNumber());
...
startActivity(employeeDetail);
}
Note: If you use Parcelable Employee objects, you do not need a bunch putExtra and getExtra methods on the Intents.
Additionally, you can store an Employee object as part of the ViewHolder for simpler data management. That way, you only need to extract data from the Cursor into an Employee, then the ViewHolder can maintain that since you are duplicating the effort within onClick to get the Cursor data.
public static class ViewHolder {
Employee employee; // See here
TextView tvFirstName;
TextView tvLastName;
TextView tvTitle;
ImageView mPeepPic;
ImageButton mDetailsButton;
CardView mCardView;
}

Related

Merging cursor only gives back first cursor in clickEvent

Passing the cursor of position clicked but when doing so log is showing me I am getting only the first row no matter where I click.
holder.mTopCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mCallback != null) {
mCallback.onTopListClick(cursor);
notifyDataSetChanged();
Log.i("FROMCLICK", DatabaseUtils.dumpCursorToString(cursor));
}
}
});
The log inside the CursorAdapter onClickListener is showing only the first rows cursor even if I click 20 rows down the list.
#Override
public void onTopListClick(Cursor cursor) {
Log.i("FistClickBeforePassing", DatabaseUtils.dumpCursorToString(cursor));
BottomFragment bottomFragment = (BottomFragment) getSupportFragmentManager().findFragmentById(R.id.bottomFragment);
bottomFragment.refreshList(cursor);
}
Same thing here before passing to the BottomFragment.
public void refreshList(Cursor cursor) {
Log.i("RIGHTBEFOREREFRESH", DatabaseUtils.dumpCursorToString(cursor));
String mEmployeeNumber = cursor.getString(1);
Log.i("REFRESHLISTNUMBER", mEmployeeNumber);
dbHandler = EmployeeDBHandler.getInstance(getContext());
db = dbHandler.getReadableDatabase();
mNewBottomCursor = db.rawQuery("SELECT * FROM " + table + " WHERE " +
/*"Employee_number" + "!=" + mStartingEmployeeID + " AND " +*/
"Manager_employee_number" + "=" + mEmployeeNumber + " ORDER BY " +
"Last_name" + " ASC", null);
Log.i("THECURSOR ", DatabaseUtils.dumpCursorToString(mNewBottomCursor));
BottomListCursorAdapter bottomListCursorAdapter = new BottomListCursorAdapter(getActivity(), cursor);
bottomListCursorAdapter.swapCursor(mNewBottomCursor);
mBottomListView.setAdapter(bottomListCursorAdapter);
}
}
Get the same cursor here for the log but do not get the same employee_number the cursor has for the REFRESHLISTNUMBER log statement. That is a random number from the list.
Not sure why the cursor isnt being passed correctly. I have a details button on each row that displays info from the cursor for each row and that is displaying correctly.
Completed Top Adapter
public class TopListCursorAdapter extends CursorAdapter {
public interface TopListClickListener {
void onTopListClick(Cursor cursor);
}
private TopListClickListener mCallback;
public TopListCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
if(!(context instanceof TopListClickListener)) {
throw new ClassCastException("Content must implement BottomListClickListener");
}
this.mCallback = (TopListClickListener) context;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.contact_cardview_top, parent, false);
}
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
ViewHolder holder;
holder = new ViewHolder();
holder.tvFirstName = (TextView) view.findViewById(R.id.personFirstName);
holder.tvLastName = (TextView) view.findViewById(R.id.personLastName);
holder.tvTitle = (TextView) view.findViewById(R.id.personTitle);
holder.mPeepPic = (ImageView) view.findViewById(R.id.person_photo);
holder.mDetailsButton = (ImageButton) view.findViewById(R.id.fullDetailButton);
holder.mTopCardView = (CardView) view.findViewById(R.id.mTopHomeScreenCV);
String mFirstName = cursor.getString(cursor.getColumnIndexOrThrow("First_name"));
String mLastName = cursor.getString(cursor.getColumnIndexOrThrow("Last_name"));
String mPayrollTitle = cursor.getString(cursor.getColumnIndexOrThrow("Payroll_title"));
String mThumbnail = cursor.getString(cursor.getColumnIndexOrThrow("ThumbnailData"));
holder.tvFirstName.setText(mFirstName);
holder.tvLastName.setText(mLastName);
holder.tvTitle.setText(mPayrollTitle);
if (mThumbnail != null) {
byte[] imageAsBytes = Base64.decode(mThumbnail.getBytes(), Base64.DEFAULT);
Bitmap parsedImage = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
holder.mPeepPic.setImageBitmap(parsedImage);
} else {
holder.mPeepPic.setImageResource(R.drawable.img_place_holder_adapter);
}
final int position = cursor.getPosition();
holder.mDetailsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cursor.moveToPosition(position);
String mEmployeeNumber = cursor.getString(cursor.getColumnIndex("Employee_number"));
String mFirstName = cursor.getString(cursor.getColumnIndex("First_name"));
String mLastName = cursor.getString(cursor.getColumnIndex("Last_name"));
String mTitle = cursor.getString(cursor.getColumnIndex("Payroll_title"));
String mPic = cursor.getString(cursor.getColumnIndex("ThumbnailData"));
String mEmail = cursor.getString(cursor.getColumnIndex("Email"));
String mPhoneMobile = cursor.getString(cursor.getColumnIndex("Phone_mobile"));
String mPhoneOffice = cursor.getString(cursor.getColumnIndex("Phone_office"));
String mCostCenter = cursor.getString(cursor.getColumnIndex("Cost_center_id"));
String mHasDirectReports = cursor.getString(cursor.getColumnIndex("Has_direct_reports"));
String mManagerNumber = cursor.getString(cursor.getColumnIndex("Manager_employee_number"));
Intent mIntent = new Intent(context, EmployeeFullInfo.class);
mIntent.putExtra("Employee_number", mEmployeeNumber);
mIntent.putExtra("First_name", mFirstName);
mIntent.putExtra("Last_name", mLastName);
mIntent.putExtra("Payroll_title", mTitle);
mIntent.putExtra("ThumbnailData", mPic);
mIntent.putExtra("Email", mEmail);
mIntent.putExtra("Phone_mobile", mPhoneMobile);
mIntent.putExtra("Phone_office", mPhoneOffice);
mIntent.putExtra("Cost_center_id", mCostCenter);
mIntent.putExtra("Has_direct_reports", mHasDirectReports);
mIntent.putExtra("Manager_employee_number", mManagerNumber);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(mIntent);
}
});
holder.mTopCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mCallback != null) {
mCallback.onTopListClick(cursor);
notifyDataSetChanged();
Log.i("FROMCLICK", DatabaseUtils.dumpCursorToString(cursor));
}
}
});
}
public static class ViewHolder {
TextView tvFirstName;
TextView tvLastName;
TextView tvTitle;
ImageView mPeepPic;
ImageButton mDetailsButton;
CardView mTopCardView;
}
}
public class TopFragment extends Fragment {
Cursor mTopCursor;
EmployeeDBHandler dbHandler;
ListView mTopListView;
TopListCursorAdapter mTopAdapter;
MatrixCursor customCursor1;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_top_list, container, false);
String table = "employees";
dbHandler = EmployeeDBHandler.getInstance(getContext());
SQLiteDatabase db = dbHandler.getWritableDatabase();
customCursor1 = new MatrixCursor(new String[]{"_id", "Employee_number", "First_name",
"Last_name", "Payroll_title", "ThumbnailData", "Email", "Phone_mobile", "Phone_office", "Cost_center_id",
"Has_direct_reports", "Manager_employee_number"});
int mStartingEmployeeID = mStartingNumber;
mTopCursor = db.rawQuery("SELECT * FROM " + table + " WHERE " + "Employee_number" + "=" + mStartingEmployeeID, null);
mTopListView = (ListView) view.findViewById(R.id.mTopList);
mTopAdapter = new TopListCursorAdapter(getContext(), mTopCursor);
mTopListView.setAdapter(mTopAdapter);
return view;
}
public void update(Cursor cursor) {
if (cursor.moveToNext()) {
customCursor1.addRow(new Object[]{cursor.getInt(0), cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(6), cursor.getString(9), cursor.getString(8), cursor.getString(4),
cursor.getString(5), cursor.getString(10), cursor.getString(7), cursor.getString(11)});
MergeCursor newCursor = new MergeCursor(new Cursor[]{mTopCursor, customCursor1});
mTopAdapter.swapCursor(newCursor);
mTopAdapter.notifyDataSetChanged();
scrollMyListToBottom();
customCursor1.close();
} cursor.moveToNext();
}
private void scrollMyListToBottom() {
mTopListView.post(new Runnable() {
#Override
public void run() {
mTopListView.setSelection(mTopAdapter.getCount() - 1);
}
});
}
}
Maybe something is happening with my MergeCursor in TopFragment that is messing with the curors? If so, not sure how to fix it or why it would be happening.
Fixed by adding a line of code to the setClickListener of the mTopCardView in the TopListCursorAdapter.
cursor.moveToPosition(position);

Update same ListView with new data in CursorAdapter

I am really stuck and have no idea what to do. I have looked into startActivityForResult and Content providers and I have no clue how to implement any of them for this app.
I am not seeing how to get the data from the database and update the displayBottomList using same listview so I don't have to redirect the user to a new layout/activity. Not sure if I can even call a new query and set that to a different cursor and switch between them. I have seen swapCursor but how does that work when using the same adapter?
I have a ListView that I want to refresh with new data from a web service call when the user clicks on a row within the list. I am using a CursorAdapter. I can get the data correctly onClick of the row.
Where I am stuck, is how do I update that listView to repopulate with the new info from the database/response without sending me to another Activity. I want the user to stay on the same screen but just update the listView with the new data.
Not sure how to get the adapter to notify the adapter to update and populate a new ListView when the onClick is in the adapter, but the ListView is being created in the MainActivity.
The Adapter for BottomListView, the one I want to update when a row is clicked.
public class BottomListViewAdapter extends CursorAdapter {
private String mEmployeeNumber;
private EmployeeDBHandler dbHandler;
public BottomListViewAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.contact_cardview_layout, parent, false);
}
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
dbHandler = new EmployeeDBHandler(context);
ViewHolder holder;
holder = new ViewHolder();
holder.tvFirstName = (TextView) view.findViewById(R.id.personFirstName);
holder.tvLastName = (TextView) view.findViewById(R.id.personLastName);
holder.tvTitle = (TextView) view.findViewById(R.id.personTitle);
holder.mPeepPic = (ImageView) view.findViewById(R.id.person_photo);
holder.mDetailsButton = (ImageButton) view.findViewById(R.id.fullDetailButton);
holder.mCardView = (CardView) view.findViewById(R.id.home_screen_cardView);
String mFirstName = cursor.getString(cursor.getColumnIndexOrThrow("First_name"));
String mLastName = cursor.getString(cursor.getColumnIndexOrThrow("Last_name"));
String mTitle = cursor.getString(cursor.getColumnIndexOrThrow("Payroll_title"));
String mThumbnail = cursor.getString(cursor.getColumnIndexOrThrow("ThumbnailData"));
holder.tvFirstName.setText(mFirstName);
holder.tvLastName.setText(mLastName);
holder.tvTitle.setText(mTitle);
if (mThumbnail != null) {
byte[] imageAsBytes = Base64.decode(mThumbnail.getBytes(), Base64.DEFAULT);
Bitmap parsedImage = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
holder.mPeepPic.setImageBitmap(parsedImage);
} else {
holder.mPeepPic.setImageResource(R.drawable.img_place_holder_adapter);
}
final int position = cursor.getPosition();
holder.mDetailsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cursor.moveToPosition(position);
String mEmployeeNumber = cursor.getString(1);
String mEmail = cursor.getString(8);
String mFirstName = cursor.getString(2);
String mLastName = cursor.getString(3);
String mPhoneMobile = cursor.getString(4);
String mPhoneOffice = cursor.getString(5);
String mCostCenter = cursor.getString(10);
String mHasDirectReports = cursor.getString(7);
String mTitle = cursor.getString(6);
String mPic = cursor.getString(9);
Intent mIntent = new Intent(context, EmployeeFullInfo.class);
mIntent.putExtra("Employee_number", mEmployeeNumber);
mIntent.putExtra("Email", mEmail);
mIntent.putExtra("First_name", mFirstName);
mIntent.putExtra("Last_name", mLastName);
mIntent.putExtra("Phone_mobile", mPhoneMobile);
mIntent.putExtra("Phone_office", mPhoneOffice);
mIntent.putExtra("Cost_center_id", mCostCenter);
mIntent.putExtra("Has_direct_reports", mHasDirectReports);
mIntent.putExtra("Payroll_title", mTitle);
mIntent.putExtra("ThumbnailData", mPic);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
view.getContext().startActivity(mIntent);
}
});
holder.mCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cursor.moveToPosition(position);
mEmployeeNumber = cursor.getString(1);
Toast.makeText(context, mEmployeeNumber, Toast.LENGTH_SHORT).show();
callNewDirectReport();
notifyDataSetChanged();
}
});
}
public static class ViewHolder {
TextView tvFirstName;
TextView tvLastName;
TextView tvTitle;
ImageView mPeepPic;
ImageButton mDetailsButton;
CardView mCardView;
}
private void callNewDirectReport() {
String mDirectReportUrl = "mURL";
HttpUrl.Builder urlBuilder = HttpUrl.parse(mDirectReportUrl).newBuilder();
urlBuilder.addQueryParameter("manager_employee_number", mEmployeeNumber);
String url = urlBuilder.build().toString();
OkHttpClient client = getUnsafeOkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
final String responseData = response.body().string();
final InputStream stream = new ByteArrayInputStream(responseData.getBytes());
final XMLPullParserHandler parserHandler = new XMLPullParserHandler();
final ArrayList<Employee> employees = (ArrayList<Employee>) parserHandler.parse(stream);
for (Employee e : employees) {
dbHandler.addEmployee(e);
}
}
});
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
My MainActivity that is calling the adapter
public class MainActivity extends AppCompatActivity {
private ProgressBar mProgressBar;
private BottomListViewAdapter mBottomAdapter;
private View mDividerView;
EmployeeDBHandler dbHandler;
private int mStartingEmployeeID = mStartingID;
private String table = "employees";
private static final int LOADER_INTEGER = 1;
private Cursor mBottomCursor, mTopCursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mDividerView = findViewById(R.id.divider);
dbHandler = new EmployeeDBHandler(getApplicationContext());
mProgressBar.setVisibility(View.VISIBLE);
mDividerView.setVisibility(View.GONE);
getXMLData();
//GUI for seeing android SQLite Database in Chrome Dev Tools
Stetho.InitializerBuilder inBuilder = Stetho.newInitializerBuilder(this);
inBuilder.enableWebKitInspector(Stetho.defaultInspectorModulesProvider(this));
Stetho.Initializer in = inBuilder.build();
Stetho.initialize(in);
}
public void getXMLData() {
OkHttpClient client = getUnsafeOkHttpClient();
Request request = new Request.Builder()
.url(getString(R.string.API_FULL_URL))
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
final String responseData = response.body().string();
final InputStream stream = new ByteArrayInputStream(responseData.getBytes());
final XMLPullParserHandler parserHandler = new XMLPullParserHandler();
final ArrayList<Employee> employees = (ArrayList<Employee>) parserHandler.parse(stream);
for (Employee e : employees) {
dbHandler.addEmployee(e);
}
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressBar.setVisibility(View.GONE);
mDividerView.setVisibility(View.VISIBLE);
displayTopList();
displayBottomList();
}
});
}
});
}
public void displayTopList() {
SQLiteDatabase db = dbHandler.getWritableDatabase();
mTopCursor = db.rawQuery("SELECT * FROM " + table + " WHERE " + "Employee_number" + "=" + mStartingEmployeeID, null);
ListView mTopListView = (ListView) findViewById(R.id.mTopList);
TopListCursorAdapter topAdapter = new TopListCursorAdapter(this, mTopCursor);
mTopListView.setAdapter(topAdapter);
}
public void displayBottomList() {
SQLiteDatabase db = dbHandler.getWritableDatabase();
mBottomCursor = db.rawQuery("SELECT * FROM " + table + " WHERE " +
"Employee_number" + "!=" + mStartingEmployeeID + " AND " +
"Manager_employee_number" + "=" + mStartingEmployeeID + " ORDER BY " +
"Last_name" + " ASC", null);
ListView mBottomListView = (ListView) findViewById(R.id.mDirectReportList);
mBottomAdapter = new BottomListViewAdapter(this, mBottomCursor);
mBottomListView.setAdapter(mBottomAdapter);
mBottomAdapter.notifyDataSetChanged();
}
}
Right now your code in callNewDirectReport() makes an API request and stores the results in the database. This will not update the adapter to show the new items, instead you need to requery the database and get a newer Cursor. Below is an example of how you may do it:
public class BottomListViewAdapter extends CursorAdapter {
private String mEmployeeNumber;
private EmployeeDBHandler dbHandler;
private Activity activityRef;
public BottomListViewAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
// keep a reference to the activity
activityRef = (Activity) context;
}
//...
private void callNewDirectReport() {
//...
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
final String responseData = response.body().string();
final InputStream stream = new ByteArrayInputStream(responseData.getBytes());
final XMLPullParserHandler parserHandler = new XMLPullParserHandler();
final ArrayList<Employee> employees = (ArrayList<Employee>) parserHandler.parse(stream);
for (Employee e : employees) {
dbHandler.addEmployee(e);
}
// the new items are in the database so requery the database to get a new fresher Cursor:
SQLiteDatabase db = dbHandler.getWritableDatabase();
Cursor fresherCursor = db.rawQuery("SELECT * FROM " + table + " WHERE " +
"Employee_number" + "!=" + mStartingEmployeeID + " AND " +
"Manager_employee_number" + "=" + mStartingEmployeeID + " ORDER BY " +
"Last_name" + " ASC", null);
//change the adapter's Cursor
activityRef.runOnUiThread(new Runnable() {
public void run() {
swapCursor(freshedCursor);
}
});
}
});
}
}
You can use startActivityForResult to receive a callback from an activity, here you have a tutorial explaining how to use it: https://developer.android.com/training/basics/intents/result.html
When you receive the callback in the onActivityResult, you can update your data and call notifyDatasetChanged.
You can't call code from an activity in another because activities are handled by android. Android could have killed the activity that you are trying to call and will just recreate it when necessary.

Json data is not getting stored in Sqlite

I am using Recyclerview ,Here is Json file the insert query written in Json array though the json data is not stored in SQLite.When we destroy the app and again restart it will only show
blank rows and again press a button and it will show json data aftr emptyrow ie:after destroy data gets lost.Do help me thank you
public class Recyclerview extends AppCompatActivity {
private RecyclerView mRecyclerView;
CustomAdapter cu;
ArrayList<Employee> arr, arr1;
Toolbar toolbar;
TextView t1, t2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recyclerview);
toolbar = (Toolbar) findViewById(R.id.toolbar1);
setSupportActionBar(toolbar);
final RecyclerView rv = (RecyclerView) findViewById(R.id.rv);
rv.setHasFixedSize(true);
arr = new ArrayList<Employee>();
arr = InitializeData();
final LinearLayoutManager llm = new LinearLayoutManager(Recyclerview.this);
rv.setLayoutManager(llm);
rv.setHasFixedSize(true);
cu = new CustomAdapter(Recyclerview.this, arr);
rv.setAdapter(cu);
registerForContextMenu(rv);
final bank ban = new bank(Recyclerview.this);
ImageButton refresh = (ImageButton) findViewById(R.id.refresh);
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(Recyclerview.this, "ok", Toast.LENGTH_LONG).show();
if (isNetworkAvailable()) {
String url = ConstantValues.BASE_URL;
RequestBody formBody = new FormBody.Builder()
.add("key1", "value1")
.add("key2", "value2")
.add("key3", "value3")
.build();
try {
post(url, formBody, new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.e("JSONDemo", "IOException", e);
}
#Override
public void onResponse(final Call call, final Response response) throws IOException {
String JSON = response.body().string();
Log.e("res", " " + JSON);
try {
JSONObject jsonObj = new JSONObject(JSON);
JSONArray resultarr = jsonObj.getJSONArray("result");
final JSONArray resultarr1 = jsonObj.getJSONArray("result1");
ban.OpenDB();
ban.OpenDB();
for (int i = 0; i < resultarr1.length(); i++) {
Employee emp = new Employee();
JSONObject result1obj = resultarr1.getJSONObject(i);
String result1Id = result1obj.getString(ConstantValues.Bank_ID);
String result1NAME = result1obj.getString(ConstantValues.Bank_NAME);
Log.e("result", " " + result1Id);
Log.e("result", " " + result1NAME);
emp.setId(result1obj.getString(ConstantValues.Bank_ID));
emp.setName(result1obj.getString(ConstantValues.Bank_NAME));
arr.add(emp);
long l = 0;
l=ban.InsertQryForTabEmpData(ConstantValues.Bank_ID,ConstantValues.Bank_NAME);
}
ban.CloseDB();
runOnUiThread(new Runnable() {
#Override
public void run() {
cu.notifyDataSetChanged();
}
});
} catch (Exception e) {
Log.e("JSONDemo", "onResponse", e);
}
}
});
} catch (Exception e) {
Log.e("JSONDemo", "Post Exception", e);
}
} else {
Toast.makeText(Recyclerview.this, "Internet not available", Toast.LENGTH_LONG).show();
}
}
});
}
private ArrayList<Employee> InitializeData() {
ArrayList<Employee> arr_emp = new ArrayList<Employee>();
bank ban = new bank(Recyclerview.this);
long l = 0;
ban.OpenDB();
arr_emp = ban.AllSelectQryForTabEmpData1();
ban.CloseDB();
return arr_emp;
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private final OkHttpClient client = new OkHttpClient();
Call post(String url, RequestBody formBody, Callback callback) throws IOException {
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Call call = client.newCall(request);
call.enqueue(callback);
return call;
}
}
It is the query of all SQLite:
public class bank {
private Context context;
private SQLiteDatabase SQLiteDb;
public bank(Context context){
this.context=context;
}
public static class DBHelper extends SQLiteOpenHelper{
public DBHelper(Context context) {
super(context, ConstantValues.DBName, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(" create table if not exists " + ConstantValues.TabEmpData+"("
+ ConstantValues.Bank_ID + " text, "
+ ConstantValues.Bank_NAME + " text )");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL(" create table if not exists " + ConstantValues.TabEmpData+"("
+ ConstantValues.Bank_ID + " text, "
+ ConstantValues.Bank_NAME + " text )");
}
}
public void OpenDB() {
SQLiteDb = new DBHelper(context).getWritableDatabase();
}
public void CloseDB() {
if (SQLiteDb.isOpen()) {
SQLiteDb.close();
}
}
public long InsertQryForTabEmpData(String ID, String NAME) {
ContentValues cv = new ContentValues();
cv.put(ConstantValues.Bank_ID, ID);
cv.put(ConstantValues.Bank_NAME, NAME);
long l = SQLiteDb.insert(ConstantValues.TabEmpData, null, cv);
return l;
}
public long UpdateQryForTabEmpData(String ID
, String NAME
) {
ContentValues cv = new ContentValues();
cv.put(ConstantValues.Bank_ID, ID);
cv.put(ConstantValues.Bank_NAME, NAME);
long l = SQLiteDb.update(ConstantValues.TabEmpData, cv, ConstantValues.Bank_ID+ "=" + ID, null);
return l;
}
public long DeleteQryForTabEmpData(String ID) {
long l = SQLiteDb.delete(ConstantValues.TabEmpData, ConstantValues.Bank_ID+ "=" + ID, null);
return l;
}
public ArrayList SelectQryForTabEmpData(String ID) {
ArrayList<String> data = new ArrayList();
String[] arg = {
"ID"
, "NAME"
};
String selection = " ID= " + ID;
String QRY = " SELECT ID,NAME FROM TabEmpData WHERE ID = " + ID;// +" AND EmpFName = 'test' grup by empid,fname,lastname having Empsalary > = 2000 order by fname asc,salry desc limit 100";
Cursor cursor = SQLiteDb.rawQuery(QRY, null);//
SQLiteDb.query(ConstantValues.TabEmpData, arg, selection, null, null, null, null, null);
while (cursor.moveToNext()) {
data.add(0, cursor.getString(cursor.getColumnIndex(ConstantValues.Bank_ID)));
data.add(1, cursor.getString(cursor.getColumnIndex(ConstantValues.Bank_NAME)));
}
cursor.close();
return data;
}
public ArrayList AllSelectQryForTabEmpData1() {
ArrayList<Employee> data = new ArrayList();
Cursor cursor = SQLiteDb.query(ConstantValues.TabEmpData, null, null, null, null, null, null, null);
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ConstantValues.Bank_ID));
String name = cursor.getString(cursor.getColumnIndex(ConstantValues.Bank_NAME));
data.add(new Employee(id, name));
}
cursor.close();
return data;
}
}
Its my Custom Adapter:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.EmpDataViewHolder> {
final bank ban = new bank(CustomAdapter.this.context);
private ArrayList<Employee> arr,filterlist;
private Context context;
public CustomAdapter(Context context, ArrayList<Employee> arr) {
this.arr=arr;
this.context=context;
Toast.makeText(context,""+arr.size(),Toast.LENGTH_LONG).show();
}
#Override
public EmpDataViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.cardview, parent, false);
EmpDataViewHolder edvh = new EmpDataViewHolder(v);
return edvh;
}
#Override
public void onBindViewHolder(EmpDataViewHolder holder, int position) {
Employee emp=arr.get(position) ;
holder.id.setText(emp.getId());
holder.name.setText(emp.getName());
holder.cv.setTag(R.string.KeyForCV,position);
}
#Override
public int getItemCount() {
return arr.size();
}
public class EmpDataViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView id;
TextView name;
public EmpDataViewHolder(View itemView) {
super(itemView);
cv= (CardView) itemView.findViewById(R.id.cv);
id= (TextView) itemView.findViewById(R.id.id);
name= (TextView) itemView.findViewById(R.id.name);
}
}
}
Do help me i want to get rid out of this problem thank you in advance

Check Row_id in database with other value in RecyclerView Adapter

This is structure of my json respose :
{
"data": [
{
"id": 23,
"title": "this is title",
"description": " this is desc",
"date": "21/2/16",
"authorname": "john smith",
"authorpic": "http://xtryz.com/users/1462862047com.yahoo.mobile.client.android.yahoo_128x128.png",
"filename": "1463770591.MP4",
"downloadlink": "http://xyrgz.com/download.zip",
"downloadcnt": "24"
},
...
]
And with clicking one Buton in each row of RecyclerView I save that json row In the Database . Know for some work I need to know is this json row exist in the Database or no ? for doing this work , I Want to use the id in the database and id of the json . and if id of the database same to id of the json , doing some work and else .
This is the QuestionDatabaseAdapter :
public class QuestionDatabaseAdapter {
private Context context;
private SQLiteOpenHelper sqLiteOpenHelper;
private static final int DATABASE_VERSION = 1;
//private SQLiteDatabase database = null;
public QuestionDatabaseAdapter(Context context) {
this.context = context;
sqLiteOpenHelper = new SQLiteOpenHelper(context, "database.db", null, DATABASE_VERSION) {
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE tbl_questions ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, question_id VARCHAR( 255 ) NOT NULL , title VARCHAR( 255 ) NOT NULL, [desc] TEXT NOT NULL, Date VARCHAR( 50 ) NOT NULL, authorName VARCHAR( 255 ) NOT NULL , authorPic VARCHAR( 255 ) NOT NULL, downLink VARCHAR( 255 ) NOT NULL )";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
};
}
//================== SAVE QUESTION IN DATABASE ==========================
public long saveQuestion(ModelQuestion modelQuestion) {
String question_id = modelQuestion.getQuestionId();
String title = modelQuestion.getQuestionTitle();
String desc = modelQuestion.getQuestionDesc();
String date = modelQuestion.getQuestionDate();
String authorName = modelQuestion.getQuestionAuthorName();
String authorPic = modelQuestion.getQuestionAuthorPic();
String downloadLink = modelQuestion.getQuestionDownLink();
SQLiteDatabase database = null;
long id = -1;
try {
ContentValues values = new ContentValues();
values.put("question_id", question_id);
values.put("title", title);
values.put("desc", desc);
values.put("date", date);
values.put("authorName", authorName);
values.put("authorPic", authorPic);
values.put("downLink", downloadLink);
database = sqLiteOpenHelper.getWritableDatabase();
id = database.insert("tbl_questions", null, values);
} catch (Exception ex) {
Log.i("DATABASE SAVE EX", ex.getMessage());
} finally {
if (database != null && database.isOpen()) {
database.close();
}
}
return id;
}
//=================== READ ALL QUESTION IN DATABASE=========================
public ArrayList<ModelQuestion> readAllQuestions() {
ArrayList<ModelQuestion> questions = null;
String[] columns = new String[]{"*"};
String selection = null;
String[] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
String limit = null;
String favorite = null;
SQLiteDatabase database = null;
try {
database = sqLiteOpenHelper.getReadableDatabase();
Cursor cursor = database.query("tbl_questions", columns, selection, selectionArgs, groupBy, having, orderBy, limit);
if (cursor != null && cursor.moveToFirst()) {
questions = new ArrayList<ModelQuestion>();
int indexQuestionId = 0;
int indexTitle = 1;
int indexDesc = 2;
int indexDate = 3;
int indexAuthorName = 4;
int indexAuthorPic = 5;
int indexDownloadLink = 6;
int indexFavorite = 7;
do {
String questionId = cursor.getString(indexQuestionId);
String questionTitle = cursor.getString(indexTitle);
String questionDesc = cursor.getString(indexDesc);
String questionDate = cursor.getString(indexDate);
String questionAuthorName = cursor.getString(indexAuthorName);
String questionAuthorPic = cursor.getString(indexAuthorPic);
String questionDownloadLink = cursor.getString(indexDownloadLink);
ModelQuestion question = new ModelQuestion();
question.setQuestionId(questionId);
question.setQuestionTitle(questionTitle);
question.setQuestionDesc(questionDesc);
question.setQuestionDate(questionDate);
question.setQuestionAuthorName(questionAuthorName);
question.setQuestionAuthorPic(questionAuthorPic);
question.setQuestionDownLink(questionDownloadLink);
questions.add(question);
} while (cursor.moveToNext());
}
} catch (Exception ex) {
Log.i("DATABASE READ ALL EX", ex.getMessage());
} finally {
if (database != null && database.isOpen()) {
database.close();
}
}
return questions;
}
//=================== DELETE ONE QUESTION IN DATABASE=========================
public int deletePerson(long id) {
int noOfDeletedRecords = 0;
String whereClause = "id=?";
String[] whereArgs = new String[]{String.valueOf(id)};
SQLiteDatabase database = null;
try {
database = sqLiteOpenHelper.getWritableDatabase();
noOfDeletedRecords = database.delete("tbl_questions", whereClause, whereArgs);
} catch (Exception ex) {
Log.i("DATABASE DELETE EX", ex.getMessage());
} finally {
if (database != null && database.isOpen()) {
database.close();
}
}
return noOfDeletedRecords;
}
}
And this is The adapterRecyclerQuestion :
public class AdapterRecyclerQuestion extends RecyclerView.Adapter<AdapterRecyclerQuestion.ViewHolder> {
private Context context;
private ArrayList<ModelQuestion> questionha;
//constructor
public AdapterRecyclerQuestion(Context context, ArrayList<ModelQuestion> questionha) {
this.context = context;
this.questionha = questionha;
}
//viewholder
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView txtTitle;
private TextView txtDesc;
private TextView txtCntDown;
private ImageView imgAuthorPic;
private TextView txtAuthorName;
private TextView txtDate;
private Button btnDownload;
private ImageView imgAddFav;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
txtTitle = (TextView) itemView.findViewById(R.id.txt_title_question);
txtDesc = (TextView) itemView.findViewById(R.id.txt_desc_question);
txtCntDown = (TextView) itemView.findViewById(R.id.txt_cnt_down_question_dy);
imgAuthorPic = (ImageView) itemView.findViewById(R.id.img_author_pic_question);
txtAuthorName = (TextView) itemView.findViewById(R.id.txt_author_name_question);
txtDate = (TextView) itemView.findViewById(R.id.txt_date_question);
btnDownload = (Button) itemView.findViewById(R.id.btn_down_question);
imgAddFav = (ImageView) itemView.findViewById(R.id.img_add_to_fav);
}
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Hello" + txtTitle.getText(), Toast.LENGTH_SHORT).show();
}
}
//oncreateviewholder
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.question_row, parent, false);
return new ViewHolder(view);
}
//onbindviewholder
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
QuestionDatabaseAdapter questionDatabaseAdapter = new QuestionDatabaseAdapter(holder.itemView.getContext());
questionDatabaseAdapter.readAllQuestions();
holder.txtTitle.setText(questionha.get(position).getQuestionTitle());
holder.txtDesc.setText(questionha.get(position).getQuestionDesc());
holder.txtCntDown.setText(questionha.get(position).getQuestionDownCnt());
holder.txtAuthorName.setText(questionha.get(position).getQuestionAuthorName());
Glide.with(holder.itemView.getContext()).load(questionha.get(position).getQuestionAuthorPic()).into(holder.imgAuthorPic);
holder.txtDate.setText(questionha.get(position).getQuestionDate());
//============= IMG ADD TO FAV ON CLICK LISTENER =========================
holder.imgAddFav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
QuestionDatabaseAdapter databaseAdapter = new QuestionDatabaseAdapter(v.getContext());
ModelQuestion question = new ModelQuestion();
question.setQuestionId(questionha.get(position).getQuestionId());
question.setQuestionTitle(questionha.get(position).getQuestionTitle());
question.setQuestionDesc(questionha.get(position).getQuestionDesc());
question.setQuestionDate(questionha.get(position).getQuestionDate());
question.setQuestionAuthorName(questionha.get(position).getQuestionAuthorName());
question.setQuestionAuthorPic(questionha.get(position).getQuestionAuthorPic());
question.setQuestionDownLink(questionha.get(position).getQuestionDownLink());
databaseAdapter.saveQuestion(question);
Toast.makeText(v.getContext(), "اضافه شد", Toast.LENGTH_SHORT).show();
}
});
//=============BTN DOWNLOAD CLICK LISTENER =========================
holder.btnDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(questionha.get(position).getQuestionDownLink()));
request.setTitle(questionha.get(position).getQuestionTitle());
request.setDescription("در حال دانلود");
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, questionha.get(position).getQuestionDownFileName());
long enqueueId = downloadManager.enqueue(request);
}
});
}
//getitemcount
#Override
public int getItemCount() {
return questionha.size();
}
}
And this is Database Structure :
(question_id is the id of question)
Now i need to compare id of database and id of the json in adapter . but i don't know how can i do this .
private ArrayList<ModelQuestion> questionha;
private ArrayList<ModelQuestion> jsonArrList;
//pass your json arraylist too in constructor from your main activity
public AdapterRecyclerQuestion(Context context, ArrayList<ModelQuestion> questionha,ArrayList<ModelQuestion> jsonArrList) {
this.context = context;
this.questionha = questionha;
this.jsonArrList = jsonArrList;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
for(int i=0;i<jsonArrList.size();i++)
{
//Check your id here
if(jsonArrList.get(i).getId().equalsIgnoreCase(questionha.get(position).getId()))
}
}

How do I get the ID item in the database?

I am new to android development and must take the value of the id in the clicked item database.
Already searched several posts but not found the answer .
Below is my code Listview :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seleciona_jogador_act);
final BancoController bc = new BancoController(this);
final ArrayList<JogadorEntidade> jogadorEntidade = bc.arrayJogador(this);
listView = (ListView) findViewById(R.id.lvSelecionar);
final SelecionaAdapter adapter = new SelecionaAdapter(this, R.layout.adapter_seleciona, jogadorEntidade);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setBackgroundTintList(ColorStateList.valueOf(background));
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertInserirJogador(SelecionaJogadorAct.this);
}
});
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//I NEED THIS CODE
Context context = getApplicationContext();
CharSequence text = "ID: " + ", Posicao: " + position;
int duration = Toast.LENGTH_SHORT;
Toast.makeText(context, text, duration).show();
//bc.deletaRegistro(id_player);
Intent intent = getIntent();
SelecionaJogadorAct.this.finish();
startActivity(intent);
}
});
}
My Adapter:
public class SelecionaAdapter extends ArrayAdapter<JogadorEntidade> {
Context context;
int layoutID;
ArrayList<JogadorEntidade> alJogador;
public SelecionaAdapter(Context context, int layoutID, ArrayList<JogadorEntidade> alJogador){
super(context, layoutID, alJogador);
this.context = context;
this.alJogador = alJogador;
this.layoutID = layoutID;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View row = convertView;
PlayerHolder holder = null;
if (row == null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutID, parent, false);
holder = new PlayerHolder();
holder.txtNome = (TextView)row.findViewById(R.id.txtNomeSelecionar);
holder.txtVitorias = (TextView)row.findViewById(R.id.txtVitóriasSelecionar);
holder.txtDerrotas = (TextView)row.findViewById(R.id.txtDerrotasSelecionar);
row.setTag(holder);
}else {
holder = (PlayerHolder)row.getTag();
}
JogadorEntidade jogadorEntidade = alJogador.get(position);
holder.txtNome.setText(jogadorEntidade.getNome());
holder.txtVitorias.setText("V: " + jogadorEntidade.vitórias);
holder.txtDerrotas.setText("D: " + jogadorEntidade.derrotas);
return row;
}
static class PlayerHolder{
TextView txtNome;
TextView txtVitorias;
TextView txtDerrotas;
}
JogadorEntidade:
public class JogadorEntidade {
public String nome;
public Integer id_jogador;
public String vitórias;
public String derrotas;
public Integer getId_jogador() {
return id_jogador;
}
public void setId_player(int id_player) {
this.id_jogador = id_player;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getVitórias() {
return vitórias;
}
public void setVitórias(String vitórias) {
this.vitórias = vitórias;
}
public String getDerrotas() {
return derrotas;
}
public void setDerrotas(String derrotas) {
this.derrotas = derrotas;
}
public JogadorEntidade(String nome, String vitórias, String derrotas){
super();
this.nome = nome;
this.vitórias = vitórias;
this.derrotas = derrotas;
}
public JogadorEntidade(){}
public void insereJogador(JogadorEntidade jogadorEntidade) {
db = banco.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(banco.NOME_JOGADOR, jogadorEntidade.getNome());
values.put(banco.VITORIAS, jogadorEntidade.getVitórias());
values.put(banco.DERROTAS, jogadorEntidade.getDerrotas());
db.insert(CriaBanco.TABELA_JOGADOR, null, values);
db.close();
}
public Cursor carregaJogador() {
Cursor cursor;
String[] campos = {banco.NOME_JOGADOR, banco.VITORIAS, banco.DERROTAS};
db = banco.getReadableDatabase();
cursor = db.query(banco.TABELA_JOGADOR, campos, null, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
db.close();
return cursor;
}
public void deletaRegistro(int id){
String where = CriaBanco.ID_JOGADOR + "=" + id;
db = banco.getReadableDatabase();
db.delete(CriaBanco.TABELA_JOGADOR, where, null);
db.close();
}
public ArrayList<JogadorEntidade> arrayJogador(Context context) {
ArrayList<JogadorEntidade> al = new ArrayList<JogadorEntidade>();
BancoController bancoController = new BancoController(context);
Cursor cursor;
cursor = bancoController.carregaJogador();
if (cursor != null) {
if (cursor.moveToFirst()) {
String nome = cursor.getString(cursor.getColumnIndex(banco.NOME_JOGADOR));
String vitorias = cursor.getString(cursor.getColumnIndex(banco.VITORIAS));
String derrotas = cursor.getString(cursor.getColumnIndex(banco.DERROTAS));
JogadorEntidade jogadorEntidade = new JogadorEntidade(nome, vitorias, derrotas);
al.add(jogadorEntidade);
while (cursor.moveToNext()) {
nome = cursor.getString(cursor.getColumnIndex(banco.NOME_JOGADOR));
vitorias = cursor.getString(cursor.getColumnIndex(banco.VITORIAS));
derrotas = cursor.getString(cursor.getColumnIndex(banco.DERROTAS));
jogadorEntidade = new JogadorEntidade(nome, vitorias, derrotas);
al.add(jogadorEntidade);
}
}
}
return al;
}
First you need to request the id when making the query (if the id is the one created in the database the column mame is _id or you can use tablename._id or whatever you need):
String[] campos = {"_id", banco.NOME_JOGADOR, banco.VITORIAS, banco.DERROTAS};
Then you need to add the id to the object when you read the cursor:
public ArrayList<JogadorEntidade> arrayJogador(Context context) {
ArrayList<JogadorEntidade> al = new ArrayList<JogadorEntidade>();
BancoController bancoController = new BancoController(context);
Cursor cursor;
cursor = bancoController.carregaJogador();
if (cursor != null) {
if (cursor.moveToFirst()) {
String nome = cursor.getString(cursor.getColumnIndex(banco.NOME_JOGADOR));
String vitorias = cursor.getString(cursor.getColumnIndex(banco.VITORIAS));
String derrotas = cursor.getString(cursor.getColumnIndex(banco.DERROTAS));
long id = cursor.getLong(cursor.getColumnIndex("_id",0));
JogadorEntidade jogadorEntidade = new JogadorEntidade(id, nome, vitorias, derrotas);
al.add(jogadorEntidade);
while (cursor.moveToNext()) {
nome = cursor.getString(cursor.getColumnIndex(banco.NOME_JOGADOR));
vitorias = cursor.getString(cursor.getColumnIndex(banco.VITORIAS));
derrotas = cursor.getString(cursor.getColumnIndex(banco.DERROTAS));
long id = cursor.getLong(cursor.getColumnIndex("_id",0));
jogadorEntidade = new JogadorEntidade(id, nome, vitorias, derrotas);
al.add(jogadorEntidade);
}
}
}
return al;
}
Anyway this is not the way to go in android. You should read all the list and then show it. You should use the viewholder pattern and only load the player when you are going to show it. Also instead of using a list you should move to recyclerviews. Listviews can be consider deprecated at this point. See the tutorial: http://developer.android.com/training/material/lists-cards.html

Categories

Resources