Here is my code:
private void InitialContact(final Context context)
{
final ContactDatabase db = new ContactDatabase(context);
context.openOrCreateDatabase("****", MODE_PRIVATE, null);
if(refrech){
refrech(db, context);
}
getcontact(db, context);
db.close();
}
A getContact fonction (In main thread)
private void getcontact(final ContactDatabase db, final Context context){
SQLiteDatabase dbread = db.getReadableDatabase();
String[] retour = {
"pseudo",
"adresse",
"image", "ID"
};
Cursor cursor = dbread.query("Contact", retour, null, null, null, null, "pseudo");
while(cursor.moveToNext()) {
String pseudo = cursor.getString(cursor.getColumnIndexOrThrow("pseudo"));
Log.d("debug", "getcontact: "+pseudo);
listcontact.add(new Contact(pseudo));
}
cursor.close();
}
And the Asynchrone task refresh
private void refrech(final ContactDatabase db, final Context context){
final SQLiteDatabase dbwrite = db.getWritableDatabase();
db.onRefresh(dbwrite);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
int ID = preferences.getInt("ID", 0);
if(ID != 0){
ApiInterface mApiService = this.getInterfaceService();
Call<ContactCall> mService = mApiService.getcontact(ID);
mService.enqueue(new Callback<ContactCall>() {
#Override
public void onResponse(Call<ContactCall> call, Response<ContactCall> response) {
ContactCall ContactCallobjet = response.body();
ArrayList pseudo = ContactCallobjet.isLogin;
for(int i = 0 ;pseudo.size() <= i; i++){
ContentValues values = new ContentValues();
String contact = (String) pseudo.get(i);
values.put("pseudo", contact);
values.put("adresse", "test");
values.put("image", "test");
values.put("ID", "5");
dbwrite.insert("Contact", null, values);
}
}
#Override
public void onFailure(Call<ContactCall> call, Throwable t) {
Log.d("DEBUG", "populateWithInitialContacts: "+t.getMessage());
}
});
} else {
Log.d("DEBUG", "populateWithInitialContacts: Error ID");
}
}
My probleme is a getContact fonction is call before a asynchrone function (refrech)
I have test a CallBack but It did not work
Have your getContact method be called in your onResponse and failure callbacks:
private void InitialContact(final Context context) {
final ContactDatabase db = new ContactDatabase(context );
context.openOrCreateDatabase("****", MODE_PRIVATE, null);
if(refrech){
refrech(db, context);
} else {
getcontact(db, context);
}
db.close();
}
private void refrech(final ContactDatabase db, final Context context){
final SQLiteDatabase dbwrite = db.getWritableDatabase();
db.onRefresh(dbwrite);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
int ID = preferences.getInt("ID", 0);
if(ID != 0){
ApiInterface mApiService = this.getInterfaceService();
Call<ContactCall> mService = mApiService.getcontact(ID);
mService.enqueue(new Callback<ContactCall>() {
#Override
public void onResponse(Call<ContactCall> call, Response<ContactCall> response) {
ContactCall ContactCallobjet = response.body();
ArrayList pseudo = ContactCallobjet.isLogin;
for(int i = 0 ;pseudo.size() <= i; i++){
ContentValues values = new ContentValues();
String contact = (String) pseudo.get(i);
values.put("pseudo", contact);
values.put("adresse", "test");
values.put("image", "test");
values.put("ID", "5");
dbwrite.insert("Contact", null, values);
// call get contacts after the response
getcontact(db, context);
}
}
#Override
public void onFailure(Call<ContactCall> call, Throwable t) {
Log.d("DEBUG", "populateWithInitialContacts: "+t.getMessage());
// call get contacts on error
getcontact(db, context);
}
});
} else {
Log.d("DEBUG", "populateWithInitialContacts: Error ID");
// call get contacts on error id
getcontact(db, context);
}
}
Related
I am trying to query my database for the transactions table where the user_id is the user's id like this:
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor cursor = db.query("transactions", null, "user_id=?", new String[]{String.valueOf(integers[0])}, null, null, null);
if(cursor != null){
if(cursor.moveToFirst()){
ArrayList<Transaction> transactions = new ArrayList<>();
for(int i = 0; i<cursor.getCount(); i++){
Transaction transaction = new Transaction();
transaction.setDate(cursor.getString(cursor.getColumnIndex("date")));
transaction.setDescription(cursor.getString(cursor.getColumnIndex("description")));
transaction.setPrice(cursor.getDouble(cursor.getColumnIndex("amount")));
transaction.setTitle(cursor.getString(cursor.getColumnIndex("title")));
transaction.setTransactionId(cursor.getInt(cursor.getColumnIndex("_id")));
transactions.add(transaction);
cursor.moveToNext();
}
cursor.close();
db.close();
return transactions;
}
}
Then, in the onPostExecute of this async task, I set the adapter like this:
if(transactions != null){
itemsRecView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
adapter.setTransactions(transactions);
itemsRecView.setAdapter(adapter);
Log.d("transactions", transactions + "");
}
However, for some reason, it's not going into the if(transaction != null){} block, and instead the else block which just Logs that the array list was null.
Update: I am getting this exception:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int com.krish.recreatemybank.Models.User.get_id()' on a null object reference at com.krish.recreatemybank.Activities.MainActivity.initTransactions(MainActivity.java:72)
..at the line execute.
What may be going wrong here? Thanks.
This is my TransactionsAdapter if needed:
public class TransactionsAdapter extends RecyclerView.Adapter<TransactionsAdapter.ItemViewHolder> {
Context context;
ArrayList<Transaction> transactions = new ArrayList<>();
public TransactionsAdapter(Context context) {
this.context = context;
}
#NonNull
#NotNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull #NotNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_main, parent, false);
return new ItemViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull #NotNull ItemViewHolder holder, int position) {
holder.title.setText(transactions.get(position).getTitle());
holder.description.setText(transactions.get(position).getDescription());
holder.transactionId.setText(transactions.get(position).getTransactionId());
holder.price.setText(String.valueOf(transactions.get(position).getPrice()));
holder.date.setText(transactions.get(position).getDate());
}
#Override
public int getItemCount() {
return transactions.size();
}
public void setTransactions(ArrayList<Transaction> transactions) {
this.transactions = transactions;
notifyDataSetChanged();
}
class ItemViewHolder extends RecyclerView.ViewHolder{
TextView title, description, date, price, transactionId;
public ItemViewHolder(#NonNull #org.jetbrains.annotations.NotNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.itemListTitle);
description = itemView.findViewById(R.id.itemListDescription);
date = itemView.findViewById(R.id.itemListDate);
price = itemView.findViewById(R.id.itemListPrice);
transactionId = itemView.findViewById(R.id.itemListId);
}
}
}
Sample transaction in DatabaseHelper.java:
private void addSampleTransaction(SQLiteDatabase db) {
utils = new Utils(context);
User user = utils.isUserLoggedIn();
if(user != null){
ContentValues transactionValues = new ContentValues();
transactionValues.put("type", "sample");
transactionValues.put("user_id", user.get_id());
transactionValues.put("description", "Hi TEST");
transactionValues.put("date", "2021-05-25");
transactionValues.put("amount", 25.00);
db.insert("transactions", null, transactionValues);
}
}
Utils methods:
public void addUserToSharedPreferences(User user){
SharedPreferences sharedPreferences = context.getSharedPreferences("logged_in_user", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
editor.putString("user", gson.toJson(user));
editor.apply();
}
public User isUserLoggedIn(){
SharedPreferences sharedPreferences = context.getSharedPreferences("logged_in_user", Context.MODE_PRIVATE);
Gson gson = new Gson();
Type type = new TypeToken<User>(){}.getType();
User user = gson.fromJson(sharedPreferences.getString("user", null), type);
return user;
}
In my RegisterActivity I am querying like this and then adding them to the shared preferences:
#Override
protected User doInBackground(Void... voids) {
try{
SQLiteDatabase db = databaseHelper.getWritableDatabase();
ContentValues userValues = new ContentValues();
userValues.put("remained_amount", 0.00);
userValues.put("first_name", first_name);
userValues.put("last_name", last_name);
userValues.put("email", emailString);
userValues.put("password", passwordString);
userValues.put("address", addressString);
long userId = db.insert("users", null, userValues);
Cursor cursor = db.query("users", null, "_id=?", new String[]{String.valueOf(userId)}, null, null, null);
if(cursor != null){
if(cursor.moveToFirst()){
User user = new User();
user.setRemained_amount(cursor.getDouble(cursor.getColumnIndex("remained_amount")));
user.set_id(cursor.getInt(cursor.getColumnIndex("_id")));
user.setAddress(cursor.getString(cursor.getColumnIndex("address")));
user.setEmail(cursor.getString(cursor.getColumnIndex("email")));
user.setPassword(cursor.getString(cursor.getColumnIndex("password")));
user.setFirst_name(cursor.getString(cursor.getColumnIndex("first_name")));
user.setLast_name(cursor.getString(cursor.getColumnIndex("last_name")));
cursor.close();
db.close();
return user;
}else{
cursor.close();
db.close();
return null;
}
}else{
db.close();
return null;
}
}catch (SQLException e){
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(User user) {
super.onPostExecute(user);
if(user != null){
warning.setVisibility(View.GONE);
Utils utils = new Utils(RegisterActivity.this);
utils.addUserToSharedPreferences(user);
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
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
I am fetching some json data into an EventApp and I am trying to store in SQLite database some of the events. I am showing the events in another activity, not the main one and whenever I go back from that activity to the main one and the I go back to the activity with the listview, the data gets duplicated every time. SO if I click to go to that activity 10 time, my data gets 10 times in the listview and in the database as well. How can I fix this?
SQLiteDatabase db = getWritableDatabase();
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
//Add new row to the database
public void addEvent(Event ev){
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.TITLE, ev.getTitle());
contentValues.put(DatabaseHelper.START_DATE, ev.getStartTime());
contentValues.put(DatabaseHelper.END_DATE, ev.getEndTime());
contentValues.put(DatabaseHelper.IMAGE_URL, ev.getImageURL());
contentValues.put(DatabaseHelper.URL, ev.getUrl());
contentValues.put(DatabaseHelper.SUBTITLE, ev.getSubtitle());
contentValues.put(DatabaseHelper.DESCRIPTION, ev.getDescription());
db.insert(TABLE_NAME, null, contentValues);
//db.close();
}
//Delete event from database
public void deleteEvent(String eventTitle){
db.execSQL("DELETE FROM " + TABLE_NAME + "WHERE " + TITLE + "=\"" + eventTitle + "\";" );
}
public int deleteEvents() {
return db.delete(DatabaseHelper.TABLE_NAME, null, null);
}
//Print the database as string
public String databaseToString(){
String dbString="";
//points to a location in results
Cursor c = getEvents();
while (c.moveToNext()){
if(c.getString(c.getColumnIndex("Title")) != null){
dbString += c.getString(c.getColumnIndex("Title"));
dbString += "\n";
}
}
//db.close();
return dbString;
}
public Cursor getEvents(){
return db.query(TABLE_NAME, ALL_COLUMNS, null, null, null, null, null, null);
}
}
This is the activity where I show the data from the database
public class StoredEventsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stored_events);
ListView listView = (ListView) findViewById(R.id.lv_stored_events);
Intent intent = getIntent();
ArrayList<Event> events = new ArrayList<Event>();
events = (ArrayList<Event>) intent.getSerializableExtra("storedEvents");
EventAdapter adapter = new EventAdapter(this, R.layout.list_view_row, R.id.stored, events );
listView.setAdapter(adapter);
}
}
Here is the method that returns the stored events
public static ArrayList<Event> returnStoredEvents(){
long id = -1;
//getStoredEvents();
Cursor c = eventsDB.getEvents();
while (c.moveToNext()){
id = c.getInt(c.getColumnIndex(eventsDB.ID));
String title = c.getString(c.getColumnIndex(eventsDB.TITLE));
String start = c.getString(c.getColumnIndex(eventsDB.START_DATE));
String end = c.getString(c.getColumnIndex(eventsDB.END_DATE));
organizeEvents.add(new Event(title, start, end, true));
}
c.close();
Log.d("DATABASE", organizeEvents.toString());
return organizeEvents;
}
Here is where I actually add some of the events:
private void readEvents(String str){
Event ev = null;
try {
JSONObject geoJSON = new JSONObject(str);
JSONArray jsonEvents = geoJSON.getJSONArray("events");
for (int i = 0; i < jsonEvents.length(); i++) {
JSONObject event = jsonEvents.getJSONObject(i);
JSONArray timeJsonEvent = event.getJSONArray("datelist");
JSONObject time = timeJsonEvent.getJSONObject(0);
title = event.getString("title_english");
Date date = new Date(time.getLong("start"));
startDate = dateFormat.format(date);
date = new Date(time.getLong("end"));
endDate = dateFormat.format(date);
imageURL = event.getString("picture_name");
url = event.getString("url");
subtitle = event.getString("subtitle_english");
description = event.getString("description_english");
if (title.charAt(0) == 'T') {
ev = new Event(title, startDate, endDate, true);
eventsDB.addEvent(ev);
}else {
ev = new Event(title, startDate, endDate, false);
}
// Process a newly found event
final Event finalEv = ev;
handler.post(new Runnable() {
public void run() {
addNewEvent(finalEv);
}
});
}
}catch (Exception e) {
Log.d(null, e.getMessage());
}
}
And here is my main:
public class MainActivity extends AppCompatActivity{
DatabaseHelper eventsDB;
ListFragment listFragment;
SimpleCursorAdapter adapter;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eventsDB = new DatabaseHelper(this);
//storedEvents.addAll(EventsListFragment.returnStoredEvents());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getTitle().equals("Sort by name")){
Toast.makeText(this, "ITEM 2 CLICKED", Toast.LENGTH_LONG).show();
EventsListFragment.sort(-1);
}else if (item.getTitle().equals("Sort by date")) {
EventsListFragment.sort(1);
}else if (item.getTitle().equals("Stored events")){
showSavedEvents();
Toast.makeText(this, "ITEM 3 CLICKED", Toast.LENGTH_LONG).show();
}
return true;
}
public void showSavedEvents(){
intent = new Intent(this, StoredEventsActivity.class);
intent.putExtra("storedEvents", EventsListFragment.returnStoredEvents());
startActivity(intent);
}
}
In my Android app,i am retreiving phone contacts through cursor. Then i want to add all these contacts in database as follows:
public class SettingsActivity extends Activity {
ToggleButton tb_hide;
ToggleButton tb_unhide;
TextView tv_add_contacts;
TextView tv_restore_contacts;
DbManager manager;
Context context;
String[] privateContacts;
Uri queryUri;
String selectIds = "";
String ContactId[];
String ContactNames[];
String ContactNumbers[];
public static String[] wholContactData;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
try{
context = this;
findView();
queryUri = ContactsContract.Contacts.CONTENT_URI;
//String selected_data = ContactsContract.Contacts.DISPLAY_NAME + " IS NOT NULL";
Cursor Cursor = getContentResolver().query
(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
privateContacts=showEvents(Cursor);
wholContactData=new String[privateContacts.length];
tv_add_contacts.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
addcontacts();
}
});
tv_restore_contacts.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
for(int i=0;i<privateContacts.length;i++){
selectIds = selectIds + " | " + privateContacts[i];
wholContactData[i]=privateContacts[i];
}
try{
addAllContacts(wholContactData);
}
catch(Exception ex)
{
Log.e("ERROR in adding all contacts", ex.toString());
}
Toast.makeText(getApplicationContext(),""+selectIds, 3000).show();
}});
}
catch(Exception ex){
Log.e("Add all contacts ERROR", ex.toString());
}
}
private void addAllContacts(final String[] selectedItems) {
try{
manager.open();
manager.Insert_phone_contact(selectedItems);
manager.close();
}
catch(Exception ex)
{
Log.e("ERROR", ex.toString());
}
}
protected String[] showEvents(Cursor cursor) {
ContactId= new String[cursor.getCount()];
ContactNames = new String[cursor.getCount()];
ContactNumbers = new String[cursor.getCount()];
int i=0;
while (cursor.moveToNext()) {
ContactId[i] = i+"";
ContactNames[i] = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
ContactNumbers[i] = Util.getContactNumber(ContactNames[i], context);
i++;
}
return ContactNames;
}
private void findView() {
TextView tv_hide = (TextView)findViewById(R.id.tv_hide);
TextView tv_hide_desc = (TextView)findViewById(R.id.tv_hide_desc);
tv_add_contacts = (TextView)findViewById(R.id.tv_add_contacts);
TextView tv_add_contacts_desc = (TextView)findViewById(R.id.tv_add_contacts_desc);
tv_restore_contacts = (TextView)findViewById(R.id.Tv_restore_contacts);
TextView tv_restore_contacts_desc = (TextView)findViewById(R.id.tv_restore_contacts_desc);
tb_hide = (ToggleButton)findViewById(R.id.tb_hide);
tb_hide.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
HideUnhideIcon();
}});
}
private void HideUnhideIcon() {
if(tb_hide.isChecked()){
PackageManager pm = getPackageManager();
ComponentName com_name = new ComponentName("com.android.discrete.main",
"com.android.discrete.main.SplashScreen");
pm.setComponentEnabledSetting(com_name,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(getApplicationContext(), "Your app is hidden now, Dial provided security code to get into discrete app.", 3000).show();
}
else if(tb_hide.isChecked()==false){
PackageManager pm = getPackageManager();
ComponentName com_name = new ComponentName("com.android.discrete.main",
"com.android.discrete.main.SplashScreen");
pm.setComponentEnabledSetting(com_name,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED
,
PackageManager.DONT_KILL_APP );
}
}
private void addcontacts() {
final ProgressDialog myPd_ring=ProgressDialog.show(this, "Phone Contacts", "Loading please wait..", true);
myPd_ring.setCancelable(true);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try
{
movetoPrivateContacts();
}catch(Exception e){}
myPd_ring.dismiss();
}
}).start();
}
private void moveToLogActivity() {
Intent i = new Intent(this, LogActivity.class);
startActivity(i);
finish();
}
private void movetoPrivateContacts() {
Intent intent = new Intent(this,privateContacts.class);
startActivity(intent);
}
#Override
public void onBackPressed() {
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
}
}
Database code is as follows:
public void Insert_phone_contact(String [] contact){
try{
SQLiteDatabase DB = this.getWritableDatabase();
ContentValues cv = new ContentValues();
for(int i=0;i<contact.length;i++){
// put all values in ContentValues
if (contact[i] !=null){
cv.put(CONTACT_NAME, ""+contact[i]);
DB.insert(TABLE_CONTACTS, null, cv);
}// insert in db
}
DB.close(); // call close
}
catch(Exception ex){
Log.e("Error in phone contact insertion", ex.toString());
}
}
i want to add all contacts to database when i click "tv_restore_contacts" .But i am getting NullPointerException. I don't know where i am wrong?
logcat Error stack is java.lang.NullPointerException.
Use the following code to grab the contacts & return them to a list datatype to save them whole list in a db or open a DB connection inside the method and do sql insert statements on each contact object you wish to store. N/B The Contacts API is deprecated be sure to use ContactsContract Api.
Private void getDetails(){
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER };
Cursor names = getContentResolver().query(uri, projection, null, null, null);
int indexName = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
names.moveToFirst();
do {
String name = names.getString(indexName);
Log.e("Name new:", name);
String number = names.getString(indexNumber);
Log.e("Number new:","::"+number);
} while (names.moveToNext());
}
I need to work with SQLite in Android.
So, do I have to download any SQLite Administration (like MySql) or it is already in device memory?
All you need is already installed. To inspect the database during development you can use the sqlite3 tool. It is installed in the emulator.
You Don't need to download anything.its already there.
You don't have to do anything besides using the built-in tools in the Android SDK. For more information please have a look at the sqlite documentation
Basically you can use Java code to create databases, insert records into them, modify them etc.
If you want a graphical way to work on the databases, simply use Eclipse's DDMS View to navigate into your app's databases folder. From there, download the database on your computer and open it with one of the many sqlite applications available.
------------------------------------------------------------------------
Sqlite
----------------------------------------------------------------------
// instance varieable
Button btn_insert,btn_update,btn_show,btn_delete,btn_search;
EditText edit_no,edit_name,edit_mark;
Cursor c;
Context context=this;
SQLiteDatabase db;
StringBuffer sb;
init
edit_no= (EditText) findViewById(R.id.edit_no);
edit_name= (EditText) findViewById(R.id.edit_name);
edit_mark= (EditText) findViewById(R.id.edit_mark);
btn_insert= (Button) findViewById(R.id.btn_insert);
btn_update= (Button) findViewById(R.id.btn_update);
btn_show= (Button) findViewById(R.id.btn_show);
btn_delete= (Button) findViewById(R.id.btn_delete);
btn_search= (Button) findViewById(R.id.btn_search);
db=openOrCreateDatabase("topstech",context.MODE_PRIVATE,null);
db.execSQL("create table if not exists register(no varchar2(20),name varchar2(20),mark varchar2(20))");
btn_insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (edit_no.getText().toString().trim().length() == 0) {
edit_no.setError("Enter Your No");
return;
} else if (edit_name.getText().toString().trim().length() == 0) {
edit_name.setError("Enter Your Name");
return;
} else if (edit_mark.getText().toString().trim().length() == 0) {
edit_mark.setError("Enter Your Mark");
return;
} else {
db.execSQL("insert into register values('" + edit_no.getText().toString() + "','" + edit_name.getText().toString() + "','" + edit_mark.getText().toString() + "')");
Toast.makeText(context, "Record Successfully Inserted...", Toast.LENGTH_SHORT).show();
Clear();
}
}
});
btn_show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
c=db.rawQuery("select * from register",null);
sb=new StringBuffer();
if(c.moveToFirst())
{
do
{
sb.append(c.getString(c.getColumnIndex("no"))+"\t");
sb.append(c.getString(c.getColumnIndex("name"))+"\t");
sb.append(c.getString(c.getColumnIndex("mark"))+"\n");
}while (c.moveToNext());
Toast.makeText(MainActivity.this, ""+sb, Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "Empty Record...", Toast.LENGTH_SHORT).show();
}
}
});
btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (edit_no.getText().toString().trim().length() == 0)
{
edit_no.setError("Enter Your No");
return;
}
else
{
c=db.rawQuery("select * from register where no='"+edit_no.getText().toString()+"'",null);
sb=new StringBuffer();
if(c.moveToFirst())
{
do
{
db.execSQL("delete from register where no='"+edit_no.getText().toString()+"'");
Toast.makeText(MainActivity.this, "1 Record Is Deleted...", Toast.LENGTH_SHORT).show();
Clear();
}while (c.moveToNext());
}
else
{
Toast.makeText(MainActivity.this, "Record Not Found...", Toast.LENGTH_SHORT).show();
Clear();
}
}
}
});
btn_search.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (edit_no.getText().toString().trim().length() == 0)
{
edit_no.setError("Enter Your No");
return;
}
else
{
c=db.rawQuery("select * from register where no='"+edit_no.getText().toString()+"'",null);
sb=new StringBuffer();
if(c.moveToFirst())
{
do
{
edit_name.setText(c.getString(c.getColumnIndex("name")));
edit_mark.setText(c.getString(c.getColumnIndex("mark")));
}while (c.moveToNext());
}
else
{
Toast.makeText(MainActivity.this, "Record Not Found...", Toast.LENGTH_SHORT).show();
Clear();
}
}
}
});
btn_update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (edit_no.getText().toString().trim().length() == 0)
{
edit_no.setError("Enter Your No");
return;
}
else
{
c=db.rawQuery("select * from register where no='"+edit_no.getText().toString()+"'",null);
sb=new StringBuffer();
if(c.moveToFirst())
{
do
{
if (edit_name.getText().toString().trim().length() == 0)
{
edit_name.setError("Enter Your Name");
return;
}
else if (edit_mark.getText().toString().trim().length() == 0)
{
edit_mark.setError("Enter Your Mark");
return;
}
else
{
//Syntex:-
// db.execSQL("update tablename set col_name='" +edit_name+"' where no='" + no+ "'");
db.execSQL("update register set name='"+edit_name.getText().toString()+"',mark='"+edit_mark.getText().toString()+"' where no='"+edit_no.getText().toString()+"'");
Toast.makeText(MainActivity.this, "1 Record Is Updated...", Toast.LENGTH_SHORT).show();
Clear();
}
}while (c.moveToNext());
}
else
{
Toast.makeText(MainActivity.this, "Record Not Found...", Toast.LENGTH_SHORT).show();
Clear();
}
}
}
});
}
-----------------------------------------
Upload Image ANd Fetch Device Contact JSON ARRAY
------------------------------------------
Upload Image Using Retrofit
#Multipart
#POST("addDocument")
Call<AddDocumentsResponse> doAddDocuments(#Header("Authorization") String token, #Part List<MultipartBody.Part> files, #PartMap Map<String, RequestBody> map);
private void uploadDocuments() {
if (Utility.checkInternetConnection(InsurenceActivity.this)) {
ArrayList<MultipartBody.Part> multipart = new ArrayList<>();
Map<String, RequestBody> map = new HashMap<>();
map.put("document_type", RequestBody.create(MediaType.parse("text/plain"), "insurance"));
map.put("expiry_date", RequestBody.create(MediaType.parse("text/plain"), str_select_date));
map.put("photo_id_type", RequestBody.create(MediaType.parse("text/plain"), ""));
multipart.add(Utility.prepareFilePart(InsurenceActivity.this, "document_file", picturePath));
messageUtil.showProgressDialog(InsurenceActivity.this);
Call<AddDocumentsResponse> registerResponseCall = ApiClient.getApiInterface().doAddDocuments(fastSave.getString(Constant.ACCESS_TOKEN), multipart, map);
Log.d("request","---- Request -----"+map.toString());
registerResponseCall.enqueue(new Callback<AddDocumentsResponse>() {
#Override
public void onResponse(Call<AddDocumentsResponse> call, Response<AddDocumentsResponse> response) {
if (response.code() == 200) {
if (response.body().getStatus().equalsIgnoreCase("fail"))
{
messageUtil.hideProgressDialog();
messageUtil.showErrorToast(response.body().getMessage());
return;
}
if (response.body().getStatus().equalsIgnoreCase("success"))
{
Log.d("response","---- Respons -----"+new Gson().toJson(response));
messageUtil.hideProgressDialog();
messageUtil.showSuccessToast(response.body().getMessage());
str_select_date = str_select_date;
picturePath = null;
Log.d("TAG", "success:............... " + new Gson().toJson(response));
finish();
}
}
}
#Override
public void onFailure(Call<AddDocumentsResponse> call, Throwable t) {
messageUtil.hideProgressDialog();
messageUtil.showErrorToast("Something went wrong");
}
});
} else {
Toast.makeText(this, R.string.no_internet_connection, Toast.LENGTH_SHORT).show();
}
}
public static MultipartBody.Part prepareFilePart(Context context, String partName, String filePath) {
if(filePath!=null) {
File file = new File(filePath);
Log.d("TAG", "prepareFilePart: " + filePath);
// RequestBody requestBody = RequestBody.create(MediaType.parse(getContentResolver().getType(Uri.fromFile(file))), file);
// Libaray Required
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
// Multipart Camera and Gallery
// RequestBody requestBody = RequestBody.create(MediaType.parse(context.getContentResolver().getType(FileProvider.getUriForFile(context, "com.", file))), file);
return MultipartBody.Part.createFormData(partName, file.getName(), requestBody);
}
else {
return MultipartBody.Part.createFormData(partName,"");
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
ll_profile_file.setVisibility(View.GONE);
img_photo_file.setVisibility(VISIBLE);
img_photo_file.setImageURI(resultUri);
picturePath = resultUri.getPath();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
}
}
}
Fetch Device Contact Fast
ArrayList<Contact> listContacts;
listContacts = new ContactFetcher(this).fetchAll();
public class ContactPhone {
public String number;
public String type;
public ContactPhone(String number, String type) {
this.number = number;
this.type = type;
}
}
public class ContactFetcher {
private final Context context;
public ContactFetcher(Context c) {
this.context = c;
}
public ArrayList<Contact> fetchAll() {
String[] projectionFields = new String[]{
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
};
ArrayList<Contact> listContacts = new ArrayList<>();
CursorLoader cursorLoader = new CursorLoader(context,
ContactsContract.Contacts.CONTENT_URI,
projectionFields, // the columns to retrieve
null, // the selection criteria (none)
null, // the selection args (none)
null // the sort order (default)
);
Cursor c = cursorLoader.loadInBackground();
final Map<String, Contact> contactsMap = new HashMap<>(c.getCount());
if (c.moveToFirst()) {
int idIndex = c.getColumnIndex(ContactsContract.Contacts._ID);
int nameIndex = c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
do {
String contactId = c.getString(idIndex);
String contactDisplayName = c.getString(nameIndex);
Contact contact = new Contact(contactId, contactDisplayName);
contactsMap.put(contactId, contact);
listContacts.add(contact);
} while (c.moveToNext());
}
c.close();
matchContactNumbers(contactsMap);
matchContactEmails(contactsMap);
return listContacts;
}
public void matchContactNumbers(Map<String, Contact> contactsMap) {
// Get numbers
final String[] numberProjection = new String[]{
Phone.NUMBER,
Phone.TYPE,
Phone.CONTACT_ID,
};
Cursor phone = new CursorLoader(context,
Phone.CONTENT_URI,
numberProjection,
null,
null,
null).loadInBackground();
if (phone.moveToFirst()) {
final int contactNumberColumnIndex = phone.getColumnIndex(Phone.NUMBER);
final int contactTypeColumnIndex = phone.getColumnIndex(Phone.TYPE);
final int contactIdColumnIndex = phone.getColumnIndex(Phone.CONTACT_ID);
while (!phone.isAfterLast()) {
final String number = phone.getString(contactNumberColumnIndex);
final String contactId = phone.getString(contactIdColumnIndex);
Contact contact = contactsMap.get(contactId);
if (contact == null) {
continue;
}
final int type = phone.getInt(contactTypeColumnIndex);
String customLabel = "Custom";
CharSequence phoneType = Phone.getTypeLabel(context.getResources(), type, customLabel);
contact.addNumber(number, phoneType.toString());
phone.moveToNext();
}
}
phone.close();
}
public void matchContactEmails(Map<String, Contact> contactsMap) {
// Get email
final String[] emailProjection = new String[]{
Email.DATA,
Email.TYPE,
Email.CONTACT_ID,
};
Cursor email = new CursorLoader(context,
Email.CONTENT_URI,
emailProjection,
null,
null,
null).loadInBackground();
if (email.moveToFirst()) {
final int contactEmailColumnIndex = email.getColumnIndex(Email.DATA);
final int contactTypeColumnIndex = email.getColumnIndex(Email.TYPE);
final int contactIdColumnsIndex = email.getColumnIndex(Email.CONTACT_ID);
while (!email.isAfterLast()) {
final String address = email.getString(contactEmailColumnIndex);
final String contactId = email.getString(contactIdColumnsIndex);
final int type = email.getInt(contactTypeColumnIndex);
String customLabel = "Custom";
Contact contact = contactsMap.get(contactId);
if (contact == null) {
continue;
}
CharSequence emailType = Email.getTypeLabel(context.getResources(), type, customLabel);
contact.addEmail(address, emailType.toString());
email.moveToNext();
}
}
email.close();
}
public class ContactEmail {
public String address;
public String type;
public ContactEmail(String address, String type) {
this.address = address;
this.type = type;
}
}
public class Contact {
public String id;
public String name;
public ArrayList<ContactEmail> emails;
public ArrayList<ContactPhone> numbers;
public Contact(String id, String name) {
this.id = id;
this.name = name;
this.emails = new ArrayList<ContactEmail>();
this.numbers = new ArrayList<ContactPhone>();
}
#Override
public String toString() {
String result = name;
if (numbers.size() > 0) {
ContactPhone number = numbers.get(0);
result += " (" + number.number + " - " + number.type + ")";
}
if (emails.size() > 0) {
ContactEmail email = emails.get(0);
result += " [" + email.address + " - " + email.type + "]";
}
return result;
}
public void addEmail(String address, String type) {
emails.add(new ContactEmail(address, type));
}
public void addNumber(String number, String type) {
numbers.add(new ContactPhone(number, type));
}
JSON ARRAY
Model model = new Model();
ArrayList<Model> contacts_arraylist=new ArrayList<>();
for (int i = 0; i < 50; i++)
{
model.setName("sanjay"+i);
model.setEmails("sanjay#gmail.com"+i);
model.setNumbers("89689527"+i);
contacts_arraylist.add(model);
}
JSONArray personarray=new JSONArray();
for (int j = 0; j < contacts_arraylist.size(); j++)
{
JSONObject person1 = new JSONObject();
try {
if(contacts_arraylist.get(j).getName()!=null)
{
person1.put("name", contacts_arraylist.get(j).getName());
}
else {
person1.put("name","");
}
if(contacts_arraylist.get(j).getEmails().length()>0)
{
person1.put("email", contacts_arraylist.get(j).getEmails());
}
else {
person1.put("email", "");
}
if(contacts_arraylist.get(j).getNumbers().length()>0)
{
person1.put("mobile_number", contacts_arraylist.get(j).getNumbers());
}
else {
person1.put("mobile_number", "");
}
personarray.put(person1);
} catch (JSONException e)
{
e.printStackTrace();
}
}
txt_array.setText(personarray.toString());
System.out.println("jsonString:---- " + personarray.toString());
}