Google place picker api, occur error in the searching process - android

Good Day,
I'm trying to use place picker api. From google.
public void onPickButtonClick(View v) {
// Construct an intent for the place picker
try {
PlacePicker.IntentBuilder intentBuilder =
new PlacePicker.IntentBuilder();
Intent intent = intentBuilder.build(this);
// Start the intent by requesting a result,
// identified by a request code.
startActivityForResult(intent, REQUEST_PLACE_PICKER);
} catch (GooglePlayServicesRepairableException e) {
// ...
} catch (GooglePlayServicesNotAvailableException e) {
// ...
}
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (requestCode == REQUEST_PLACE_PICKER
&& resultCode == Activity.RESULT_OK) {
// The user has selected a place. Extract the name and address.
final Place place = PlacePicker.getPlace(data, this);
final CharSequence name = place.getName();
final CharSequence address = place.getAddress();
String attributions = PlacePicker.getAttributions(data);
if (attributions == null) {
attributions = "";
}
mViewName.setText(name);
mViewAddress.setText(address);
mViewAttributions.setText(Html.fromHtml(attributions));
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
But it result in that after launching the application loading the places. It just flash and turn white and return to the page where i launch this application.
Thank You In Advance
code
public class POI extends ActionBarActivity {
int REQUEST_PLACE_PICKER = 1;
TextView mViewName, mViewAddress, mViewAttributions;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poi_horizontal);
mViewName = (TextView) findViewById(R.id.name);
mViewAddress = (TextView) findViewById(R.id.address);
mViewAttributions = (TextView) findViewById(R.id.attributions);
}
public void PickButtonClick(View v) {
// Construct an intent for the place picker
try {
PlacePicker.IntentBuilder intentBuilder =
new PlacePicker.IntentBuilder();
Intent intent = intentBuilder.build(this);
// Start the intent by requesting a result,
// identified by a request code.
startActivityForResult(intent, REQUEST_PLACE_PICKER);
} catch (GooglePlayServicesRepairableException e) {
// ...
} catch (GooglePlayServicesNotAvailableException e) {
// ...
}
}
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (requestCode == REQUEST_PLACE_PICKER
&& resultCode == POI.RESULT_OK) {
// The user has selected a place. Extract the name and address.
final Place place = PlacePicker.getPlace(data, this);
final CharSequence name = place.getName();
final CharSequence address = place.getAddress();
String attributions = PlacePicker.getAttributions(data);
if (attributions == null) {
attributions = "";
}
mViewName.setText(name);
mViewAddress.setText(address);
mViewAttributions.setText(Html.fromHtml(attributions));
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_poi, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

Related

I want to hide search bar from google place picker api

Click to this to view Image I'm Using Google Place Picker Api and now i want to hide upper search bar from place picker is there any way to do .
i search a lot on internet but not find any solution.
btn_map.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
PlacePicker.IntentBuilder intentBuilder = new PlacePicker.IntentBuilder();
intentBuilder.setLatLngBounds(BOUNDS_MOUNTAIN_VIEW);
Intent intent = intentBuilder.build(MainActivity.this);
startActivityForResult(intent, 1);
} catch (Exception e) {
e.getMessage();
}
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == PLACE_PICKER_REQUEST
&& resultCode == Activity.RESULT_OK) {
final Place place = PlacePicker.getPlace(this, data);
final CharSequence name = place.getName();
final CharSequence address = place.getAddress();
String attributions = (String) place.getAttributions();
if (attributions == null) {
attributions = "";
}
} else {
super.onActivityResult(requestCode,resultCode, data);
}
}

android app implement google auto complete activity for 2 inputs

I have 2 edit text inputs in my app.One is from place and another one to place.For these 2 inputs I have implemented google auto complete activity but problem when user click on any one of these inputs google autocomplete intent after user place selection completed intent call onActivityResult().
In onActivityResult() how to know which input clicked.
here is my code
fromPlaceEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_REGIONS).setTypeFilter(AutocompleteFilter.TYPE_FILTER_GEOCODE)
.build();
Intent intent =
new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY).setFilter(typeFilter)
.build(MainActivity.this);
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
});
toPlaceEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_REGIONS).setTypeFilter(AutocompleteFilter.TYPE_FILTER_GEOCODE)
.build();
Intent intent =
new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY).setFilter(typeFilter)
.build(MainActivity.this);
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(this, data);
String fullName= (String) place.getAddress();
#// here I want to know which input clicked and set fullname in input text#
fromPlaceEdit.setText(fullName);
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(this, data);
// TODO: Handle the error.
Log.i("fdfdf", status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
}
}
I did it different way.
I have created two global boolean value each for from place and to place.
then when user click on from place or to place change boolean value of same place then on onActivityResult check which boolean value is true and set result place name to same input box.
Code follows:
public boolean fromplaceSlected =false ;
public boolean toplaceSlected =false;
fromPlaceEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_REGIONS).setTypeFilter(AutocompleteFilter.TYPE_FILTER_GEOCODE)
.build();
Intent intent =
new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY).setFilter(typeFilter)
.build(MainActivity.this);
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
});
toPlaceEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_REGIONS).setTypeFilter(AutocompleteFilter.TYPE_FILTER_GEOCODE)
.build();
Intent intent =
new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY).setFilter(typeFilter)
.build(MainActivity.this);
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("request", String.valueOf(requestCode));
// Check that the result was from the autocomplete widget.
if (requestCode == REQUEST_CODE_AUTOCOMPLETE) {
if (resultCode == RESULT_OK) {
// Get the user's selected place from the Intent.
Place place = PlaceAutocomplete.getPlace(getContext(), data);
String fullName = (String) place.getAddress();
if(fromplaceSlected){
Log.e("from place",fullName);
fromPlaceEdit.setText(fullName);
fromplaceSlected=false;
toplaceSlected=false;
}
else if(toplaceSlected){
Log.e("toplace" ,fullName);
toPlaceEdit.setText(fullName);
fromplaceSlected=false;
toplaceSlected=false;
}
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(getContext(), data);
Log.e("sdsdsdd", "Error: Status = " + status.toString());
fromplaceSlected=false;
toplaceSlected=false;
} else if (resultCode == RESULT_CANCELED) {
// Indicates that the activity closed before a selection was made. For example if
// the user pressed the back button.
fromplaceSlected=false;
toplaceSlected=false;
}
}
}
Your code may work, but it's a bit hacky. Here is the good way to do it:
public static final int PLACE_AUTOCOMPLETE_FROM_PLACE_REQUEST_CODE=1;
public static final int PLACE_AUTOCOMPLETE_TO_PLACE_REQUEST_CODE=2;
fromPlaceEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
//Do your stuff from place
startActivityForResult(intent, PLACE_AUTOCOMPLETE_FROM_PLACE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
});
toPlaceEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
//Do your stuff to place
startActivityForResult(intent, PLACE_AUTOCOMPLETE_TO_PLACE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_AUTOCOMPLETE_FROM_PLACE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
//Do your ok >from place< stuff here
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
//Handle your error >from place<
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
} else if (requestCode == PLACE_AUTOCOMPLETE_TO_PLACE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
//Do your ok >to place< stuff here
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
//Handle your error >to place<
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
}
}
From documentation:
requestCode int: If >= 0, this code will be returned in onActivityResult() when the activity exits.

Parse FB Login Crash on Function Not Included in Login

I have integrated Parse Login (v1.10.3) and never had this issue until I integrated FB Login (v4.8.2). If uninstall and re-install the app and launch, when the app launches I receive an error from an activity that occurs after Login. I have the MainActivity as the launch page and it checks for a current user. If the current user is null it redirects to the LoginActivity. The LoginActivity crashes with a Null Pointer Exception error that occurs in an Adapter linked to a Fragment called from the Main Adapter. Why is my Login Activity being skipped?
I have a lot of logs in my code as I was trying to determine if there is a current user value at some point or if there is any Login function executed that would cause it to skip the Login, but none of it is executed and the current user is always Null (which I expect).
Login Activity
public static final List<String> mPermissions = new ArrayList<String>() {
{
add("public_profile");
add("email");
add("gender");
add("user_birthday");
}};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//set and transition to signup page
mSignUpTextView = (TextView)findViewById(R.id.signupText);
mSignUpTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, SignupActivity.class);
startActivity(intent);
}
});
//set and transition to reset password page
mResetPasswordText = (TextView)findViewById(R.id.login_ForgotPasswordText);
mResetPasswordText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, ResetPasswordActivity.class);
startActivity(intent);
}
});
//set and handle all login tasks
mUsername = (EditText)findViewById(R.id.usernameField);
mPassword = (EditText)findViewById(R.id.passwordField);
mLoginButton = (Button)findViewById(R.id.loginButton);
//Facebook login
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("public_profile, email, user_birthday, user_friends"));
callbackManager = CallbackManager.Factory.create();
mFbProfile = Profile.getCurrentProfile();
Log.d("Login FB", String.valueOf(mFbProfile));
// Other app specific specialization
// Callback registration
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ParseFacebookUtils.logInWithReadPermissionsInBackground(LoginActivity.this, mPermissions, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
Log.d("Login", "Uh oh. The user cancelled the Facebook login.");
if (err != null) {
Log.d("ParseFacebookLogin", "Error: " + err.getLocalizedMessage());
}
}
else if (user.isNew()) {
Log.d("Login", "User signed up and logged in through Facebook!");
getUserDetailsFromFB();
//success
FlokkApp.updateParseInstallation(user);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
Log.d("Login FB", "User logged in through Facebook!");
}
else {
Log.d("Login", "User logged in through Facebook!");
getUserDetailsFromParse();
//success
FlokkApp.updateParseInstallation(user);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
});
}
});
//Regular Parse Login ----------------------------------------------------------
mLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String username = mUsername.getText().toString();
String password = mPassword.getText().toString();
username = username.trim();
password = password.trim();
//noinspection StatementWithEmptyBody
if (username.isEmpty() || password.isEmpty()){
// display message if field is blank
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage(R.string.login_error_message)
.setTitle(R.string.login_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
else {
// login user
ParseUser.logInInBackground(username, password, new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
//success
FlokkApp.updateParseInstallation(user);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
//Toast.makeText(LoginActivity.this, "Successful Login", Toast.LENGTH_SHORT).show();
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage(e.getMessage())
.setTitle(R.string.login_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}
});
}
//Facebook login required below ------------------------------------
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("Login", "on activity result");
super.onActivityResult(requestCode, resultCode, data);
ParseFacebookUtils.onActivityResult(requestCode, resultCode, data);
}
//Facebook save new user code -----------------------------------------------
private void saveNewUser() {
Log.d("Login", "Save new user");
parseUser = ParseUser.getCurrentUser();
parseUser.setUsername(name);
parseUser.setEmail(email);
//will need to update once I figure out how facebook sends the data
boolean genderValue;
if (gender == "Male") {
genderValue = true;
} else {
genderValue = false;
};
parseUser.put(ParseConstants.KEY_GENDERMALE, genderValue);
String searchtext = name.toLowerCase().trim();
parseUser.put(ParseConstants.KEY_SEARCHTEXT, searchtext);
//Saving profile photo as a ParseFile
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bitmap = null; //((BitmapDrawable) mProfileImage.getDrawable()).getBitmap();
if (bitmap != null) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
byte[] data = stream.toByteArray();
String thumbName = parseUser.getUsername().replaceAll("\\s+", "");
final ParseFile parseFile = new ParseFile(thumbName + "_android_FBLogin.jpg", data);
parseFile.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
parseUser.put(ParseConstants.KEY_PROFILEPIC, parseFile);
//Finally save all the user details
parseUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
Toast.makeText(LoginActivity.this, "New user:" + name + " Signed up", Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
private void getUserDetailsFromFB() {
Log.d("Login", "getUserDetails From FB");
// Suggested by https://disqus.com/by/dominiquecanlas/
Bundle parameters = new Bundle();
parameters.putString("fields", "email,name,gender,picture");
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/me",
parameters,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
try {
Log.d("Response", response.getRawResponse());
email = response.getJSONObject().getString("email");
//mEmailID.setText(email);
name = response.getJSONObject().getString("name");
mUsername.setText(name);
gender = response.getJSONObject().getString("gender");
JSONObject picture = response.getJSONObject().getJSONObject("picture");
JSONObject data = picture.getJSONObject("data");
// Returns a 50x50 profile picture
String pictureUrl = data.getString("url");
Log.d("Profile pic", "url: " + pictureUrl);
new ProfilePhotoAsync(pictureUrl).execute();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
).executeAsync();
}
private void getUserDetailsFromParse() {
Log.d(" Login", "getUserDetails From parse");
parseUser = ParseUser.getCurrentUser();
//Fetch profile photo
try {
ParseFile parseFile = parseUser.getParseFile(ParseConstants.KEY_PROFILEPIC);
byte[] data = parseFile.getData();
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
//mProfileImage.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
//mEmailID.setText(parseUser.getEmail());
mUsername.setText(parseUser.getUsername());
//Toast.makeText(LoginActivity.this, "Welcome back " + mUsername.getText().toString(), Toast.LENGTH_SHORT).show();
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_login, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//Required for facebook
class ProfilePhotoAsync extends AsyncTask<String, String, String> {
public Bitmap bitmap;
String url;
public ProfilePhotoAsync(String url) {
this.url = url;
}
#Override
protected String doInBackground(String... params) {
// Fetching data from URI and storing in bitmap
bitmap = DownloadImageBitmap(url);
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//mProfileImage.setImageBitmap(bitmap);
saveNewUser();
}
}
public static Bitmap DownloadImageBitmap(String url) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("IMAGE", "Error getting bitmap", e);
}
return bm;
}
Main Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ParseAnalytics.trackAppOpened(getIntent());
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser == null) {
navigateToLogin();
Log.d("Login Check", String.valueOf(ParseUser.getCurrentUser()));
}
else {
}
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
mTabs = (SlidingTabLayout) findViewById(R.id.tabs);
mTabs.setDistributeEvenly(true);
mTabs.setViewPager(mPager);
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.myflokk.testflokkd",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
//included onResume as a part of facebook integration
#Override
protected void onResume() {
super.onResume();
// Logs 'install' and 'app activate' App Events.
AppEventsLogger.activateApp(this);
}
//included onPause as a part of facebook integration
#Override
protected void onPause() {
super.onPause();
// Logs 'app deactivate' App Event.
AppEventsLogger.deactivateApp(this);
}
private void navigateToLogin() {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will automatically handle clicks on the Home/Up button, so long as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
switch (id) {
case R.id.addEvent:
startActivity(new Intent(this, AddEventActivity.class));
break;
case R.id.editProfile:
startActivity(new Intent(this, UserProfileEditActivity.class));
break;
case R.id.action_logout:
ParseUser.logOut();
navigateToLogin();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onStart() {
super.onStart();
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser == null) {
navigateToLogin();
Log.d("Login Check 2", String.valueOf(ParseUser.getCurrentUser()));
}
else {
}
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.myflokk.testflokkd/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.myflokk.testflokkd/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
class MyPagerAdapter extends FragmentPagerAdapter {
String[] tabs;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
tabs = getResources().getStringArray(R.array.tabs);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new UserEventListFragment();
case 1:
return new UserSearchFragment();
case 2:
return new UserProfileActivityFragment();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabs[position];
}
#Override
public int getCount() {
return 3;
}
}
Event Adapter that Causes the Error
protected Context mContext;
protected List<ParseObject> mEvents;
private SimpleDateFormat mFormat = new SimpleDateFormat("E, MMM d", Locale.US);
protected Date mDate;
protected List<Object> mLikeList = new ArrayList<>();
protected int mLikes = 0;
protected String Flokking = "I am flokking to this event!";
public EventAdapter(Context context, List<ParseObject> events) {
super(context, R.layout.row_event_list, events);
mContext = context;
mEvents = events;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.row_event_list, null);
holder = new ViewHolder();
holder.eventName = (TextView) convertView.findViewById(R.id.eventRow_TextEventName);
holder.eventLocation = (TextView) convertView.findViewById(R.id.eventRow_TextEventLocation);
holder.eventImage = (ImageView) convertView.findViewById(R.id.eventRow_EventImage);
holder.eventDate = (TextView) convertView.findViewById(R.id.eventRow_Date);
holder.eventNotLiked = (ImageView) convertView.findViewById(R.id.eventRow_ImageNotLiked);
holder.eventLiked = (ImageView) convertView.findViewById(R.id.eventRow_ImageLiked);
holder.eventFlokkingCount = (TextView) convertView.findViewById(R.id.eventRow_FlokkingCount);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ParseObject event = mEvents.get(position);
ParseObject details = mEvents.get(position);
final String currentEvent = details.getObjectId();
//Log.d("EventAdapter", "This is the position --> " + position);
holder.eventName.setText(event.getString(ParseConstants.KEY_EVENTNAME));
holder.eventLocation.setText(event.getString(ParseConstants.KEY_EVENTVENUE));
holder.eventFlokkingCount.setText(event.getNumber(ParseConstants.EVENT_LIKECOUNT).toString());
//get the date and assign to mDate and then change the way the date is displayed
mDate = event.getDate(ParseConstants.KEY_EVENTDATE);
holder.eventDate.setText(mFormat.format(mDate));
mLikeList = event.getList(ParseConstants.EVENT_LIKES);
Log.d("Login Event Check", String.valueOf(ParseUser.getCurrentUser()));
if (mLikeList == null || mLikeList.isEmpty()) {
//this is false and the user has not liked the event
holder.eventLiked.setVisibility(View.INVISIBLE);
holder.eventNotLiked.setVisibility(View.VISIBLE);
}
else {
//if there are users in the list check for the current user
if (mLikeList.contains(ParseUser.getCurrentUser().getObjectId())) {
// true
holder.eventLiked.setVisibility(View.VISIBLE);
holder.eventNotLiked.setVisibility(View.INVISIBLE);
}
else {
holder.eventLiked.setVisibility(View.INVISIBLE);
holder.eventNotLiked.setVisibility(View.VISIBLE);
}
}
Error Log
02-01 19:05:28.800 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.myflokk.testflokkd, PID: 1933
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.parse.ParseUser.getObjectId()' on a null object reference
at com.myflokk.testflokkd.Adapters.EventAdapter.getView(EventAdapter.java:98)

How to set an image on imageView from the gallery and image taken by camera in Android?

In my app I want to set an image on a ImageView from gallery and I want to set an image which is taken by the camera. I have tried this code, when I load image from the gallery, it is working. But when I try to take a picture to set on ImageView, that activity is loaded but the image is not showing in the ImageView. Any solution for this? Here is my code:
First Activity
public class MainActivity extends ActionBarActivity {
private static int RESULT_LOAD_IMAGE = 1;
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
Bitmap photo;
String picturePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
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);
}
});
// this.imageView = (ImageView)this.findViewById(R.id.imgView);
Button photoButton = (Button) this.findViewById(R.id.button2);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#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]);
picturePath = cursor.getString(columnIndex);
cursor.close();
int flagval = 1;
/* ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));*/
sendImage(flagval);
}
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
/* photo = (Bitmap) data.getExtras().get("data");
//imageView.setImageBitmap(photo);
int flagvalt=2;
try {
sendImage(flagvalt);
}
catch (Exception e){
Toast.makeText(MainActivity.this, "Method error", Toast.LENGTH_SHORT).show();
}*/
try {
loadCamPic();
Toast.makeText(MainActivity.this, "Method invoked", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Method error", Toast.LENGTH_SHORT).show();
}
}
}
public void sendImage(int flag) {
if (flag == 1) {
Toast.makeText(MainActivity.this, "Loc:" + picturePath, Toast.LENGTH_SHORT).show();
Intent myIntent1 = new Intent(MainActivity.this, ImageUploadActivity.class);
myIntent1.putExtra("key", picturePath);
MainActivity.this.startActivity(myIntent1);
}
/*else if(flag==2) {
Intent intent = new Intent(MainActivity.this, ImageUploadActivity.class);
intent.putExtra("BitmapImage", photo);
}*/
}
void loadCamPic() {
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String pathName = baseDir + "/DCIM/CAMERA";
File parentDir = new File(pathName);
File[] files = parentDir.listFiles();
Date lastDate = null;
String lastFileName;
boolean isFirstFile = true;
for (File file : files) {
if (isFirstFile) {
lastDate = new Date(file.lastModified());
isFirstFile = false;
}
if (file.getName().endsWith(".jpg") || file.getName().endsWith(".jpeg")) {
Date lastModDate = new Date(file.lastModified());
if (lastModDate.after(lastDate)) {
lastDate = lastModDate;
lastFileName = file.getName();
String pathName2 = pathName + lastFileName;
// Log.e(TAG, "Method invoked");
Intent intent = new Intent(MainActivity.this, ImageUploadActivity.class);
Bundle extras = new Bundle();
extras.putString("FILE_PATH", pathName2);
extras.putString("FILE_NAME", lastFileName);
intent.putExtras(extras);
MainActivity.this.startActivity(intent);
}
}
}
}
}
Second Activity
public class ImageUploadActivity extends ActionBarActivity {
private Button upload;
private Bitmap bitmap;
private ProgressDialog dialog;
String picturePath;
String filename;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_upload);
//Image from sdcard
Intent intent1 = getIntent();
picturePath = intent1.getExtras().getString("key");
imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
bitmap = (BitmapFactory.decodeFile(picturePath));
//Camera Image
/* Intent intent = getIntent();
bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(bitmap);*/
if (picturePath == null) {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
filename = extras.getString("FILE_NAME");
String filepath = extras.getString("FILE_PATH");
Toast.makeText(ImageUploadActivity.this, "Success:" + filepath, Toast.LENGTH_SHORT).show();
imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(filepath));
bitmap = (BitmapFactory.decodeFile(filepath));
}
upload = (Button) findViewById(R.id.upload);
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (bitmap == null) {
Toast.makeText(getApplicationContext(),
"Please select image", Toast.LENGTH_SHORT).show();
} else {
dialog = ProgressDialog.show(ImageUploadActivity.this, "Uploading",
"Please wait...", true);
new ImageUploadTask().execute();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_image_upload, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class ImageUploadTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... unsued) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost("http://10.10.10.15/test/upload.php");
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
/* entity.addPart("uploaded_file", new ByteArrayBody(data,
"myImage.jpg"));*/
// String newFilename= filename.concat("file");
// newFilename=filename+newFilename;
entity.addPart("uploaded_file", new ByteArrayBody(data,
filename));
// Log.e(TAG, "Method invoked");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = reader.readLine()) != null) {
builder.append(aux);
}
String sResponse = builder.toString();
return sResponse;
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Exception Message 1", Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
// (null);
}
#Override
protected void onProgressUpdate(Void... unsued) {
}
#Override
protected void onPostExecute(String sResponse) {
try {
if (dialog.isShowing())
dialog.dismiss();
if (sResponse != null) {
Toast.makeText(getApplicationContext(),
"Photo uploaded successfully",
Toast.LENGTH_SHORT).show();
Log.e("Response", sResponse);
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Exception Message",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
}
Take a look at the selected as best answer here Take photo w/ camera intent and display in imageView or textView? and you could find out how to take a picture and set it as a background of an imageView programmatically

zxing barcode scanner results in null

I followed guide from this page and I get the intent fired up. It also found barcode. However when
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
showMessage("result", scanResult.toString());
}
// else continue with any other code you need in the method
}
is reached the dialog(showMessage function basically just creates dialog with title and text) shows following text:
Format: null
Contents: null
Raw bytes: (0bytes)
Orientation: null
EC level: null
Have I missed some part or is it just issue with bar codes? I have tried every product with barcode that I have lying around but no change.
My project used to do something like that:
public class MenuScreen extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_screen);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_menu_screen, menu);
return true;
}
public void onScanCodeClick(View view) {
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.setPackage("com.google.zxing.client.android");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
try {
startActivityForResult(intent, 0);
} catch (ActivityNotFoundException aex) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("No Application Found");
builder.setMessage("We could not find an application to scan QR CODES."
+ " Would you like to download one from Android Market?");
builder.setPositiveButton("Yes, Please",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent marketIntent = new Intent(Intent.ACTION_VIEW);
marketIntent.setData(Uri
.parse("market://details?id=com.google.zxing.client.android"));
startActivity(marketIntent);
}
});
builder.setNegativeButton("No, Thanks", null);
builder.create().show();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
// Handle successful scan
Intent intent2 = new Intent();
intent2.setClass(this, MenuCodeSuccess.class);
intent2.putExtra("qrDetails", contents);
startActivity(intent2);
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}
}
onScanCodeClick is just an onClickListener for button. You can of course init your button and use this code instead.
And here is an xml layout:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnCount="2" >
<Button
android:id="#+id/menuScreen_SCANCODE"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onScanCodeClick"
android:text="#string/scanButton" />
</TableLayout>
Please don't care the style of layout, all what you need is just in java class. :) but it should be working anyway.
// In side onActivityResult(), try this code
if (resultCode == IntentIntegrator.REQUEST_CODE) {
Log.e("inside Request code~~~~~~~~>", "Barcode>>>>");
IntentResult scanResult = IntentIntegrator.parseActivityResult(
requestCode, resultCode, data);
if (scanResult == null) {
Log.e("Scan Result~~~~~~~~>", "value>>> Null");
return;
}
final String result = scanResult.getContents();
final String result1 = scanResult.getFormatName();
if (result != null) {
handlerBarcode.post(new Runnable() {
#Override
public void run() {
// txtScanResult.setText(result);
// txtScanResultFormat.setText(result1);
Toast.makeText(Activity_Form_Data_4.this,
"Code:" + result + " Format:" + result1,
Toast.LENGTH_SHORT).show();
}
});
}
}

Categories

Resources