Save and load Contacts when swapping Activities - java

Hey guys maybe someone of you can help me:
What im doing: I have a button in my ContactView that lets me select a phonecontact and inserts name and phonenumber into textviews.
The Problem I have is that when i swap between MainActivity and ContactActivity the Contact is deleted and i need to select again a contact
Here is my ContactView code
public class ContactView extends AppCompatActivity {
private static final int RESULT_PICK_CONTACT = 85;
private TextView textView1;
private TextView textView2;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_view);
textView1 = (TextView) findViewById(R.id.TxtName);
textView2 = (TextView) findViewById(R.id.TxtNumber);
editText = (EditText) findViewById(R.id.editText);
}
public void onClick(View v) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// check whether the result is ok
if (resultCode == RESULT_OK) {
// Check for the request code, we might be usign multiple startActivityForReslut
switch (requestCode) {
case RESULT_PICK_CONTACT:
contactPicked(data);
break;
}
} else {
Log.e("ContactView", "Failed to pick contact");
}
}
/**
* Query the Uri and read contact details. Handle the picked contact data.
*
* #param data
*/
private void contactPicked(Intent data) {
Cursor cursor = null;
try {
String phoneNo = null;
String name = null;
// getData() method will have the Content Uri of the selected contact
Uri uri = data.getData();
//Query the content uri
cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
// column index of the phone number
int phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
// column index of the contact name
int nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
phoneNo = cursor.getString(phoneIndex);
name = cursor.getString(nameIndex);
// Set the value to the textviews
textView1.setText(name);
textView2.setText(phoneNo);
} catch (Exception e) {
e.printStackTrace();
}
}
This is the code within my MainAcitivty for the ContactButton that lets me go to ContactView:
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if(id == R.id.action_contactView)
{
Intent ContactIntent = new Intent(this, ContactView.class);
startActivity(ContactIntent);
}
return true;
}
is there a way to check if my intent data is empty? or somehow save the strings as long they are not null?
WITH SHAREDPREFERENCE:
public class ContactView extends AppCompatActivity {
private static final int RESULT_PICK_CONTACT = 85;
private TextView textView1;
private TextView textView2;
private EditText editText;
public SharedPreferences settings = getSharedPreferences("SelectedContact", MODE_PRIVATE);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_view);
textView1 = (TextView) findViewById(R.id.TxtName);
textView2 = (TextView) findViewById(R.id.TxtNumber);
editText = (EditText) findViewById(R.id.editText);
SharedPreferences settings = getSharedPreferences("SelectedContact", MODE_PRIVATE);
String name = settings.getString("contactName", "");//the second parameter set a default data if “contactName” is empty
if (!name.isEmpty()){
textView1.setText(name);
}
String phoneNo = settings.getString("contactPhone", "");//the second parameter set a default data if “contactName” is empty
if (!phoneNo.isEmpty()){
textView2.setText(phoneNo);
}
}
public void onClick(View v) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// check whether the result is ok
if (resultCode == RESULT_OK) {
// Check for the request code, we might be usign multiple startActivityForReslut
switch (requestCode) {
case RESULT_PICK_CONTACT:
contactPicked(data);
break;
}
} else {
Log.e("ContactView", "Failed to pick contact");
}
}
/**
* Query the Uri and read contact details. Handle the picked contact data.
*
* #param data
*/
private void contactPicked(Intent data) {
Cursor cursor = null;
try {
String phoneNo = null;
String name = null;
// getData() method will have the Content Uri of the selected contact
Uri uri = data.getData();
//Query the content uri
cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
// column index of the phone number
int phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
// column index of the contact name
int nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
phoneNo = cursor.getString(phoneIndex);
name = cursor.getString(nameIndex);
// Set the value to the textviews
textView1.setText(name);
textView2.setText(phoneNo);
SharedPreferences.Editor editor = settings.edit();
editor.putString("contactName",name );
editor.putString("contactPhone", phoneNo);
editor.commit();
} catch (Exception e) {
e.printStackTrace();
}
}

If you want to save the state of an activity use SharedPreferences
SharedPreferences settings = getSharedPreferences("SelectedContact", MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(“contactName”,name );
editor.putString(“contactPhone”,phoneNo);
editor.commit();
now in your onCreate of ContactView check if that variables contains data
SharedPreferences settings = getSharedPreferences(“SelectedContact”, MODE_PRIVATE);
String name = settings.getString(“contactName”, “”);//the second parameter set a default data if “contactName” is empty
if (!name.isEmpty()){
yourEditText.setText(name);
}
I hope this helps you.
Tell me if this works!

Related

Send data with PutExtra when clicking back button

I have the following problem.
Activity 1: Where do I send a user ID by PutExtra.
Activity 2: Get the data with GetExtra.
At some point in Activity 2 I send to Activity 3, sending is done again with PutExtra.
I want to go back to activity 2, sending the data as PutExtra. But in activity 2 you already have a GetExtra that expects the data from activity 1, so it is giving an error. How can I send this data from Activity 3 to Activity 2 and not conflict with Activity 2 because I already expect data with GetExtra from Activity 1.
Note: The data sent is always the same. It is always the user ID that is sent as PutExtra and also received as GetExtra.
EDIT:
Code sending or given from Activity 2 to Activity 3
public class PerfilEmpTab2 extends Fragment {
private RecyclerView mCardServicoList;
private String mId_Empresa = null;
private DatabaseReference mDatabaseServicos;
private boolean mProcessAddServico = false;
public PerfilEmpTab2() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_perfil_emp_tab2, container, false);
/* Recebe id de outra tela*/
mId_Empresa = getActivity().getIntent().getExtras().getString("id_empresa");
mDatabaseServicos = FirebaseDatabase.getInstance().getReference().child("Produtos_Empresas").child(mId_Empresa);
/*Recuperar REcyclerView*/
mCardServicoList = (RecyclerView) view.findViewById(R.id.cardListaServicos);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
//mCardCategList.setHasFixedSize(true);
mCardServicoList.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
/*Fim Recycler View*/
loadServicos();
return view;
}
private void loadServicos() {
FirebaseRecyclerAdapter<CardServico_row, CardServicosViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<CardServico_row, CardServicosViewHolder>(
CardServico_row.class,
R.layout.card_servicos_row,
CardServicosViewHolder.class,
mDatabaseServicos
) {
#Override
protected void populateViewHolder(final CardServicosViewHolder viewHolder, final CardServico_row model, int position) {
final String servico_key = getRef(position).getKey();
final String nome_produto = model.getNome_produto();
final String duracao = model.getDuracao();
final String valor = model.getValor();
final String valorOld = model.getValorOld();
viewHolder.setNome_produto(model.getNome_produto());
viewHolder.setDuracao(model.getDuracao());
viewHolder.setValor(model.getValor());
viewHolder.setValorOld(model.getValorOld());
/*Clique na view*/
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intentServicoDetalhes = new Intent(getActivity(), ServicoDetalhes.class);
intentServicoDetalhes.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentServicoDetalhes.putExtra("id_empresa", mId_Empresa);
startActivity(intentServicoDetalhes);
}
});
viewHolder.mAddBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Toast.makeText(Categorias.this, nome + post_key, Toast.LENGTH_LONG).show();
CharSequence opcoes[] = new CharSequence[] {"Editar Serviço", "Ver Detalhes"};
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//builder.setTitle("Opçoes");
//builder.setCancelable(false);
builder.setItems(opcoes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// the user clicked on colors[which]
switch (which) {
case 0:
Toast.makeText(getActivity().getApplication(), "Dados" + "-" + servico_key + "-" + nome_produto + "-" + duracao + "-" + valor + "-" + valorOld, Toast.LENGTH_LONG).show();
/*Intent criarSubC = new Intent(Categorias.this, CadastroSubCategorias.class);
criarSubC.putExtra("id_categ", post_key);
startActivity(criarSubC);*/
mProcessAddServico = false;
break;
case 1:
Toast.makeText(getActivity().getApplication(), "Dados" + "-" + servico_key + "-" + nome_produto + "-" + duracao + "-" + valor + "-" + valorOld, Toast.LENGTH_LONG).show();
mProcessAddServico = false;
break;
}
}
});
builder.show();
}
});
}
};
mCardServicoList.setAdapter(firebaseRecyclerAdapter);
}
public static class CardServicosViewHolder extends RecyclerView.ViewHolder{
View mView;
ImageButton mAddBtn;
public CardServicosViewHolder (View itemView){
super(itemView);
mView = itemView;
mAddBtn = (ImageButton) mView.findViewById(R.id.addServico_tab2);
}
public void setNome_produto(String nome_produto){
TextView card_nomeProduto = (TextView) mView.findViewById(R.id.tvNomeProduto);
card_nomeProduto.setText(nome_produto);
}
public void setDuracao(String duracao){
TextView card_duracao = (TextView) mView.findViewById(R.id.tvDuracao);
card_duracao.setText(duracao);
}
public void setValor(String valor){
TextView card_valor = (TextView) mView.findViewById(R.id.tvValor);
card_valor.setText(valor);
}
public void setValorOld(final String valorOld){
if ( valorOld != null ){
TextView card_valorOld = (TextView) mView.findViewById(R.id.tvValorOld);
card_valorOld.setText(valorOld);
card_valorOld.setPaintFlags(card_valorOld.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); // Risca o texto
//card_valorOld.setPaintFlags(card_valorOld.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG)); // Remove o Risca o texto
} else {
TextView card_valorOld = (TextView) mView.findViewById(R.id.tvValorOld);
card_valorOld.setText(valorOld);
card_valorOld.setVisibility(View.GONE);
}
}
}
}
In Activity 3 I get:
mId_Empresa = getIntent().getExtras().getString("id_empresa");
When you start activity 3 call startActivityForResult(intent, code) instead of startActivity(intint). Then in Activity 3 override finish() and call setResult(Activity.RESULT_OK, data) where data is an object that you have created new Intent() and called putExtra data.putExtra(key, value) on as you want. Then in Activity 2 override onActivityResult(int requestCode, int resultCode, Intent data) to handle it. requestCode is the code you started the activity with. Be aware that onActivityResult occurs before onResume so attempting to update the UI from onActivityResult might not work as expected eg notifying an adapter.
Refer to this doc for more info
https://developer.android.com/training/basics/intents/result.html
EDIT: added code example
Starting activity 3 from activity 2:
static final int SERVICO_DETALHES_REQUEST = 1; // The request code
#Override
public void onClick(View view) {
{
Intent intentServicoDetalhes = new Intent(getActivity(), ServicoDetalhes.class);
intentServicoDetalhes.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentServicoDetalhes.putExtra("id_empresa", mId_Empresa);
startActivityForResult(intentServicoDetalhes, SERVICO_DETALHES_REQUEST );
}
Setting the result from activity 3:
#Override
public void finish()
{
Intent data = new Intent();
data.putExtra("id_empresa", "new_id");
setResult(Activity.RESULT_OK, data);
super.finish();
}
Handling the result from activity 2:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == SERVICO_DETALHES_REQUEST && resultCode == RESULT_OK)
String newId = data.getStringExtra("id_empresa");
}

Issues In Intent Passing Using Database

My problem is how to pass Rating bar value in to another activity using another putExtra method?any one solve this problem?
Here is my First activity
public void giveRating(View v)
{
String Name = spinner.getSelectedItem().toString();
Float Rating = ratingBar.getRating();
String query = "insert into Rating values('"+Name+"',"+Rating+")";
try
{
sqLiteDatabase.execSQL(query);
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setMessage("DATA SAVED");
ab.show();
}catch (Exception e)
{
Log.e("InsertionException",""+e);
}
}
public void viewRating(View v)
{
try {
StringBuffer sb = new StringBuffer();
String query = "select * from Rating";
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
boolean res = cursor.moveToFirst();
if (res) {
do {
String Name = cursor.getString(0);
String Rating = cursor.getString(1);
sb.append(Name + ":" + Rating+"\n");
} while (cursor.moveToNext());
} else {
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setMessage("No data To read");
ab.show();
}
String value = sb.toString();
Intent i = new Intent(MainActivity.this, Items.class);
i.putExtra("k1", value);
startActivity(i);
}
catch (Exception e)
{
Log.e("ReadDataEXception",""+e);
}
Second Activity
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.items_layout);
textView = (TextView)findViewById(R.id.tv3);
textView1 = (TextView)findViewById(R.id.tv4);
Intent i = getIntent();
String name;
Bundle b = getIntent().getExtras();
name= b.getString("k1");
textView.setText(name);
textView.setTextSize(20);
Database Activity
public Database(Context c)
{
super(c,DBNAME,null,VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
try {
String query = "create table Rating(Name TEXT,Rating REAL)";
db.execSQL(query);
}catch (Exception e)
{
Log.e("TableCreationException",""+e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
You could simply add another putExtra with keyName like
Intent i = new Intent(MainActivity.this, Items.class);
i.putExtra("name", name);
i.putExtra("rating",rating);
startActivity(i);
And get from Items activity
Intent i = getIntent();
String name;
String rating;
Bundle b = getIntent().getExtras();
name= b.getString("name");
rating= b.getString("rating");
textView.setText(name);
textView1.setText(rating);
textView.setTextSize(20);
Hope it is helpful for you.

SwipeRefreshLayout doesn't update list view

I wanted to add swipe to refresh for my listview in a Fragment but it doesn't seem to work as it doesn't update my list view at all. Here is how my activity works:
Users open up PictureFragment where a list of images (listview)
are shown.
Users press "add button" which will open up UploadImageActivity to add in image.
Once done, UploadImageActivity will close and users now get back to PictureFragment (not updated their latest image upload yet).
User swipes down to update, << Doesn't update the latest image into listview!
Hope a kind soul can help me resolve this.
public class PictureFragment extends Fragment {
private ListView listView;
private int smiley_id;
private String title, date, caption, image;
private ImageButton addPicButton;
private SwipeRefreshLayout swipeRefreshLayout;
private PictureAdapter adapter;
private TableDatabase tableDatabase;
private Cursor cursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_picture, container, false);
// Set listview
listView = (ListView) rootView.findViewById(R.id.piclistView);
adapter = new PictureAdapter(getActivity().getApplicationContext(), R.layout.row_feed);
listView.setAdapter(adapter);
// Retrieve data from database
tableDatabase = new TableDatabase(getActivity());
// Get rows of database
cursor = tableDatabase.getInformation(tableDatabase);
// Start from the last so that listview displays latest image first
// Check for existing rows
if(cursor.moveToLast()) {
do {
// Get items from each column
smiley_id = cursor.getInt(0);
title = cursor.getString(1);
date = cursor.getString(2);
caption = cursor.getString(3);
image = cursor.getString(4);
// Saves images added by user into listview
PictureItem pictureItem = new PictureItem(smiley_id, title, date, caption, image);
adapter.add(pictureItem);
} while (cursor.moveToPrevious());
}
// Swipe on refresh
swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh);
swipeRefreshLayout.setEnabled(false);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
(new Handler()).postDelayed(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
}, 1000);
}
});
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if(firstVisibleItem == 0) swipeRefreshLayout.setEnabled(true);
else swipeRefreshLayout.setEnabled(false);
}
});
// Lead user to UploadImageActivity to insert image to listview
addPicButton = (ImageButton) rootView.findViewById(R.id.addPictureButton);
addPicButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity().getApplicationContext(), UploadImageActivity.class));
}
});
return rootView;
}
UploadImageActivity.java
public class UploadImageActivity extends ActionBarActivity implements View.OnClickListener{
private Calendar cal = Calendar.getInstance();
private SimpleDateFormat dateFormatter = new SimpleDateFormat("dd MMM yyyy, EEE # hh:mm a");
EditText pic_title, pic_caption;
ImageView picture;
Button smiley1, smiley2, smiley3, smiley4, smiley5, selected_smiley;
// To store in database
int smiley_id = R.drawable.smile1; // Set default smiley as first smiley if not chosen
String title, date, caption;
String uriPicture; // Save uri in string format to store image as text format in database
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_picture);
// Removes shadow under action bar
getSupportActionBar().setElevation(0);
pic_title = (EditText) findViewById(R.id.picture_title);
pic_caption = (EditText) findViewById(R.id.picture_caption);
picture = (ImageView) findViewById(R.id.imagebutton);
smiley1 = (Button) findViewById(R.id.button1);
smiley2 = (Button) findViewById(R.id.button2);
smiley3 = (Button) findViewById(R.id.button3);
smiley4 = (Button) findViewById(R.id.button4);
smiley5 = (Button) findViewById(R.id.button5);
selected_smiley = (Button) findViewById(R.id.select_smiley);
picture.setOnClickListener(this);
smiley1.setOnClickListener(this);
smiley2.setOnClickListener(this);
smiley3.setOnClickListener(this);
smiley4.setOnClickListener(this);
smiley5.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_event, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_ok) {
title = pic_title.getText().toString();
date = dateFormatter.format(cal.getTime());
caption = pic_caption.getText().toString();
// Do not save data
if(title.isEmpty()) {
alertUser("Upload failed!", "Please enter title.");
}
else if(caption.isEmpty()) {
alertUser("Upload failed!", "Please enter caption.");
}
else if(uriPicture.isEmpty()) {
alertUser("Upload failed!", "Please upload an image.");
}
// Save data when title, caption and image are not empty
else {
// Add information into database
TableDatabase tableDatabase = new TableDatabase(this);
tableDatabase.putInformation(tableDatabase, smiley_id, title, date, caption, uriPicture);
Toast.makeText(getBaseContext(), "Details successfully saved", Toast.LENGTH_LONG).show();
finish();
}
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
// Show the image picked by user
case R.id.imagebutton:
picture.setImageDrawable(null);
Crop.pickImage(this);
break;
// Saves the user's smiley choice
case R.id.button1:
selected_smiley.setBackgroundResource(R.drawable.smile1);
selected_smiley.setText("");
setSmileyID(R.drawable.smile1);
break;
case R.id.button2:
selected_smiley.setBackgroundResource(R.drawable.smile2);
selected_smiley.setText("");
setSmileyID(R.drawable.smile2);
break;
case R.id.button3:
selected_smiley.setBackgroundResource(R.drawable.smile3);
selected_smiley.setText("");
setSmileyID(R.drawable.smile3);
break;
case R.id.button4:
selected_smiley.setBackgroundResource(R.drawable.smile4);
selected_smiley.setText("");
setSmileyID(R.drawable.smile4);
break;
case R.id.button5:
selected_smiley.setBackgroundResource(R.drawable.smile5);
selected_smiley.setText("");
setSmileyID(R.drawable.smile5);
break;
default:
break;
}
}
// This method sets the smiley ID according to what the user picks.
private void setSmileyID(int smileyID) {
this.smiley_id = smileyID;
}
// This method calls alert dialog to inform users a message.
private void alertUser(String title, String message) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(UploadImageActivity.this);
dialogBuilder.setTitle(title);
dialogBuilder.setMessage(message);
dialogBuilder.setPositiveButton("Ok", null);
dialogBuilder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == Crop.REQUEST_PICK && resultCode == RESULT_OK) {
beginCrop(data.getData());
} else if(requestCode == Crop.REQUEST_CROP) {
handleCrop(resultCode, data);
}
}
// This method allows users to crop image in square.
private void beginCrop(Uri source) {
Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
Crop.of(source, destination).asSquare().start(this);
}
// This method ensures there are no errors in cropping.
private void handleCrop(int resultCode, Intent result) {
if(resultCode == RESULT_OK) {
picture.setImageURI(Crop.getOutput(result));
uriPicture = Crop.getOutput(result).toString();
} else if(resultCode == Crop.RESULT_ERROR) {
Toast.makeText(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show();
}
}
TableDatabase.java
public class TableDatabase extends SQLiteOpenHelper {
public String query = "CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" +
TableData.TableInfo.SMILEY + " INTEGER NOT NULL, " +
TableData.TableInfo.TITLE + " TEXT, " +
TableData.TableInfo.DATE + " TEXT, " +
TableData.TableInfo.CAPTION + " TEXT, " +
TableData.TableInfo.IMAGE + " TEXT);";
public TableDatabase(Context context) {
super(context, TableData.TableInfo.DATABASE_NAME, null, TableData.TableInfo.DATABASE_VERSION);
// Check if database is created
Log.d("Database operations", "Database created");
}
#Override
public void onCreate(SQLiteDatabase db) {
// Create table
db.execSQL(query);
Log.d("Database operations", "Table created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// Insert user information into the database
public void putInformation(TableDatabase data, int smiley, String title, String date, String caption, String image) {
// Write data into database
SQLiteDatabase sqLiteDatabase = data.getWritableDatabase();
ContentValues contentValues = new ContentValues();
// Add value from each column into contentvalue
contentValues.put(TableData.TableInfo.SMILEY, smiley);
contentValues.put(TableData.TableInfo.TITLE, title);
contentValues.put(TableData.TableInfo.DATE, date);
contentValues.put(TableData.TableInfo.CAPTION, caption);
contentValues.put(TableData.TableInfo.IMAGE, image);
// Insert into sqlite database
sqLiteDatabase.insert(TableData.TableInfo.TABLE_NAME, null, contentValues);
Log.d("Database operations", "One row inserted");
}
// Retrieve data from database
public Cursor getInformation(TableDatabase data) {
// Read data from sqlite database
SQLiteDatabase sqLiteDatabase = data.getReadableDatabase();
String[] columns = { TableData.TableInfo.SMILEY, TableData.TableInfo.TITLE, TableData.TableInfo.DATE, TableData.TableInfo.CAPTION, TableData.TableInfo.IMAGE };
// Points to first row of table
return sqLiteDatabase.query(TableData.TableInfo.TABLE_NAME, columns, null, null, null, null, null);
}

Long click removing from arrayList

After adding the removal on long click part, i tried to add a call option the same way, but it didn't work.
I wrote the code here in the second box (first box is without the call option changes that didn't work) and highlighted the changes I tried with // signs.
This is the code: (i will add my attempts of creating the long click removal if you want)
public static final int PICK_CONTACT = 1;
private ArrayList<String> contactList;
private ArrayAdapter<String> arrayAdapter;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_work__contacts);
Button btnPickContact = (Button) findViewById(R.id.btnPickContact);
btnPickContact.setOnClickListener(new View.OnClickListener() {
public void onClick(View _view) {
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
});
//you may fill it here e.g. from your db
contactList=new ArrayList<String>();
arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, contactList);
final ListView lv = (ListView) findViewById(R.id.ContactListView);
lv.setAdapter(arrayAdapter);
lv.setLongClickable(true);
lv.setClickable(true);
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
arrayAdapter.notifyDataSetChanged();
arrayAdapter.remove(arrayAdapter.getItem(pos));
}
#SuppressWarnings("deprecation")
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case (PICK_CONTACT): {
if (resultCode == Activity.RESULT_OK) {
Uri contentUri = data.getData();
//Phone Name
Cursor c = managedQuery(contentUri, null, null, null, null);
c.moveToFirst();
String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
//Phone Number
String contactId = contentUri.getLastPathSegment();
Cursor cursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone._ID + "=?", new String[] { contactId },
null);// < - Note, not CONTACT_ID!
startManagingCursor(cursor);
Boolean numbersExist = cursor.moveToFirst();
int phoneNumberColumnIndex = cursor
.getColumnIndex(Phone.NUMBER);
String phoneNumber = "";
while (numbersExist) {
phoneNumber = cursor.getString(phoneNumberColumnIndex);
phoneNumber = phoneNumber.trim();
numbersExist = cursor.moveToNext();
}
stopManagingCursor(cursor);
//Set
arrayAdapter.add(name + "-" + phoneNumber);
arrayAdapter.notifyDataSetChanged();
}
break;
}
}
}
}
public static final int PICK_CONTACT = 1;
private ArrayList<String> contactList;
private ArrayAdapter<String> arrayAdapter;
// private ArrayList<Integer> contactList2;
// private ArrayAdapter<Integer> arrayAdapter2;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_work__contacts);
Button btnPickContact = (Button) findViewById(R.id.btnPickContact);
btnPickContact.setOnClickListener(new View.OnClickListener() {
public void onClick(View _view) {
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
});
//you may fill it here e.g. from your db
contactList=new ArrayList<String>();
// contactList2=new ArrayList<Integer>();
arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, contactList);
// arrayAdapter2 = new ArrayAdapter<Integer>(this,
// android.R.layout.simple_list_item_1, contactList2);
final ListView lv = (ListView) findViewById(R.id.ContactListView);
lv.setAdapter(arrayAdapter);
lv.setLongClickable(true);
lv.setClickable(true);
// final ListView lv2 = (ListView) findViewById(R.id.ContactListView);
// lv.setAdapter(arrayAdapter2);
// lv.setLongClickable(true);
// lv.setClickable(true);
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
arrayAdapter.notifyDataSetChanged();
arrayAdapter.remove(arrayAdapter.getItem(pos));
Log.v("long clicked","pos: " + pos);
return true;
}
});
// lv2.setOnItemClickListener(new OnItemClickListener() {
// public void onItemClick(AdapterView<?> parent, View view,
// int position, long id) {
//
//String url = "tel:"+position;
// Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
// startActivity(intent);
//
//}
//});
}
#SuppressWarnings("deprecation")
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case (PICK_CONTACT): {
if (resultCode == Activity.RESULT_OK) {
Uri contentUri = data.getData();
//Phone Name
Cursor c = managedQuery(contentUri, null, null, null, null);
c.moveToFirst();
String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
//Phone Number
String contactId = contentUri.getLastPathSegment();
Cursor cursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone._ID + "=?", new String[] { contactId },
null);// < - Note, not CONTACT_ID!
startManagingCursor(cursor);
Boolean numbersExist = cursor.moveToFirst();
int phoneNumberColumnIndex = cursor
.getColumnIndex(Phone.NUMBER);
String phoneNumber = "";
// Integer iInteger = new Integer(phoneNumberColumnIndex);
while (numbersExist) {
phoneNumber = cursor.getString(phoneNumberColumnIndex);
phoneNumber = phoneNumber.trim();
numbersExist = cursor.moveToNext();
}
stopManagingCursor(cursor);
//Set
arrayAdapter.add(name + " - " + phoneNumber);
arrayAdapter.notifyDataSetChanged();
// arrayAdapter2.add(iInteger);
// arrayAdapter2.notifyDataSetChanged();
}
break;
}
}
}
}
Anybody has an idea why it didn't work ?
Thank you
I think the best way is to implement a long click listener as you already did.
After that, I suggest you to show a message dialog for user to confirm. I share you a method to do this :
private AlertDialog showCustomDialog(final Activity act, CharSequence title, CharSequence message, CharSequence buttonYes, CharSequence buttonNo, final int selectedIndex) {
AlertDialog.Builder customDialog = new AlertDialog.Builder(act);
customDialog.setTitle(title);
customDialog.setMessage(message);
customDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
picURL.remove(selectedIndex);
}
});
customDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
}
});
return customDialog.show();
}
Last thing : I see you're removing from the adapter, but not in the list. Maybe this is what causing your error ?

Android SQLite database seems to clear every time i open a new activity

I've been trying to fix these two bugs for a while and I feel like it has to do with a fundamental misunderstanding of what happens when I open up a new activity. Basically the program is a task management program. It works fine when I add new tasks without modifying the category, and the database updates fine and the main page of the application updates as I add new tasks to display these new tasks.
However, I recently added functionality for an "add categories" button. The purpose of this button is to open up a new listactivity that allows users to add new categories of tasks. Every time I open this from the task editing activity and then press the back button to get back to the main page, all of the tasks in the database get cleared. Wondering if anyone can tell me what's going on and why the data is getting wiped out.
here's the relevant code snippet from the front page (the list view showing all of the tasks:
private RemindersDbAdapter mDbHelper;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reminder_list);
mDbHelper = new RemindersDbAdapter(this);
mDbHelper.open();
fillData();
registerForContextMenu(getListView());
}
private void fillData() {
Cursor remindersCursor = mDbHelper.fetchAllReminders();
startManagingCursor(remindersCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{RemindersDbAdapter.KEY_TITLE};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text1};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter reminders =
new SimpleCursorAdapter(this, R.layout.reminder_row, remindersCursor, from, to);
setListAdapter(reminders);
}
Here's some of the code for my task editing view (the one calling the activity for the category listing):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new RemindersDbAdapter(this);
//mCatDbHelper = new CategoriesDbAdapter(this);
setContentView(R.layout.reminder_edit);
mCalendar = Calendar.getInstance();
mTitleText = (EditText) findViewById(R.id.title);
//mBodyText = (EditText) findViewById(R.id.body);
mDateButton = (Button) findViewById(R.id.reminder_date);
mTimeButton = (Button) findViewById(R.id.reminder_time);
mLowPriorityButton = (Button) findViewById(R.id.low_priority);
mMedPriorityButton = (Button) findViewById(R.id.med_priority);
mHighPriorityButton = (Button) findViewById(R.id.high_priority);
mManageCategories = (Button) findViewById(R.id.manage_categories);
mSchoolRadio = (RadioButton)findViewById(R.id.radio_schoolwork);
mFamilyRadio = (RadioButton)findViewById(R.id.radio_family);
mOtherRadio = (RadioButton)findViewById(R.id.radio_other);
mContext = this;
priority = "Low";
category = "Other";
mConfirmButton = (Button) findViewById(R.id.confirm);
mRowId = savedInstanceState != null ? savedInstanceState.getLong(RemindersDbAdapter.KEY_ROWID)
: -1L;
registerButtonListenersAndSetDefaultText();
}
private void setRowIdFromIntent() {
if (mRowId == -1L) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(RemindersDbAdapter.KEY_ROWID)
: -1L;
}
}
#Override
protected void onPause() {
super.onPause();
mDbHelper.close();
}
#Override
protected void onResume() {
super.onResume();
mDbHelper.open();
setRowIdFromIntent();
//if(mRowId != -1L)
populateFields();
}
#Override
protected Dialog onCreateDialog(int id) {
switch(id) {
case DATE_PICKER_DIALOG:
return showDatePicker();
case TIME_PICKER_DIALOG:
return showTimePicker();
}
return super.onCreateDialog(id);
}
private void populateFields() {
// Only populate the text boxes and change the calendar date
// if the row is not null from the database.
if (mRowId != -1L) {
Cursor reminder = mDbHelper.fetchReminder(mRowId);
startManagingCursor(reminder);
mTitleText.setText(reminder.getString(
reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_TITLE)));
category = reminder.getString(reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_CATEGORY));
if(category.equals("School"))
mSchoolRadio.setChecked(true);
else if(category.equals("Family"))
mFamilyRadio.setChecked(true);
else
mOtherRadio.setChecked(true);
// Get the date from the database and format it for our use.
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
Date date = null;
try {
String dateString = reminder.getString(reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_DATE_TIME));
date = dateTimeFormat.parse(dateString);
mCalendar.setTime(date);
} catch (ParseException e) {
Log.e("ReminderEditActivity", e.getMessage(), e);
}
} else {
// This is a new task - add defaults from preferences if set.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String defaultTitleKey = getString(R.string.pref_task_title_key);
String defaultTimeKey = getString(R.string.pref_default_time_from_now_key);
String defaultTitle = prefs.getString(defaultTitleKey, null);
String defaultTime = prefs.getString(defaultTimeKey, null);
if(defaultTitle != null)
mTitleText.setText(defaultTitle);
if(defaultTime != null)
mCalendar.add(Calendar.MINUTE, Integer.parseInt(defaultTime));
}
updateDateButtonText();
updateTimeButtonText();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if(mRowId == -1L)
mRowId = -1L;
outState.putLong(RemindersDbAdapter.KEY_ROWID, mRowId);
}
/*
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
mRowId = savedInstanceState != null ? savedInstanceState.getLong(RemindersDbAdapter.KEY_ROWID)
: -1L;
}
*/
private void saveState() {
String title = mTitleText.getText().toString();
//String body = mBodyText.getText().toString();
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
String reminderDateTime = dateTimeFormat.format(mCalendar.getTime());
if (mRowId == -1L) {
long id = mDbHelper.createReminder(title, priority, category, reminderDateTime);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateReminder(mRowId, title, priority, category, reminderDateTime);
}
new ReminderManager(this).setReminder(mRowId, mCalendar);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
}
Here's the call (in the same class as the above code) to the new CategoryListActivity activity that's causing the problems:
mManageCategories.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(mContext, CategoryListActivity.class);
startActivity(i);
//populateFields();
}
});
I left out a lot of the less relevant code. Anyway like I said above... the main problem is that as soon as I start this new CategoryListActivity activity, the database and all the tasks get wiped out. weirdly, even if I restart the emulator the tasks don't get wiped as long as I don't start the CategoryListActivity. If anyone has any idea what's going on please help.
Andrew checkout this two links that will explain you everything about database integration.
http://www.devx.com/wireless/Article/40842/1954
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

Categories