App crashes whenever I press login. Need help in Debugging - android-studio

I am building a dating app. I coded the part where a swipe of left or right would register it in the Firebase Database. App runs and everything but now when I try to login from the login page the app crashes. The only thing that I changed prior to the crashes was in the MainActivty so therefore I am including that. Since i am new to this i dont really know how to fix this.
The following is the MainActivity.java
package com.example.macdate;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.lorentzos.flingswipe.SwipeFlingAdapterView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private cards cards_data[];
private ArrayAdapter arrayAdapter;
private int i;
private FirebaseAuth mAuth;
private String currentUId;
private DatabaseReference usersDb;
ListView listView;
List<cards> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usersDb = FirebaseDatabase.getInstance().getReference().child("Users");
mAuth = FirebaseAuth.getInstance();
checkUserSex();
rowItems = new ArrayList<cards>();
arrayAdapter = new arrayAdapter(this, R.layout.item, rowItems);
SwipeFlingAdapterView flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
flingContainer.setAdapter(arrayAdapter);
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
rowItems.remove(0); // Every time the swipe is done completely the card is removed
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
cards obj = (cards) dataObject;
String userId = obj.getUserId();
usersDb.child(oppositeUserSex).child(userId).child("connections").child("nope").child(currentUId).setValue(true); //registering the swipes to the database
Toast.makeText(MainActivity.this, "left", Toast.LENGTH_SHORT).show();
}
#Override
public void onRightCardExit(Object dataObject) {
cards obj = (cards) dataObject;
String userId = obj.getUserId();
usersDb.child(oppositeUserSex).child(userId).child("connections").child("yeps").child(currentUId).setValue(true);
Toast.makeText(MainActivity.this, "right", Toast.LENGTH_SHORT).show(); }
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
}
#Override
public void onScroll(float scrollProgressPercent) {
}
});
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
Toast.makeText(MainActivity.this, "click", Toast.LENGTH_SHORT).show(); }
});
}
private String userSex;
private String oppositeUserSex;
public void checkUserSex(){
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference maleDb = FirebaseDatabase.getInstance().getReference().child("Users").child("Male");
maleDb.addChildEventListener((new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if(dataSnapshot.getKey().equals(user.getUid())){
userSex = "Male";
oppositeUserSex = "Female";
getOppositeSexUsers();
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}));
DatabaseReference femaleDb = FirebaseDatabase.getInstance().getReference().child("Users").child("Female");
femaleDb.addChildEventListener((new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if(dataSnapshot.getKey().equals(user.getUid())){
userSex = "Female";
oppositeUserSex = "Male";
getOppositeSexUsers();
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}));
}
public void getOppositeSexUsers(){
DatabaseReference oppositeSexDb = FirebaseDatabase.getInstance().getReference().child("Users").child(oppositeUserSex);
oppositeSexDb.addChildEventListener((new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if(dataSnapshot.exists() && !dataSnapshot.child("connections").child("nope").hasChild(currentUId) && !dataSnapshot.child("connections").child("yeps").hasChild(currentUId)){
cards item = new cards(dataSnapshot.getKey(),dataSnapshot.child("name").getValue().toString());
rowItems.add(item);
arrayAdapter.notifyDataSetChanged();
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}));
}
public void logoutUser(View view){
mAuth.signOut();
Intent intent = new Intent(MainActivity.this,ChooseLoginRegistrationActivity.class); //takes out to the choose page
startActivity(intent);
finish();
return;
}
}
The following is the Logcat
2020-04-11 00:23:27.262 12387-12431/com.example.macdate D/EGL_emulation: eglMakeCurrent: 0xaf6b2ca0: ver 3 0 (tinfo 0xa5f308f0)
2020-04-11 00:23:27.301 12387-12488/com.example.macdate D/FA: Connected to remote service
2020-04-11 00:23:27.303 12387-12488/com.example.macdate V/FA: Processing queued up service tasks: 4
2020-04-11 00:23:27.684 12387-12387/com.example.macdate D/AndroidRuntime: Shutting down VM
2020-04-11 00:23:27.685 12387-12387/com.example.macdate E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.macdate, PID: 12387
java.lang.NullPointerException: Attempt to invoke interface method 'int java.lang.CharSequence.length()' on a null object reference
at java.util.regex.Matcher.reset(Matcher.java:1052)
at java.util.regex.Matcher.<init>(Matcher.java:180)
at java.util.regex.Pattern.matcher(Pattern.java:1006)
at com.google.firebase.database.core.utilities.Validation.isValidPathString(com.google.firebase:firebase-database##19.2.1:40)
at com.google.firebase.database.core.utilities.Validation.validatePathString(com.google.firebase:firebase-database##19.2.1:44)
at com.google.firebase.database.DataSnapshot.hasChild(com.google.firebase:firebase-database##19.2.1:80)
at com.example.macdate.MainActivity$5.onChildAdded(MainActivity.java:165)
at com.google.firebase.database.core.ChildEventRegistration.fireEvent(com.google.firebase:firebase-database##19.2.1:79)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##19.2.1:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##19.2.1:55)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

Related

Activity not moving to another activty in android studio

package com.example.bookapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.bookapp.databinding.ActivityLoginBinding;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class LoginActivity extends AppCompatActivity {
private ActivityLoginBinding binding;
private FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
private Button BtnLogin;
private EditText TxtEmail;
private EditText TxtPassword;
private TextView singUp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
firebaseAuth = firebaseAuth.getInstance();
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Please wait");
progressDialog.setCanceledOnTouchOutside(false);
BtnLogin =(Button) findViewById(R.id.loginBtn);
singUp =(TextView) findViewById(R.id.noAccountTv);
singUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Intent i = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(i);
}
});
BtnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
validateData();
}
});
}
private String email = "", password = "";
private void validateData() {
TxtEmail =(EditText) findViewById(R.id.emailet);
email =TxtEmail.getText().toString().trim();
TxtPassword = (EditText) findViewById(R.id.passwordet);
password = TxtPassword.getText().toString().trim();
if(!Patterns.EMAIL_ADDRESS.matcher(email).matches())
{
Toast.makeText(this, "Invalid Email Pattern..!", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(password))
{
Toast.makeText(this,"Please enter password",Toast.LENGTH_SHORT).show();
}
else
{
loginUser();
}
}
private void loginUser()
{
progressDialog.setMessage("Logging In");
progressDialog.show();
firebaseAuth.signInWithEmailAndPassword(email,password)
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
checkUser();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure( Exception e) {
progressDialog.dismiss();
Toast.makeText(LoginActivity.this,""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
private void checkUser()
{
progressDialog.setMessage("Checking User..");
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");
ref.child(firebaseUser.getUid())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot)
{
progressDialog.dismiss();
String userType = ""+snapshot.child("userType").getValue();
if(userType.equals("user"))
{
Intent i = new Intent(LoginActivity.this,DashboardUserActivity.class);
startActivity(i);
finish();
}
else if(userType.equals("admin"))
{
Intent i = new Intent(LoginActivity.this,DashboardAdminActivity.class);
startActivity(i);
finish();
}
}
#Override
public void onCancelled(DatabaseError error) {
}
});
}
}
Application is unable to move to the DashboardAdminActivity/DashboardUserActivity while progressbar is showing & email and password validation is also working, but it's not going to the next activities according to the "usertype".
I also tried intent another way, but it's not working, if you guys can find any error/correction in my code, it would be appreciated.

How to start service in main activity by coding proximity sensor in service class

How to start service in main activity by coding proximity sensor in the service class.
my code not working please tell me
This Service class
public class ModeOnOff extends Service {
private SensorManager sensorManager;
private Sensor proximitySensor;
private SensorEventListener proximitySensorListener;
#Override
public void onCreate() {
SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
if (sensorManager!=null){
Sensor proximitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
if (proximitySensor!=null) {
sensorManager.registerListener(proximitySensorListener, proximitySensor, SensorManager.SENSOR_DELAY_NORMAL);
}
} else {
Toast.makeText(this, "Senor service not detected.", Toast.LENGTH_SHORT).show();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Sensor();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
//Function
private void Sensor(){
proximitySensorListener = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType()==Sensor.TYPE_PROXIMITY){
if (sensorEvent.values[0] > 3){
Toast.makeText(ModeOnOff.this, "Hii", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ModeOnOff.this, "By", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
}
And This Main Activity
public class MainActivity extends AppCompatActivity {
Button btnSensor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSensor = findViewById(R.id.btnSensor);
btnSensor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(MainActivity.this, ModeOnOff.class));
}
});
}
}
I want to code the proximity sensor in the service class and start the service from the main activity
how to startService - startService(new Intent(MainActivity.this, ModeOnOff.class));

I am trying to start new activity through intent but facing this error

I am working on multiple Activities and i got this error while using
context - java.lang.NullPointerException: Attempt to invoke virtual
method
'java.lang.String android.content.Context.getPackageName()' on a null
object reference
public class myadapter extends FirebaseRecyclerAdapter<Asia, myadapter.myviewholder> {
private Context context;
Asia asiaData;
I have created the context constructer
public myadapter(#NonNull FirebaseRecyclerOptions<Asia> options, Context context, Asia asiaData) {
super(options);
this.context = context;
this.asiaData = asiaData;
}
public myadapter(#NonNull FirebaseRecyclerOptions<Asia> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull myviewholder holder, int position, #NonNull Asia asia) {
I got error on null reference on Context
final Asia temp = asiaData;
holder.tvName.setText(asia.getConName());
holder.tvCap.setText(asia.getCapital());
Glide.with(holder.img.getContext()).load(asia.getImg()).into(holder.img);
holder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(new Intent(context, MainActivityCountry.class));
intent.putExtra("name", temp.getConName());
intent.putExtra("capital", temp.getCapital());
intent.putExtra("desc", temp.getDesc());
intent.putExtra("img", temp.getImg());
context.startActivity(intent);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
});
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_item, parent, false);
return new myviewholder(view);
}
/* ******** VIEW HOLDER ********** */
class myviewholder extends RecyclerView.ViewHolder {
ImageView img;
TextView tvName, tvCap;
public myviewholder(#NonNull View itemView) {
super(itemView);
img = itemView.findViewById(R.id.img);
tvName = (TextView) itemView.findViewById(R.id.tvName);
tvCap = (TextView) itemView.findViewById(R.id.tvCap);
}
}
}
Here is the Activity where i have call the adapter
package com.example.recyclerview;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.FirebaseDatabase;
public class ActivityAsia extends AppCompatActivity {
RecyclerView rv;
Context context;
Button btn_addCountry;
myadapter adapter;
ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
setTitle("Recycler View");
rv = findViewById(R.id.rView);
btn_addCountry = findViewById(R.id.btn_addCountry);
img =(ImageView)findViewById(R.id.img);
rv.setLayoutManager(new LinearLayoutManager(this));
FirebaseRecyclerOptions<Asia> options = new FirebaseRecyclerOptions.Builder<Asia>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("Asia"), Asia.class)
.build();
adapter = new myadapter(options);
rv.setAdapter(adapter);
btn_addCountry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ActivityAsia.this, AddItemAsia.class);
startActivity(intent);
}
});
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
In your ActivityAsia activity call adapter like this
adapter = new myadapter(ActivityAsia.this,options);
rv.setAdapter(adapter);
and in your myadapter like this
public class myadapter extends FirebaseRecyclerAdapter<Asia, myadapter.myviewholder> {
private Context context;
FirebaseRecyclerOptions<Asia> options;
public myadapter(Context context,#NonNull FirebaseRecyclerOptions<Asia> options) {
super(options);
this.context = context;
this. options = options;
}
#Override
protected void onBindViewHolder(#NonNull myviewholder holder, int position, #NonNull Asia asia) {
final Asia temp = options;
holder.tvName.setText(asia.getConName());
holder.tvCap.setText(asia.getCapital());
Glide.with(holder.img.getContext()).load(asia.getImg()).into(holder.img);
holder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(new Intent(context, MainActivityCountry.class));
intent.putExtra("name", temp.getConName());
intent.putExtra("capital", temp.getCapital());
intent.putExtra("desc", temp.getDesc());
intent.putExtra("img", temp.getImg());
context.startActivity(intent);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
});
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_item, parent, false);
return new myviewholder(view);
}
/* ******** VIEW HOLDER ********** */
class myviewholder extends RecyclerView.ViewHolder {
ImageView img;
TextView tvName, tvCap;
public myviewholder(#NonNull View itemView) {
super(itemView);
img = itemView.findViewById(R.id.img);
tvName = (TextView) itemView.findViewById(R.id.tvName);
tvCap = (TextView) itemView.findViewById(R.id.tvCap);
}
}
}

How to fix "android.content.ActivityNotFoundException" android-studio 2.3.3

I have a small problem where when I click a certain button within my app, the app completely crashes each time without fail.
I am using android studio 2.3.3 and the app is a barcode scanner, here is the error message I get:
android.content.ActivityNotFoundException: No Activity found to handle
Intent { act=android.intent.action.VIEW dat=5010029217902 }
Here is the section of code that is causing the error:
}
});
builder.setNeutralButton("Visit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myResult));
startActivity(browserIntent);
}
});
builder.setMessage(result.getText());
AlertDialog alert1 = builder.create();
alert1.show();
The result when you scan a barcode is often not a valid URL. It is often just a string with several digits. It has no schema or protocol, so it is (very possibly) not defined "what type of resource locator it is". Android's ACTION_VIEW intent is mostly use this information to decide "start which app/activity to open this URL". With a lack of the important information, Android has no idea to open it.
You may specify some cases for handling the result. For example, if the result begins with "http://" or "https://", directly use your code to handle, but if it is just a string of numbers, display it directly, or append it after some string before it is used for Uri.parse, for example "https://google.com/search?q=", to search this barcode's value as you may wanted, or other things you want to do with that 13 digit result.
For example, (the code below written in mobile hasn't been tested, just show the idea):
#Override
public void onClick(DialogInterface dialog, int which) {
Intent browserIntent;
if (myResult.startsWith("http://") || myResult.startsWith("https://"))
browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myResult));
else
browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://google.com/search?q=" + myResult));
startActivity(browserIntent);
}
package com.example.priyanka.qrbarcodescanner;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import android.content.ClipboardManager;
import com.google.zxing.Result;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
import static android.Manifest.permission.CAMERA;
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private static final int REQUEST_CAMERA = 1;
private ZXingScannerView scannerView;
private static int camId = Camera.CameraInfo.CAMERA_FACING_BACK;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
int currentApiVersion = Build.VERSION.SDK_INT;
if(currentApiVersion >= Build.VERSION_CODES.M)
{
if(checkPermission())
{
Toast.makeText(getApplicationContext(), "Permission already granted!", Toast.LENGTH_LONG).show();
}
else
{
requestPermission();
}
}
}
private boolean checkPermission()
{
return (ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA) == PackageManager.PERMISSION_GRANTED);
}
private void requestPermission()
{
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, REQUEST_CAMERA);
}
#Override
public void onResume() {
super.onResume();
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
if (checkPermission()) {
if(scannerView == null) {
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
}
scannerView.setResultHandler(this);
scannerView.startCamera();
} else {
requestPermission();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
scannerView.stopCamera();
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_CAMERA:
if (grantResults.length > 0) {
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (cameraAccepted){
Toast.makeText(getApplicationContext(), "Permission Granted, Now you can access camera", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(getApplicationContext(), "Permission Denied, You cannot access and camera", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(CAMERA)) {
showMessageOKCancel("You need to allow access to both the permissions",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{CAMERA},
REQUEST_CAMERA);
}
}
});
return;
}
}
}
}
break;
}
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new android.support.v7.app.AlertDialog.Builder(MainActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
#Override
public void handleResult(Result result) {
Log.d("QRCodeScanner", result.getText());
Log.d("QRCodeScanner", result.getBarcodeFormat().toString());
final static String myResult = 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 which) {
scannerView.resumeCameraPreview(MainActivity.this);
}
});
builder.setNeutralButton("Visit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myResult));
startActivity(browserIntent);
}
});
builder.setMessage(result.getText());
AlertDialog alert1 = builder.create();
alert1.show();
}
}
package com.example.priyanka.qrbarcodescanner;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import android.content.ClipboardManager;
import com.google.zxing.Result;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
import static android.Manifest.permission.CAMERA;
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private static String myResult;
private static final int REQUEST_CAMERA = 1;
private ZXingScannerView scannerView;
private static int camId = Camera.CameraInfo.CAMERA_FACING_BACK;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
int currentApiVersion = Build.VERSION.SDK_INT;
if(currentApiVersion >= Build.VERSION_CODES.M)
{
if(checkPermission())
{
Toast.makeText(getApplicationContext(), "Permission already granted!", Toast.LENGTH_LONG).show();
}
else
{
requestPermission();
}
}
}
private boolean checkPermission()
{
return (ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA) == PackageManager.PERMISSION_GRANTED);
}
private void requestPermission()
{
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, REQUEST_CAMERA);
}
#Override
public void onResume() {
super.onResume();
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
if (checkPermission()) {
if(scannerView == null) {
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
}
scannerView.setResultHandler(this);
scannerView.startCamera();
} else {
requestPermission();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
scannerView.stopCamera();
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_CAMERA:
if (grantResults.length > 0) {
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (cameraAccepted){
Toast.makeText(getApplicationContext(), "Permission Granted, Now you can access camera", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(getApplicationContext(), "Permission Denied, You cannot access and camera", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(CAMERA)) {
showMessageOKCancel("You need to allow access to both the permissions",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{CAMERA},
REQUEST_CAMERA);
}
}
});
return;
}
}
}
}
break;
}
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new android.support.v7.app.AlertDialog.Builder(MainActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
#Override
public void handleResult(Result result) {
Log.d("QRCodeScanner", result.getText());
Log.d("QRCodeScanner", result.getBarcodeFormat().toString());
myResult = 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 which) {
scannerView.resumeCameraPreview(MainActivity.this);
}
});
builder.setNeutralButton("Visit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myResult));
startActivity(browserIntent);
}
});
builder.setMessage(result.getText());
AlertDialog alert1 = builder.create();
alert1.show();
}
}

Error Parsing Data java.lang.IllegalStateException: Not on the main thread when trying to add a marker

I am trying to update markers on Google map using a service, but when I use the "setParkingSpotMarker" function that add a marker to every item at the list I get an error "java.lang.IllegalStateException: Not on the main thread"
The function "setParkingSpotMarker" is called in the loop inside the service -DataUpdateService.
I don't know how to change my code so it will update the markers on the main thread.I have read some posts about that but didn't understand how to change it in my code.
this is the service:
package com.example.sailon;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
public class DataUpdateService extends Service {
Timer myTimer = new Timer();
MyTimerTask myTask = new MyTimerTask();
MyMap mymap;
String teamID;
static LatLng teamLocation;
ArrayList<TeamsList> teamsList= new ArrayList<TeamsList>() ;
public ArrayList<UnitInHeatForMap> unitswithteam= new ArrayList<UnitInHeatForMap>();
String action;
Context fromContext;
String CompName;
String heatNum;
boolean isSailor;
String usermail;
GPSTracker gps;
private final IBinder mBinder = new LocalBinder();
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("PS", "DataUpdateService onStartCommand");
return Service.START_NOT_STICKY;
}
#Override
// return thee instance of the local binder to the activity
public IBinder onBind(Intent intent) {
Log.d("PS", "DataUpdateService onBind");
return mBinder;
}
public class LocalBinder extends Binder {
DataUpdateService getService() {
Log.d("PS", "DataUpdateService LocalBinder onBind");
return DataUpdateService.this;
}
}
public class MyTimerTask extends TimerTask {
#Override
public void run() {
String unitToUpdate= mymap.getUnitToUpdate (CompName,heatNum,usermail);
Log.d("NY","CompName " +CompName);
Log.d("NY","heatNum " +heatNum);
Log.d("NY","usermail " +usermail);
Log.d("NY","unitToUpdate" +unitToUpdate);
Log.d("NY","isSailor" +isSailor);
if (isSailor){
gps = new GPSTracker(DataUpdateService.this,unitToUpdate );
if( ! (gps.canGetLocation())){
gps.showSettingsAlert();
}
}
unitswithteam=mymap.refresh (CompName,heatNum);
int j= unitswithteam.size();
for (int i=0; i<j;i++){
teamID=unitswithteam.get(i).getTeamID();
Log.d("NY","teamID "+i+teamID);
UnitsInHeats us=unitswithteam.get(i).getUnit();
teamLocation = new LatLng(us.getLat(),us.getLng() );
Log.d("NY","team location "+i + " "+us.getLat());
mymap.setParkingSpotMarker(teamLocation,teamID);
if (i==(j-1)){
CameraPosition secound =new CameraPosition.Builder()
.target(teamLocation)
.zoom(15.5f)
.bearing(300)
.tilt(50)
.build();
mymap.moveMyMapCamera(secound);
}
}
}
}
// called from the activity
public void MapUpdateFromService(Context context, MyMap map, final String action,
String CompName, String heatNum, boolean isSailor , String usermail) {
Log.d("PS", "DataUpdateService MapUpdateFromService");
this.mymap = map;
this.action = action;
this.CompName=CompName;
this.heatNum=heatNum;
this.isSailor=isSailor;
this.usermail=usermail;
// this command activate the run function from the inner class MyTimerTask every 5 seconds.
myTimer.schedule(myTask,0,5000);
}
public void onDestroy() {
super.onDestroy();
// cancel the scheduler.
myTimer.cancel();
}
}
this is the activity that calls the service:
package com.example.sailon;
import java.util.ArrayList;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import android.app.ActionBar;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class Map extends Activity {
Bundle extras;
// private GoogleMap map;
static LatLng teamLocation;
//public static ArrayList<Teams> teams;
ArrayList<TeamsList> teamsList= new ArrayList<TeamsList>() ;
Marker mark;
double lat;
double lng;
GPSTracker gps;
String Location ;
String teamID;
String CompName;
MyMap mymap;
String heatNum;
String CompID;
boolean isSailor;
String usermail;
static LatLng BeerSheva = new LatLng(31.250919, 34.783916);
public ArrayList<UnitInHeatForMap> unitswithteam= new ArrayList<UnitInHeatForMap>();
// ArrayList<LatLng> List= new ArrayList<LatLng>() ;
DataUpdateService dbuService;
boolean dbuBound=false;// when service connected get true
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
mymap= new MyMap(this,((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap());
//map=((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
extras = getIntent().getExtras();
CompName=extras.getString("CompName");
heatNum=extras.getString("heatNum");
isSailor=extras.getBoolean("isSailor");
usermail=extras.getString("usermail");
Log.d("CompName",CompName);
Log.d("heatNum",heatNum);
// get action bar
ActionBar actionBar = getActionBar();
// Enabling Up / Back navigation
actionBar.setDisplayHomeAsUpEnabled(true);
if (mymap!=null){
Log.d("PS", "map isnt null");
mymap.setMapType();
mymap.setMyLocationEnabled(true);
CameraPosition firstZom =new CameraPosition.Builder()
.target(BeerSheva)
.zoom(15.5f)
.bearing(300)
.tilt(50)
.build();
mymap.moveMyMapCamera(firstZom);
}
}
// serviceConnerction is an interface that must be implemented when using bound service
private ServiceConnection sConnection=new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d("PS", "Map onServiceConnected");
DataUpdateService.LocalBinder binder=(DataUpdateService.LocalBinder)service;
dbuService=binder.getService();
Log.d("PS", "Map callupdate");
dbuService.MapUpdateFromService(Map.this,mymap,"ActionSearch",CompName,heatNum, isSailor,usermail);
dbuBound=true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
Log.d("PS", "Map onServiceDisconnected");
dbuBound=false;
}
};
#Override
protected void onStart() {
super.onStart();
// Bind to DataUpdateService
Log.d("PS", "Map onStart");
Intent intent= new Intent(this,DataUpdateService.class);
bindService(intent,sConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStop() {
super.onStop();
// Unbind from the service
Log.d("PS", "Map onStop");
if(dbuBound){
unbindService(sConnection);
dbuBound=false;
}
}
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) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.logoutAction:
Intent i = new Intent(Map.this, MainActivity.class);
startActivity(i);
return true;
case R.id.VideoAction:
Intent intent = new Intent("android.media.action.VIDEO_CAMERA");
startActivity(intent);
return true;
case R.id.CallAction:
Intent call = new Intent(Intent.ACTION_DIAL);
startActivity(call);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
this is the calss of the map:
package com.example.sailon;
import android.content.Context;
import android.util.Log;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.parse.ParseException;
import java.util.ArrayList;
/**
* Created by Evyatar.m on 21/02/2015.
*/
public class MyMap {
private GoogleMap map;
static LatLng BeerSheva = new LatLng(31.250919, 34.783916);
String CompID;
String teamID;
String CompName;
String heatNum;
ArrayList<TeamsList> teamsList= new ArrayList<TeamsList>() ;
public ArrayList<UnitInHeatForMap> unitswithteam2= new ArrayList<UnitInHeatForMap>();
static LatLng teamLocation;
Model DB;
public MyMap(Context context, GoogleMap map) {
Log.d("PS", "MyMap builder");
DB = Model.getInstance(context);
this.map = map;
}
public String getUnitToUpdate (String CompName,String heatNum, String usermail){
String unit=null;
try {
CompID= DB.getCompIDByName(CompName);
} catch (com.parse.ParseException e) {
e.printStackTrace();
}
try {
unit= DB.getUnitToUpdateFromDB (CompID,heatNum, usermail);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return unit;
}
public void setMyLocationEnabled(boolean b){
Log.d("PS", "MyMap set location enable");
map.setMyLocationEnabled(true);
}
public void setParkingSpotMarker(LatLng teamLocation,String teamID) {
Log.d("PS", "ParkingMap setParkinSpotMarker");
map.addMarker(new MarkerOptions()
.position(teamLocation)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.iconsmall))
.title("Team " +teamID)).showInfoWindow();
}
public void setMapType(){
Log.d("PS", "MyMap setType");
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
public void moveMyMapCamera(CameraPosition firstZom) {
Log.d("PS", "MyMap moveParkingMapCamera");
map.moveCamera(CameraUpdateFactory.newCameraPosition(firstZom));
}
//updates all points on map
public ArrayList<UnitInHeatForMap> refresh (String CompName,String heatNum){
Log.d("PS", "MyMap refresh");
try {
CompID= DB.getCompIDByName(CompName);
} catch (com.parse.ParseException e) {
e.printStackTrace();
}
try {
DB.setUnitInHeatForMap (new Model.CallbackModel () {
#Override
public void done (ArrayList<UnitInHeatForMap> unitswithteam){
if (unitswithteam.size() >0){
unitswithteam2=unitswithteam;
}
}
}, CompID, heatNum,this);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return unitswithteam2;
}
}
please help me
thanks !!!**
The run method of the TimerTask runs on background thread, and you can only update the map on the main thread.
So you have to wrap the following Map UI update codes into runOnUiThread()
mymap.setParkingSpotMarker(teamLocation,teamID);
if (i==(j-1)){
CameraPosition secound =new CameraPosition.Builder()
.target(teamLocation)
.zoom(15.5f)
.bearing(300)
.tilt(50)
.build();
mymap.moveMyMapCamera(secound);
}
You need to have an Activity to apply runOnUIThread, so you need to put your
fromContext = ((Map)context);
inside the first line of your MapUpdateFromService method. Then you can call runOnUiThread() in your TimerTask's run() method.
((Map)fromContext).runOnUiThread(new Runnable() {
#Override
public void run() {
//run your Map UI update code
}
});
This is also a similar issue of this problem.

Resources