I'm new at Eclipse and the Android applications making so here comes a very rookie question. How can I make this function work properly? I have just copy > paste it to my public class nowActivity extends Activity { and fixed the errors that accord. The function is as follows:
package weather.right;
import weather.right.now.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class nowActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(this, "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show();
}else{
showGPSDisabledAlertToUser();
}
}
public void goToSo(View view) {
goToUrl("http://erik-edgren.nu/weather");
}
private void goToUrl(String url) {
Uri uriUrl = Uri.parse(url);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
}
private void showGPSDisabledAlertToUser(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Goto Settings Page To Enable GPS",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
Thanks in advance.
protected void onCreate1(Bundle savedInstanceState) should be protected void onCreate(Bundle savedInstanceState)?
You are supposed to override the onCreate() method. See this for more details.
For Android, sub-classes of Activity are supposed to implement certain methods so to do this you have to override certain methods by matching the parent class' methods exactly. onCreate() is one such method.
For the emulator, GPS can be tested by following the guide here. Otherwise it will show up as disabled.
Related
I am trying to use AlertDialog widget in my app, but whatever I do the app crashes at launch. I know something is messed up or not defined but can't seem to find it.I have defined a button for triggering the alert dialog and set 'yes' and 'no' options for the dialog. Selecting 'yes' will result in exiting the app and showing a toast and Selecting 'no' will close the alert dialog and return to app by showing a toast. This is how it should work on paper but as I said the app will crash on launch.
My code:
package com.example.togglebutton;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity {
private Button bt;
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bt = (Button) findViewById(R.id.btn);
builder = new AlertDialog.Builder(this);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
builder.setMessage("Do you want to close this application ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id, ) {
finish();
Toast.makeText(getApplicationContext(), "you chose yes",
Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Toast.makeText(getApplicationContext(), "you chose no ",
Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.setTitle("AlertDialogExample");
alert.show();
}
});
}
}
SOLUTION OF YOUR PROBLEM
You need to set the layout of the activity and in the above-posted code what we can see that it is missing. So just add the line below super.onCreate(savedInstanceState);
setContentView(R.layout.YOUR_LAYOUT_NAME);
NOTE: Replace YOUR_LAYOUT_NAME with the name of the layout file which you have defined for MainActivity.
Because you forgot this line
super.onCreate(savedInstanceState);
setContentView(R.layout.yourLayout);
Add setContentView(R.layout.activity_main) below super.onCreate(savedInstanceState);
I am designing an app for scan Barcode. There are three activities where I have used Barcode Scanner, only in one Activity the code is working fine and other two activities its taking too much time to scan and some times scans but displaying wrong result.
I am very confused about what the problem is. Same code I have copy paste in all three activities.
build.gradle:
compile 'me.dm7.barcodescanner:zxing:1.9'
Code:
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import com.google.zxing.Result;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class ScanBoxActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private ZXingScannerView scannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
}
#Override
public void onResume()
{
super.onResume();
if(scannerView== null)
{
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
}
scannerView.setResultHandler(this);
scannerView.startCamera();
}
#Override
public void onDestroy(){
super.onDestroy();
scannerView.stopCamera();
}
#Override
public void handleResult(final Result result) {
final String scanResult = result.getText();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scan Result");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
Toast.makeText(ScanBoxActivity.this,""+scanResult,Toast.LENGTH_SHORT).show();
}
});
builder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
onResume();
}
});
builder.setMessage(scanResult);
AlertDialog alert = builder.create();
alert.show();
}
}
compile 'com.edwardvanraak:MaterialBarcodeScanner:0.0.6-ALPHA'
compile 'com.google.android.gms:play-services-vision:11.0.4'
This library has google support and easy to implement and I have implemented it in one of my app. So, if you face any further issue , ask me freely.
DO you have samples of the code you used AYUSH ARYA to share or maybe an e m a i l?
I wrote code to check the GPS settings and make an alert dialog, but it doesn't show up in android emulator.
This is the code that used to check the GPS settings and show the alert dialog.
package com.example.user.testlocation;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class Location extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
}
private void isLocationEnalbled(){
LocationManager locationManager=(LocationManager)getSystemService(LOCATION_SERVICE);
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)|| !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
AlertDialog.Builder alertDialog=new AlertDialog.Builder(this);
alertDialog.setTitle("Enable Location");
alertDialog.setMessage("Your locations setting is not enabled. Please enabled it in settings menu.");
alertDialog.setPositiveButton("Location Settings", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
Intent intent=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
dialog.cancel();
}
});
AlertDialog alert=alertDialog.create();
alert.show();
}
else{
AlertDialog.Builder alertDialog=new AlertDialog.Builder(this);
alertDialog.setTitle("Confirm Location");
alertDialog.setMessage("Your Location is enabled, please enjoy");
alertDialog.setNegativeButton("Back to interface",new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
dialog.cancel();
}
});
AlertDialog alert=alertDialog.create();
alert.show();
}
}
}
It doesn't show any error, but the alert dialog doesn't display when I implement it.
You never call the isLocationEnalbled() method which does the check. Add this to your class, so that the app checks isLocationEnalbled() everytime the activity is resumed.
#Override
public void onResume() {
super.onResume();
isLocationEnalbled();
}
in your onCreate() method you have to call isLocationEnalbled()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
isLocationEnalbled()
}
I've seen this in some application , the application size is about 6 mb but it download a file about 100kb and update the application .
it's very interesting , I've searched alot but I couldn't find any way to do it .
How can I do so ?
thanks
I do it using the below class, but it does require downloading the new APK, so it may not be exactly what you need. It is done this way because we do not use the play store.
If there is an update available, start the Runnable class.
It starts the download, and when the download is completed it asks if you want to update, then starts the update.
All you need to do is figure out how to host the APK file. I use a windows server and IIS7, with a mime setup so it is recognized by android as an installable APK.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
public class GetUpdate implements Runnable{
Context cxt;
String line;
String filepath = "";
int continueornot=0;
ProgressBar progBar;
Button buttOk;
DownloadManager mgr=null;
long lastDownload=-1L;
public GetUpdate(Context contextIn, String lineIn, ProgressBar progressBar,Button okButtIn){
cxt = contextIn;
line = lineIn;
this.progBar = progressBar;
this.buttOk = okButtIn;
}
#Override
public void run() {
filepath = cxt.getExternalFilesDir("/MyFileStorage/").getAbsolutePath();
AlertDialog.Builder alert = new AlertDialog.Builder(cxt);
alert.setTitle("Update Availible");
alert.setMessage("Start the download?");
// Set an EditText view to get user input
//final EditText serverURL = new EditText(cxt);
//alert.setView(serverURL);
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//String tempFilepath = cxt.getExternalFilesDir("/MyFileStorage/").getAbsolutePath();
File myExternalFile = new File(filepath);
File[] sdDirList = myExternalFile.listFiles();
if(sdDirList != null){
for(int x=0;x<sdDirList.length;x++){
String fileNameString = sdDirList[x].toString();
System.out.println("File: " + sdDirList[x].toString());
if(fileNameString.trim().equalsIgnoreCase("podcodes.txt")
||fileNameString.trim().equalsIgnoreCase("vehiclesTrailers.txt")
||fileNameString.trim().equalsIgnoreCase("checks.txt")
||sdDirList[x].toString().endsWith(".apk")){
sdDirList[x].delete();
}
}
}
BroadcastReceiver onComplete=new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
AlertDialog.Builder alert = new AlertDialog.Builder(cxt);
alert.setTitle("Update Availible");
alert.setMessage("Start the update?");
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(cxt.getApplicationContext(), "Updating!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
String lastDownloaded = mgr.getUriForDownloadedFile(lastDownload).toString();
//String lastDownloadFileName = lastDownloaded.substring(lastDownloaded.lastIndexOf("/")+1);
intent.setDataAndType(Uri.parse(lastDownloaded), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
cxt.startActivity(intent);
Globals.setExit(true);
}
});
alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
progBar.setVisibility(View.GONE);
buttOk.setText("OK");
buttOk.setEnabled(true);
buttOk.setVisibility(View.VISIBLE);
}
});
alert.show();
}
};
mgr=(DownloadManager)cxt.getSystemService(Context.DOWNLOAD_SERVICE);
cxt.registerReceiver(onComplete,
new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
BroadcastReceiver onNotificationClick=new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
Toast.makeText(ctxt, "Downloading InCab Update!", Toast.LENGTH_LONG).show();
}
};
cxt.registerReceiver(onNotificationClick,
new IntentFilter(DownloadManager.ACTION_NOTIFICATION_CLICKED));
Uri uri=Uri.parse(Globals.getServerURL()+"/LatestAndroid/"+line.trim());
//Environment
// .getExternalStoragePublicDirectory("MyFileStorage/"+line.trim())
// .mkdirs();
lastDownload=
mgr.enqueue(new DownloadManager.Request(uri)
.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |
DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(true)
.setTitle(line.trim())
.setDescription("Incab Update.")
.setDestinationInExternalFilesDir(cxt,"MyFileStorage", line.trim()));
Toast.makeText(cxt.getApplicationContext(), "Downloading!", Toast.LENGTH_LONG).show();
continueornot=1;
progBar.setVisibility(View.VISIBLE);
buttOk.setVisibility(View.VISIBLE);
buttOk.setText("Downloading..");
buttOk.setEnabled(false);
}
});
alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
continueornot=2;
progBar.setVisibility(View.GONE);
buttOk.setText("OK");
buttOk.setEnabled(true);
buttOk.setVisibility(View.VISIBLE);
//cancel(true);
}
});
alert.show();
progBar.setVisibility(View.GONE);
buttOk.setText("OK");
buttOk.setEnabled(true);
buttOk.setVisibility(View.VISIBLE);
}
}
I have an app location listener which pops up toast alerts when the user gets within a specified distance of any point in a list. Instead of a toast popup I'd like to call a dialog fragment that, when the user selects yes, transfers the user into a quiz activity which asks them a question based on their location.
In short I want to be able to display this dialog fragment, instead of the toast, in my location listener activity. Thus far I have tried
DialogFragment dialog = new LocationDialog();
showDialog(dialog);
in place of the toast alert but I get the error "The method showDialog(DialogFragment) is undefined for the type QLocationListener. I've been going around in circles following various tutorials, guides and Google's android documentation without avail so some guidance would be greatly appreciated.
All my code is functioning as standalone apps I'm just struggling to link the location listener + main activity to the quiz via the dialog fragment. I also hope to be able to pass location information to the quiz in a bundle so it knows which question and answers to display but that's a task for another day...
Main Activity
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.location.LocationManager;
import android.os.Bundle;
public class MainActivity extends Activity {
private static final long MINIMUM_DISTANCECHANGE_FOR_UPDATE = 1;
private static final long MINIMUM_TIME_BETWEEN_UPDATE = 1000;
private LocationManager locationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
QLocationListener qLL = new QLocationListener();
qLL.parentActivity = this;
// create the hard-coded list of points of interest
ArrayList<QuizContent> pointList = new ArrayList<QuizContent>();
// ExampleA
QuizContent MapPoint = new QuizContent(25,5, "example question?", "a", "b","c","d", "a");
// ExampleB
QuizContent MapPoint2 = new QuizContent(26,5, "example question?", "a", "b","c","d", "a");
// ExampleC
QuizContent MapPoint3 = new QuizContent(27,5, "example question?", "a", "b","c","d", "a");
pointList.add(MapPoint);
pointList.add(MapPoint2);
pointList.add(MapPoint3);
// now set up the location manager and listener
qLL.pointList = pointList;
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATE,
MINIMUM_DISTANCECHANGE_FOR_UPDATE,
qLL
);
}
}
QLocation Listener
import java.util.ArrayList;
import android.app.AlertDialog;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.widget.Toast;
import android.widget.TextView;
public class QLocationListener implements LocationListener {
public MainActivity parentActivity ;
// this is my list of quiz content (questions, answers, locations)
public ArrayList<QuizContent> pointList;
// this method is called when the location is changed
public void onLocationChanged(Location location) {
// now measure distance from all locations in quiz list
for (int i=0;i<pointList.size();i++){
QuizContent gp = pointList.get(i);
Location fixedLoc = new Location("one");
Double lat = Double.valueOf(String.valueOf(gp.getLatitude()));
Double lng = Double.valueOf(String.valueOf(gp.getLongitude()));
fixedLoc.setLatitude(lat);
fixedLoc.setLongitude(lng);
Log.i("location",lat+" "+location.getLatitude());
Log.i("location",lng+" "+location.getLongitude());
// calculate distance
float distance = location.distanceTo(fixedLoc);
if (i == 0) { // this is location a
if (distance < 10) {
DialogFragment dialog = new LocationDialog();
showDialog(dialog);
}
}
if (i == 1) { // this is location b
if (distance < 10) {
Toast.makeText(parentActivity.getBaseContext(),
"Welcome to location b", Toast.LENGTH_LONG).show();
}
}
if (i == 3) { // this is location c
if (distance < 10) {
Toast.makeText(parentActivity.getBaseContext(),
"Welcome to location c", Toast.LENGTH_LONG).show();
}
}
}
}
public void onProviderDisabled(String s) {
}
public void onProviderEnabled(String s) {
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
Dialog Fragment
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
public class LocationDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setMessage("Quiz Location Found, answer the question?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(getActivity(), Quiz.class));
// take the quiz!
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return alertDialog.create();
}
}
You need to call showDialog on Activity/App context
Try:
From activity:
QLocationListener qLocationListener= new QLocationListener(this)
In QLocationListener:
Activity act;
QLocationListener(Activity a)
{
//Constructor
act=a;
}
and then finally where you call showDialog:
act.showDialog(dialog);