Camera activity does not start on the second time - java

I have making a tab based app. There are three tabs. One of the tab is used to camera. So when I press camera tab then it opens up camera activity so that I could take pictures. Until here it works fine. When I take picture then that picture is showed in ImageView. From here when I press any other tab and then I press camera tab then camera activity does not start. It keep shows me that previous image on ImageView. What I want is whenever user taps on camera tab then it should opens camera activity. How can I achieve this effect?
Here is my code. Below os oncreate method which is in camera activity. So when camera tab is pressed it opens this activity.
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
userFunctions = new UserFunctions();
globalUID = getIntent().getExtras().getString("globalUID");
Toast.makeText(getApplicationContext(), globalUID, Toast.LENGTH_LONG).show();
ivUserImage = (ImageView)findViewById(R.id.ivUserImage);
bUpload = (Button)findViewById(R.id.bUpload);
openCamera();
}
private void openCamera() {
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CameraResult);
}
Update
I did this but still the same problem
boolean flag = true;
#Override
protected void onResume() {
super.onResume();
//flag = true;
if(flag) {
openCamera();
flag = false;
}
}
Edit
After following Imran's answer my code looks like this now. I am also adding additional code. But this code still does not work.
public class Camera extends Activity {
ImageView ivUserImage;
Button bUpload;
Intent i;
int CameraResult = 0;
Bitmap bmp;
public String globalUID;
UserFunctions userFunctions;
String photoName;
InputStream is;
String largeImagePath;
int serverResponseCode = 0;
public static boolean flag = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
userFunctions = new UserFunctions();
globalUID = getIntent().getExtras().getString("globalUID");
//flag = getIntent().getExtras().getBoolean("flag");
Toast.makeText(getApplicationContext(), globalUID, Toast.LENGTH_LONG).show();
ivUserImage = (ImageView)findViewById(R.id.ivUserImage);
bUpload = (Button)findViewById(R.id.bUpload);
//openCamera();
if(flag ==true)
openCamera();
}
#Override
protected void onResume() {
super.onResume();
if(flag==true)
openCamera();
}
private void openCamera() {
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CameraResult);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
flag = false;
if(resultCode == RESULT_OK) {
//set image taken from camera on ImageView
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
ivUserImage.setImageBitmap(bmp);
//Create new Cursor to obtain the file Path for the large image
String[] largeFileProjection = {
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA
};
String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
Cursor myCursor = this.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, largeFileProjection, null, null, largeFileSort);
try {
myCursor.moveToFirst();
//This will actually give you the file path location of the image.
largeImagePath = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
File f = new File("" + largeImagePath);
photoName = f.getName();
bUpload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new Upload().execute(largeImagePath, globalUID, photoName);
}
});
} finally {
myCursor.close();
}
}
}
}
Here is my tab activity code
public class DashboardActivity extends TabActivity {
UserFunctions userFunctions;
public String globalUID;
DatabaseHandler db;
boolean flag = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
db = new DatabaseHandler(getApplicationContext());
// Check login status in database
userFunctions = new UserFunctions();
if(userFunctions.isUserLoggedIn(getApplicationContext())){
//globalUID = getIntent().getExtras().getString("globalUID");
HashMap<String, String> data = db.getUserDetails();
globalUID = data.get("uid");
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Resusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
//Home
intent = new Intent(this, Home.class);
intent.putExtra("globalUID", globalUID);
spec = tabHost.newTabSpec("home").setIndicator("", res.getDrawable(R.drawable.home_icon)).setContent(intent);
tabHost.addTab(spec);
//Camera
intent = new Intent(this, Camera.class);
intent.putExtra("globalUID", globalUID);
//intent.putExtra("flag", flag);
spec = tabHost.newTabSpec("camera").setIndicator("", res.getDrawable(R.drawable.camera_icon)).setContent(intent);
tabHost.addTab(spec);
//Albums
intent = new Intent(this, Albums.class);
intent.putExtra("globalUID", globalUID);
spec = tabHost.newTabSpec("albums").setIndicator("", res.getDrawable(R.drawable.albums_icon)).setContent(intent);
tabHost.addTab(spec);
//tabHost.setCurrentTab(1);
} else {
// user is not logged in show login screen
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
}
}
Here is my whole camera activity
public class Camera extends Activity {
ImageView ivUserImage;
Button bUpload;
Intent i;
int CameraResult = 0;
Bitmap bmp;
public String globalUID;
UserFunctions userFunctions;
String photoName;
InputStream is;
String largeImagePath;
int serverResponseCode = 0;
public static boolean flag = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
userFunctions = new UserFunctions();
globalUID = getIntent().getExtras().getString("globalUID");
//flag = getIntent().getExtras().getBoolean("flag");
Toast.makeText(getApplicationContext(), globalUID, Toast.LENGTH_LONG).show();
ivUserImage = (ImageView)findViewById(R.id.ivUserImage);
bUpload = (Button)findViewById(R.id.bUpload);
//openCamera();
//if(flag ==true)
openCamera();
}
/*
#Override
protected void onResume() {
super.onResume();
if(flag==true)
openCamera();
}*/
private void openCamera() {
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CameraResult);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
flag = false;
if(resultCode == RESULT_OK) {
//set image taken from camera on ImageView
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
ivUserImage.setImageBitmap(bmp);
//Create new Cursor to obtain the file Path for the large image
String[] largeFileProjection = {
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA
};
String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
Cursor myCursor = this.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, largeFileProjection, null, null, largeFileSort);
try {
myCursor.moveToFirst();
//This will actually give you the file path location of the image.
largeImagePath = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
File f = new File("" + largeImagePath);
photoName = f.getName();
bUpload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new Upload().execute(largeImagePath, globalUID, photoName);
}
});
} finally {
myCursor.close();
}
}
}
public class Upload extends AsyncTask<String, Integer, String> {
ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(Camera.this, "", "Uploading file...", true);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String success = "false";
Bitmap bitmapOrg = setImageToImageView(largeImagePath);//BitmapFactory.decodeFile(largeImagePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeToString(ba, 0);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",ba1));
nameValuePairs.add(new BasicNameValuePair("imageName", photoName));
nameValuePairs.add(new BasicNameValuePair("uid", globalUID));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.info/android/fileupload.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if(response != null) {
success = "true";
}
is = entity.getContent();
} catch(Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
dialog.dismiss();
return success;
}
protected void onProgressUpdate(Integer...progress) {
}
protected void onPostExecute(String f) {
Toast.makeText(getApplicationContext(), "File uploaded", Toast.LENGTH_LONG).show();
}
}
public Bitmap setImageToImageView(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, o2);
return bitmap;
}
public boolean fileData(String guid, String photoName) {
Toast.makeText(getApplicationContext(), photoName, Toast.LENGTH_LONG).show();
JSONObject json = userFunctions.uploadFileData(guid, photoName);
try {
if(Integer.parseInt(json.getString("success")) != 1) {
Toast.makeText(getApplicationContext(), json.getInt("error_msg"), Toast.LENGTH_LONG).show();
//register_error.setText(json.getString("error_msg"));
return false;
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
}

This is because when you are switching between tabs your activity doesnt call onCreate again.
Try moving call to openCamera(); into onResume method and it should be fine.
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
userFunctions = new UserFunctions();
globalUID = getIntent().getExtras().getString("globalUID");
Toast.makeText(getApplicationContext(), globalUID, Toast.LENGTH_LONG).show();
ivUserImage = (ImageView)findViewById(R.id.ivUserImage);
bUpload = (Button)findViewById(R.id.bUpload);
}
protectd void onResume(){
super.onResume();
openCamera();
}
private void openCamera() {
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CameraResult);
}

Each Activity in an TabHost calls onCreate() only once for reason of efficiency. This is why the openCamera() doesn't get called again and again.
In order to handle this, you can in the parent Activity to implement and register an OnTabChangeListener, where you can catch which tab is clicked and perform any desired action.
Hope this helps!

add onResume() in your activity and call openCamera(); from onResume() also as:
public static boolean flag = true;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
userFunctions = new UserFunctions();
globalUID = getIntent().getExtras().getString("globalUID");
Toast.makeText(getApplicationContext(), globalUID, Toast.LENGTH_LONG).show();
ivUserImage = (ImageView)findViewById(R.id.ivUserImage);
bUpload = (Button)findViewById(R.id.bUpload);
if(flag ==true)
openCamera();
}
#Override
protected void onResume() {
super.onResume();
if(flag==true)
openCamera();
}
and in on onActivityResut()
flag =false;
or on tabclick
YourflagActivity.flag=true;

Related

How do I make that different button, different imageview will be affected

I'm very new to this coding thing and I hope that anyone of you can help me out on this. Basically I have three different buttons with different image view and I would like to upload them to my MySQL. However when I press all three button at different times, it will only affect the 1 of the image views. Appreciate if you could help.
public static final int resultloadimage = 1;
private static final int RESULT_OK = -1;
Button btnupadloadnric, btnuploaddl, btnuploadvl,updateButton;
ImageView ivnric,ivdl,ivvl;
EditText fullanme, telephone;
String encodedimage;
ConnectionClass connectionClass;
String filename = null;
byte[] image = null;
private byte[] byteArray;
public Profile() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_profile, container, false);
btnupadloadnric = v.findViewById(R.id.btnAdminUploadNRICFragment);
btnuploaddl = v.findViewById(R.id.btnAdminUploadDLFragment);
btnuploadvl = v.findViewById(R.id.btnAdminUploadVCLFragment);
ivdl = v.findViewById(R.id.ivadminprofiledl);
ivnric = v.findViewById(R.id.ivadminprofilenric);
ivvl = v.findViewById(R.id.ivadminprofilevl);
fullanme = v.findViewById(R.id.etAdminFullNameProfileFragment);
telephone = v.findViewById(R.id.etAdminPhoneNumberProfileFragment);
updateButton = v.findViewById(R.id.btnAdminUpdateProfileFragment);
connectionClass = new ConnectionClass();
btnuploadvl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, resultloadimage);
}
});
btnuploaddl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, resultloadimage);
}
});
btnupadloadnric.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, resultloadimage);
}
});
updateButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
UploadImage uploadImage = new UploadImage();
uploadImage.execute("");
}
});
return v;
}
#Override
public void onActivityResult(int requestCode, int resultcode, Intent data)
{
super.onActivityResult(requestCode,resultcode,data);
if (requestCode == resultloadimage && resultcode == RESULT_OK && null !=data){
Bitmap originbitmap = null;
Uri selectedImage = data.getData();
InputStream imagestream;
try {
imagestream = getActivity().getContentResolver().openInputStream(selectedImage);
originbitmap = BitmapFactory.decodeStream(imagestream);
}catch (FileNotFoundException e)
{
Toast.makeText(getActivity(),"Done",Toast.LENGTH_LONG).show();
}
if (originbitmap!=null){
this.ivdl.setImageBitmap(originbitmap);
Log.w("Image in", "Done");
try {
Bitmap image = ((BitmapDrawable)ivdl.getDrawable()).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 90 , byteArrayOutputStream);
byteArray = byteArrayOutputStream.toByteArray();
encodedimage = Base64.encodeToString(byteArray,Base64.DEFAULT);
UploadImage uploadImage = new UploadImage();
uploadImage.execute("");
}catch (Exception e){
Log.w("asd", "Exception");
}
Toast.makeText(getActivity(),"Done",Toast.LENGTH_LONG).show();
}
}
else{
System.out.println("Error Occured");
}
}
public class UploadImage extends AsyncTask<String,String,String>
{
#Override
protected String doInBackground(String... strings) {
try {
Connection con = connectionClass.CONN();
if (con==null) {
Toast.makeText(getActivity(),"Check Internet", Toast.LENGTH_LONG).show();
}else{
String command = "Insert into driverprofile (DrivingL, Username, Password) values('" + encodedimage + "', 'Admin1', '12345')";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(command);
if (rs.next()){}
}
} catch (Exception ex) {
ex.getMessage();
}
return null;
}
}
}
I think you should change request codes for each gallery intent on each button click.
btnuploadvl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, "request code for btnuploadvl");
}
});
btnuploaddl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, "request code for btnuploaddl");
}
});
btnupadloadnric.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, "request code for btnupadloadnric");
}
});
And then check request code detecting which button is clicked on onActivityResult.

check to see if a button have been clicked

In my activity I am able to upload a picture from the gallery.
I would like to check if the user has indeed uploaded the picture prior to hitting confirm. One way of achieving this, I want to check if the upload picture button has been clicked.
I also want to see if an edittext has been filled through the following code but is struggling with image:
String name = mName.getText().toString();
// Number age = mAge.getText(;
String headline = mHeadline.getText().toString();
// age = ((String) age).trim();
name = name.trim();
headline = headline.trim();
if (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!
below is how the image is being selected:
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();
}
Update:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_creation);
feedBack = new FeedbackDialog(this, "AF-46D8F2A319EA-0A");
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);
male = (RadioButton)findViewById(R.id.rimale);
female = (RadioButton)findViewById(R.id.rifemale);
lmale = (RadioButton)findViewById(R.id.rlmale);
lfemale = (RadioButton)findViewById(R.id.rlfemale);
seekBarMinimum = (SeekBar) findViewById(R.id.sbseekBarMinimumAge);
seekBarMaximum = (SeekBar) findViewById(R.id.sbseekBarMaximumAge);
seekBarDistance = (SeekBar) findViewById(R.id.sbseekBarDistance);
seekBarActivityDistance = (SeekBar) findViewById(R.id.sbseekBarActivityDistance);
mConfirm = (Button)findViewById(R.id.btnConfirm);
mConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
findViewById(R.id.btnConfirm).setBackgroundResource(R.drawable.gray_bac);
String name = mName.getText().toString();
// Number age = mAge.getText(;
String headline = mHeadline.getText().toString();
// age = ((String) age).trim();
name = name.trim();
headline = headline.trim();
if (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();
if(male.isChecked())
gender = "Male";
else
gender = "Female";
if(lmale.isChecked())
lgender = "Male";
else
lgender = "Female";
age = Integer.parseInt(mAge.getText().toString());
ParseInstallation installation = ParseInstallation.getCurrentInstallation();
installation.put("Name", name);
installation.put("UserAge", age);
installation.put("Headline", headline);
installation.put("Gender", gender);
installation.put("Looking_Gender", lgender);
installation.put("Minimum_Age", seekBarMinimum.getProgress());
installation.put("Maximum_Age", seekBarMaximum.getProgress());
installation.put("Maximum_Distance_Match", seekBarDistance.getProgress());
installation.put("Maximum_Distance_Activity", seekBarActivityDistance.getProgress());
installation.saveInBackground();
currentUser.put("Name", name);
currentUser.put("UserAge", age);
currentUser.put("Headline", headline);
currentUser.put("Gender", gender);
currentUser.put("Looking_Gender", lgender);
currentUser.put("Minimum_Age", seekBarMinimum.getProgress());
currentUser.put("Maximum_Age", seekBarMaximum.getProgress());
currentUser.put("Maximum_Distance_Match", seekBarDistance.getProgress());
currentUser.put("Maximum_Distance_Activity", seekBarActivityDistance.getProgress());
/* 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 */
ImageView myImgView = (ImageView) findViewById(R.id.profilePicturePreview);
Bitmap bitmap = ((BitmapDrawable) myImgView.getDrawable()).getBitmap();
// 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 "Profile Picture" and set the string
currentUser.put("ImageName", "Profile Picture");
// Create a column named "ImageFile" and insert the image
currentUser.put("ProfilePicture", file);
currentUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
setProgressBarIndeterminateVisibility(false);
if (e == null) {
// Success!
Intent intent = new Intent(ProfileCreation.this, betaEventsActivity.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_message)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}
});
SeekBar seekBar = (SeekBar) findViewById(R.id.sbseekBarDistance);
final TextView seekBarValue = (TextView) findViewById(R.id.tvseekBarDistanceValue);
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 seekBarActivity = (SeekBar) findViewById(R.id.sbseekBarActivityDistance);
final TextView seekBarActivityValue = (TextView) findViewById(R.id.tvseekBarActivityDistanceValue);
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.sbseekBarMinimumAge);
final TextView txtMinimum = (TextView) findViewById(R.id.tvMinAge);
seekBarMinimum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
if (progress <= 18) {
seekBar.setProgress(18);
} else {
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.sbseekBarMaximumAge);
final TextView txtMaximum = (TextView) findViewById(R.id.tvMaxAge);
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 can set a boolean to true, if image is selected by user in onActivityResult
//global variable
boolean imagePicked = false;
//In onActivityResult change its value
#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) {
imagePicked = true;
//other things
}
else {
imagePicked = false;
//other things
}
In last button click check imagePicked is true or false and proceed accordingly.
Hope it helps.

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 display lat/long markers on google map v2 android

I'm currently working on an android app with web services, using an external database. The app consists of several tasks and each task is assigned to each camera id. Each camera have specific long/lat stored in the database. So right now when I select a specific task, there would be a guide button showing the user current location as a marker in the google map. I want to display the long/lat of the task as a marker on the google map, so there would be 2 marker. Just need some help with the android coding. Any help would be appreciated!
GoogleMapActivity.java
public class GoogleMapActivity extends Activity implements LocationListener {
GoogleMap map;
private String cameraid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_map);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
}
#Override
public void onLocationChanged(Location location) {
map.clear();
MarkerOptions mp = new MarkerOptions();
mp.position(new LatLng(location.getLatitude(), location.getLongitude()));
mp.title("My Current Location");
map.addMarker(mp);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 16));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
AcceptTask.java
public class AcceptTask extends SherlockActivity {
private static String sendingURL,
url,
imageURL,
dateTimeP,
notificationID,
cameraID;
private String check = null;
// JSON Node names
private static final String TAG_GET = "jobViewResult",
TAG_IMAGEURL = "imageurl",
TAG_MESSAGE = "vmessage",
TAG_GETA = "assignResult",
TAG_STATUS = "assignStatus";
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
private TextView tvCamera, tvDate;
private ImageView my_image;
// contacts JSONObject
JSONObject api = null;
private long userInteractionTime = 0;
AsyncTask<Void, Void, Void> mRegisterTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accept_task);
tvCamera = (TextView) findViewById(R.id.tv_CameraID);
tvDate = (TextView) findViewById(R.id.tv_DateR);
my_image = (ImageView) findViewById(R.id.img_Task);
//set the icon clickable
getSupportActionBar().setHomeButtonEnabled(true);
//add an < arrow on the icon
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
File file = new File("/sdcard/LocationSystem/pendingtask_temp.jpg" );
if (file.exists()) {
file.delete();
}
if(isNetworkConnected()){
try{
// getting intent data
Intent intent = getIntent();
/** Get values from previous intent */
dateTimeP = intent.getStringExtra("TAG_IMAGE_TIME_DATE_P");
cameraID = intent.getStringExtra("TAG_CAMERA_ID_P");
notificationID = intent.getStringExtra("TAG_NOTIFICATION_ID");
/** Display cameraID and date time */
tvCamera.setText(cameraID);
tvDate.setText(dateTimeP);
url = "url";
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
api = json.getJSONObject(TAG_GET);
check = api.getString(TAG_MESSAGE);
// Storing each json item in variable
imageURL = api.getString(TAG_IMAGEURL);
} catch (JSONException e) {
e.printStackTrace();
}
if(check.equals("Job available")){
new DownloadImageTask().execute(imageURL);
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogTheme));
builder.setCancelable(false);
builder.setTitle("Job Unavailable");
builder.setMessage(check);
// Setting Icon to Dialog
builder.setIcon(R.drawable.ic_action_error);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent loadIntent = new Intent();
loadIntent.putExtra("startUpdate_PList", "start");
setResult(Activity.RESULT_OK, loadIntent);
finish();
}
});
builder.show();
}
} catch(Exception e) {
if(e != null) {
showServerErrorDialog();
}
}
}else{showNetworkErrorDialog();}
}
private void showServerErrorDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogTheme));
builder.setCancelable(false);
builder.setTitle("Server Error");
builder.setMessage("Server is currently unable to connect. Please check your network connectivity.");
// Setting Icon to Dialog
builder.setIcon(R.drawable.ic_action_error);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.show();
}
private void showNetworkErrorDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogTheme));
builder.setTitle("No Network Connection");
builder.setMessage("Please turn on your mobile 3G or connect to a network in order to use this application.");
// Setting Icon to Dialog
builder.setIcon(R.drawable.ic_action_error);
builder.setPositiveButton("Close",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
AcceptTask.this.finish();
}
});
builder.setNegativeButton("Setting",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//calling setting menu
startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
}
});
builder.show();
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
return false;
} else{
return true;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case android.R.id.home:
if(my_image.getDrawable() != null){
File file = new File("/sdcard/LocationSystem/pendingtask_temp.jpg" );
if (file.exists()) {
file.delete();
}
}
Intent loadIntent = new Intent();
loadIntent.putExtra("startUpdate_PList", "start");
setResult(Activity.RESULT_OK, loadIntent);
finish();
break;
default:
return super.onOptionsItemSelected(item);
}
return false;
}
#Override
public void onUserInteraction() {
userInteractionTime = System.currentTimeMillis();
super.onUserInteraction();
Log.i("appname","Interaction");
}
#Override
public void onUserLeaveHint() {
long uiDelta = (System.currentTimeMillis() - userInteractionTime);
super.onUserLeaveHint();
if (uiDelta < 100){
Logout();
}
}
#Override
public void onResume() {
super.onResume();
if(isNetworkConnected()){
try{
SharedPreferences checkLogin1 = getApplicationContext().getSharedPreferences( "checklogin", 0);
String staffID = checkLogin1.getString("staffID", "");
String staffPassword = checkLogin1.getString("password", "");
DefaultHttpClient httpClient = new DefaultHttpClient();
//get the unique id
SharedPreferences pref = getApplicationContext().getSharedPreferences( "checklogin", 0);
String checkID = pref.getString("loginRID", "");
HttpGet request = new HttpGet(url);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
// Read response data into buffer
char[] buffer = new char[(int) responseEntity
.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
JSONObject svr = new JSONObject(new String(buffer));
JSONObject obj = svr.getJSONObject("loginTestResult");
String validation = obj.getString("valid");
String position = obj.getString("position");
String companyID = obj.getString("companyID");
String messageStatus = obj.getString("message");
if(validation.equals("1")){
checkNotNull(SERVER_URL, "SERVER_URL");
checkNotNull(SENDER_ID, "SENDER_ID");
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(this);
//mDisplay = (TextView) findViewById(R.id.display);
//gcmIDtxt =(TextView) findViewById(R.id.gcmID);
registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION));
final String regId = GCMRegistrar.getRegistrationId(this);
System.out.print(regId);
if (regId.equals("")) {
// Automatically registers application on startup.
GCMRegistrar.register(this, SENDER_ID);
} else {
// Device is already registered on GCM, check server.
// if (GCMRegistrar.isRegisteredOnServer(this)) {
// // Skips registration.
// //mDisplay.append(getString(R.string.already_registered) + "\n");
// //gcmIDtxt.setText(regId);
//
// } else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
boolean registered =
ServerUtilities.register(context, regId);
// At this point all attempts to register with the app
// server failed, so we need to unregister the device
// from GCM - the app will try to register again when
// it is restarted. Note that GCM will send an
// unregistered callback upon completion, but
// GCMIntentService.onUnregistered() will ignore it.
if (!registered) {
GCMRegistrar.unregister(context);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
// }
}
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogTheme));
builder.setCancelable(false);
builder.setTitle("Error");
builder.setMessage(messageStatus + " Please sign in again.");
// Setting Icon to Dialog
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences pref2 = getApplicationContext().getSharedPreferences("checklogin", 0);
final SharedPreferences.Editor editor1 = pref2.edit();
editor1.putInt("login", 0);
editor1.commit();
Intent intent = new Intent(AcceptTask.this, LoginPage.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
builder.show();
}
} catch(Exception e) {
if(e != null) {
showServerErrorDialog();
}
}
}else{
showNetworkErrorDialog();
}
//runAcceptedTask();
}
private final BroadcastReceiver mHandleMessageReceiver =
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
//mDisplay.append(newMessage + "\n");
}
};
private void checkNotNull(Object reference, String name) {
if (reference == null) {
throw new NullPointerException(
getString(R.string.error_config, name));
}
}
private void Logout(){
if(isNetworkConnected()){
try{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
DefaultHttpClient httpClient = new DefaultHttpClient();
//get the unique id
SharedPreferences pref = getApplicationContext().getSharedPreferences( "checklogin", 0);
String checkID = pref.getString("loginRID", "");
String staffID = pref.getString("staffID", "");
HttpGet request = new HttpGet(url);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
// Read response data into buffer
char[] buffer = new char[(int) responseEntity
.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
JSONObject svr = new JSONObject(new String(buffer));
JSONObject obj = svr.getJSONObject("logoutResult");
String messageStatus = obj.getString("userMessage");
if(messageStatus.equals("Updated Successfully!!")){
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogTheme));
builder.setCancelable(false);
builder.setTitle("Error");
builder.setMessage(messageStatus);
// Setting Icon to Dialog
builder.setIcon(R.drawable.ic_action_error);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.show();
}
} catch (Exception e) {
if(e != null) {
showServerErrorDialog();
}
}
}
else{
showNetworkErrorDialog();
}
}
//accept task button
public void acceptTask(View v) {
File file = new File("/sdcard/LocationSystem/pendingtask_temp.jpg" );
if (file.exists()) {
file.delete();
}
AlertDialog.Builder builder = new AlertDialog.Builder(AcceptTask.this);
builder.setTitle("Confirm Accept");
builder.setMessage("Are you sure to accept this job?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if(isNetworkConnected()){
try{
// Do do my action here
SharedPreferences pref = getApplicationContext().getSharedPreferences(
"checklogin", 0);
String staffID = pref.getString("staffID", "");
//sendingURL = ""+staffID;
sendingURL = "url";
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(sendingURL);
try {
api = json.getJSONObject(TAG_GETA);
check = api.getString(TAG_STATUS);
} catch (JSONException e) {
if(e != null) {
showServerErrorDialog();}
}
if(check.equals("Job available")){
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(sendingURL);
try {
HttpResponse response = httpclient.execute(httpget);
Toast.makeText(getApplicationContext(), "You accepted the job.", Toast.LENGTH_SHORT).show();
Intent loadIntent = new Intent();
loadIntent.putExtra("startUpdate_PList", "start");
setResult(Activity.RESULT_OK, loadIntent);
finish();
}
catch (IOException e) {
if(e != null) {
showServerErrorDialog();}
}
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(AcceptTask.this, R.style.AlertDialogTheme));
builder.setCancelable(false);
builder.setTitle("Job Unavailable");
builder.setMessage(check);
// Setting Icon to Dialog
builder.setIcon(R.drawable.ic_action_error);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent loadIntent = new Intent();
loadIntent.putExtra("startUpdate_PList", "start");
setResult(Activity.RESULT_OK, loadIntent);
finish();
}
});
builder.show();
}
} catch(Exception e) {
if(e != null) {
showServerErrorDialog();
}
}
}else{
showNetworkErrorDialog();
}
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private class DownloadImageTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
protected String doInBackground(String... urls) {
int count;
try {
URL url = new URL(urls[0]);
URLConnection connection = url.openConnection();
connection.connect();
int lenghtOfFile = connection.getContentLength();
InputStream in = new BufferedInputStream(url.openStream(), 8192);
byte data[] = new byte[1024];
// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/LocationSystem/pendingtask_temp.jpg");
long total = 0;
while((count = in.read(data)) != -1){
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
File file = new File(getExternalCacheDir(), "pendingtask_temp.jpg" );
if (file.exists()) {
file.delete();
}else{
output.write(data, 0, count);
}
}
output.flush();
output.close();
in.close();
} catch (Exception e) {
Log.e("Error", e.getMessage());
if(e != null) {
showServerErrorDialog();
}
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
String imagePath = Environment.getExternalStorageDirectory().toString() + "/LocationSystem/pendingtask_temp.jpg";
// setting downloaded into image view
my_image.setImageDrawable(Drawable.createFromPath(imagePath));
File file = new File("/sdcard/LocationSystem/pendingtask_temp.jpg" );
if (file.exists()) {
file.delete();
}
if (my_image.getDrawable() == null){
Toast.makeText(AcceptTask.this, "Please select again!",Toast.LENGTH_LONG).show();
finish();
}
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//pDialog.setButton("Cancel", (DialogInterface.OnClickListener) null);
pDialog.setButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
AcceptTask.this.finish();
}
});
pDialog.setCancelable(false);
pDialog.show();
return pDialog;
default:
return null;
}
}
#Override
public void onBackPressed() {
if(my_image.getDrawable() != null){
File file = new File("/sdcard/LocationSystem/pendingtask_temp.jpg" );
if (file.exists()) {
file.delete();
}
}
Intent loadIntent = new Intent();
loadIntent.putExtra("startUpdate_PList", "start");
setResult(Activity.RESULT_OK, loadIntent);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.accept_task, menu);
return true;
}
}
You can do an asynck task to get the DB values and call this task in onlocationchange.

Categories

Resources