Android Image Cropper does not work with images from camera - image

I am using Image Cropper provided by ArthurHub, It used to work perfectly fine on all tested devices, I can crop images from both gallery and camera. Recently on Galaxy A51 device after updating; if you try to crop image camera the App crashes, but cropping from gallery works fine!
Here is my code and build.gradle files
This is my build.gradle(:app) file:
apply plugin: 'com.android.application'
android {
compileSdkVersion 30
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "com.bostanji.cropper"
minSdkVersion 21
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.navigation:navigation-fragment:2.3.4'
implementation 'androidx.navigation:navigation-ui:2.3.4'
api 'com.theartofdev.edmodo:android-image-cropper:2.8.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
This is my code:
package com.bostanji.cropper;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
imageView = findViewById(R.id.imageView);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startCropper();
}
});
}
private void startCropper(){
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON).setAspectRatio(1,1)
.start(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
imageView.setImageURI(resultUri);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
#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);
}
}

Related

Directions API Crashes the Application on Smartphone and BlueStacks but Not on Android Studio Emulator

I am using Java client library for Google Maps API Web Services to draw routes between two points. it works fine on Android Studio's Emulator but crashes on Blue Stack and my Smartphone.
I have created Maps Activity from project Templates, only edited AppGradle and MapsActivity. App works fine as intended but only on Android Studio's emulator.
Here is the working image in Android Studio Emulator(Android 10)
enter image description here
So app crashes at this line(what i found so far) :
-- directions.destination(destination).setCallback(new PendingResult.Callback() {
Here is my MapsActivity:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final String TAG = "TaG";
private GoogleMap mMap;
static final int REQUEST_LOCATION_PERMISSION = 99;
double mUserlatitude, mUserlongitude;
ArrayList<PolylineData> mPolyLinesData = new ArrayList<>();
Marker marker =null;
GeoApiContext mGeoApiContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mGeoApiContext = new GeoApiContext.Builder().apiKey("google_maps_api_key").build();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
enableMyLocation();
mMap.getUiSettings().setZoomControlsEnabled(true);
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(31.522738, 74.358556);
marker = mMap.addMarker(new MarkerOptions().position(sydney));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 12));
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
LatLng start = new LatLng(mUserlatitude,mUserlongitude);
calculateDirections(start,marker);
return false;
}
});
}
private void enableMyLocation() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0, locationListener);
} else {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION_PERMISSION);
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults) {
// Check if location permissions are granted and if so enable the
// location data layer.
switch (requestCode) {
case REQUEST_LOCATION_PERMISSION:
if (grantResults.length > 0
&& grantResults[0]
== PackageManager.PERMISSION_GRANTED) {
enableMyLocation();
}else{
enableMyLocation();
}
break;
}
}
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
mUserlatitude = location.getLatitude();
mUserlongitude = location.getLongitude();
//Toast.makeText(MapsActivity.this, Double.toString(mUserlatitude), Toast.LENGTH_SHORT).show();
//Toast.makeText(MapsActivity.this, marker.getPosition().toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
private void calculateDirections(LatLng start, Marker marker){
Log.d(TAG, "calculateDirections: calculating directions.");
com.google.maps.model.LatLng destination = new com.google.maps.model.LatLng(
marker.getPosition().latitude,
marker.getPosition().longitude
);
DirectionsApiRequest directions = new DirectionsApiRequest(mGeoApiContext);
directions.alternatives(true);
directions.origin(
new com.google.maps.model.LatLng(
start.latitude,start.longitude
)
);
//Log.d(TAG, "calculateDirections: destination: " + destination.toString());
directions.destination(destination).setCallback(new PendingResult.Callback<DirectionsResult>() {
#Override
public void onResult(DirectionsResult result) {
Log.d(TAG, "calculateDirections: routes: " + result.routes[0].toString());
Log.d(TAG, "calculateDirections: duration: " + result.routes[0].legs[0].duration);
Log.d(TAG, "calculateDirections: distance: " + result.routes[0].legs[0].distance);
Log.d(TAG, "calculateDirections: geocodedWayPoints: " + result.geocodedWaypoints[0].toString());
addPolylinesToMap(result);
}
#Override
public void onFailure(Throwable e) {
Log.e(TAG, "calculateDirections: Failed to get directions: " + e.getMessage() );
return;
}
});
}
private void addPolylinesToMap(final DirectionsResult result){
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
if(mPolyLinesData.size() > 0){
for(PolylineData polylineData: mPolyLinesData){
polylineData.getPolyline().remove();
}
mPolyLinesData.clear();
mPolyLinesData = new ArrayList<>();
}
double firstduration = 0;
for(DirectionsRoute route: result.routes){
List<com.google.maps.model.LatLng> decodedPath = PolylineEncoding.decode(route.overviewPolyline.getEncodedPath());
List<LatLng> newDecodedPath = new ArrayList<>();
// This loops through all the LatLng coordinates of ONE polyline.
for(com.google.maps.model.LatLng latLng: decodedPath){
Log.d(TAG, "run: latlng: " + latLng.toString());
newDecodedPath.add(new LatLng(
latLng.lat,
latLng.lng
));
}
Polyline polyline = mMap.addPolyline(new PolylineOptions().addAll(newDecodedPath));
polyline.setColor(ContextCompat.getColor(getApplicationContext(), R.color.quantum_grey));
polyline.setClickable(true);
mPolyLinesData.add(new PolylineData(polyline, route.legs[0]));
double thisduration = route.legs[0].duration.inSeconds;
if(firstduration == 0) {
firstduration= thisduration;
onPolylineClickListener.onPolylineClick(polyline);
}
if(thisduration < firstduration){
firstduration = thisduration;
onPolylineClickListener.onPolylineClick(polyline);
}
if(result.routes.length == 1) onPolylineClickListener.onPolylineClick(polyline);
}
}
});
}
GoogleMap.OnPolylineClickListener onPolylineClickListener = new GoogleMap.OnPolylineClickListener() {
#Override
public void onPolylineClick(Polyline polyline) {
int index = 0;
for(PolylineData polylineData: mPolyLinesData){
index++;
//Log.d(TAG, "onPolylineClick: toString: " + polylineData.toString());
if(polyline.getId().equals(polylineData.getPolyline().getId())){
polylineData.getPolyline().setColor(ContextCompat.getColor(getApplicationContext(), R.color.quantum_lightblue));
polylineData.getPolyline().setZIndex(1);
if(marker != null)marker.remove();
LatLng endlocation = new LatLng(polylineData.getLeg().endLocation.lat, polylineData.getLeg().endLocation.lng);
marker = mMap.addMarker(new MarkerOptions().position(endlocation).title("Trip # "+ index).snippet("Duration: "+polylineData.getLeg().duration));
marker.showInfoWindow();
zoomRoute(polyline.getPoints());
}
else{
polylineData.getPolyline().setColor(ContextCompat.getColor(getApplicationContext(), R.color.quantum_grey));
polylineData.getPolyline().setZIndex(0);
}
}
}
};
public void zoomRoute(List<LatLng> lstLatLngRoute) {
if (mMap == null || lstLatLngRoute == null || lstLatLngRoute.isEmpty()) return;
LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder();
for (LatLng latLngPoint : lstLatLngRoute)
boundsBuilder.include(latLngPoint);
int routePadding = 120;
LatLngBounds latLngBounds = boundsBuilder.build();
mMap.animateCamera(
CameraUpdateFactory.newLatLngBounds(latLngBounds, routePadding),
600,
null
);
}
public static class PolylineData {
private Polyline polyline;
private DirectionsLeg leg;
public PolylineData(Polyline polyline, DirectionsLeg leg) {
this.polyline = polyline;
this.leg = leg;
}
public Polyline getPolyline() {
return polyline;
}
public void setPolyline(Polyline polyline) {
this.polyline = polyline;
}
public DirectionsLeg getLeg() {
return leg;
}
public void setLeg(DirectionsLeg leg) {
this.leg = leg;
}
#Override
public String toString() {
return "PolylineData{" +
"polyline=" + polyline +
", leg=" + leg +
'}';
}
}
}
Below is the App Gradle:
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.example.myapplication"
minSdkVersion 16
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
targetCompatibility = 1.8
sourceCompatibility = 1.8
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.google.android.gms:play-services-maps:17.0.0'
implementation 'com.google.firebase:firebase-auth:19.3.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.google.maps:google-maps-services:0.13.0'
implementation 'org.slf4j:slf4j-simple:1.7.25'
implementation 'com.google.android.libraries.places:places:2.2.0'
}
This solved my problem.
After debugging my app, I found out that adding this to my dependencies in app-level gradle file (build.gradle(app)) helped resolve the issue.
implementation group: 'com.github.seratch', name: 'java-time-backport', version: '1.0.0'

Jav 8 Splash Screen.getSplashScreen() always returns null. Jar is invoked via Java Web Start using JNLP file

manifest file
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.6.5
Created-By: 20.1-b02 (Sun Microsystems Inc.)
SplashScreen-Image: Images/Splash.gif
Permissions: all-permissions
Application-Name: DealEntry Application
The path to the splash screen is correct
On SplashScreen.getSplashScreen() null is returned. Somehow it is not working in my application. Altough I tried a demo where it worked.
import org.apache.log4j.Logger;
import javax.swing.*;
import java.awt.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.event.*;
public class Splash extends Frame implements ActionListener {
static void renderSplashFrame(Graphics2D g, int frame)
{
final String[] comps = {"foo", "bar", "baz"};
g.setComposite(AlphaComposite.Clear);
g.fillRect(120,140,200,40);
g.setPaintMode();
g.setColor(Color.BLACK);
g.drawString("Loading "+comps[(frame/5)%3]+"...", 120, 150);
}
public Splash() {
final SplashScreen splash = SplashScreen.getSplashScreen();
Always returns null when the jar os executed using javaws.
if (splash == null) {
System.out.println("SplashScreen.getSplashScreen() returned
null");
return;
}
Graphics2D g = splash.createGraphics();
if (g == null) {
System.out.println("g is null");
return;
}
}
public void actionPerformed(ActionEvent ae) {
}
private static WindowListener closeWindow = new WindowAdapter(){
public void windowClosing(WindowEvent e){
e.getWindow().dispose();
}
};
public static void main (String args[]) {
Splash test = new Splash();
}
}

Parse.com Signup with a Profile Picture and cover from a drawable

This is my SignUp.class I want to upload a profile picture drawable into User class in the profilepic column and a profile cover in the profilecover column
R.drawable.avatar_circle is the profile picture drawable and R.drawable.drawer_header_light is the drawable for the profile cover.
package com.addict.secret;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseGeoPoint;
import com.parse.ParseUser;
import com.parse.SignUpCallback;
import de.hdodenhof.circleimageview.CircleImageView;
public class SignUp extends AppCompatActivity {
ProgressDialog login;
ProgressDialog progress;
EditText emailTxt, usernameTxt, passwordTxt, passwordConfirmTxt;
Button registerBtn, termsBtn, aboutBtn;
CheckBox mcheckbox;
ParseUser User = new ParseUser();
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
Toolbar toolbar = (Toolbar) findViewById(R.id.appBar_reset);
toolbar.setTitle(R.string.title_activity_sign_up);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.icon_back_arrow);
final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fabprof);
fab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new AlertDialog.Builder(SignUp.this, R.style.AppCompatAlertDialogStyle)
.setIcon(R.drawable.ic_new_releases_black_24dp)
.setTitle(R.string.comingsoontitle)
.setMessage(getResources().getString(R.string.comingsoon))
.setNegativeButton(android.R.string.ok, null)
.create().show();
}
});
//termsBtn = (Button) findViewById(R.id.termsBtn);
//termsBtn.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// TermsDialogFragment dialog = TermsDialogFragment.newInstance();
// dialog.show(getSupportFragmentManager(), "DialogFragment");
// }
// });
//aboutBtn = (Button) findViewById(R.id.aboutBtn);
//aboutBtn.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// startActivity(new Intent(SignUp.this, About.class));
// }
// });
emailTxt = (EditText) findViewById(R.id.email);
usernameTxt = (EditText) findViewById(R.id.Username);
passwordTxt = (EditText) findViewById(R.id.password);
passwordConfirmTxt = (EditText) findViewById(R.id.passwordConfirm);
registerBtn = (Button) findViewById(R.id.registerBtn);
//Snackbar.make(context,getResources().getString(R.string.accept_notification);
registerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = emailTxt.getText().toString();
String username = usernameTxt.getText().toString();
String password = passwordTxt.getText().toString();
String passwordConfirm = passwordConfirmTxt.getText().toString();
Log.d("email", email);
Log.d("username", username);
Log.d("password", password);
Log.d("password confirm", passwordConfirm);
if (username.equals("")){
Toast.makeText(SignUp.this, R.string.signup_error_message_username, Toast.LENGTH_SHORT).show();
}
else if (email.equals("")){
Toast.makeText(SignUp.this, R.string.signup_error_message_email, Toast.LENGTH_SHORT).show();
}
else if (password.equals("") || password.length() < 6){
Toast.makeText(SignUp.this, R.string.signup_error_message_password6, Toast.LENGTH_SHORT).show();
}
else if (!passwordConfirm.equals(password)){
Toast.makeText(SignUp.this, R.string.signup_error_message_password, Toast.LENGTH_SHORT).show();
}
else {
progress = new ProgressDialog(SignUp.this, R.style.AppCompatAlertDialogStyle);
progress.setTitle(R.string.signup_dialog_title);
progress.setMessage(getResources().getString(R.string.signup_message));
progress.setCanceledOnTouchOutside(false);
progress.show();
registration(username, email, password);
}
}
});
}
private void registration(final String username, String email, final String password){
ParseGeoPoint currentLocation = new ParseGeoPoint(49.2827, -123.1207);;
User.setUsername(username);
User.put("status", getResources().getString(R.string.default_status));
User.setEmail(email);
User.setPassword(password);
User.put("Location", currentLocation);
User.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
progress.dismiss();
Toast.makeText(SignUp.this, R.string.success_signup, Toast.LENGTH_SHORT).show();
signInUser(username, password);
SignUp.this.finish();
} else {
progress.dismiss();
final Dialog dialog = new Dialog(SignUp.this, R.style.AppCompatAlertDialogStyle);
dialog.setContentView(R.layout.dialog_error);
// set the custom dialog components - text, image and button
TextView text = (TextView) dialog.findViewById(R.id.message);
text.setText(R.string.signup_error_parse);
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.error_fox);
Button dialogButton = (Button) dialog.findViewById(R.id.ok);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}
});
}
private void signInUser(String username, String password){
login = new ProgressDialog(SignUp.this, R.style.AppCompatAlertDialogStyle);
login.setTitle(R.string.login_title);
login.setMessage(getResources().getString(R.string.login_message));
login.setCanceledOnTouchOutside(false);
login.show();
ParseUser.logInInBackground(username, password, new LogInCallback() {
#Override
public void done(ParseUser parseUser, ParseException e) {
if (e == null) {
login.dismiss();
Toast.makeText(SignUp.this, R.string.success_login, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(SignUp.this, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(SignUp.this, R.string.error_login, Toast.LENGTH_SHORT).show();
}
}
});
}
#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_sign_up, 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);
}
}
First you should get the drawable and store it as a Bitmap:
Bitmap profilePic = BitmapFactory.decodeResource(context.getResources(), R.drawable.avatar_circle);
Bitmap profileCover = BitmapFactory.decodeResource(context.getResources(), R.drawable.drawer_header_light);
Then when you're signing up the user:
ParseGeoPoint currentLocation = new ParseGeoPoint(49.2827, -123.1207);;
User.setUsername(username);
User.put("status", getResources().getString(R.string.default_status));
User.setEmail(email);
User.setPassword(password);
User.put("profilepic", profilePic);
User.put("profilecover", profileCover);
User.put("Location", currentLocation);

unfortunately your app has stopped working when I click on button

When I click on my app first button it stopped working
kindly advice,what can be the issue?
In my code,I am trying to open one layout when it button is click then is open another layout and then when its button is being clicked then is save data in database.
My loginActivity code is -
package com.example.ahmed.vehiclepermitapp;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class LoginActivity extends Activity {
private static final int EDIT=0, DELETE=1;
EditText carTxt, statusTxt;
ImageView contactImageImgView;
List<Contact> Contacts = new ArrayList<Contact>();
ListView contactListView;
Uri imageUri=Uri.parse("android.resource://com.newthinktank.helloworld/drawable/search.png");
DatabaseHandler dbHandler;
int longClickItemIndex;
ArrayAdapter<Contact> contactAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
final Button loginBtn = (Button) findViewById(R.id.btnLogin);
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.activity_main);
carTxt = (EditText) findViewById(R.id.txtCar);
statusTxt = (EditText) findViewById(R.id.txtStatus);
contactListView = (ListView) findViewById(R.id.listView);
contactImageImgView = (ImageView) findViewById(R.id.imgViewContactImage);
dbHandler = new DatabaseHandler(getApplicationContext());
registerForContextMenu(contactListView);
contactListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
longClickItemIndex = position;
return false;
}
});
TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
tabHost.setup();
TabHost.TabSpec tabSpec = tabHost.newTabSpec("Creator");
tabSpec.setContent(R.id.Creator);
tabSpec.setIndicator("Creator");
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("List");
tabSpec.setContent(R.id.List);
tabSpec.setIndicator("List");
tabHost.addTab(tabSpec);
final Button addBtn = (Button) findViewById(R.id.btnLogin);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Contact contact = new Contact(dbHandler.getContactCount(), String.valueOf(carTxt.getText()), String.valueOf(statusTxt.getText()), imageUri);
if (!contactExists(contact)) {
dbHandler.createContact(contact);
Contacts.add(contact);
contactAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), String.valueOf(carTxt.getText()) + " has been add to list", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(getApplicationContext(), String.valueOf(carTxt.getText()) + "already exists. please use different name", Toast.LENGTH_SHORT).show();
}
});
carTxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
addBtn.setEnabled(String.valueOf(carTxt.getText()).trim().length() > 0);
}
#Override
public void afterTextChanged(Editable s) {
}
});
contactImageImgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Contact Image"), 1);
}
});
if (dbHandler.getContactCount() != 0)
Contacts.addAll(dbHandler.getAllContacts());
populateList();
}
});}
public void onCreateContextMenu(ContextMenu menu,View view,ContextMenu.ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu,view,menuInfo);
menu.setHeaderIcon(R.drawable.pencil_con);
menu.setHeaderTitle("Option");
menu.add(Menu.NONE,EDIT,menu.NONE,"Edit Option");
menu.add(Menu.NONE,DELETE,menu.NONE,"Delete Option");
}
public boolean onContextItemSelected(MenuItem item){
switch (item.getItemId()){
case EDIT:
dbHandler.updateContact(Contacts.get(longClickItemIndex));
contactAdapter.notifyDataSetChanged();
break;
case DELETE:
dbHandler.deleteContact(Contacts.get(longClickItemIndex));
Contacts.remove(longClickItemIndex);
contactAdapter.notifyDataSetChanged();
break;
}
return super.onContextItemSelected(item);
}
private boolean contactExists(Contact contact){
String name = contact.getCar();
int countactCount = Contacts.size();
for (int i = 0; i < countactCount; i++)
{
if (name.compareToIgnoreCase(Contacts.get(i).getCar()) == 0)
return true;
}
return false;
}
public void onActivityResult(int reqcode, int rescode, Intent data){
if(rescode == RESULT_OK){
if(reqcode == 1){
imageUri = data.getData();
contactImageImgView.setImageURI(data.getData());
}
}
}
private void populateList() {
contactAdapter = new ContactListAdapter();
contactListView.setAdapter(contactAdapter);
}
class ContactListAdapter extends ArrayAdapter<Contact> {
public ContactListAdapter() {
super(LoginActivity.this, R.layout.listview_item, Contacts);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = getLayoutInflater().inflate(R.layout.listview_item, parent, false);
Contact currentContact = Contacts.get(position);
TextView car = (TextView) view.findViewById(R.id.contactname);
car.setText(currentContact.getCar());
TextView status = (TextView) view.findViewById(R.id.status);
status.setText(currentContact.getStatus());
ImageView img = (ImageView) view.findViewById(R.id.img);
img.setImageURI(currentContact.getimageURI());
return view;
}
}
}
it give this error on logcat
09-06 05:05:16.954
4910-4910/com.example.ahmed.vehiclepermitapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.ahmed.vehiclepermitapp.LoginActivity$1.onClick(LoginActivity.java:85)
at android.view.View.performClick(View.java:4106)
at android.view.View$PerformClick.run(View.java:17052)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5059)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
at dalvik.system.NativeStart.main(Native Method)

The widgets in a new activity not showing up

I am working on an application that has a button which will lead to a new activity. I managed to make that work but when I am trying to add a button in the new activity with xml it is not showing up. I tried to make it work with programming but I was only able to make a button big as the whole screen. When I tried to change the size of the button with programming it could not work. Can someone please tell me how can I make that widgets show on the new activity preferably using XML.
This is the code of my first activity:
package com.example.user.myapp;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.view.View;
import android.content.Intent;
public class MainActivity extends ActionBarActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_actions, menu);
return super.onCreateOptionsMenu(menu);
}
public void sendButton(View view){
Intent intent = new Intent(this, Ut.class);
startActivity(intent);
}
#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);
}
}
And this is the code of my second activity:
package com.example.user.myapp;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Button;
import android.content.Intent;
public class Ut extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.activity_ut);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#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);
}
}
and this is the code that I added after Intent intent = getIntent() when I tried to make it work with programming
Button button2 = new Button(this);
button2.setWidth(10);
button2.setHeight(10);
setContentView(button2);
With this code a button big as the whole screen showed up although I set the size of it.
Can somebody tell me how I can make this work?

Resources