i got 2 toolbar when multi select in listview - java

Hi everyone I got a problem with my app SMS, when I long press on a contact it show the new toolbar but I don't know who to remove the other toolbar :/
if you can help me thank you ..
Here is my Main activity :
package com.ducha.messavtext;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.provider.Telephony;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import com.ducha.training3.R;
import java.util.ArrayList;
#TargetApi(Build.VERSION_CODES.KITKAT)
public class MainActivity extends AppCompatActivity implements BaseColumns {
private Cursor cursor;
private Cursor cursorPhone;
private Cursor cursorContact;
private final Uri uriSms = Telephony.Sms.CONTENT_URI;
private final Uri uriPhone = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
private final Uri uri = Uri.parse("content://sms/inbox");
private String body;
private String numero;
private String id;
private String contact;
private final String[] selectionSms = new String[]{Telephony.Sms._ID, Telephony.Sms.BODY, Telephony.Sms.THREAD_ID, Telephony.Sms.ADDRESS, Telephony.Sms.DATE, Telephony.Sms.READ,};
private final String[] selectionPhone = new String[]{ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER,};
private final String[] selectionContact = new String[]{ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME,};
public static ArrayList<CreateContactAdapter> listContact = new ArrayList<>();;
public static boolean runMain;
public static ContactAdapter adapter;
public static byte[] myPhoto;
private ArrayList<String> idList = new ArrayList<>();;
private Context ctx = this;
private int read;
private int messageUnread = 0;
private ListView lv;
private ArrayList<String> diffNumber;
private byte[] photo;
private Toolbar toolbar;
#Override
protected void onResume() {
super.onResume();
runMain = true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
clearIfNotEmpty();
isTheDefaultApp();
findId();
getInfoMain();
getMyContactPicture();
ConfigToolbar();
lv.setAdapter(adapter);
lv.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
lv.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
final int selectedItem = lv.getCheckedItemCount();
mode.setTitle(selectedItem + " Item selected");
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.select_menu, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode arg0, MenuItem item) {
switch (item.getItemId()) {
case R.id.remove_item:
SparseBooleanArray select = adapter.getSelectedIds();
for (int i = (select.size() - 1); i >= 0; i--) {
if (select.valueAt(i)) {
CreateContactAdapter contact = (CreateContactAdapter) adapter.getItem(select.keyAt(i));
adapter.remove(contact);
}
}
arg0.finish();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
adapter.removeSelection();
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, PrintMessage.class);
String persoId = listContact.get(position).id;
String numero = listContact.get(position).numero;
String contact = listContact.get(position).contact;
String body = listContact.get(position).body;
byte[] bmp = listContact.get(position).photo;
intent.putExtra("id", persoId);
intent.putExtra("numero", numero);
intent.putExtra("contact", contact);
intent.putExtra("photo", bmp);
markMessageRead(ctx, numero, body);
startActivity(intent);
}
});
}
private void clearIfNotEmpty() {
if (!listContact.isEmpty())
listContact.clear();
}
private void getMyContactPicture() {
Uri uriContact = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode("0659641613"));
cursorContact = this.getContentResolver().query(uriContact, selectionContact, null, null, null);
cursorContact.moveToFirst();
long idContact = cursorContact.getLong(0);
myPhoto = openPhoto(idContact);
}
#TargetApi(Build.VERSION_CODES.KITKAT)
private void isTheDefaultApp() {
final String packageName = MainActivity.this.getPackageName();
if (!Telephony.Sms.getDefaultSmsPackage(MainActivity.this).equals(packageName)) {
Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, packageName);
startActivity(intent);
}
}
private void findId() {
toolbar = (Toolbar) findViewById(R.id.my_toolbar);
lv = (ListView) findViewById(R.id.ListView01);
}
#TargetApi(Build.VERSION_CODES.KITKAT)
public void getInfoMain() {
cursor = this.getContentResolver().query(uriSms, selectionSms, null, null, "date DESC");
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
id = cursor.getString(2);
if (!(idList.contains(id))) {
body = cursor.getString(1);
numero = cursor.getString(3);
read = cursor.getInt(5);
if (read == 0)
messageUnread++;
diffNumber = getDifferentNumber(numero);
cursorPhone = this.getContentResolver().query(uriPhone, selectionPhone,
ContactsContract.CommonDataKinds.Phone.NUMBER + "='" + diffNumber.get(0) +"' OR " +
ContactsContract.CommonDataKinds.Phone.NUMBER + "='" + diffNumber.get(1) + "' OR " +
ContactsContract.CommonDataKinds.Phone.NUMBER + "='" + diffNumber.get(2) + "' OR " +
ContactsContract.CommonDataKinds.Phone.NUMBER + "='" + diffNumber.get(3) + "'", null, null);
if (cursorPhone.moveToFirst()) {
contact = cursorPhone.getString(0);
Uri uriContact = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(numero));
cursorContact = this.getContentResolver().query(uriContact, selectionContact, null, null, null);
cursorContact.moveToFirst();
long idContact = cursorContact.getLong(0);
photo = openPhoto(idContact);
if (photo != null)
listContact.add(new CreateContactAdapter(contact, numero, body, id, photo, read));
else
listContact.add(new CreateContactAdapter(contact, numero, body, id, null, read));
} else {
listContact.add(new CreateContactAdapter("no", numero, body, id, null, read));
}
idList.add(id);
}
cursor.moveToNext();
}
}
cursor.close();
adapter = new ContactAdapter(listContact, this);
}
private void ConfigToolbar() {
setSupportActionBar(toolbar);
if (messageUnread > 0)
getSupportActionBar().setTitle("Messages (" + messageUnread + ")");
else
getSupportActionBar().setTitle("Messages");
}
public byte[] openPhoto(long contactId) {
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = getContentResolver().query(photoUri, new String[]{ContactsContract.Contacts.Photo.PHOTO}, null, null, null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return data;
}
}
} finally {
cursor.close();
}
return null;
}
private void markMessageRead(Context context, String number, String body) {
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
try {
while (cursor.moveToNext()) {
if ((cursor.getString(cursor.getColumnIndex("address")).equals(number)) && (cursor.getInt(cursor.getColumnIndex("read")) == 0)) {
if (cursor.getString(cursor.getColumnIndex("body")).startsWith(body)) {
String SmsMessageId = cursor.getString(cursor.getColumnIndex("_id"));
ContentValues values = new ContentValues();
values.put("read", true);
context.getContentResolver().update(Uri.parse("content://sms/inbox"), values, "_id=" + SmsMessageId, null);
return;
}
}
}
} catch (Exception e) {
Log.e("Mark Read", "Error in Read: " + e.toString());
}
}
public ArrayList<String> getDifferentNumber(String number) {
ArrayList<String> num = new ArrayList<>();
if (number.matches("^[06|07]{2}[0-9]{8}")) {
num.add(number.replaceAll(".{2}", "$0 "));
num.add(number.replaceAll("06", "+336"));
num.add(number.replaceAll(".{2}", "$0 ").replaceAll("0", "+33 "));
num.add(number);
} else if (number.matches("[06|07]{2}( [0-9]{2}){4}")) {
num.add(number.replaceAll(" ", ""));
num.add(number.replaceAll("0", "+33 "));
num.add(number.replaceAll(" ", "").replaceAll("0", "+33"));
num.add(number);
} else if (number.matches("\\+[3]{2}[0-9]{8}.")) {
num.add(number.replaceAll("\\+33", "0"));
num.add(number.replaceAll("\\+33", "0").replaceAll(".{2}", "$0 "));
num.add(number.replaceAll("\\+33", "0").replaceAll(".{2}", "$0 ").replaceAll("^0", "+33 "));
num.add(number);
} else if (number.matches("\\+33 [6|7]( [0-9]{2}){4}")) {
num.add(number.replaceAll(" ", ""));
num.add(number.replaceAll(" ", "").replaceAll("\\+33", "0"));
num.add(number.replaceAll(" ", "").replaceAll("\\+33", "0").replaceAll(".{2}", "$0 "));
num.add(number);
} else {
num.add(numero);
num.add(numero);
num.add(numero);
num.add(numero);
}
return num;
}
public boolean edit(MenuItem item) {
// actions
return true;
}
public boolean newMessage(MenuItem item) {
startActivity(new Intent(this, NewMessage.class));
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.setting :
startActivity(new Intent(this, Apparence.class));
}
return true;
}
#Override
protected void onPause() {
super.onPause();
runMain = false;
}
}

Try adding the following to your styles.xml:
<style name="MyAppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">#color/my_primary_color</item>
<item name="colorPrimaryDark">#color/my_primary_dark_color</item>
<item name="colorAccent">#color/my_accent_color</item>
<item name="windowActionModeOverlay">true</item>
</style>

Related

How to pick an image from gallery and store into SqLite database

I want to pick an image from phone gallery and store it in SqLite database. I have code where I am storing into database name, email, addres etc, but I do not know how to pick an Image from phone gallery and store an that Image into SqLite database. I will be thankful if you help me just with that, the rest for placing the Image into ListView I think I know how to do that.. Thanks
Here is my code for my DatabaseHelper:
package com.example.zadacaeden;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "test.db";
public static final String TABLE_NAME = "kompanii_table";
public static final String COL_1 = "id";
public static final String COL_2 = "name";
public static final String COL_3 = "address";
public static final String COL_4 = "phone";
public static final String COL_5 = "website";
public static final String COL_6 = "email";
public static final String COL_7 = "latitude";
public static final String COL_8 = "longitude";
public static final String COL_9 = "kategorija";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
//SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table "+TABLE_NAME+"( id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, address VARCHAR, phone VARCHAR," +
" website VARCHAR, email VARCHAR, latitude VARCHAR, longitude VARCHAR, kategorija VARCHAR )" );
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
// ZA DA SE VNESE DATATA
public boolean insertData(String name, String address, String phone, String website, String email, String latitude, String longitude, String kategorija){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, name);
contentValues.put(COL_3, address);
contentValues.put(COL_4, phone);
contentValues.put(COL_5, website);
contentValues.put(COL_6, email);
contentValues.put(COL_7, latitude);
contentValues.put(COL_8, longitude);
contentValues.put(COL_9, kategorija);
long result = db.insert(TABLE_NAME, null, contentValues);
if(result == -1){
return false;
}else {
return true;
}
}
// ZA DA SE PRINTA DATATA OD BAZATA U LISTI - SERVICES
public ArrayList<Item> getDataServices(){
ArrayList<Item> arrayList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
//SELECT columnName FROM yourTable WHERE CONTAINS (columnName, ‘yourSubstring’);
String query = "select * from "+TABLE_NAME +" where "+ COL_9 +" like '%Servis%'";
Cursor cursor = db.rawQuery(query, null);
while (cursor.moveToNext()){
String ime = cursor.getString(1);
String adresa = cursor.getString(2);
String telefon = cursor.getString(3);
String websajt = cursor.getString(4);
Item item = new Item(ime, adresa, telefon, websajt);
arrayList.add(item);
}
return arrayList;
}
// ZA DA SE PRINTA DATATA OD BAZATA U LISTI - FUN
public ArrayList<Item> getDataFun(){
ArrayList<Item> arrayList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
//SELECT columnName FROM yourTable WHERE CONTAINS (columnName, ‘yourSubstring’);
String query = "select * from "+TABLE_NAME +" where "+ COL_9 +" like '%Zabava%'";
Cursor cursor = db.rawQuery(query, null);
while (cursor.moveToNext()){
String ime = cursor.getString(1);
String adresa = cursor.getString(2);
String telefon = cursor.getString(3);
String websajt = cursor.getString(4);
Item item = new Item(ime, adresa, telefon, websajt);
arrayList.add(item);
}
return arrayList;
}
// ZA DA SE PRINTA DATATA OD BAZATA U LISTI - INDUSTRY
public ArrayList<Item> getDataIndustry(){
ArrayList<Item> arrayList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
//SELECT columnName FROM yourTable WHERE CONTAINS (columnName, ‘yourSubstring’);
String query = "select * from "+TABLE_NAME +" where "+ COL_9 +" like '%Industrija%'";
Cursor cursor = db.rawQuery(query, null);
while (cursor.moveToNext()){
String ime = cursor.getString(1);
String adresa = cursor.getString(2);
String telefon = cursor.getString(3);
String websajt = cursor.getString(4);
Item item = new Item(ime, adresa, telefon, websajt);
arrayList.add(item);
}
return arrayList;
}
// ZA DA SE PRINTA DATATA OD BAZATA U LISTI - EDUCATION
public ArrayList<Item> getDataEducation(){
ArrayList<Item> arrayList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
//SELECT columnName FROM yourTable WHERE CONTAINS (columnName, ‘yourSubstring’);
String query = "select * from "+TABLE_NAME +" where "+ COL_9 +" like '%Edukacija%'";
Cursor cursor = db.rawQuery(query, null);
while (cursor.moveToNext()){
String ime = cursor.getString(1);
String adresa = cursor.getString(2);
String telefon = cursor.getString(3);
String websajt = cursor.getString(4);
Item item = new Item(ime, adresa, telefon, websajt);
arrayList.add(item);
}
return arrayList;
}}
Here is my Activity Class where I am entering the values of everything what is stored into DB:
package com.example.zadacaeden;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class Vnesuvanje extends AppCompatActivity {
// ZA CHECKBOX
ArrayList<String> selection = new ArrayList<String>();
public String final_checkB_selection = "";
// ZA BAZA
CheckBox servis;
CheckBox zabava;
CheckBox industrija;
CheckBox edukacija;
///////////
ListView ll;
DatabaseHelper databaseHelper;
ArrayList<Item> arrayList;
MyAdapter myAdapter;
Button buttonSave;
EditText editIme, editAdresa, editTelefon, editWebsajt, editEmail, editLatitude, editLongitude;
// Za image
Button btnChooseImage;
private static final int GALLERY_REQUEST_CODE = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vnesuvanje);
//ActionBar menu
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setIcon(R.drawable.logo);
// CheckBoxs
servis = (CheckBox) findViewById(R.id.Services);
zabava = (CheckBox) findViewById(R.id.Fun);
industrija = (CheckBox) findViewById(R.id.Industry);
edukacija = (CheckBox) findViewById(R.id.Education);
// Edit Texts
editIme = (EditText) findViewById(R.id.Ime);
editAdresa = (EditText) findViewById(R.id.Adresa);
editTelefon = (EditText) findViewById(R.id.Telefon);
editWebsajt = (EditText) findViewById(R.id.WebSite);
editEmail = (EditText) findViewById(R.id.Email);
editLatitude = (EditText) findViewById(R.id.Latitude);
editLongitude = (EditText) findViewById(R.id.Longitude);
// Button
buttonSave = (Button) findViewById(R.id.btnSave);
// ListView / DataBase / ArrayList
ll = (ListView) findViewById(R.id.listView);
databaseHelper = new DatabaseHelper(this);
arrayList = new ArrayList<>();
AddData();
}
// ZA DA SE DODADE DATATA VO TABELA
public void AddData(){
buttonSave.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
boolean isInserted = databaseHelper.insertData(
editIme.getText().toString(),
editAdresa.getText().toString(),
editTelefon.getText().toString(),
editWebsajt.getText().toString(),
editEmail.getText().toString(),
editLatitude.getText().toString(),
editLongitude.getText().toString(),
final_checkB_selection
);
if(isInserted == true) {
Toast.makeText(Vnesuvanje.this, "Data Inserted", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(Vnesuvanje.this, "Data not Inserted", Toast.LENGTH_LONG).show();
}
}
}
);
}
// CHECKBOX TEST
public void selectItem(View view) {
boolean checked = ((CheckBox) view).isChecked();
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.Services:
if(checked)
{
selection.add("Servis");
System.out.println(selection);
}
else if(!checked)
{
selection.remove("Servis");
System.out.println(selection);
}
break;
case R.id.Fun:
if(checked)
{
selection.add("Zabava");
System.out.println(selection);
}
else if(!checked)
{
selection.remove("Zabava");
System.out.println(selection);
}
break;
case R.id.Industry:
if(checked)
{
selection.add("Industrija");
System.out.println(selection);
}
else if(!checked)
{
selection.remove("Industrija");
System.out.println(selection);
}
break;
case R.id.Education:
if(checked)
{
selection.add("Edukacija");
System.out.println(selection);
}
else if(!checked)
{
selection.remove("Edukacija");
System.out.println(selection);
}
break;
}
final_checkB_selection = selection.toString();
}}
And in this Activity I am placing into listView the data from Database:
package com.example.zadacaeden;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import static android.view.View.OnClickListener;
public class ServicesScreen extends AppCompatActivity {
// implements SearchView.OnQueryTextListener
// x i y za swipe/slide - left/right
float x1, x2, y1, y2;
//za click na slikite imagebutton
private ImageButton button;
//Za print od baza u ListView
ListView ll;
DatabaseHelper databaseHelper;
public static ArrayList<Item> arrayList;
MyAdapter myAdapter;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_services_screen);
//ActionBar menu
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setIcon(R.drawable.logo);
//Image button services on click
button = findViewById(R.id.ServicesImageBtn);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
openServicesScreen();
}
});
//Image button fun on click
button = findViewById(R.id.FunImageBtn);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
openFunScreen();
}
});
//Image button industry on click
button = findViewById(R.id.IndustryImageBtn);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
openIndustryScreen();
}
});
//Image button education on click
button = findViewById(R.id.EducationImageBtn);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
openEducationScreen();
}
});
//ListView
ll = (ListView) findViewById(R.id.listView);
databaseHelper = new DatabaseHelper(this);
arrayList = new ArrayList<>();
loadDataInListView();
// SEARCH
search();
//
/////////////////////////START SWIPE LEFT-RIGHT ON LISTVIEW/////////////
SwipeListViewTouchListener touchListener =
new SwipeListViewTouchListener(
ll,
new SwipeListViewTouchListener.OnSwipeCallback() {
#Override
public void onSwipeLeft(ListView listView, int[] reverseSortedPositions) {
Intent i = new Intent(ServicesScreen.this, FunScreen.class);
startActivity(i);
}
#Override
public void onSwipeRight(ListView listView, int[] reverseSortedPositions) {
Intent i = new Intent(ServicesScreen.this, MainActivity.class);
startActivity(i);
}
},
true, // example : left action = dismiss
false); // example : right action without dismiss animation
ll.setOnTouchListener(touchListener);
/////////////////////////////////END SWIPE LEFT-RIGHT ON LISTVIEW///////////////////////////////////////////////
}
//SEARCH VO LISTI////////////////
public void search(){
EditText theFilter = (EditText) findViewById(R.id.searchFilter);
theFilter.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
(ServicesScreen.this).myAdapter.getFilter().filter(s);
}
#Override
public void afterTextChanged(Editable s) { }
});
}
// END SEARCH VO LISTI////////////////
/////////ZA VNESUVANJE SCREEN KLIK/////////////////////////////
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.example_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.item1) {
Intent intent = new Intent(this, Vnesuvanje.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
/////////END ZA VNESUVANJE SCREEN KLIK/////////////////////////////
// DATABAZA da gi printa vo listView
public void loadDataInListView(){
arrayList = databaseHelper.getDataServices();
myAdapter = new MyAdapter(this, arrayList);
ll.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
//ImageButton Open ServicesScreen function
public void openServicesScreen() {
Intent intent = new Intent(this, ServicesScreen.class);
startActivity(intent);
}
//ImageButton Open FunScreen function
public void openFunScreen() {
Intent intent = new Intent(this, FunScreen.class);
startActivity(intent);
}
//ImageButton Open IndustryScreen function
public void openIndustryScreen() {
Intent intent = new Intent(this, IndustryScreen.class);
startActivity(intent);
}
//ImageButton Open EducationScreen function
public void openEducationScreen() {
Intent intent = new Intent(this, EducationScreen.class);
startActivity(intent);
}
//Swipe left - right
public boolean onTouchEvent(MotionEvent touchEvent){
switch (touchEvent.getAction()){
case MotionEvent.ACTION_DOWN:
x1 = touchEvent.getX();
y1 = touchEvent.getY();
break;
case MotionEvent.ACTION_UP:
x2 = touchEvent.getX();
y2 = touchEvent.getY();
if(x1 > x2){
Intent i = new Intent(ServicesScreen.this, FunScreen.class);
startActivity(i);
} else if(x1 < x2){
Intent i = new Intent(ServicesScreen.this, MainActivity.class);
startActivity(i);
}
break;
}
return false;
}
//END Swipe left - right
}
Use BLOB from SQLite for your purposes.
Also you have to add a new field to your data class with type of byte[] (ByteArray in Kotlin)
Use this code for converting your drawable to byte[]:
Drawable d;
Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bitmapdata = stream.toByteArray();
And this code to convert byte[] to drawable when you want to retreive data from DB:
BitmapDrawable(BitmapFactory.decodeByteArray(blob, 0, blob.size))
Where blob - your byte[] from DB
Hope this helps

attempt to invoke a virtual method on a null object [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to practise on the loader and content provider i have a database of students that contains (name , degree) in the activity_main.xml i have a recyclerview and 2 editText one for name other for degree my target is that when a user click on the button the name will appear in the recyclerview
here's my logcat
FATAL EXCEPTION: main
Process: com.example.abdelmagied.myapplication, PID: 16160
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.abdelmagied.myapplication.recyclerview.swapcursor(android.database.Cursor)' on a null object reference
at com.example.abdelmagied.myapplication.MainActivity.onLoadFinished(MainActivity.java:97)
at com.example.abdelmagied.myapplication.MainActivity.onLoadFinished(MainActivity.java:17)
at android.support.v4.app.LoaderManagerImpl$LoaderInfo.callOnLoadFinished(LoaderManager.java:476)
at android.support.v4.app.LoaderManagerImpl$LoaderInfo.onLoadComplete(LoaderManager.java:444)
at android.support.v4.content.Loader.deliverResult(Loader.java:126)
at android.support.v4.content.CursorLoader.deliverResult(CursorLoader.java:105)
at android.support.v4.content.CursorLoader.deliverResult(CursorLoader.java:37)
at android.support.v4.content.AsyncTaskLoader.dispatchOnLoadComplete(AsyncTaskLoader.java:255)
at android.support.v4.content.AsyncTaskLoader$LoadTask.onPostExecute(AsyncTaskLoader.java:80)
at android.support.v4.content.ModernAsyncTask.finish(ModernAsyncTask.java:485)
at android.support.v4.content.ModernAsyncTask$InternalHandler.handleMessage(ModernAsyncTask.java:502)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
this is my mainactivity class
package com.example.abdelmagied.myapplication;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor>{
public static final String[] MAIN_STUDENT_PROJECTION = {
studentContract.StudentEntry._ID ,
studentContract.StudentEntry.COLUMN_NAME ,
studentContract.StudentEntry.COLUMN_DEGREE ,
};
public static final int INDEX_COLUMN_ID = 0;
public static final int INDEX_COLUMN_NAME = 1;
public static final int INDEX_COLUMN_DEGREE = 2;
private recyclerview recyclerAdapter;
private int mposition = RecyclerView.NO_POSITION;
public static final int ID_STUDNET_LOADER = 99;
// details of the recyclerview
RecyclerView recycler;
RecyclerView.Adapter myadapter;
RecyclerView.LayoutManager mymanager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// adjust the recyclerview
recycler = (RecyclerView) findViewById(R.id.recyclerid);
myadapter = new recyclerview(this);
mymanager = new LinearLayoutManager(this);
recycler.setAdapter(myadapter);
recycler.setLayoutManager(mymanager);
getSupportLoaderManager().initLoader(ID_STUDNET_LOADER , null , this);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
switch(id)
{
case ID_STUDNET_LOADER :
Uri Query = studentContract.StudentEntry.CONTENT_URI;
return new CursorLoader(this ,
Query ,
MAIN_STUDENT_PROJECTION ,
null ,
null ,
null
);
default:
throw new RuntimeException("Loader is not implemented : " + id);
}
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
recyclerAdapter.swapcursor(data);
if(mposition == RecyclerView.NO_POSITION) mposition = 0;
recycler.smoothScrollToPosition(mposition);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
recyclerAdapter.swapcursor(null);
}
public void addtodatabase(View view) {
EditText name = (EditText) findViewById(R.id.name);
EditText degree=(EditText) findViewById(R.id.degree);
// make a contentvalues and put name , degree , salary on it...
ContentValues values = new ContentValues();
values.put(studentContract.StudentEntry.COLUMN_NAME , name.getText().toString());
values.put(studentContract.StudentEntry.COLUMN_DEGREE , degree.getText().toString());
getContentResolver().insert(studentContract.StudentEntry.CONTENT_URI , values);
}
}
here's the recyclerview adapter
package com.example.abdelmagied.myapplication;
import android.content.Context;
import android.database.Cursor;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by AbdELMagied on 8/4/2017.
*/
public class recyclerview extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context context;
private Cursor mycursor;
public recyclerview(Context context) {
this.context = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.recyclerrow , parent , false);
return new viewholder(view);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
mycursor.move(position);
viewholder myholder = (viewholder) holder;
myholder.mytxt.setText(mycursor.getString(MainActivity.INDEX_COLUMN_NAME));
}
void swapcursor(Cursor mycurso)
{
this.mycursor = mycurso;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
if(mycursor == null) return 0;
return mycursor.getCount();
}
public class viewholder extends RecyclerView.ViewHolder
{
public TextView mytxt;
public viewholder(View itemView) {
super(itemView);
mytxt = (TextView) itemView.findViewById(R.id.textView);
}
}
}
here's my content provider
package com.example.abdelmagied.myapplication;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.text.TextUtils;
/**
* Created by AbdELMagied on 8/4/2017.
*/
public class studentprovider extends ContentProvider {
databaseopenhelper mydatabase;
static final int STUDENT = 100;
static final int STUDENT_WITH_ID = 101;
private UriMatcher urimatcher = matcher();
private UriMatcher matcher() {
UriMatcher mymatcher = new UriMatcher(UriMatcher.NO_MATCH);
mymatcher.addURI(studentContract.authority, "student", STUDENT);
mymatcher.addURI(studentContract.authority, "student/#", STUDENT_WITH_ID);
return mymatcher;
}
#Override
public boolean onCreate() {
mydatabase = new databaseopenhelper(getContext());
return true;
}
#Nullable
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Cursor returncursor;
switch (urimatcher.match(uri)) {
case STUDENT:
returncursor = mydatabase.getReadableDatabase().query(
studentContract.StudentEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
break;
case STUDENT_WITH_ID:
String where = "_id = " + uri.getLastPathSegment() + (!TextUtils.isEmpty(selection)? " AND " + selection : "");
returncursor = mydatabase.getReadableDatabase().query(
studentContract.StudentEntry.TABLE_NAME,
projection,
where,
selectionArgs,
null,
null,
sortOrder
);
break;
default:
throw new UnsupportedOperationException("not found uri " + uri);
}
returncursor.setNotificationUri(getContext().getContentResolver() , uri);
return returncursor;
}
#Nullable
#Override
public String getType(Uri uri) {
return null;
}
#Nullable
#Override
public Uri insert(Uri uri, ContentValues values) {
long rowid = mydatabase.getWritableDatabase().insert(studentContract.StudentEntry.TABLE_NAME, null , values);
if(rowid > 0)
{
Uri _uri = ContentUris.withAppendedId(studentContract.StudentEntry.CONTENT_URI, rowid);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;
}
throw new SQLException("Faild to add a record " + uri);
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
if(selection == "") selection= "1";
int numberofdeleted = 0;
switch (urimatcher.match(uri))
{
case STUDENT:
String where = "_id = " + uri.getLastPathSegment() + (!TextUtils.isEmpty(selection)? "AND " + selection : "");
numberofdeleted = mydatabase.getWritableDatabase().delete("students" , where , selectionArgs);
break;
default:
throw new UnsupportedOperationException("uri not found " + uri);
}
if(numberofdeleted != 0)
{
getContext().getContentResolver().notifyChange(uri , null);
}
return numberofdeleted;
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
}
here's the database class
package com.example.abdelmagied.myapplication;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by AbdELMagied on 8/4/2017.
*/
public class databaseopenhelper extends SQLiteOpenHelper {
public databaseopenhelper(Context context) {
super(context, "student.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
final String SQL_CREATE_STUDENT_TABLE =
"CREATE TABLE " + studentContract.StudentEntry.TABLE_NAME + " (" +
studentContract.StudentEntry._ID + " INTEGER PRIMARY KEY , " +
studentContract.StudentEntry.COLUMN_NAME + " TEXT , " +
studentContract.StudentEntry.COLUMN_DEGREE + " TEXT ); " ;
db.execSQL(SQL_CREATE_STUDENT_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop database if exists student");
onCreate(db);
}
}
here's studentcontract class
package com.example.abdelmagied.myapplication;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.text.TextUtils;
/**
* Created by AbdELMagied on 8/4/2017.
*/
public class studentprovider extends ContentProvider {
databaseopenhelper mydatabase;
static final int STUDENT = 100;
static final int STUDENT_WITH_ID = 101;
private UriMatcher urimatcher = matcher();
private UriMatcher matcher() {
UriMatcher mymatcher = new UriMatcher(UriMatcher.NO_MATCH);
mymatcher.addURI(studentContract.authority, "student", STUDENT);
mymatcher.addURI(studentContract.authority, "student/#", STUDENT_WITH_ID);
return mymatcher;
}
#Override
public boolean onCreate() {
mydatabase = new databaseopenhelper(getContext());
return true;
}
#Nullable
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Cursor returncursor;
switch (urimatcher.match(uri)) {
case STUDENT:
returncursor = mydatabase.getReadableDatabase().query(
studentContract.StudentEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
break;
case STUDENT_WITH_ID:
String where = "_id = " + uri.getLastPathSegment() + (!TextUtils.isEmpty(selection)? " AND " + selection : "");
returncursor = mydatabase.getReadableDatabase().query(
studentContract.StudentEntry.TABLE_NAME,
projection,
where,
selectionArgs,
null,
null,
sortOrder
);
break;
default:
throw new UnsupportedOperationException("not found uri " + uri);
}
returncursor.setNotificationUri(getContext().getContentResolver() , uri);
return returncursor;
}
#Nullable
#Override
public String getType(Uri uri) {
return null;
}
#Nullable
#Override
public Uri insert(Uri uri, ContentValues values) {
long rowid = mydatabase.getWritableDatabase().insert(studentContract.StudentEntry.TABLE_NAME, null , values);
if(rowid > 0)
{
Uri _uri = ContentUris.withAppendedId(studentContract.StudentEntry.CONTENT_URI, rowid);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;
}
throw new SQLException("Faild to add a record " + uri);
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
if(selection == "") selection= "1";
int numberofdeleted = 0;
switch (urimatcher.match(uri))
{
case STUDENT:
String where = "_id = " + uri.getLastPathSegment() + (!TextUtils.isEmpty(selection)? "AND " + selection : "");
numberofdeleted = mydatabase.getWritableDatabase().delete("students" , where , selectionArgs);
break;
default:
throw new UnsupportedOperationException("uri not found " + uri);
}
if(numberofdeleted != 0)
{
getContext().getContentResolver().notifyChange(uri , null);
}
return numberofdeleted;
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
}
recyclerAdapter is never instantiated. onCreate would be an ideal place to instantiate this object of type recyclerview.

Android Quiz App,back and next buttons issue

I am developing a quiz application,and im facing with a issue with back and next button. Here is the situation:
I have 40 questions in total,and in the java class of quiz i initialize an integer rowID=1
W
hen I'm at the first position the button is disabled, but when I press next still it stays disabled, the same thing for next button
I have a TextView which shows the number of current question, and if I'm at the question number 40 and I press next again, it goes 41. it shouldn't go
Here is my code:
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.shawnlin.numberpicker.NumberPicker;
import org.json.JSONObject;
import java.util.List;
import java.util.concurrent.TimeUnit;
import retrofit2.Call;
import retrofit2.Callback;
import static autoshkolla.almotech.org.autoshkollastudenti.R.id.testi;
public class Activity_Quiz extends AppCompatActivity {
SaveData saveData;
String ApiKey;
Dialog dialog;
Gson gson;
Button next_question, previous_question;
int quizID, questionID, trueanswer, useranswer;
int rowID = 1;
String question, filename, mime, image;
SQLiteDatabase db;
TextView viewquestion, question_number, user_email, user_id, quiz_number;
QuizAdapter quizAdapter;
private AllLectureAdapter adapter;
DbProductModel dbProductModel;
List < Quiz_Data > lecture;
RadioGroup my_answer;
NumberPicker numberPicker;
Button start_timer, stop_timer;
MyCountDownTimer myCountDownTimer;
TextView koha;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity__quiz);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(false);
getSupportActionBar().setTitle(Html.fromHtml("<font color='#FFFFFF'><b>QUIZ</b></font>"));
saveData = new SaveData(getApplication());
gson = new GsonBuilder().create();
ApiKey = "bearer " + saveData.getAutoUserToken();
if (!saveData.getQuizStatus().equalsIgnoreCase("start")) {
myCountDownTimer = new MyCountDownTimer(2400000, 1000);
myCountDownTimer.start();
loading();
generate_quiz(ApiKey);
saveData.setQuizStatus("in_progress");
}
question_number = (TextView) findViewById(R.id.questionnumber);
user_email = (TextView) findViewById(R.id.email);
user_id = (TextView) findViewById(R.id.ID);
quiz_number = (TextView) findViewById(testi);
user_email.setText("Email : " + saveData.getAutoUserEmail());
user_id.setText("ID : " + saveData.getAutoUserId() + "");
next_question = (Button) findViewById(R.id.nextbtn);
previous_question = (Button) findViewById(R.id.prevbtn);
viewquestion = (TextView) findViewById(R.id.question);
my_answer = (RadioGroup) findViewById(R.id.useranswer);
final QuizSendModel results = new QuizSendModel();
koha = (TextView) findViewById(R.id.time);
if (rowID > 1 && rowID < 40) {
previous_question.setEnabled(true);
next_question.setEnabled(true);
} else if (rowID == 40) {
next_question.setEnabled(false);
} else if (rowID == 1) {
previous_question.setEnabled(false);
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.gotoquestion);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Dialog dialog = new Dialog(Activity_Quiz.this);
dialog.setContentView(R.layout.questions);
dialog.setCancelable(true);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
Button shiko = (Button) dialog.findViewById(R.id.shikopyetje);
numberPicker = (NumberPicker) dialog.findViewById(R.id.number_picker);
dialog.show();
/* Window window = dialog.getWindow();
window.setLayout(400, 600);*/
shiko.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
question_number.setText(String.valueOf(numberPicker.getValue()) + "/40");
String[] proj = {
UsersProvider.QUESTION,
UsersProvider.USER_ANSWER
};
String[] args = {
String.valueOf(numberPicker.getValue())
};
Cursor c = getContentResolver().query(UsersProvider.CONTENT_URI, proj, UsersProvider.ID_ROW + " = ?", args, null);
if (c.moveToFirst()) {
do {
viewquestion.setText(c.getString(c.getColumnIndex(UsersProvider.QUESTION)));
String uswanswradio = c.getString(c.getColumnIndex(UsersProvider.USER_ANSWER));
if (uswanswradio == null) {
my_answer.clearCheck();
} else if (uswanswradio.equalsIgnoreCase("0")) {
my_answer.check(R.id.radioJO);
} else if (uswanswradio.equalsIgnoreCase("1")) {
my_answer.check(R.id.radioPO);
}
} while (c.moveToNext());
}
dialog.dismiss();
}
});
}
});
viewquestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Cursor c = getContentResolver().query(UsersProvider.CONTENT_URI, null, null, null, null);
if (c.moveToFirst()) {
do {
/*Toast.makeText(getApplicationContext()," "+c.getString(c.getColumnIndex(UsersProvider.NAME))+", "+c.getString(c.getColumnIndex(UsersProvider.ADDRESS)),Toast.LENGTH_LONG).show();
System.out.println("emri : "+c.getString(c.getColumnIndex(UsersProvider.NAME))+" address : "+c.getString(c.getColumnIndex(UsersProvider.ADDRESS)));*/
results.setId_question(c.getString(c.getColumnIndex(UsersProvider.ID_QUESTION)));
results.setUser_answer(c.getString(c.getColumnIndex(UsersProvider.USER_ANSWER)));
System.out.println("pyetja : " + results.getId_question());
System.out.println("uans : " + results.getUser_answer());
} while (c.moveToNext());
}
}
});
my_answer.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group,
int checkedId) {
if (checkedId == R.id.radioPO) {
useranswer = 1;
} else if (checkedId == R.id.radioJO) {
useranswer = 0;
}
ContentValues values = new ContentValues();
values.put(UsersProvider.USER_ANSWER, useranswer);
String row = String.valueOf(rowID);
String[] whereArgs = {
row
};
getContentResolver().update(UsersProvider.CONTENT_URI, values, UsersProvider.ID_ROW + " =? ", whereArgs);
}
});
previous_question.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rowID = rowID - 1;
question_number.setText(rowID + "/40");
String[] proj = {
UsersProvider.QUESTION,
UsersProvider.USER_ANSWER
};
String[] args = {
String.valueOf(rowID)
};
Cursor c = getContentResolver().query(UsersProvider.CONTENT_URI, proj, UsersProvider.ID_ROW + " = ?", args, null);
if (c.moveToFirst()) {
do {
viewquestion.setText(c.getString(c.getColumnIndex(UsersProvider.QUESTION)));
String uswanswradio = c.getString(c.getColumnIndex(UsersProvider.USER_ANSWER));
System.out.println("pergjigjeeuserit : " + c.getString(c.getColumnIndex(UsersProvider.USER_ANSWER)));
if (uswanswradio == null) {
my_answer.clearCheck();
} else if (uswanswradio.equalsIgnoreCase("0")) {
my_answer.check(R.id.radioJO);
} else if (uswanswradio.equalsIgnoreCase("1")) {
my_answer.check(R.id.radioPO);
}
} while (c.moveToNext());
}
}
});
next_question.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
my_answer.clearCheck();
rowID = rowID + 1;
question_number.setText(rowID + "/40");
String[] proj = {
UsersProvider.QUESTION,
UsersProvider.USER_ANSWER
};
String[] args = {
String.valueOf(rowID)
};
Cursor c = getContentResolver().query(UsersProvider.CONTENT_URI, proj, UsersProvider.ID_ROW + " = ?", args, null);
if (c.moveToFirst()) {
do {
viewquestion.setText(c.getString(c.getColumnIndex(UsersProvider.QUESTION)));
String uswanswradio = c.getString(c.getColumnIndex(UsersProvider.USER_ANSWER));
if (uswanswradio == null) {
my_answer.clearCheck();
} else if (uswanswradio.equalsIgnoreCase("0")) {
my_answer.check(R.id.radioJO);
} else if (uswanswradio.equalsIgnoreCase("1")) {
my_answer.check(R.id.radioPO);
}
} while (c.moveToNext());
}
}
});
String[] proj = {
UsersProvider.QUESTION
};
String[] args = {
String.valueOf(1)
};
Cursor c = getContentResolver().query(UsersProvider.CONTENT_URI, proj, UsersProvider.ID_ROW + " = ?", args, null);
if (c.moveToFirst()) {
do {
rowID = 1;
viewquestion.setText(c.getString(c.getColumnIndex(UsersProvider.QUESTION)));
} while (c.moveToNext());
}
}
public void generate_quiz(String APIKEY) {
API api = APIClient.getApi(APIKEY);
Call < Quiz > totclient = api.quiz();
totclient.enqueue(new Callback < Quiz > () {
#Override
public void onResponse(Call < Quiz > call, retrofit2.Response < Quiz > response) {
dialog.dismiss();
// Log.d(TAG, "Succes:" + response.body().isError());
JSONObject obj = new JSONObject();
System.out.println("AllLectures:" + gson.toJson(response.body()));
System.out.println("quiz id:" + gson.toJson(response.body().getQuizNumber()));
quiz_number.setText("Testi : " + gson.toJson(response.body().getQuizNumber()));
if (!gson.toJson(response.body()).equalsIgnoreCase("null")) {
if (gson.toJson(response.body().getError()).equalsIgnoreCase("false")) {
ContentValues values = new ContentValues();
getContentResolver().delete(UsersProvider.CONTENT_URI, null, null);
lecture = response.body().getData();
final List < Quiz_Data > movies = response.body().getData();
for (int i = 0; i < movies.size(); i++) {
quizID = response.body().getQuizNumber();
questionID = response.body().getData().get(i).getId();
question = response.body().getData().get(i).getQuestion();
trueanswer = response.body().getData().get(i).getTrueAnswer();
filename = response.body().getData().get(i).getOriginalFilename();
mime = response.body().getData().get(i).getMime();
image = response.body().getData().get(i).getImage();
values.put(UsersProvider.QUESTION, question);
values.put(UsersProvider.ID_ROW, i + 1);
values.put(UsersProvider.ID_QUESTION, questionID);
values.put(UsersProvider.TRUE_ANSWER, trueanswer);
// values.put(UsersProvider.USER_ANSWER,-1);
values.put(UsersProvider.ORIGINAL_FILENAME, filename);
values.put(UsersProvider.MIME, mime);
values.put(UsersProvider.IMAGE, image);
Uri uri = getContentResolver().insert(UsersProvider.CONTENT_URI, values);
// Toast.makeText(getApplicationContext(),uri.toString(),Toast.LENGTH_LONG).show();
System.out.println("URI :" + uri);
}
} else {
}
} else {
Toast.makeText(getApplicationContext(), "Sesioni juaj ka skaduar ju duhet te rilogoheni", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call < Quiz > call, Throwable t) {
dialog.dismiss();
}
});
}
public void loading() {
dialog = new MaterialDialog.Builder(Activity_Quiz.this)
.title("Duke hyre ne sistem!")
.content("Ju lutem prisni...")
.progress(true, 0)
.show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//handle the click on the back arrow click
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
int progress = (int)(millisUntilFinished / 10000);
koha.setText("" + String.format("%d : %d",
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
}
#Override
public void onFinish() {
//finish();
saveData.setQuizStatus("start");
Toast.makeText(getApplicationContext(), "Koha mbaroi", Toast.LENGTH_LONG).show();
}
}
}
Thank You!
Your buttons' states are only updated once since the logic is in onCreate.
Consider transferring that logic into a function and call it in the button's onClick handler after updating the rowID.
For example
private void updateButtonState() {
if (rowID > 1 && rowID < 40) {
previous_question.setEnabled(true);
next_question.setEnabled(true);
} else if (rowID == 40) {
next_question.setEnabled(false);
} else if (rowID == 1) {
previous_question.setEnabled(false);
}
}
And in your onClick
#Override
public void onClick(View v) {
rowID = rowID - 1; // + 1 if next button
updateButtonState();
...
}

How to populate ListView with SQLite database info with next button click

I am building an app that populates a ListView with a single random record from a SQLite DB every time I click on a "next" button for a guessing-style game. Currently I am able to pull a random record from the DB when the app opens, however, I do not know if I need a new class and I do not know where to put the code for the "next" button, nor do I know what the code should be. I'm basically trying to get the app to refresh the ListView with a new single random record from the DB every time someone clicks on a button that says "next". I already have the xml layout done and the app opens and displays the first random record perfectly. Thank you for any help! :)
MainActivity class:
package com.example.derek.guessinggame;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.Menu;
import android.view.MenuInflater;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager fragmentManager = getSupportFragmentManager();
if (fragmentManager.findFragmentById(android.R.id.content) == null) {
GuessListFragment guessListFragment = new GuessListFragment();
fragmentManager.beginTransaction().add(android.R.id.content, guessListFragment).commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
ContentProvider class:
package com.example.derek.guessinggame;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.util.Log;
public class GuessProvider extends ContentProvider {
private GuessDatabase mOpenHelper;
private static final String TAG = GuessProvider.class.getSimpleName();
private static final UriMatcher sUriMatcher = buildUriMatcher();
private static final int GUESS = 100;
private static final int GUESS_ID = 101;
private Uri uri;
private String selection;
private String[] selectionArgs;
private static UriMatcher buildUriMatcher() {
final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
final String authority = GuessContract.CONTENT_AUTHORITY;
matcher.addURI(authority, "guess", GUESS);
matcher.addURI(authority, "guess/*", GUESS_ID);
return matcher;
}
#Override
public boolean onCreate() {
mOpenHelper = new GuessDatabase(getContext());
return true;
}
private void deleteDatabase() {
mOpenHelper.close();
GuessDatabase.deleteDatabase(getContext());
mOpenHelper = new GuessDatabase(getContext());
}
#Override
public String getType(Uri uri) {
final int match = sUriMatcher.match(uri);
switch (match) {
case GUESS:
return GuessContract.Guess.CONTENT_TYPE;
case GUESS_ID:
return GuessContract.Guess.CONTENT_ITEM_TYPE;
default:
throw new IllegalArgumentException("Unknown Uri: " + uri);
}
}
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
final SQLiteDatabase db = mOpenHelper.getReadableDatabase();
final int match = sUriMatcher.match(uri);
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(GuessDatabase.Tables.GUESS);
switch (match) {
case GUESS:
// do nothing
break;
case GUESS_ID:
String id = GuessContract.Guess.getGuessId(uri);
queryBuilder.appendWhere(BaseColumns._ID + "=" + id);
break;
default:
throw new IllegalArgumentException("Unknown Uri: " + uri);
}
Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder);
return cursor;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
Log.v(TAG, "insert(uri=" + uri + ", values=" + values.toString());
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
switch (match) {
case GUESS:
long recordId = db.insertOrThrow(GuessDatabase.Tables.GUESS, null, values);
return GuessContract.Guess.buildGuessUri(String.valueOf(recordId));
default:
throw new IllegalArgumentException("Unknown Uri: " + uri);
}
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Log.v(TAG, "update(uri=" + uri + ", values=" + values.toString());
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
String selectionCriteria = selection;
switch (match) {
case GUESS:
// do nothing
break;
case GUESS_ID:
String id = GuessContract.Guess.getGuessId(uri);
selectionCriteria = BaseColumns._ID + "=" + id
+ (!TextUtils.isEmpty(selection) ? " AND (" + selection + ")" : "");
break;
default:
throw new IllegalArgumentException("Unknown Uri: " + uri);
}
return db.update(GuessDatabase.Tables.GUESS, values, selectionCriteria, selectionArgs);
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
Log.v(TAG, "delete(uri=" + uri);
if (uri.equals(GuessContract.BASE_CONTENT_URI)) {
deleteDatabase();
return 0;
}
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
switch (match) {
case GUESS_ID:
String id = GuessContract.Guess.getGuessId(uri);
String selectionCriteria = BaseColumns._ID + "=" + id
+ (!TextUtils.isEmpty(selection) ? " AND (" + selection + ")" : "");
return db.delete(GuessDatabase.Tables.GUESS, selectionCriteria, selectionArgs);
default:
throw new IllegalArgumentException("Unknown Uri: " + uri);
}
}
}
ListLoader class:
package com.example.derek.guessinggame;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.support.v4.content.AsyncTaskLoader;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class GuessListLoader extends AsyncTaskLoader<List<Guess>> {
private static final String LOG_TAG = GuessListLoader.class.getSimpleName();
private List<Guess> mGuess;
private ContentResolver mContentResolver;
private Cursor mCursor;
public GuessListLoader(Context context, Uri uri, ContentResolver contentResolver) {
super(context);
mContentResolver = contentResolver;
}
#Override
public List<Guess> loadInBackground() {
String[] projection = {BaseColumns._ID,
GuessContract.GuessColumns.GUESS_TITLE,
GuessContract.GuessColumns.GUESS_ANSWER,
GuessContract.GuessColumns.GUESS_HINT1,
GuessContract.GuessColumns.GUESS_HINT2,
GuessContract.GuessColumns.GUESS_HINT3,
GuessContract.GuessColumns.GUESS_HINT4,
GuessContract.GuessColumns.GUESS_HINT5};
List<Guess> entries = new ArrayList<Guess>();
mCursor = mContentResolver.query(GuessContract.URI_TABLE, projection, null, null, " random()");
if (mCursor != null) {
if (mCursor.moveToFirst()) {
do {
int _id = mCursor.getInt(mCursor.getColumnIndex(BaseColumns._ID));
String title = mCursor.getString(mCursor.getColumnIndex(GuessContract.GuessColumns.GUESS_TITLE));
String answer = mCursor.getString(mCursor.getColumnIndex(GuessContract.GuessColumns.GUESS_ANSWER));
String hint1 = mCursor.getString(mCursor.getColumnIndex(GuessContract.GuessColumns.GUESS_HINT1));
String hint2 = mCursor.getString(mCursor.getColumnIndex(GuessContract.GuessColumns.GUESS_HINT2));
String hint3 = mCursor.getString(mCursor.getColumnIndex(GuessContract.GuessColumns.GUESS_HINT3));
String hint4 = mCursor.getString(mCursor.getColumnIndex(GuessContract.GuessColumns.GUESS_HINT4));
String hint5 = mCursor.getString(mCursor.getColumnIndex(GuessContract.GuessColumns.GUESS_HINT5));
Guess guess = new Guess(_id, title, answer, hint1, hint2, hint3, hint4, hint5);
entries.add(guess);
} while (mCursor.isLast());
}
}
return entries;
}
#Override
public void deliverResult(List<Guess> guess) {
if (isReset()) {
if (guess != null) {
mCursor.close();
}
}
List<Guess> oldGuessList = mGuess;
if (mGuess == null || mGuess.size() == 0) {
Log.d(LOG_TAG, "++++++++ No data returned");
}
mGuess = guess;
if (isStarted()) {
super.deliverResult(guess);
}
if (oldGuessList != null && oldGuessList != guess) {
mCursor.close();
}
}
#Override
protected void onStartLoading() {
if (mGuess != null) {
deliverResult(mGuess);
}
if (takeContentChanged() || mGuess == null) {
forceLoad();
}
}
#Override
protected void onStopLoading() {
cancelLoad();
}
#Override
protected void onReset() {
onStopLoading();
if (mCursor != null) {
mCursor.close();
}
mGuess = null;
}
#Override
public void onCanceled(List<Guess> guess) {
super.onCanceled(guess);
if (mCursor != null) {
mCursor.close();
}
}
#Override
public void forceLoad() {
super.forceLoad();
}
}
ListFragment class:
package com.example.derek.guessinggame;
import android.content.ContentResolver;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import java.util.List;
public class GuessListFragment extends ListFragment
implements LoaderManager.LoaderCallbacks<List<Guess>> {
private static final String LOG_TAG = GuessListFragment.class.getSimpleName();
private GuessCustomAdapter mAdapter;
private static final int LOADER_ID = 1;
private ContentResolver mContentResolver;
private List<Guess> mGuess;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
mContentResolver = getActivity().getContentResolver();
mAdapter = new GuessCustomAdapter(getActivity(), getChildFragmentManager());
setEmptyText("No entries");
setListAdapter(mAdapter);
setListShown(false);
getLoaderManager().initLoader(LOADER_ID, null, this);
}
#Override
public Loader<List<Guess>> onCreateLoader(int id, Bundle args) {
mContentResolver = getActivity().getContentResolver();
return new GuessListLoader(getActivity(), GuessContract.URI_TABLE, mContentResolver);
}
#Override
public void onLoadFinished(Loader<List<Guess>> loader, List<Guess> guess) {
mAdapter.setData(guess);
mGuess = guess;
if(isResumed()) {
setListShown(true);
} else {
setListShownNoAnimation(true);
}
}
#Override
public void onLoaderReset(Loader<List<Guess>> loader) {
mAdapter.setData(null);
}
}
SQLiteOpenHelper class:
package com.example.derek.guessinggame;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
public class GuessDatabase extends SQLiteOpenHelper {
private static final String TAG = GuessDatabase.class.getSimpleName();
private static final String DATABASE_NAME = "guess.db";
private static final int DATABASE_VERSION = 2;
private final Context mContext;
interface Tables {
String GUESS = "guess";
}
public GuessDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + Tables.GUESS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ GuessContract.GuessColumns.GUESS_TITLE + " TEXT NOT NULL,"
+ GuessContract.GuessColumns.GUESS_ANSWER + " TEXT NOT NULL,"
+ GuessContract.GuessColumns.GUESS_HINT1 + " TEXT NOT NULL,"
+ GuessContract.GuessColumns.GUESS_HINT2 + " TEXT NOT NULL,"
+ GuessContract.GuessColumns.GUESS_HINT3 + " TEXT NOT NULL,"
+ GuessContract.GuessColumns.GUESS_HINT4 + " TEXT NOT NULL,"
+ GuessContract.GuessColumns.GUESS_HINT5 + " TEXT NOT NULL)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
int version = oldVersion;
if (version == 1) {
version = 2;
}
if (version != DATABASE_VERSION) {
db.execSQL("DROP TABLE IF EXISTS " + Tables.GUESS);
onCreate(db);
}
}
public static void deleteDatabase(Context context) {
context.deleteDatabase(DATABASE_NAME);
}
}
ArrayAdapter class:
package com.example.derek.guessinggame;
import android.content.Context;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class GuessCustomAdapter extends ArrayAdapter<Guess> {
private LayoutInflater mLayoutInflater;
private static FragmentManager sFragmentManager;
public GuessCustomAdapter(Context context, FragmentManager fragmentManager) {
super(context, android.R.layout.simple_expandable_list_item_2);
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
sFragmentManager = fragmentManager;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final View view;
if (convertView == null) {
view = mLayoutInflater.inflate(R.layout.custom_guess, parent, false);
} else {
view = convertView;
}
final Guess guess = getItem(position);
final int _id = guess.getId();
final String title = guess.getTitle();
final String answer = guess.getAnswer();
final String hint1 = guess.getHint1();
final String hint2 = guess.getHint2();
final String hint3 = guess.getHint3();
final String hint4 = guess.getHint4();
final String hint5 = guess.getHint5();
((TextView) view.findViewById(R.id.guess_title)).setText(title);
((TextView) view.findViewById(R.id.guess_answer)).setText(answer);
((TextView) view.findViewById(R.id.guess_hint1)).setText(hint1);
((TextView) view.findViewById(R.id.guess_hint2)).setText(hint2);
((TextView) view.findViewById(R.id.guess_hint3)).setText(hint3);
((TextView) view.findViewById(R.id.guess_hint4)).setText(hint4);
((TextView) view.findViewById(R.id.guess_hint5)).setText(hint5);
return view;
}
public void setData(List<Guess> guesses) {
clear();
if (guesses != null) {
for (Guess guess : guesses) {
add(guess);
}
}
}
}
Contract class:
package com.example.derek.guessinggame;
import android.net.Uri;
import android.provider.BaseColumns;
public class GuessContract {
interface GuessColumns{
String GUESS_ID = "_id";
String GUESS_TITLE = "guess_title";
String GUESS_ANSWER = "guess_answer";
String GUESS_HINT1 = "guess_hint1";
String GUESS_HINT2 = "guess_hint2";
String GUESS_HINT3 = "guess_hint3";
String GUESS_HINT4 = "guess_hint4";
String GUESS_HINT5 = "guess_hint5";
}
public static final String CONTENT_AUTHORITY = "com.example.derek.guessinggame.provider";
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
private static final String PATH_GUESS = "guess";
public static final Uri URI_TABLE = Uri.parse(BASE_CONTENT_URI.toString() + "/" + PATH_GUESS);
public static final String[] TOP_LEVEL_PATHS = {
PATH_GUESS
};
public static class Guess implements GuessColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendEncodedPath(PATH_GUESS).build();
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd." + CONTENT_AUTHORITY + ".guess";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd." + CONTENT_AUTHORITY + ".guess";
public static Uri buildGuessUri(String guessId) {
return CONTENT_URI.buildUpon().appendEncodedPath(guessId).build();
}
public static String getGuessId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
}
Getters and Setter class:
package com.example.derek.guessinggame;
public class Guess {
private int _id;
private String title;
private String answer;
private String hint1;
private String hint2;
private String hint3;
private String hint4;
private String hint5;
public Guess(int _id, String title, String answer, String hint1, String hint2, String hint3, String hint4, String hint5) {
this._id = _id;
this.title = title;
this.answer = answer;
this.hint1 = hint1;
this.hint2 = hint2;
this.hint3 = hint3;
this.hint4 = hint4;
this.hint5 = hint5;
}
public int getId() {
return _id;
}
public void setId(int _id) {
this._id = _id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public String getHint1() {
return hint1;
}
public void setHint1(String hint1) {
this.hint1 = hint1;
}
public String getHint2() {
return hint2;
}
public void setHint2(String hint2) {
this.hint2 = hint2;
}
public String getHint3() {
return hint3;
}
public void setHint3(String hint3) {
this.hint3 = hint3;
}
public String getHint4() {
return hint4;
}
public void setHint4(String hint4) {
this.hint4 = hint4;
}
public String getHint5() {
return hint5;
}
public void setHint5(String hint5) {
this.hint5 = hint5;
}
}

cursor Error : Make sure the Cursor is initialized correctly before accessing data from it

I am getting this Error when i enter the existing RegId in Database..
**DatabaseHandler.java**
package com.example.aaqib.scoolbag;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.content.Context;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHandler extends SQLiteOpenHelper {
//Creating a Database ScoolBag
SQLiteDatabase mDb;
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "ScoolBag";
public static final String KEY_NAME = "Name";
public static final String KEY_MOBILENO = "Contact";
public static final String KEY_REGID = "Registration";
public static final String KEY_EMAIL = "Email";
public static final String KEY_PASSWORD = "Password";
// Table name
public static final String tblReg="tblReg";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String vQuery = "Create Table " + tblReg + "(Registration Text primary key,Name Text not null,Password Text not null,Email Text not null,Contact Text not null)";
Log.d("StudentData", "onCreate: " + vQuery);
db.execSQL(vQuery);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS tblReg");
onCreate(db);
}
//using to insert
public void InsertRecord(String vInsertRecord) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(vInsertRecord);
db.close();
}
public void close()
{
mDb.close();
}
/*public Cursor login(String regid)throws SQLiteException
{
String where =(KEY_REGID + "=?");
Cursor m = mDb.query(true, tblReg, new String[]{KEY_REGID, KEY_NAME, KEY_PASSWORD,KEY_EMAIL,KEY_MOBILENO}, where, new String[]{regid}, null, null, null, null);
if (m != null) {
// m.moveToFirst();
}
return m;
}*/
//fetching a emailid
public Cursor getEmailid(String email)throws SQLiteException
{
String where =(KEY_EMAIL + "=?");
Cursor m = mDb.query(true,tblReg, new String[]{KEY_REGID, KEY_NAME, KEY_PASSWORD,KEY_EMAIL,KEY_MOBILENO}, where, new String[]{email}, null, null, null, null);
if (m != null) {
}
return m;
}
//fetching cursor id
public Cursor getRegid(String reg)throws SQLiteException
{
String where =(KEY_REGID + "=?");
Cursor j = mDb.query(true, tblReg, new String[]{KEY_REGID, KEY_NAME, KEY_PASSWORD,KEY_EMAIL,KEY_MOBILENO}, where, new String[]{reg}, null, null, null, null);
if (j!= null) {
//j.moveToFirst();
}
return j;
}
public DatabaseHandler open() throws SQLiteException {
mDb = getWritableDatabase();
return this;
}
}
acitivity_registration.java
package com.example.aaqib.scoolbag;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import static android.view.View.OnClickListener;
public class activity_registration extends Activity {
EditText reg, Name, Pas1, Pas2, Email, Contact;
String regid,emailid;
SQLiteDatabase db;
DatabaseHandler dbh = new DatabaseHandler(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_registration);
reg = (EditText) findViewById(R.id.editText);
Name = (EditText) findViewById(R.id.editText2);
Pas1 = (EditText) findViewById(R.id.editText3);
Pas2 = (EditText) findViewById(R.id.editText4);
Email = (EditText) findViewById(R.id.editText5);
Contact = (EditText) findViewById(R.id.editText6);
Button btnReg = (Button) findViewById(R.id.btnRegister);
//button used to register
btnReg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbh.open();
try {
//get the id from database
dbh.open();
Cursor c=dbh.getRegid(reg.getText().toString().trim());
if((c != null) && c.moveToFirst())
{
regid = c.getString(c.getColumnIndex("RegId"));
c.close();
}
//get the email id from database
Cursor email = dbh.getEmailid(Email.getText().toString().trim());
if (email != null && email.moveToFirst()) {
emailid = email.getString(email.getColumnIndex("Email"));
email.close();
}
if (reg.getText().toString().equals("") || Name.getText().toString().equals("") || Pas1.getText().toString().equals("") || Pas2.getText().toString().equals("") || Email.getText().toString().equals("") || Contact.getText().toString().equals("")) {
Toast.makeText(getApplicationContext(), "Fill All Mandatory Fields", Toast.LENGTH_SHORT).show();
}
else if (!Email.getText().toString().trim().matches("[a-zA-Z0-9._-]+#[a-z]+.[a-z]+"))
{
Email.setError("Invalid Email Address");
Email.requestFocus();
}
else if (Email.getText().toString().equals(emailid))
{
Toast.makeText(getApplicationContext(), "Email is already registered", Toast.LENGTH_SHORT).show();
}
else if (Email.getText().toString().equals(regid))
{
Toast.makeText(getApplicationContext(), "Registration Id already exist", Toast.LENGTH_SHORT).show();
}
else if (!Contact.getText().toString().trim().matches("^[0-9]{10}$")) {
Contact.setError("Invalid Contact Number");
Contact.requestFocus();
}
else if (!Name.getText().toString().trim().matches("([a-zA-Z ]+)$")) {
Name.setError("Invalid Name");
Name.requestFocus();
}
else if (!Pas1.getText().toString().trim().matches(Pas2.getText().toString().trim())) {
Pas2.setError("Password Not Matched");
Pas2.requestFocus();
}
else {
InsertRecord();
Refresh();
Intent i = new Intent(activity_registration.this, activity_home.class);
startActivity(i);
finish();
}
}
catch (Exception e)
{
String ex=e.toString();
Toast.makeText(getApplicationContext(), ex, Toast.LENGTH_SHORT).show();
}
}
});
}
public void InsertRecord()
{
String vQuery = "insert into tblReg (Registration,Name,Password,Email,Contact)values('" + reg.getText().toString().trim() + "','" + Name.getText().toString().trim() + "','"+ Pas2.getText().toString().trim()+"','"+ Email.getText().toString().trim()+"','"+ Contact.getText().toString().trim() +"')";
DatabaseHandler db = new DatabaseHandler(this);
db.InsertRecord(vQuery);
Toast.makeText(getApplicationContext(), "Inserted successful", Toast.LENGTH_SHORT).show();
}
public void Refresh()
{
reg.setText("");
Name.setText("");
Pas1.setText("");
Pas2.setText("");
Email.setText("");
Contact.setText("");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_registration, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Any help would be appreciated.
In your table there is no column as RegId so change following line
regid = c.getString(c.getColumnIndex("RegId"));
to
regid = c.getString(c.getColumnIndex("Registration"));
Hope this will helps you.

Categories

Resources