I am developing an app that whenever you click on the get location (gpsBtn), GPS will be enabled and the Location of the user will be shown in a TextView. I get java.lang.NullPointerException error,the app has stops unexpectedly. How do I fix this?
public class MainActivity extends AppCompatActivity {
public LocationManager lm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, new MyLocationListener());
Button gpsBtn = (Button)findViewById(R.id.getLocation);
gpsBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showCurrentLocation();
}
});
public void showCurrentLocation() {
// TODO Auto-generated method stub
final TextView textView=(TextView)findViewById(R.id.textView);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
textView.setText(String.valueOf(location.getLatitude()));
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#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
}
}
Android manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mehrdad.myapplication" >
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
try.....move your final TextView textView=(TextView)findViewById(R.id.textView); to the onCreate() method. Also add textView.setText(String.valueOf(location.getLatitude())); line inside the try and catch block.
try{
textView.setText(String.valueOf(location.getLatitude()));
}catch(Exception e){
// exception occurs......
}
FULL CODE
public class MainActivity extends AppCompatActivity {
public LocationManager lm;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, new MyLocationListener());
textView = (TextView)findViewById(R.id.textView);
Button gpsBtn = (Button)findViewById(R.id.getLocation);
gpsBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showCurrentLocation();
}
});
public void showCurrentLocation() {
// TODO Auto-generated method stub
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
try{
textView.setText(String.valueOf(location.getLatitude()));
}catch(Exception e){
// exception occurs......
}
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#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
}
}
Related
this is my code....
StudentLogin.java class
public class StudentLogin extends Activity implements OnClickListener, OnItemSelectedListener{
Spinner sp1,sp2;
EditText reg;
Button b1,b2,b3;
String a1,a2,studreg,studdept,studyr;
SQLiteDatabase db1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_login);
reg=(EditText) findViewById(R.id.editText1);
sp1=(Spinner)findViewById(R.id.spinner1);
sp2=(Spinner)findViewById(R.id.spinner2);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Cursor c=db1.rawQuery("Select * from StudReg", null); // Im getting an error here
int count=c.getCount();
int flag=0;
c.moveToFirst();
String regno=reg.getText().toString();
String yr=a1;
String dept=a2;
Toast.makeText(getApplicationContext(), regno, Toast.LENGTH_LONG).show();
if(regno.trim().length()>0&&!yr.equals("Select Year")&&!dept.equals("Select Dept"))
{
for(int i=0;i<count;i++)
{
studreg=c.getString(c.getColumnIndex("register"));
studdept=c.getString(c.getColumnIndex("deptmt"));
studyr=c.getString(c.getColumnIndex("year"));
if(regno.equals(studreg)&&yr.equals(studyr)&&dept.equals(studdept))
{
flag=1;
break;
}
c.moveToNext();
}
c.close();
if(flag==1)
{
Intent inn=new Intent(StudentLogin.this,StudyMaterials.class);
startActivity(inn);
}
else
{
Toast.makeText(getApplicationContext(), "Invalid User!\nKindly try again..", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "Kindly fill all the fields..", Toast.LENGTH_SHORT).show();
}
}
});
b2=(Button)findViewById(R.id.button2);
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intt=new Intent(StudentLogin.this,StudentRegister.class);
startActivity(intt);
}
});
b3=(Button)findViewById(R.id.button3);
b3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent int1=new Intent(StudentLogin.this,Update.class);
startActivity(int1);
}
});
sp1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> p, View v,
int a, long l) {
// TODO Auto-generated method stub
a1=p.getItemAtPosition(a).toString();
//Toast.makeText(getApplicationContext(), a1, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
sp2.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> p, View v,
int a, long l) {
// TODO Auto-generated method stub
a2=p.getItemAtPosition(a).toString();
//Toast.makeText(getApplicationContext(), a2, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
List<String> categories = new ArrayList<String>();
categories.add("Select Department");
categories.add("CSE");
categories.add("IT");
categories.add("CIVIL");
categories.add("MECH");
categories.add("ECE");
categories.add("EEE");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp2.setAdapter(dataAdapter);
List<String> categories1 = new ArrayList<String>();
categories1.add("Select Year");
categories1.add("I");
categories1.add("II");
categories1.add("III");
categories1.add("IV");
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, categories1);
dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp1.setAdapter(dataAdapter1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.student_login, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
public void onItemSelected(AdapterView<?> p, View v, int it,
long l) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
This code validates whether the user is already registered or not..
Please help me solve this error...
you need to initialize database
//dbHelper its a helper class for database
database = dbHelper.getWritableDatabase();
You have given the table name but you are not saying it on which db the table exists(as db1 is not initialized).So follow #Madhur answer to solve this null pointer exception.Also a suggestion when working with db(better to use loaders instead of working on MainThread).
I do use the Google Maps API v2 to get my location on the map. Is it possible to write the correct address in the information of the marker?
I didn't find anything useful in the internet..
Here is my code. Thanks in advance!
#SuppressLint("NewApi")
public class MainActivity extends Activity implements LocationListener {
GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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 position");
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
}
}
you want to add extra information on the marker? If i understood correctly then you can add a snipper.
LatLng mark = new LatLng(Double.parseDouble(lat), Double.parseDouble(longi));
map.addMarker(new MarkerOptions().title("MY Position").snippet("Extra info").position(mark));
Can I know how to create AsyncTask for Android from all of these? I would like to remove the buttons and let all of these run in the background then redirect to the MainPage.java after clicking Logout.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
Button btnDelete = (Button)findViewById(R.id.delete);
Button btnSignUp = (Button)findViewById(R.id.btnSignUp);
Button btnLogin = (Button)findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(),HomePage.class);
startActivity(intent);
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this,SignUp.class);
startActivity(intent);
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
cDB.resetTables();
mDB.resetTables();
db.resetTables();
pDB.resetTables();
}
});
}
here is one AsyncTask Example. This will show a peogress dialog while executing the task.
private class LoginProcessing extends AsyncTask<Object, Void, Void> {
private LoginCredentials myLoginCredentials;
private ProgressDialog progressDialog;
public LoginProcessing(LoginCredentials Credentials) {
super();
myLoginCredentials=Credentials;
}
protected void onPreExecute (){
progressDialog = ProgressDialog.show(context, "", "Please Wait...",true);
}
#Override
protected Void doInBackground(Object... arg0) {
// TODO Auto-generated method stub
//Code to do the process in background
return null;
}
protected void onPostExecute(Void result){
progressDialog.dismiss();
//Your code after the process
}
}
You can call this Task as,
new LoginProcessing(loginCredentials).execute();
In this Example loginCredentials is the parameter I am passing to the AsyncTask. You can change it to your own parameter.
I integrated Google+ button, and I see it in my app but it's "greyed out" or white, it's not red and white and when I click it nothing happens. Here's my code:
public class Menu extends Activity implements OnClickListener, ConnectionCallbacks,
OnConnectionFailedListener{
private static final int REQUEST_CODE_RESOLVE_ERR = 9000;
private ProgressDialog mConnectionProgressDialog;
private PlusClient mPlusClient;
private ConnectionResult mConnectionResult;
private PlusOneButton mPlusOneButton;
ImageButton exit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final PlusOneButton mPlusOneButton = new PlusOneButton(this);
mPlusClient = new PlusClient.Builder(this, this, this).clearScopes()
.build();
mPlusOneButton.initialize("https://market.android.com/details?id=" + getPackageName(),
new OnPlusOneClickListener() {
#Override
public void onPlusOneClick(Intent intent) {
mPlusOneButton.setVisibility(View.INVISIBLE);
startActivityForResult(intent, 0);
}
});
setContentView(R.layout.menu);
inicijalizujVars();
}
#Override
protected void onStart() {
super.onStart();
mPlusClient.connect();
}
#Override
protected void onStop() {
super.onStop();
mPlusClient.disconnect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (mConnectionProgressDialog.isShowing()) {
if (result.hasResolution()) {
try {
result.startResolutionForResult(this,
REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
mPlusClient.connect();
}
}
}
mConnectionResult = result;
}
#Override
protected void onActivityResult(int requestCode, int responseCode,
Intent intent) {
if (requestCode == REQUEST_CODE_RESOLVE_ERR
&& responseCode == RESULT_OK) {
mConnectionResult = null;
mPlusClient.connect();
}
}
private void inicijalizujVars() {
exit = (ImageButton) findViewById(R.id.imageButtonExit);
exit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
public void onResume(){
super.onResume();
}
#Override
public void onBackPressed()
{
super.onBackPressed();
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
}
And my button in my layout xml:
<com.google.android.gms.plus.PlusOneButton
xmlns:plus="http://schemas.android.com/apk/lib/com.google.android.gms.plus"
android:id="#+id/plus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="30dp"
android:layout_marginTop="-30dp"
android:gravity="center"
plus:annotation="bubble"
plus:size="tall" />
How do I get values from a SeekBar?
I have a code of a class that has three SeekBars (PRICEbar)
I want to pass the values of these SeekBars to next Activity (screen)
as Intents
I know how toimplement OnClickListener but how can I extract the
values from the SeekBars?
ex: if PRICEbar is pointing to value 10 ... I need to get the value of 10
Filters.java
public class Filters extends Activity implements OnSeekBarChangeListener{
// declare text objects variables
private SeekBar PRICEbar;
private TextView PRICEtextProgress,DISTANCEtextProgress, RATINGtextProgress;
Button back;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// load the layout
setContentView(R.layout.filters);
PRICEbar = (SeekBar)findViewById(R.id.PRICEseekBarID); // make seekbar object
PRICEbar.setOnSeekBarChangeListener(this);
PRICEbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
PRICEtextProgress = (TextView)findViewById(R.id.PRICEtextViewProgressID);
PRICEtextProgress.setText("Price:: Rs "+progress);
seekBar.setMax(100);
}
});
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (seekBar == PRICEbar)
PRICEtextProgress.setText("Price:: Rs "+progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
The SeekBar class is a subclass of ProgressBar, which contains a getProgress() method.
Calling PRICEbar.getProgress() will return the value you are looking for.