I'm taking a Udemy course and trying to make an Instagram clone in Android Studio. However, the course is a bit outdated and its causing problems with the main activity. The project does not recognize AppCompatActivity and won't even import it. It's my first time implementing a parse server on a project so I'm a bit confused. I managed to code the build.gradle in a way to get the 2nd activity to work but I cannot get the main activity to work. I have looked for solutions everywhere and cannot find any. This is also my first time asking a question here so sorry if I messed anything up. Here's my code:
MainActivity
package com.parse.starter;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Switch;
import com.parse.LogInCallback;
import com.parse.Parse;
import com.parse.ParseAnalytics;
import com.parse.ParseAnonymousUtils;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SaveCallback;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ParseAnalytics.trackAppOpenedInBackground(getIntent());
}
}
StarterApplication:
package com.parse.starter;
import android.app.Application;
import android.util.Log;
import com.parse.Parse;
import com.parse.ParseACL;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseUser;
import com.parse.SaveCallback;
public class StarterApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
// Enable Local Datastore.
Parse.enableLocalDatastore(this);
// Add your initialization code here
Parse.initialize(new Parse.Configuration.Builder(getApplicationContext())
.applicationId("")
.clientKey("")
.server("")
.build()
);
ParseObject object = new ParseObject("ExampleObject");
object.put("myNumber", "123");
object.put("myString", "rob");
object.saveInBackground(new SaveCallback () {
#Override
public void done(ParseException ex) {
if (ex == null) {
Log.i("Parse Result", "Successful!");
} else {
Log.i("Parse Result", "Failed" + ex.toString());
}
}
});
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
defaultACL.setPublicReadAccess(true);
defaultACL.setPublicWriteAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
}
}
build.gradle(Project):
buildscript {
repositories {
mavenCentral()
jcenter()
maven {
url 'https://maven.google.com/'
name 'Google'
}
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.0'
}
}
allprojects {
repositories {
mavenCentral()
}
}
ext {
compileSdkVersion = 22
buildToolsVersion = "23.0.1"
minSdkVersion = 9
targetSdkVersion = 23
}
build.gradle(Module):
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion '22.0.1'
defaultConfig {
applicationId "com.parse.starter"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
multiDexEnabled true
}
dexOptions {
javaMaxHeapSize "4g"
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.parse.bolts:bolts-tasks:1.3.0'
compile 'com.parse:parse-android:1.13.0'
compile 'com.google.android.gms:play-services:9.4.0'
compile 'com.android.support:multidex:1.0.0'
}
You're using outdated/deprecated code.
Don't copy the whole code from the sample or tutorials because they might be using an older version of the android studio hence outdated code.
I suggest making a fresh project and using androidx this time
For your problem try importing androidx.appcompat.app.AppCompatActivity
and add this dependency androidx.appcompat:appcompat:1.4.1
Related
I am trying to create an Android program, and met an error of which I have no idea how to solve.
My app crashes after I put in the email. I suspect that the problem is related with firebase. I have tried different ways of solving of this problem, such as changing the versions of firebase implementations, but without any success.
Here is my code
MainActivity.java
package com.chat.mychatapp;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.database.FirebaseListAdapter;
import com.github.library.bubbleview.BubbleTextView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
import android.text.format.DateFormat;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {
public static int SIGN_IN_CODE = 1;
private RelativeLayout activity_main;
private FirebaseListAdapter<Message> adapter;
private FloatingActionButton sendBtn;
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == SIGN_IN_CODE){
if(resultCode == RESULT_OK){
Snackbar.make(activity_main, "You are authorized", Snackbar.LENGTH_LONG).show();
displayAllMessages();
}else{
Snackbar.make(activity_main, "You are NOT authorized", Snackbar.LENGTH_LONG).show();
finish();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity_main = findViewById(R.id.activity_main);
sendBtn = findViewById(R.id.sendBtn);
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText textField = findViewById(R.id.messageField);
if(textField.getText().toString().equals(""))
return;
FirebaseDatabase.getInstance().getReference().push().setValue(
new Message(Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser()).getEmail(),
textField.getText().toString()
)
);
textField.setText("");
}
});
//User not autorized
if(FirebaseAuth.getInstance().getCurrentUser() == null){
startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().build(), SIGN_IN_CODE);
}else{
Snackbar.make(activity_main, "You are authorized", Snackbar.LENGTH_LONG).show();
displayAllMessages();
}
}
private void displayAllMessages() {
ListView listOfMessages = findViewById(R.id.messageList);
adapter = new FirebaseListAdapter<Message>(this, Message.class, R.layout.list_item, FirebaseDatabase.getInstance().getReference()) {
#Override
protected void populateView(View v, Message model, int position) {
TextView m_user, m_time;
BubbleTextView m_text;
m_user = v.findViewById(R.id.messageUser);
m_time = v.findViewById(R.id.messageTime);
m_text = v.findViewById(R.id.messageText);
m_user.setText(model.getUserName());
m_text.setText(model.getMessage());
m_time.setText(DateFormat.format("dd-mm-yyyy HH:mm:ss",model.getTime()));
}
};
listOfMessages.setAdapter(adapter);
}
}
build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.chat.mychatapp"
minSdkVersion 19
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'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
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.firebase:firebase-analytics:17.2.1'
implementation 'com.google.android.material:material:1.0.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.gms:play-services-auth:17.0.0'
implementation 'com.google.firebase:firebase-auth:19.2.0'
implementation 'com.google.firebase:firebase-database:19.2.0'
implementation 'com.firebaseui:firebase-ui:0.6.2'
implementation 'com.github.lguipeng:BubbleView:1.0.1'
//implementation 'com.google.firebase:firebase-firestore:21.3.1'
}
apply plugin: 'com.google.gms.google-services'
Error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.chat.mychatapp, PID: 18455
java.lang.NoSuchMethodError: No virtual method fetchProvidersForEmail(Ljava/lang/String;)Lcom/google/android/gms/tasks/Task; in class Lcom/google/firebase/auth/FirebaseAuth; or its super classes (declaration of 'com.google.firebase.auth.FirebaseAuth' appears in /data/app/com.chat.mychatapp-s_3u6mmiv0A6KE9ijznfqQ==/base.apk)
at com.firebase.ui.auth.ui.AcquireEmailHelper.checkAccountExists(AcquireEmailHelper.java:55)
at com.firebase.ui.auth.ui.email.SignInNoPasswordActivity.onClick(SignInNoPasswordActivity.java:73)
at android.view.View.performClick(View.java:7339)
at android.widget.TextView.performClick(TextView.java:14222)
at android.view.View.performClickInternal(View.java:7305)
at android.view.View.access$3200(View.java:846)
at android.view.View$PerformClick.run(View.java:27787)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7078)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
Update the following dependency:
implementation 'com.firebaseui:firebase-ui:0.6.2'
into this:
implementation 'com.firebaseui:firebase-ui:6.2.0'
https://github.com/firebase/FirebaseUI-Android
From the docs:
Removed the deprecated fetchProvidersForEmail(String) method from the FirebaseAuth class, as well as the associated ProviderQueryResult class. Use fetchSignInMethodsForEmail(String) instead.
Therefore update the firebaseUI and you can use fetchSignInMethodsForEmail(String) instead.
I am struggling with an error since two day. Hope someone can help me.
I am using AndroidStudio 3.3.1 on MacOS. When I build the project, i receiver the following error message:
Error: Program type already present: com.loopj.android.http.BaseJsonHttpResponseHandler
My build.gradle looks like:
apply plugin: 'com.android.application'
compileSdkVersion 28
buildToolsVersion "28.0.3"
defaultConfig {
applicationId "lalalalalalala"
minSdkVersion 19
targetSdkVersion 28
versionCode 7
versionName "1.6"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
shrinkResources false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.config
}
}
productFlavors {
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:design:28.1.0'
testImplementation 'junit:junit:4.12'
implementation 'com.loopj.android:android-async-http:1.4.9'
implementation 'com.github.delight-im:Android-AdvancedWebView:v3.0.0'
implementation 'com.google.firebase:firebase-messaging:17.4.0'
implementation 'com.google.firebase:firebase-core:16.0.7'
}
apply plugin: 'com.google.gms.google-services'
as dependencies I have
dependencies {
classpath 'com.android.tools.build:gradle:3.3.1'
classpath 'com.google.gms:google-services:4.2.0'
}
in gradle.properties is
org.gradle.jvmargs=-Xmx1536m
android.useAndroidX=true
android.enableJetifier=true
and in in gradle-wrapper.properties I have
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip
I start to believe is a bug of AndroidStudio 3.3.1.
Does anyone see a problem in my code ?
Any help is highly appreciated :)
edit:
package lalalalalala;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.webkit.WebViewClient;
import com.loopj.android.http.*;
import im.delight.android.webview.AdvancedWebView;
public class MainActivity extends Activity implements AdvancedWebView.Listener {
private AdvancedWebView WebView;
protected static boolean isActivityRunning;
public static boolean checkIfAppIsRunnung()
{
return isActivityRunning;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Cookies
AsyncHttpClient myClient = new AsyncHttpClient();
PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
myClient.setCookieStore(myCookieStore);
setContentView(R.layout.activity_main);
WebView = (AdvancedWebView) findViewById(R.id.webWiew);
WebView.setListener(this, this);
WebView.setThirdPartyCookiesEnabled(false);
Intent mIntent = new Intent(this, MyFirebaseMessagingService.class);
startService(mIntent);
WebView.loadUrl("lalalalalalala");
WebView.setWebViewClient(new WebViewClient());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
WebView.onActivityResult(requestCode, resultCode, intent);
// ...
}
#Override
public void onPageStarted(String url, Bitmap favicon) { }
#Override
public void onPageFinished(String url) { }
#Override
public void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent) { }
#Override
public void onExternalPageRequest(String url) { }
}
Below is the fatal error that I keep getting on my App. I am trying to run a chat messenger feature on my application using Firebase. It was running however it has since kept crashing the app entirely. I've made a few edits to the code in the hope of resolving the issues, but to no avail.
I've been following this tutorial on youtbe https://www.youtube.com/watch?v=Xn0tQHpMDnM and it appears by reading the comments that no one else has a similiar error to me.
According to the log, the errors are found on line 99 - displayChatMessage(); as well as on Line 109 - adapter = new FirebaseListAdapter<ChatMessage>(this,ChatMessage.class,R.layout.chat_list_item,FirebaseDatabase.getInstance().getReference()) {
I'm hoping this maybe just a simple code error which I have created, or is it possible it could be to do with my gradle build. Below is the error log I am getting.
FATAL EXCEPTION: main
Process: com.example.aids.a09application, PID: 30713
java.lang.NoSuchMethodError: No virtual method zzEq()Z in class Lcom/google/firebase/FirebaseApp; or its super classes (declaration of 'com.google.firebase.FirebaseApp' appears in /data/app/com.example.aids.a09application-2/split_lib_dependencies_apk.apk:classes33.dex)
at com.google.firebase.database.FirebaseDatabase.getInstance(Unknown Source)
at com.google.firebase.database.FirebaseDatabase.getInstance(Unknown Source)
at com.example.aids.a09application.MainChatActivity.displayChatMessage(MainChatActivity.java:109)
at com.example.aids.a09application.MainChatActivity.onCreate(MainChatActivity.java:99)
at android.app.Activity.performCreate(Activity.java:6912)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2877)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2985)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1635)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6692)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
Below is the MainActivity Class for the chat messenger in my application:
package com.example.aids.a09application;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.text.format.DateFormat;
import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.database.FirebaseListAdapter;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
/**
* Created by Aids on 29/08/2017.
*/
public class MainChatActivity extends AppCompatActivity {
private static int SIGN_IN_REQUEST_CODE = 1;
private FirebaseListAdapter<ChatMessage> adapter;
RelativeLayout chat_activity_main;
FloatingActionButton fab;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == (R.id.menu_signout))
{
AuthUI.getInstance().signOut( this ).addOnCompleteListener( new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Snackbar.make( chat_activity_main, "You have been signed out.", Snackbar.LENGTH_SHORT).show();
finish();
}
} );
}
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate( R.menu.chat_main_menu, menu );
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult( requestCode, resultCode, data );
if (requestCode == SIGN_IN_REQUEST_CODE)
{
if(resultCode == RESULT_OK)
{
Snackbar.make( chat_activity_main, "Succesfully signed in. Welcome!", Snackbar.LENGTH_SHORT).show();
displayChatMessage();
}
else {
Snackbar.make( chat_activity_main, "We couldn't sign you in. Please try again!", Snackbar.LENGTH_SHORT).show();
finish();
}
}
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.chat_activity_main );
chat_activity_main = (RelativeLayout) findViewById( R.id.chat_activity_main );
fab = (FloatingActionButton) findViewById( R.id.fab );
fab.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText input = (EditText)findViewById( R.id.input );
FirebaseDatabase.getInstance().getReference().push().setValue( new ChatMessage(input.getText().toString(),
FirebaseAuth.getInstance().getCurrentUser().getEmail()));
input.setText( "" );
}
} );
if (FirebaseAuth.getInstance().getCurrentUser() == null) {
startActivityForResult( AuthUI.getInstance().createSignInIntentBuilder().build(), SIGN_IN_REQUEST_CODE );
} else {
Snackbar.make( chat_activity_main, "Welcome" + FirebaseAuth.getInstance().getCurrentUser().getEmail(), Snackbar.LENGTH_SHORT ).show();
//Load Content
displayChatMessage();
}
}
private void displayChatMessage() {
ListView listofMessage = (ListView) findViewById( R.id.list_of_messages );
adapter = new FirebaseListAdapter<ChatMessage>(this,ChatMessage.class,R.layout.chat_list_item,FirebaseDatabase.getInstance().getReference()) {
#Override
protected void populateView(View v, ChatMessage model, int position) {
//Get references to the views of chat_list_item.xml
TextView messageText, messageUser, messageTime;
messageText = (TextView) v.findViewById( R.id.message_text );
messageUser = (TextView) v.findViewById( R.id.message_user );
messageTime = (TextView) v.findViewById( R.id.message_time );
messageText.setText( model.getMessageText() );
messageUser.setText( model.getMessageUser() );
messageTime.setText( DateFormat.format( "dd-mm-yyyy (HH:MM:SS)",model.getMessageTime() ) );
}
};
listofMessage.setAdapter( adapter );
}
}
Gradle Build Module:App
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
applicationId "com.example.aids.a09application"
minSdkVersion 16
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
aaptOptions.cruncherEnabled = false
aaptOptions.useNewCruncher = false
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
android {
useLibrary 'org.apache.http.legacy'
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.google.firebase:firebase-core:11.2.0'
compile 'com.google.firebase:firebase-messaging:11.2.0'
compile 'com.android.support:appcompat-v7:26.0.1'
compile 'com.google.android.gms:play-services-maps:11.2.0'
compile 'com.google.firebase:firebase-auth:11.2.0' // ADDED
compile 'com.google.android.gms:play-services-auth:11.2.0' // ADDED
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:design:26.0.1'
compile 'com.android.support:support-v4:26.0.1'
compile 'com.android.support:recyclerview-v7:26.0.1'
compile 'com.firebaseui:firebase-ui-auth:2.3.0'
compile 'com.firebaseui:firebase-ui:2.3.0'
}
apply plugin: 'com.google.gms.google-services'
I had a similar problem while reading/writing to firebase database this small change worked for me. Try removing unnecessary firebase dependencies and make sure you use the same version for all the firebase dependencies for those that you use. In my case I changed my firebase dependencies from:
implementation 'com.google.firebase:firebase-firestore:11.8.0'
implementation 'com.google.firebase:firebase-database:16.0.1'
implementation 'com.google.firebase:firebase-core:16.0.0'
to these:
implementation 'com.google.firebase:firebase-firestore:11.8.0'
implementation 'com.google.firebase:firebase-database:11.8.0'
implementation 'com.google.firebase:firebase-core:11.8.0'
I'm sure you might have spent a lot of time trying to fix this. Might as well turn out worth a shot :)
I am trying to build a android application that can ranging nearby beacons, and get related information such as UUID and distance from the beacon. The problem I am facing now is that the Ranging function can not detect a single beacon at all. I am pretty sure the function is right because I have downloaded another similar demo project that can scan beacons pretty well on the same device.
The application now have no reaction at all after the beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null)) function, and the debugger shows the thread stuck in didRangeBeaconsInRegion function and the beacons size is always 0.
Is there something wrong with my code? Or is it because my setting or configuration is not correct?
Code:
package com.example.ma.contextualawarenessapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.os.RemoteException;
import android.widget.TextView;
import org.altbeacon.beacon.Beacon;
import org.altbeacon.beacon.BeaconConsumer;
import org.altbeacon.beacon.BeaconManager;
import org.altbeacon.beacon.BeaconParser;
import org.altbeacon.beacon.RangeNotifier;
import org.altbeacon.beacon.Region;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;
public class GeofencingActivity extends AppCompatActivity implements BeaconConsumer {
protected static final String TAG = "GeofencingActivity";
private BeaconManager beaconManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_geofencing);
beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.bind(this);
}
#Override
protected void onDestroy() {
super.onDestroy();
beaconManager.unbind(this);
}
#Override
protected void onPause() {
super.onPause();
if (beaconManager.isBound(this)) beaconManager.setBackgroundMode(true);
}
#Override
protected void onResume() {
super.onResume();
if (beaconManager.isBound(this)) beaconManager.setBackgroundMode(false);
}
#Override
public void onBeaconServiceConnect() {
beaconManager.setRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
for (Beacon beacon : beacons) {
logToDisplay(getCurrentTimeStamp() + " | Beacon " + beacon.toString() + " is about " + beacon.getDistance() + " meters away.");
}
/*if (beacons.size() > 0) {
EditText editText = (EditText)GeofencingActivity.this
.findViewById(R.id.geofencingText);
Beacon firstBeacon = beacons.iterator().next();
logToDisplay("The first beacon "+firstBeacon.toString()+" is about "+firstBeacon.getDistance()+" meters away."); }
*/}
});
try {
beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null));
} catch (RemoteException e) { }
}
private void logToDisplay(final String line) {
runOnUiThread(new Runnable() {
public void run() {
TextView editText = (TextView)GeofencingActivity.this
.findViewById(R.id.geofencingText);
editText.append(line+"\n");
}
});
}
private static String getCurrentTimeStamp() {
Locale locale = new Locale("es", "ES");
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS", locale);
Date now = new Date();
return sdf.format(now);
}
}
build.gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.example.ma.contextualawarenessapplication"
minSdkVersion 18
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'org.altbeacon:android-beacon-library:2+#aar'
}
buildscript {
repositories {
jcenter()
mavenCentral()
flatDir {
dirs 'libs'
}
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.0-alpha5'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
A few things to check when you cannot get detections with the Android Beacon Library:
Make sure your beacon is transmitting an AltBeacon format. If not, you simply need to register a BeaconParser expression to make it detect Eddystone or proprietary beacon types like iBeacon.
If you are unsure of the format advertised, try using the Locate app, which will tell you the format it detects.
If the device giving you trouble detecting has Android 6.0+, make sure you have obtained location permissions, as described here.
I followed this link and the answer with most results gives me that the method, setOnGroupExpandListener cannot be resolved. I'm new to android and currently doing stuff basically by checking out how others have done it and try to learn from them.
ExpendableListAdapter listAdapter;
ExpandableListView expListView;
private int lastExpandedPosition = -1;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
expListView.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
if (lastExpandedPosition != -1
&& groupPosition != lastExpandedPosition) {
expListView.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = groupPosition;
}
});
This is in my MainActivity.java, setOnGroupExpandListener is underlined and "not resolved".
These are the imported classes:
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ExpandableListView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
This is the content of my build.gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
defaultConfig {
applicationId "com.example.kevin.ha1kattai"
minSdkVersion 10
targetSdkVersion 22
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.2.1'
}
This is my project file
Android ExpandableListView Support Min SDK:10. Please change YourminSdkVersion .
android:minSdkVersion
An integer designating the minimum API Level required for the application to run.
Please set minSdkVersion as 13 or 17 for better approach
Edited
defaultConfig {
applicationId "com.example.kevin.ha1kattai"
minSdkVersion 15
targetSdkVersion 22
versionCode 1
versionName "1.0"
}