In Android how to fetch the contacts and save to database implements? - java

In My android program I have NumberList.java with list_layout.xml
In xml there is a edit text field,and a button ..in edit text we can enter a phone number and with the button we can save..
But my requirement is I want to fetch the number from contacts and save them through a button..MainActivity.java is the program which fetchs the selected contact number..But I cant save as like NumberList.java.
How can I implement???
NumberList.java
public class NumberList extends Activity implements OnClickListener{
private RemindersDbAdapter mDbAdapter;
private EditText numbr;
private Button btnAdd;
private Button btnTree;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list_layout);
mDbAdapter=new RemindersDbAdapter(this);
mDbAdapter.open();
numbr=(EditText) findViewById(R.id.editNumber);
btnAdd=(Button) findViewById(R.id.btnSave);
btnAdd.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSave:
if((numbr.getText().toString()!=null)&&(numbr.getText().toString().length()>=7))
{ mDbAdapter.createReminder(numbr.getText().toString(), "", "");
mDbAdapter.close();
finish();
}
else
{
Toast.makeText(getApplicationContext(), "plz enter correct number", Toast.LENGTH_SHORT).show();
}
default:
break;
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mDbAdapter.close();
}}
and the another one which fetchs the contacts number from contact list
MainActivity.java
public class MainActivity extends Activity {
Button buttonReadContact;
TextView textPhone;
EditText ed;
final int RQS_PICKCONTACT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonReadContact = (Button)findViewById(R.id.readcontact);
textPhone = (TextView)findViewById(R.id.phone);
ed = (EditText)findViewById(R.id.phno1);
buttonReadContact.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
//Start activity to get contact
final Uri uriContact = ContactsContract.Contacts.CONTENT_URI;
Intent intentPickContact = new Intent(Intent.ACTION_PICK, uriContact);
startActivityForResult(intentPickContact, RQS_PICKCONTACT);
}});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(resultCode == RESULT_OK){
if(requestCode == RQS_PICKCONTACT){
Uri returnUri = data.getData();
Cursor cursor = getContentResolver().query(returnUri, null, null, null, null);
if(cursor.moveToNext()){
int columnIndex_ID = cursor.getColumnIndex(ContactsContract.Contacts._ID);
String contactID = cursor.getString(columnIndex_ID);
int columnIndex_HASPHONENUMBER = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
String stringHasPhoneNumber = cursor.getString(columnIndex_HASPHONENUMBER);
if(stringHasPhoneNumber.equalsIgnoreCase("1")){
Cursor cursorNum = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactID,
null,
null);
//Get the first phone number
if(cursorNum.moveToNext()){
int columnIndex_number = cursorNum.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String stringNumber = cursorNum.getString(columnIndex_number);
ed.setText(stringNumber);
}
}else{
textPhone.setText("NO Phone Number");
}
}else{
Toast.makeText(getApplicationContext(), "NO data!", Toast.LENGTH_LONG).show();
}
}
}
}
}

this is what you need just create a table and with name and phone_no and fill db details in below code
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
readContacts(getApplicationContext());
}
});
public void readContacts(Context ctx, String no) {
ContentValues cvs cvs = new ContentValues();
Cursor phones = ctx.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, ContactsContract.Contacts.DISPLAY_NAME + " ASC");
if (phones.getCount() > 0) {
while (phones.moveToNext()) {
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (!TextUtils.isEmpty(phoneNumber)) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
cvs.put("name", name );
cvs.put("phone_no", phoneNumber );
}
}
}
insertItem(cvs, "readtables");
}
private void insertItem(ContentValues cbs, String Tablename) {
SQLiteDatabase db = dbl.getWritableDatabase();
try {
CreateTablenew(Tablename);
db.insert("Tablename", null, cbs);
} catch (SQLException e) {
}
}

Related

Sqlite Error On Android Application

Im trying to build an app that sets many alarm clocks and i want to save the alarms with an SQLite database. Already watched many tutorials for this but still having a problem using the database. Firstly i want to save the alarm one by one by pushing a button. I tried also to insert manually 2 alarms but it didnt worked either. What am i doing wrong? I am pretty new to this!
DBHelper Class
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBName.db";
public static final String ALARMS_TABLE_NAME = "alarms";
public static final String ALARMS_COLUMN_ID = "id";
public static final String ALARMS_COLUMN_HOUR = "hour";
public static final String ALARMS_COLUMN_MINUTES = "minutes";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, 33);
}
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE "+ALARMS_TABLE_NAME+" ("+ALARMS_COLUMN_ID+ " INTEGER PRIMARY KEY , "+
ALARMS_COLUMN_HOUR+ " INTEGER, "+ALARMS_COLUMN_MINUTES+" INTEGER)");
InsertAlarms(db);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS "+ALARMS_TABLE_NAME);
onCreate(db);
}
void AddAlarm(Alarm alarm)
{
SQLiteDatabase db= this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(ALARMS_COLUMN_HOUR, alarm.getHour());
cv.put(ALARMS_COLUMN_MINUTES, alarm.getMinutes());
db.insert(ALARMS_TABLE_NAME, null, cv);
db.close();
}
Cursor getAllAlarms()
{
SQLiteDatabase db=this.getWritableDatabase();
Cursor cur= db.rawQuery("SELECT * FROM "+ALARMS_TABLE_NAME,null);
return cur;
}
void InsertAlarms(SQLiteDatabase db) //insert manually 2 alarms
{
ContentValues cv=new ContentValues();
cv.put(ALARMS_COLUMN_ID, 1);
cv.put(ALARMS_COLUMN_HOUR, 20);
cv.put(ALARMS_COLUMN_MINUTES, 20);
db.insert(ALARMS_TABLE_NAME, null, cv);
cv.put(ALARMS_COLUMN_ID, 2);
cv.put(ALARMS_COLUMN_HOUR, 20);
cv.put(ALARMS_COLUMN_MINUTES, 20);
db.insert(ALARMS_TABLE_NAME, null, cv);
}
int getAlarmCount()
{
SQLiteDatabase db=this.getWritableDatabase();
Cursor cur= db.rawQuery("Select * from "+ALARMS_TABLE_NAME, null);
int x= cur.getCount();
cur.close();
return x;
}
Class Alarm:
public class Alarm {
int _id;
int _hour;
int _minutes;
public Alarm(int Hour, int Minutes)
{
this._hour=Hour;
this._minutes=Minutes;
}
public int getID()
{
return this._id;
}
public void SetID(int ID)
{
this._id=ID;
}
public int getHour()
{
return this._hour;
}
public int getMinutes()
{
return this._minutes;
}
public void setHour(int Hour)
{
this._hour=Hour;
}
public void setMinutes(int Minutes)
{
this._minutes=Minutes;
}
Activity AddAlarm
public class AddAlarm extends Activity {
EditText txtHour;
EditText txtMinutes;
DBHelper dbHelper;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addalarm);
txtHour=(EditText)findViewById(R.id.txtHour);
txtMinutes=(EditText)findViewById(R.id.txtMinutes);
Button button1 = (Button)findViewById(R.id.addalarmbtn);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
btnAddAlarm_Click(v);
}
});
}
public void btnAddAlarm_Click(View view)
{
boolean ok=true;
try
{
int hour=Integer.parseInt(txtHour.getText().toString());
int minutes=Integer.parseInt(txtMinutes.getText().toString());
Alarm al=new Alarm(hour,minutes);
Toast.makeText(AddAlarm.this,"ADDED! ", Toast.LENGTH_LONG).show();
dbHelper.AddAlarm(al);
}
catch(Exception ex)
{
Toast.makeText(AddAlarm.this,"ERROR! ", Toast.LENGTH_LONG).show();
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
Intent intent=getIntent();
DBHelper mydb;
TextView xupnitiria;
String hour;
public static boolean flag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.set_alarm_button);
//Bundle extras=intent.getExtras();
mydb=new DBHelper(this);
xupnitiria =(TextView)findViewById(R.id.xupnitiria);
xupnitiria.setText(xupnitiria.getText()+String.valueOf(mydb.getAlarmCount()));
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
Intent a= new Intent(MainActivity.this, AddAlarm.class);
startActivity(a);
}
});
}
Errors on android Monitor
10-04 15:07:26.592 2625-2625/com.google.android.gms E/ActivityThread: Service com.google.android.gms.chimera.GmsIntentOperationService has leaked ServiceConnection csk#8709fba that was originally bound here
android.app.ServiceConnectionLeaked: Service com.google.android.gms.chimera.GmsIntentOperationService has leaked ServiceConnection csk#8709fba that was originally bound here
at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1336)
at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:1231)
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1450)
at android.app.ContextImpl.bindService(ContextImpl.java:1422)
at android.content.ContextWrapper.bindService(ContextWrapper.java:636)
at android.content.ContextWrapper.bindService(ContextWrapper.java:636)
at android.content.ContextWrapper.bindService(ContextWrapper.java:636)
at android.content.ContextWrapper.bindService(ContextWrapper.java:636)
at com.google.android.gms.chimera.container.zapp.ZappLogOperation.onHandleIntent(:com.google.android.gms:0)
at com.google.android.chimera.IntentOperation.onHandleIntent(:com.google.android.gms:1)
at bvq.run(:com.google.android.gms:9)
at bvn.run(:com.google.android.gms:10)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Add following in onCreate() of AddAlarm.java:
dbHelper=new DBHelper(this);
Also to see error log in logcat add following in try-catch block:
ex.printStackTrace();
AddAlarm Activity:
public class AddAlarm extends Activity {
EditText txtHour;
EditText txtMinutes;
DBHelper dbHelper;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addalarm);
txtHour = (EditText) findViewById(R.id.txtHour);
txtMinutes = (EditText) findViewById(R.id.txtMinutes);
dbHelper=new DBHelper(this);
Button button1 = (Button) findViewById(R.id.addalarmbtn);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
btnAddAlarm_Click(v);
}
});
}
public void btnAddAlarm_Click(View view) {
boolean ok = true;
try {
int hour = Integer.parseInt(txtHour.getText().toString());
int minutes = Integer.parseInt(txtMinutes.getText().toString());
Alarm al = new Alarm(hour, minutes);
Toast.makeText(AddAlarm.this, "ADDED! ", Toast.LENGTH_LONG).show();
dbHelper.AddAlarm(al);
} catch (Exception ex) {
Toast.makeText(AddAlarm.this, "ERROR! ", Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}
}

Retrieve contact from mobile's phone directory

This code can open a built-in contacts directory on a mobile device. However, when I select a contact, the app reports "done", but doesn't retrieve the contact number -- the user can't send a message.
How do I retrieve the contact number? List View is not a solution: I need to return just the one number, not extra information.
Here's my code:
public EditText no;
public EditText msg;
public Button cancel;
public Button snd;
public String Number,name,Message;
public int run=0;
public static final int PICK_CONTACT=1;
public void callContacts(View v)
{
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent,PICK_CONTACT);
}
#Override
public void onActivityResult(int reqCode,int resultCode,Intent data)
{
super.onActivityResult(reqCode,resultCode,data);
if(reqCode==PICK_CONTACT)
{
if(resultCode== ActionBarActivity.RESULT_OK)
{
Uri contactData = data.getData();
Cursor c = getContentResolver().query(contactData,null,null,null,null);
if(c.moveToFirst())
{
name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.CONTENT_URI.toString()));
Toast.makeText(this,"done",Toast.LENGTH_SHORT).show();
}
}
}
}
and here is the onCreate method
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
no = (EditText)findViewById(R.id.num);
msg = (EditText)findViewById(R.id.sms);
cancel = (Button)findViewById(R.id.cancel);
snd = (Button)findViewById(R.id.snd);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
msg.setText("");
no.setText("");
callContacts(null);
}
});
snd.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Number = no.toString();
Message = msg.getText().toString();
SmsManager manager = SmsManager.getDefault();
ArrayList<String>long_sms = manager.divideMessage(Message);
manager.sendMultipartTextMessage(Number,null,long_sms,null,null);
Toast.makeText(getApplicationContext(),"Sent Successfully",Toast.LENGTH_SHORT).show();
}
});
}
Here is the code just for selecting one phone number from contact list. i found this code simplest. let me know if there is any problem.
start activity with pick intent on phone data type:
findViewById(R.id.choose_contact_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent pickContact = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(pickContact, PICK_CONTACT_REQUEST);
}
});
Now set onAcitivityResult();
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
switch (requestCode){
case PICK_CONTACT_REQUEST:
if (resultCode == RESULT_OK){
Uri contactUri = intent.getData();
Cursor nameCursor = getContentResolver().query(contactUri, null, null, null, null);
if (nameCursor.moveToFirst()){
String name = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
((EditText)findViewById(R.id.person_name)).setText(name);
((EditText)findViewById(R.id.enter_mobile)).setText(number);
nameCursor.close();
}
}
break;
}
}

Storing and retrieving user uploaded images in parse

I have successfully been able to store user entered information into parse, but I haven't figure out how to do store a user uploaded image that would be associated with the current user in parse, and to retrieve a user image at a later time.
To clarify this, below is the code I have used for my profile creation activity, an activity that is prompted after the user has signing using social media and responds to a series of questions like age, preferred name, and where those information are later updated in the parse database and added to the current user.
Also in the activity, the user is already able to upload a picture from their device, my issue now resolves around taking that uploaded picture and storing it on parse, and associating the image with the current user who has signing using their social media account - the social media integration is done through parse.
I have looked into the following guide, but is still greatly confused.
https://www.parse.com/docs/android_guide#files
Any assistance would be greatly appreciated.
Thanks in advance.
public class ProfileCreation extends Activity {
private static final int RESULT_LOAD_IMAGE = 1;
FrameLayout layout;
Button save;
protected EditText mName;
protected EditText mAge;
protected EditText mHeadline;
protected Button mConfirm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_creation);
Parse.initialize(this, "ID", "ID");
mName = (EditText)findViewById(R.id.etxtname);
mAge = (EditText)findViewById(R.id.etxtage);
mHeadline = (EditText)findViewById(R.id.etxtheadline);
mConfirm = (Button)findViewById(R.id.btnConfirm);
mConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = mName.getText().toString();
String age = mAge.getText().toString();
String headline = mHeadline.getText().toString();
age = age.trim();
name = name.trim();
headline = headline.trim();
if (age.isEmpty() || name.isEmpty() || headline.isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileCreation.this);
builder.setMessage(R.string.signup_error_message)
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
else {
// create the new user!
setProgressBarIndeterminateVisibility(true);
ParseUser currentUser = ParseUser.getCurrentUser();
currentUser.put("name", name);
currentUser.put("age", age);
currentUser.put("headline", headline);
currentUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
setProgressBarIndeterminateVisibility(false);
if (e == null) {
// Success!
Intent intent = new Intent(ProfileCreation.this, MoodActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileCreation.this);
builder.setMessage(e.getMessage())
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}
});
save = (Button) findViewById(R.id.button2);
String picturePath = PreferenceManager.getDefaultSharedPreferences(this).getString("picturePath", "");
if (!picturePath.equals("")) {
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
SeekBar seekBar = (SeekBar) findViewById(R.id.seekBarDistance);
final TextView seekBarValue = (TextView) findViewById(R.id.seekBarDistanceValue);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
seekBarValue.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
SeekBar seekBarMinimum = (SeekBar) findViewById(R.id.seekBarMinimumAge);
final TextView txtMinimum = (TextView) findViewById(R.id.tMinAge);
seekBarMinimum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
txtMinimum.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
SeekBar seekBarMaximum = (SeekBar) findViewById(R.id.seekBarMaximumAge);
final TextView txtMaximum = (TextView) findViewById(R.id.tMaxAge);
seekBarMaximum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
txtMaximum.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
Button buttonLoadImage = (Button) findViewById(R.id.btnPictureSelect);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Locate the image in res >
Bitmap bitmap = BitmapFactory.decodeFile("picturePath");
// Convert it to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress image to lower quality scale 1 - 100
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
Object image = null;
try {
String path = null;
image = readInFile(path);
} catch (Exception e) {
e.printStackTrace();
}
// Create the ParseFile
ParseFile file = new ParseFile("picturePath", (byte[]) image);
// Upload the image into Parse Cloud
file.saveInBackground();
// Create a New Class called "ImageUpload" in Parse
ParseObject imgupload = new ParseObject("Image");
// Create a column named "ImageName" and set the string
imgupload.put("Image", "picturePath");
// Create a column named "ImageFile" and insert the image
imgupload.put("ImageFile", file);
// Create the class and the columns
imgupload.saveInBackground();
// Show a simple toast message
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
private byte[] readInFile(String path) throws IOException {
// TODO Auto-generated method stub
byte[] data = null;
File file = new File(path);
InputStream input_stream = new BufferedInputStream(new FileInputStream(
file));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
data = new byte[16384]; // 16K
int bytes_read;
while ((bytes_read = input_stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, bytes_read);
}
input_stream.close();
return buffer.toByteArray();
}
}
Also in the activity, the user is already able to upload a picture
from their device, my issue now resolves around taking that uploaded
picture and storing it on parse, and associating the image with the
current user who has signing using their social media account - the
social media integration is done through parse.
Read the docs on files and on the response type when a file is upload to parse.com
"media":{"__type":"File","name":"e580f231-...-picf1","url":"http://files.parse.com/..52d6-picf1"}
So, after POST on the file to parse, you have a logical FILE entity that you can then point to in another class.
In that other clase , you can also point to the user who created the FILE.
Class2 {"createdby" : pointer($user), "media" : pointer($file)}
With that, you have a separate class with 2 , pointer types ( toUser, toFile ) and the col headers on the data browser will show :
pointer<_User> for the user
file for the file

Issues uploading images

I have successfully been able to store user entered information into parse, but I have been having difficulty storing images into to parse, to be able to retrieve at a later date.
To clarify this, below is the code I have used for my profile creation activity, an activity that is prompted after the user has signing using social media and responds to a series of questions like age, preferred name, and where those information are later updated in the parse database and added to the current user.
Also in the activity, the user is already able to upload a picture from their device, my issue now resolves around taking that uploaded picture and storing it on parse, and associating the image with the current user who has signing using their social media account - the social media integration is done through parse.
I have looked into the following guide, but is still greatly confused.https://www.parse.com/docs/android_guide#files
Now I have tried to accomplish this, and have left my comments in the code below.
Any assistance would be greatly appreciated. Thanks in advance.
public class ProfileCreation extends Activity {
private static final int RESULT_LOAD_IMAGE = 1;
FrameLayout layout;
Button save;
protected EditText mName;
protected EditText mAge;
protected EditText mHeadline;
protected ImageView mprofilePicture;
protected Button mConfirm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_creation);
RelativeLayout v = (RelativeLayout) findViewById(R.id.main);
v.requestFocus();
Parse.initialize(this, "ID", "ID");
mName = (EditText)findViewById(R.id.etxtname);
mAge = (EditText)findViewById(R.id.etxtage);
mHeadline = (EditText)findViewById(R.id.etxtheadline);
mprofilePicture = (ImageView)findViewById(R.id.profilePicturePreview);
mConfirm = (Button)findViewById(R.id.btnConfirm);
mConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = mName.getText().toString();
String age = mAge.getText().toString();
String headline = mHeadline.getText().toString();
age = age.trim();
name = name.trim();
headline = headline.trim();
if (age.isEmpty() || name.isEmpty() || headline.isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileCreation.this);
builder.setMessage(R.string.signup_error_message)
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
else {
// create the new user!
setProgressBarIndeterminateVisibility(true);
ParseUser currentUser = ParseUser.getCurrentUser();
/* This is the section where the images is converted, saved, and uploaded. I have not been able Locate the image from the ImageView, where the user uploads the picture to imageview from either their gallery and later on from facebook */
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
/*fron image view */);
// Convert it to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress image to lower quality scale 1 - 100
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] image = stream.toByteArray();
// Create the ParseFile
ParseFile file = new ParseFile("profilePicture.png", image);
// Upload the image into Parse Cloud
file.saveInBackground();
// Create a column named "ImageName" and set the string
currentUser.put("ImageName", "AndroidBegin Logo");
// Create a column named "ImageFile" and insert the image
currentUser.put("ProfilePicture", file);
// Create the class and the columns
currentUser.saveInBackground();
currentUser.put("name", name);
currentUser.put("age", age);
currentUser.put("headline", headline);
currentUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
setProgressBarIndeterminateVisibility(false);
if (e == null) {
// Success!
Intent intent = new Intent(ProfileCreation.this, MoodActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileCreation.this);
builder.setMessage(e.getMessage())
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}
});
SeekBar seekBar = (SeekBar) findViewById(R.id.seekBarDistance);
final TextView seekBarValue = (TextView) findViewById(R.id.seekBarDistanceValue);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
seekBarValue.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
Button mcancel = (Button)findViewById(R.id.btnBack);
mcancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProfileCreation.this.startActivity(new Intent(ProfileCreation.this, LoginActivity.class));
}
});
SeekBar seekBarMinimum = (SeekBar) findViewById(R.id.seekBarMinimumAge);
final TextView txtMinimum = (TextView) findViewById(R.id.tMinAge);
seekBarMinimum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
txtMinimum.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
SeekBar seekBarMaximum = (SeekBar) findViewById(R.id.seekBarMaximumAge);
final TextView txtMaximum = (TextView) findViewById(R.id.tMaxAge);
seekBarMaximum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
txtMaximum.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
Button buttonLoadImage = (Button) findViewById(R.id.btnPictureSelect);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
private byte[] readInFile(String path) throws IOException {
// TODO Auto-generated method stub
byte[] data = null;
File file = new File(path);
InputStream input_stream = new BufferedInputStream(new FileInputStream(
file));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
data = new byte[16384]; // 16K
int bytes_read;
while ((bytes_read = input_stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, bytes_read);
}
input_stream.close();
return buffer.toByteArray();
}
}
You need to wait for the file to finish saving before you add it to the user.
Try adding a completion block to your file.saveInBackground() call, and moving all the currentUser manipulation into that completion block.

How to get the position of the item in list to remove using gesture action in gesture overlayview

MainActivity.java
public class MainActivity extends ListActivity implements OnGesturePerformedListener {
static SQLiteDatabase db;
public static String TABEl_CREATE="CONTACTS";
public static String DATA_BASE_TABLE_CREATE = "create table if not exists " +TABEl_CREATE+ "(Name text not null ,Number number unique not null)";
GestureLibrary lib;
private ArrayList<String> results = new ArrayList<String>();
ArrayAdapter<String> adapter;
ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = openOrCreateDatabase("contacts", MODE_PRIVATE, null);
db.execSQL(DATA_BASE_TABLE_CREATE);
lv = (ListView) findViewById (android.R.id.list);
populatelv();
lib = GestureLibraries.fromRawResource(this, R.raw.gestures);
if (!lib.load()) {
finish();
}
GestureOverlayView gesture = (GestureOverlayView)
findViewById(R.id.gestures);
gesture.addOnGesturePerformedListener(this);
}
private void populatelv() {
// TODO Auto-generated method stub
Cursor c = db.rawQuery("SELECT Name FROM " +TABEl_CREATE, null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String Name = c.getString(c.getColumnIndex("Name"));
results.add( Name );
}while (c.moveToNext());
}
}
adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1,android.R.id.text1,results);
lv.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
// TODO Auto-generated method stub
ArrayList<Prediction> predictions = lib.recognize(gesture);
if (predictions.size() > 0)
{
String action = predictions.get(0).name;
if (predictions.get(0).score > 1.0)
{
if ("ADD".equals(action))
{
Toast.makeText(this, "Adding a contact",
Toast.LENGTH_SHORT).show();
Intent i = new Intent(MainActivity.this,Database.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
else
if ("delete".equals(action))
{
Toast.makeText(this, "Removing a contact",Toast.LENGTH_SHORT).show();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0,
View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
// Here,how can i get the position of the specific listitem where gesture action took place..?
// String str = lv.getItemAtPosition(arg2).toString();
//Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
// String delete = "delete from contacts where Name = '"+str+"'";
//db.execSQL(delete);
//Toast.makeText(getApplicationContext(), "Deleted", Toast.LENGTH_SHORT).show();
}
}) ;
}
else if ("refresh".equals(action))
{
Toast.makeText(this, "Reloading contacts",
Toast.LENGTH_SHORT).show();
}
}
}
}
}
Database.java
public class Database extends Activity {
Button add;
EditText name,number;
SQLiteDatabase db;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.database);
db= MainActivity.db;
db = openOrCreateDatabase("contacts", MODE_PRIVATE, null);
add = (Button) findViewById(R.id.button1);
name = (EditText) findViewById(R.id.editText1);
number = (EditText) findViewById(R.id.editText2);
add.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String nval,nbval;
nval = name.getText().toString();
nbval = number.getText().toString();
if(nval.length()>0 && nbval.length()>0)
{
ContentValues cv = new ContentValues();
cv.put("Name", nval);
cv.put("Number", nbval);
db.insert("CONTACTS","title", cv);
Toast.makeText(getApplicationContext(), "Inserted sucessfully",Toast.LENGTH_SHORT ).show();
}
else
{
Toast.makeText(getApplicationContext(), "Please fill all fields!!!", Toast.LENGTH_SHORT).show();
}
}
});
}
public void onBackPressed()
{
Intent intent=new Intent(Database.this,MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
};
}
Here,i'm trying to display contacts in listview by retrieving from database which is done by Database.java.I'm able add the contacts into database using gesture but when i tried to delete the specific contact from list using gesture,i can't able to do..I'm new to development of android applications..please suggest me..here is my code.

Categories

Resources