Value on Spinner can't post to databae mySql - java

logcat doesn't give me a specific error, it only shows the error location, which is on line 155 {id_status = spStatus.getSelectedItem().toString();}
I don't know the right keyword to solve the error. I've been browsing, and I think this is the same as the tutorial I followed. where is my mistake? give me more detailed instructions
my java like this:
package src.bkkpost.loker;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Calendar;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import src.bkkpost.MainActivity;
import src.bkkpost.R;
import src.bkkpost.loker.adapter.AdapterStatus;
import src.bkkpost.model.Value;
import src.bkkpost.util.BaseApiService;
import src.bkkpost.util.SharedPrefManager;
import src.bkkpost.util.UtilsApi;
public class UpdateLoker extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
//string spinner kelamin
String[] idStatus = {"10", "20"};
String[] nama_status = {"Buka", "Tutup"};
//string spinner kelamin
String[] id_kelamin = {"5001", "5002", "5003"};
String[] nama_kelamin = {"Pria/Wanita", "Pria", "Wanita"};
//string spinner pendidikan
String[] pendidikan_id = {"3001", "3002", "3003", "30004", "3005", "3006", "3007"};
String[] nama_pendidikan = {"SD", "SMP", "SMA", "SMK ", "Diploma/(D3)", "Sarjana/(S1)", "Master/(S2)"};
//string spinner pendidikan
String[] jurusan_id = {"30001", "300301", "300302", "3000401", "3000402", "3000403", "3000404",
"3000405", "3000406", "3000407", "3000408", "3000409", "3000410", "3000411", "3000412", "3000413", "3000414",
"3000415", "300501", "300502", "300503", "300504", "300505", "300506", "300075"};
String[] nama_jurusan = {"Semua Jurusan", "IPA", "IPS", "Administrasi Perkantoran ", "Akuntansi ", "ANalisis Kimia ",
"Animasi ", "Broadcasting ", "Elektronik ", "Farmasi ", "Multimedia ", "Otomotif ", "Pariwisata ", "Pemasaran ",
"Perbankan ", "Perhotelan", "Tata Boga ", "Tata Busana ", "Perpajakan(D3/S1) ", "Broadcasting(D3/S1)", "Teknik Mesin(D3/S1)",
"Pariwisata(D3/S1)", "Sekretaris (D3/S1)", "Hubungan Masyarakat (D3/S1)", "Akuntansi(D3/S1) "};
AutoCompleteTextView date;
DatePickerDialog datePickerDialog;
BaseApiService mApiservice;
ProgressDialog loading;
Context mContex;
SharedPrefManager sharedPrefManager;
public static final String URL = "http://192.168.43.164/gokerja/";
private ProgressDialog progress;
String bkk_id, posisi, nama_pt, alamat_pt, waktu_buka, id_status;
#BindView(R.id.post_btn_upload)
Button btnUpload;
#BindView(R.id.post_bkk_id)
TextView tvBkkid;
#BindView(R.id.post_posisi)
AutoCompleteTextView etPosisi;
#BindView(R.id.post_namaperusahaan)
AutoCompleteTextView etNamaperusahan;
#BindView(R.id.post_alamat_pt)
AutoCompleteTextView etAlamat;
#BindView(R.id.post_tanggal)
AutoCompleteTextView etTangggal;
#BindView(R.id.post_spin_statusup)
Spinner spStatus;
#OnClick(R.id.post_btn_upload)
void daftar() { }
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loker_update_loker);
ButterKnife.bind(this);
sharedPrefManager = new SharedPrefManager(this);
tvBkkid.setText(sharedPrefManager.getSPNama());
mApiservice = UtilsApi.getAPIService();
mContex = this;
date = (AutoCompleteTextView) findViewById(R.id.post_tanggal);
date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final java.util.Calendar c = java.util.Calendar.getInstance();
int mYear = c.get(java.util.Calendar.YEAR);
int mMont = c.get(Calendar.MONTH);
int mDay = c.get(java.util.Calendar.DAY_OF_MONTH);
//date picker dialog
datePickerDialog = new DatePickerDialog(UpdateLoker.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int month, int dayOfMonth) {
date.setText(year + "-"
+ (month + 1) + "-" + dayOfMonth);
}
}, mYear, mMont, mDay);
datePickerDialog.show();
}
});
//get spinner status
final Spinner spinnerStatus = (Spinner) findViewById(R.id.post_spin_statusup);
spinnerStatus.setOnItemSelectedListener(this);
AdapterStatus adapterStatus = new AdapterStatus(getApplicationContext(), idStatus);
spinnerStatus.setAdapter(adapterStatus);
progress = new ProgressDialog(this);
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (etPosisi.getText().toString().equals("")) {
etPosisi.setError("Posisi harus di isi");
} else if (etNamaperusahan.getText().toString().equals("")) {
etNamaperusahan.setError("Perusahaan harus di isi");
} else if (etAlamat.getText().toString().equals("")) {
etAlamat.setError("alamat harus di isi");
} else {
//Untuk menampilkan progress dialog
progress.setCancelable(false);
progress.setMessage("Loading...");
progress.show();
bkk_id = tvBkkid.getText().toString();
posisi = etPosisi.getText().toString();
nama_pt = etNamaperusahan.getText().toString();
alamat_pt = etAlamat.getText().toString();
waktu_buka = etTangggal.getText().toString();
id_status = spStatus.getSelectedItem().toString();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
BaseApiService api = retrofit.create(BaseApiService.class);
Call<Value> call = api.post_loker(bkk_id, posisi, nama_pt, alamat_pt, waktu_buka, id_status);
call.enqueue(new Callback<Value>() {
#Override
public void onResponse(Call<Value> call, Response<Value> response) {
String value = response.body().getValue();
String message = response.body().getMessage();
progress.dismiss();
if (value.equals("1")) {
AlertDialog.Builder alert = new AlertDialog.Builder(UpdateLoker.this);
alert.setTitle("Confirm");
alert.setMessage("Iklan Lowongan kerja telah berhasil dibuat");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(mContex, MainActivity.class));
dialog.dismiss();
}
});
alert.show();
} else {
AlertDialog.Builder alert = new AlertDialog.Builder(UpdateLoker.this);
alert.setTitle("Confirm");
alert.setMessage("Terjadi Kesalahan Jaringan, Iklan gagal dibuat");
alert.setPositiveButton("Coba Lagi", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(mContex, UpdateLoker.class));
dialog.dismiss();
}
});
alert.show();
}
}
#Override
public void onFailure(Call<Value> call, Throwable t) {
t.printStackTrace();
progress.dismiss();
AlertDialog.Builder alert = new AlertDialog.Builder(UpdateLoker.this);
alert.setTitle("Error 301");
alert.setMessage("Terjadi kesalahan jaringan, Iklan gagal dibuat");
alert.setPositiveButton("Coba Lagi", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
//Toast.makeText(UpdateLoker.this, "semelekete", Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
this my Logcat
09-04 17:13:15.904 16015-16015/src.bkkpost D/AndroidRuntime: Shutting down VM
09-04 17:13:15.904 16015-16015/src.bkkpost W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x419f3d58)
--------- beginning of /dev/log/system
09-04 17:13:15.904 16015-16015/src.bkkpost E/AndroidRuntime: FATAL EXCEPTION: main
Process: src.bkkpost, PID: 16015
java.lang.NullPointerException
at src.bkkpost.loker.UpdateLoker$2.onClick(UpdateLoker.java:155)
at android.view.View.performClick(View.java:4444)
at android.view.View$PerformClick.run(View.java:18457)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5113)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
at dalvik.system.NativeStart.main(Native Method)

Related

Please help i got error on a null object reference. when i click confirm button [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
My logcat here
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.barberbooking, PID: 13610
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.barberbooking.Model.Salon.getSalonId()'
on a null object reference
at com.example.barberbooking.Fragments.BookingStep4Fragment.lambda$null$0$BookingStep4Fragment(BookingStep4Fragment.java:260)
at com.example.barberbooking.Fragments.-$$Lambda$BookingStep4Fragment$4Ef790x-NNkmXHs_bv2YFCA2Nyk.onSuccess(Unknown
Source:4)
at com.google.android.gms.tasks.zzn.run(Unknown Source:4)
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)
My Bookingstep4fragment
package com.example.barberbooking.Fragments;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.barberbooking.Common.Common;
import com.example.barberbooking.Database.CartDataSource;
import com.example.barberbooking.Database.CartDatabase;
import com.example.barberbooking.Database.CartItem;
import com.example.barberbooking.Database.LocalCartDataSource;
import com.example.barberbooking.Model.BookingInformation;
import com.example.barberbooking.Model.EventBus.ConfirmBookingEvent;
import com.example.barberbooking.Model.FCMResponse;
import com.example.barberbooking.Model.FCMsendData;
import com.example.barberbooking.Model.MyNotification;
import com.example.barberbooking.Model.MyToken;
import com.example.barberbooking.R;
import com.example.barberbooking.Retrofit.IFCMApi;
import com.example.barberbooking.Retrofit.RetrofitClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.Timestamp;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.UUID;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import dmax.dialog.SpotsDialog;
import io.paperdb.Paper;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
#SuppressWarnings("ALL")
public class BookingStep4Fragment extends Fragment {
CartDataSource cartDataSource;
CompositeDisposable compositeDisposable = new CompositeDisposable();
SimpleDateFormat simpleDateFormat;
Unbinder unbinder;
IFCMApi ifcmApi;
AlertDialog dialog;
#BindView(R.id.txt_booking_barber_text)
TextView txt_booking_barber_text;
#BindView(R.id.txt_booking_time_text)
TextView txt_booking_time_text;
#BindView(R.id.txt_salon_address)
TextView txt_salon_address;
#BindView(R.id.txt_salon_open_hours)
TextView txt_salon_open_hours;
#BindView(R.id.txt_salon_phone)
TextView txt_salon_phone;
#BindView(R.id.txt_salon_website)
TextView txt_salon_website;
#BindView(R.id.txt_salon_name)
TextView txt_salon_name;
#OnClick(R.id.btn_confirm)
void confirmBooking() {
dialog.show();
//DatabaseUtils.getAllCart(CartDatabase.getInstance(getContext()),
//this);
compositeDisposable.add(cartDataSource.getAllItemFromCart(Common.currentUser.getPhoneNumber())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<List<CartItem>>() {
#Override
public void accept(List<CartItem> cartItems) throws Exception {
String startTime = Common.convertTimeSlotToString(Common.currentTimeSlot);
String[] convertTime = startTime.split("-");
String[] startTimeConvert = convertTime[0].split(":");
int startHourInt = Integer.parseInt(startTimeConvert[0].trim());
int startMinInt = Integer.parseInt(startTimeConvert[1].trim()); // We get 00
Calendar bookingDateWithourHouse = Calendar.getInstance();
bookingDateWithourHouse.setTimeInMillis(Common.currentDate.getTimeInMillis());
bookingDateWithourHouse.set(Calendar.HOUR_OF_DAY, startHourInt);
bookingDateWithourHouse.set(Calendar.MINUTE, startMinInt);
//Create timestamp object and apply to BookingInformation
Timestamp timestamp = new Timestamp(bookingDateWithourHouse.getTime());
final BookingInformation bookingInformation = new BookingInformation();
bookingInformation.setCityBook(Common.city);
bookingInformation.setTimestamp(timestamp);
bookingInformation.setDone(false);
bookingInformation.setBarberId(Common.currentBarber.getBarberId());
bookingInformation.setBarberName(Common.currentBarber.getName());
bookingInformation.setCustomerName(Common.currentUser.getName());
bookingInformation.setCustomerPhone(Common.currentUser.getPhoneNumber());
bookingInformation.setSalonId(Common.currentSalon.getSalonId());
bookingInformation.setSalonAddress(Common.currentSalon.getAddress());
bookingInformation.setSalonName(Common.currentSalon.getName());
bookingInformation.setTime(new StringBuilder(Common.convertTimeSlotToString(Common.currentTimeSlot))
.append(" at ")
.append(simpleDateFormat.format(bookingDateWithourHouse.getTime())).toString());
bookingInformation.setSlot(Long.valueOf(Common.currentTimeSlot));
bookingInformation.setCartItemList(cartItems);
DocumentReference bookingDate = FirebaseFirestore.getInstance()
.collection("AllSalon")
.document(Common.city)
.collection("Branch")
.document(Common.currentSalon.getSalonId())
.collection("Barber")
.document(Common.currentBarber.getBarberId())
.collection(Common.simpleDateFormat.format(Common.currentDate.getTime()))
.document(String.valueOf(Common.currentTimeSlot));
bookingDate.set(bookingInformation)
.addOnSuccessListener((aVoid) -> {
resetStaticData();
getActivity().finish(); activity
Toast.makeText(getContext(), "Success", Toast.LENGTH_SHORT).show();
//DatabaseUtils.clearCart(CartDatabase.getInstance(getContext()));
cartDataSource.clearCart(Common.currentUser.getPhoneNumber())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<Integer>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onSuccess(Integer integer) {
addToUserBooking(bookingInformation);
}
#Override
public void onError(Throwable e) {
Toast.makeText(getContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}).addOnFailureListener(e -> {
Toast.makeText(getContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
});
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable throwable) throws Exception {
Toast.makeText(getContext(), "" + throwable.getMessage(), Toast.LENGTH_SHORT).show();
}
}));
}
private void addToUserBooking(BookingInformation bookingInformation) {
final CollectionReference userBooking = FirebaseFirestore.getInstance()
.collection("User")
.document(Common.currentUser.getPhoneNumber())
.collection("Booking");
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
Timestamp toDayTimeStamp = new Timestamp(calendar.getTime());
userBooking
.whereGreaterThanOrEqualTo("timestamp", toDayTimeStamp)
.whereEqualTo("done", false)
.limit(1)
.get()
.addOnCompleteListener(task -> {
if (task.getResult().isEmpty()) {
userBooking.document()
.set(bookingInformation)
.addOnSuccessListener(aVoid -> {
MyNotification myNotification = new MyNotification();
myNotification.setUid(UUID.randomUUID().toString());
myNotification.setTitle("New Booking");
myNotification.setContent("You have a new appoiment for customer hair care with " + Common.currentUser.getName());
myNotification.setRead(false); // We will only filter notification with 'read' is false on barber staff app
myNotification.setServerTimestamp(FieldValue.serverTimestamp());
FirebaseFirestore.getInstance()
.collection("AllSalon")
.document(Common.city)
.collection("Branch")
.document(Common.currentSalon.getSalonId())
.collection("Barber")
.document(Common.currentBarber.getBarberId())
.collection("Notifications")
.document(myNotification.getUid())
.set(myNotification)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
//First , get Token base on Barber id
FirebaseFirestore.getInstance()
.collection("Tokens")
.whereEqualTo("userPhone", Common.currentBarber.getUsername())
.limit(1)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful() && task.getResult().size() > 0) {
MyToken myToken = new MyToken();
for (DocumentSnapshot tokenSnapShot : task.getResult())
myToken = tokenSnapShot.toObject(MyToken.class);
FCMsendData sendRequest = new FCMsendData();
Map<String, String> dataSend = new HashMap<>();
dataSend.put(Common.TITLE_KEY, "New Booking");
dataSend.put(Common.CONTENT_KEY, "You have new booking from user "+ Common.currentUser.getName());
sendRequest.setTo(myToken.getToken());
sendRequest.setData(dataSend);
compositeDisposable.add(ifcmApi.sendNotification(sendRequest)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<FCMResponse>() {
#Override
public void accept(FCMResponse fcmResponse) throws Exception {
dialog.dismiss();
addToCalendar(Common.currentDate,
Common.convertTimeSlotToString(Common.currentTimeSlot));
resetStaticData();
getActivity().finish(); //Close Activity
Toast.makeText(getContext(), "Success", Toast.LENGTH_SHORT).show();
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable throwable) throws Exception {
Log.d("NOTIFICATION_ERROR", throwable.getMessage());
addToCalendar(Common.currentDate,
Common.convertTimeSlotToString(Common.currentTimeSlot));
resetStaticData();
getActivity().finish(); //Close Activity
Toast.makeText(getContext(), "Success", Toast.LENGTH_SHORT).show();
}
}));
}
}
});
}
});
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
if (dialog.isShowing())
dialog.dismiss();
resetStaticData();
getActivity().finish(); // Close activity
Toast.makeText(getContext(), "Success", Toast.LENGTH_SHORT).show();
}
});
}
private void addToCalendar(Calendar bookingDate, String startDate) {
String startTime = Common.convertTimeSlotToString(Common.currentTimeSlot);
String[] convertTime = startTime.split("-"); //Split ex : 9:00-10:00
//Get start time : get 9:00
String[] startTimeConvert = convertTime[0].split(":");
int startHourInt = Integer.parseInt(startTimeConvert[0].trim()); int startMinInt = Integer.parseInt(startTimeConvert[1].trim());
String[] endTimeConvert = convertTime[1].split(":");
int endHourInt = Integer.parseInt(endTimeConvert[0].trim());
int endMinInt = Integer.parseInt(endTimeConvert[1].trim());
Calendar startEvent = Calendar.getInstance();
startEvent.setTimeInMillis(bookingDate.getTimeInMillis());
startEvent.set(Calendar.HOUR_OF_DAY, startHourInt);
startEvent.set(Calendar.MINUTE, startMinInt);
Calendar endEvent = Calendar.getInstance();
endEvent.setTimeInMillis(bookingDate.getTimeInMillis());
endEvent.set(Calendar.HOUR_OF_DAY, endHourInt); hour
endEvent.set(Calendar.MINUTE, endMinInt);
SimpleDateFormat calendarDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
String startEventTime = calendarDateFormat.format(startEvent.getTime());
String endEventTime = calendarDateFormat.format(endEvent.getTime());
addToDeviceCalendar(startEventTime, endEventTime, "Haircut Booking",
new StringBuilder("Haircut from ")
.append(startTime)
.append(" with ")
.append(Common.currentBarber.getName())
.append(" at ")
.append(Common.currentSalon.getName()).toString(),
new StringBuilder("Address: ").append(Common.currentSalon.getAddress()).toString());
}
private void addToDeviceCalendar(String startEventTime, String endEventTime, String title, String description, String location) {
SimpleDateFormat calendarDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
try {
Date start = calendarDateFormat.parse(startEventTime);
Date end = calendarDateFormat.parse(endEventTime);
ContentValues event = new ContentValues();
event.put(CalendarContract.Events.CALENDAR_ID, getCalendar(getContext()));
event.put(CalendarContract.Events.TITLE, title);
event.put(CalendarContract.Events.DESCRIPTION, description);
event.put(CalendarContract.Events.EVENT_LOCATION, location);
event.put(CalendarContract.Events.DTSTART, start.getTime());
event.put(CalendarContract.Events.DTEND, end.getTime());
event.put(CalendarContract.Events.ALL_DAY, 0);
event.put(CalendarContract.Events.HAS_ALARM, 1);
String timeZone = TimeZone.getDefault().getID();
event.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone);
Uri calendars;
if (Build.VERSION.SDK_INT >= 22)
calendars = Uri.parse("content://com.android.calendar/events");
else
calendars = Uri.parse("content://calendar/events");
Uri uri_save = getActivity().getContentResolver().insert(calendars, event);
Paper.init(getActivity());
Paper.book().write(Common.EVENT_URI_CACHE, uri_save.toString());
} catch (ParseException e) {
e.printStackTrace();
}
}
private String getCalendar(Context context) {
String gmailIdCalendar = "";
String projection[] = {"_id", "calendar_displayName"};
Uri calendars = Uri.parse("content://com.android.calendar/calendars");
ContentResolver contentResolver = context.getContentResolver();
Cursor managedCursor = contentResolver.query(calendars, projection, null, null, null);
if (managedCursor.moveToFirst()) {
String calName;
int nameCol = managedCursor.getColumnIndex(projection[1]);
int idCol = managedCursor.getColumnIndex(projection[0]);
do {
calName = managedCursor.getString(nameCol);
if (calName.contains("#gmail.com")) {
gmailIdCalendar = managedCursor.getString(idCol);
break; // Exit as soon as have io
}
} while (managedCursor.moveToNext());
managedCursor.close();
}
return gmailIdCalendar;
}
private void resetStaticData() {
Common.step = 0;
Common.currentTimeSlot = -1;
Common.currentSalon = null;
Common.currentBarber = null;
Common.currentDate.add(Calendar.DATE, 0);//Current date
}
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
#Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void setDataBooking(ConfirmBookingEvent event) {
if (event.isConfirm()) {
setData();
}
}
private void setData() {
txt_booking_barber_text.setText(Common.currentBarber.getName());
txt_booking_time_text.setText(new StringBuilder(Common.convertTimeSlotToString(Common.currentTimeSlot))
.append(" at ")
.append(simpleDateFormat.format(Common.currentDate.getTime())));
txt_salon_address.setText(Common.currentSalon.getAddress());
txt_salon_website.setText(Common.currentSalon.getWebsite());
txt_salon_name.setText(Common.currentSalon.getName());
txt_salon_open_hours.setText(Common.currentSalon.getOpenHours());
}
static BookingStep4Fragment instance;
public static BookingStep4Fragment getInstance() {
if(instance == null) ;
instance = new BookingStep4Fragment();
return instance;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ifcmApi = RetrofitClient.getInstance().create(IFCMApi.class);
//Apply format for date display on Confirm
simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
dialog = new SpotsDialog.Builder().setContext(getContext()).setCancelable(false)
.build();
}
#Override
public void onDestroy() {
compositeDisposable.clear();
super.onDestroy();
{ if (dialog != null) { dialog.dismiss(); dialog = null; }}
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View itemView = inflater.inflate(R.layout.fragment_bookingstep_four, container, false);
unbinder = ButterKnife.bind(this, itemView);
cartDataSource = new LocalCartDataSource(CartDatabase.getInstance(getContext()).cartDAO());
return itemView;
}
}
Check those lines
bookingInformation.setSalonId(Common.currentSalon.getSalonId());
.document(Common.currentSalon.getSalonId())
The error is clear
Attempt to invoke virtual method 'java.lang.String com.example.barberbooking.Model.Salon.getSalonId()' on a null object
You are sending salonId null

Insert/show/load in json crashed

First of all: 1. When i insert empty data into sql it crashed 2. When load json crashed 3. Pressing with empty data show records crashed Please help!
Here is MainActivity:
package com.example.user.notebook;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.example.user.notebook.Students;
public class MainActivity extends Activity {
LinearLayout mainLayout=null;
EditText lessons=null,student=null,grade=null,observations=null;
Button insertRecord=null,showRecords=null;
ArrayList<Students> result= new ArrayList<>();
TableLayout resultLayout=null;
Database db=null;
LinearLayout jsonLayout=null;
Button loadJSON=null,saveJSON=null;
public void makeJSON()
{
jsonLayout=new LinearLayout(this);
mainLayout.addView(jsonLayout);
loadJSON=new Button(this);
loadJSON.setText("LOAD JSON");
jsonLayout.addView(loadJSON);
loadJSON.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
AlertDialog.Builder alert = new
AlertDialog.Builder(MainActivity.this);
alert.setTitle("Load FILE");
alert.setMessage("Specify file name: ");
final EditText input = new EditText(MainActivity.this);
alert.setView(input);
alert.setPositiveButton("Ok",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
String value = input.getText().toString();
File myfile=new File(
Environment.getExternalStorageDirectory(),value);
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(new
FileInputStream(myfile), "utf8"),65536);
String line="";
line=br.readLine();
try {
JSONArray x=new JSONArray(line);
Log.d("TEST","I have read "+x);
int i;
for(i=0;i<x.length();i++)
{
JSONObject p=x.getJSONObject(i);
String lessons=p.getString("lessons");
String student=p.getString("student");
String observations=p.getString("observations");
double grade =p.getDouble("grade");
db.insert(lessons, student, observations, grade);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
br.close();
}catch(IOException e)
{
Log.d("TEST",e.getMessage());
}
}});
alert.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
}
});
alert.show();
}
});
saveJSON=new Button(this);
saveJSON.setText("SAVE JSON");
saveJSON.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
result=db.getResults();
final JSONArray x=new JSONArray();
int i;
for(i=0;i<result.size();i++)
{
JSONObject p=new JSONObject();
try {
p.put("lessons", result.get(i).lessons);
p.put("student",result.get(i).student);
p.put("observations", result.get(i).observations);
p.put("grade", result.get(i).grade);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
x.put(p);
}
String s=x.toString();
AlertDialog.Builder alert = new
AlertDialog.Builder(MainActivity.this);
alert.setTitle("Create FILE");
alert.setMessage("Specify file name: ");
final EditText input = new EditText(MainActivity.this);
alert.setView(input);
alert.setPositiveButton("Ok",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
String value = input.getText().toString();
File myfile=new File(
Environment.getExternalStorageDirectory(),value);
try {
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(myfile), "UTF8"));
out.append(x.toString());
out.flush();
out.close();
Log.d("TEST", "Write "+x);
}catch(IOException e)
{
Log.d("TEST",e.getMessage());
}
}});
alert.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
}
});
alert.show();
}
});
jsonLayout.addView(saveJSON);
}
public void makeInputs()
{
LinearLayout l1=new LinearLayout(this);
mainLayout.addView(l1);
lessons=new EditText(this);
lessons.setHint("lessons");
l1.addView(lessons);
student=new EditText(this);
student.setHint("student");
l1.addView(student);
observations=new EditText(this);
observations.setHint("observations");
l1.addView(observations);
grade=new EditText(this);
l1.addView(grade);
grade.setHint("grade");
}
public void makeButtons()
{
LinearLayout l2=new LinearLayout(this);
mainLayout.addView(l2);
insertRecord=new Button(this);
insertRecord.setText("INSERT RECORD");
l2.addView(insertRecord);
showRecords=new Button(this);
showRecords.setText("SHOW RECORDS");
l2.addView(showRecords);
insertRecord.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
db.insert(lessons.getText().toString(),
student.getText().toString(),
observations.getText().toString(),
Double.parseDouble(grade.getText().toString()));
}
});
showRecords.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
result=db.getResults();
updateTable();
}
});
}
public void makeTable()
{
resultLayout=new TableLayout(this);
ScrollView scroll=new ScrollView(this);
mainLayout.addView(scroll);
scroll.addView(resultLayout);
TableRow r1=new TableRow(this);
resultLayout.addView(r1);
}
public void updateTable()
{
resultLayout.removeAllViews();
makeTable();
int i;
for(i=0;i<result.size();i++)
{
Students c=result.get(i);
TableRow r=new TableRow(this);
resultLayout.addView(r);
TextView t1,t2,t3,t4;
t1=new TextView(this);
t1.setText(c.lessons);
t2=new TextView(this);
t2.setText(c.student);
t3=new TextView(this);
t3.setText(c.observations);
t4=new TextView(this);
t4.setText(""+c.grade);
r.addView(t1);
r.addView(t2);
r.addView(t3);
r.addView(t4);
ImageView delimage=new ImageView(this);
r.addView(delimage);
delimage.setId(i);
delimage.setImageResource(R.drawable.remove);
delimage.setClickable(true);
delimage.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
String cardetails="lessons: "+
result.get(v.getId()).lessons+
" lessons: "+
result.get(v.getId()).student+
" student: "+
result.get(v.getId()).observations+
"observations: "+
result.get(v.getId()).grade+
" grade: ";
Log.d("TEST","Delete school is "+cardetails);
}
});
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainLayout=new LinearLayout(this);
setContentView(mainLayout);
mainLayout.setOrientation(LinearLayout.VERTICAL);
db=new Database(this, "school.db", null, 2);
makeInputs();
makeButtons();
makeJSON();
makeTable();
}
}
Database
package com.example.user.notebook;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class Database extends SQLiteOpenHelper{
private Context mcontext;
private SQLiteDatabase database;
public Database(Context context, String name, CursorFactory factory,
int version) {
super(context, name, null, version);
mcontext=context;
database=this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table school(lessons text,student text,observations text,grade double)");
}
public ArrayList<Students> getResults()
{
ArrayList<Students> x= new ArrayList<Students>();
Cursor cursor=database.rawQuery("select * from school",null);
if(cursor.getCount()==0)
{
cursor.close();
return x;
}
int lessonsindex=cursor.getColumnIndex("lessons");
int studentindex=cursor.getColumnIndex("student");
int observationsindex=cursor.getColumnIndex("observations");
int gradeindex=cursor.getColumnIndex("grade");
cursor.moveToFirst();
do
{
Students c;
c=new Students(cursor.getString(lessonsindex),
cursor.getString(studentindex),
cursor.getString(observationsindex),
cursor.getDouble(gradeindex));
x.add(c);
}while(cursor.moveToNext());
cursor.close();
return null;
}
public void delete(String lessons,String student, String observations, double grade)
{
database.execSQL("delete from school where lessons='"+lessons+"' and student='"+
student+"'and observations='"+observations+"' and grade = '"+grade);
}
public void insert(String lessons,String student, String observations, double grade)
{
database.execSQL("insert into school(lessons,student,observations,grade) values('"+
lessons+"','"+student+"','"+observations+"','"+grade+"')");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table school");
onCreate(db);
}
public void clearData()
{
database.execSQL("delete from school");
}
}
LogCat:
01-24 22:10:49.962 2421-2421/? E/Zygote: v2
01-24 22:10:49.972 2421-2421/? E/SELinux: [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
01-24 22:14:42.292 2421-2421/com.example.user.notebook E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.notebook, PID: 2421
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
at com.example.user.notebook.MainActivity.updateTable(MainActivity.java:257)
at com.example.user.notebook.MainActivity$4.onClick(MainActivity.java:235)
at android.view.View.performClick(View.java:4808)
at android.view.View$PerformClick.run(View.java:19918)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5608)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1397)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1192)
also
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.notebook, PID: 4373
java.lang.NumberFormatException: Invalid double: ""
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseDouble(StringToReal.java:267)
at java.lang.Double.parseDouble(Double.java:301)
at com.example.user.notebook.MainActivity$3.onClick(MainActivity.java:230)
at android.view.View.performClick(View.java:4808)
at android.view.View$PerformClick.run(View.java:19918)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5608)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1397)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1192)
Youre trying to go through results.size() which is null. Follow your code.
.....
result=db.getResults();
final JSONArray x=new JSONArray();
int i;
for(i=0;i<result.size();i++)
....
This will go into the db.getResults.
public ArrayList<Students> getResults()
{
ArrayList<Students> x= new ArrayList<Students>();
Cursor cursor=database.rawQuery("select * from school",null);
if(cursor.getCount()==0)
{
cursor.close();
return x;
}
int lessonsindex=cursor.getColumnIndex("lessons");
int studentindex=cursor.getColumnIndex("student");
int observationsindex=cursor.getColumnIndex("observations");
int gradeindex=cursor.getColumnIndex("grade");
cursor.moveToFirst();
do
{
Students c;
c=new Students(cursor.getString(lessonsindex),
cursor.getString(studentindex),
cursor.getString(observationsindex),
cursor.getDouble(gradeindex));
x.add(c);
}while(cursor.moveToNext());
cursor.close();
return null;
}
If you look at this method...you are returning x, but x is null. You are not adding anything to X. Then... you return null at the end.... this is where your issue is.
PS: please use better names for your variables.
ArrayList<Students> x= new ArrayList<Students>();
could be a lot better and easier to understand if it was something like....
ArrayList<Students> studentsResults = new ArrayList<Students>();
Now obviously you don't have to do it, but it makes more easier to read code...and its cleaner...way cleaner
You have two issues, the first masking the second which was more obvious and hence the initial attempts to fix that which resulted in nothing working.
The first issue is that you were getting the result array in the onCLick and then calling the updateTable() method, in which the result array retrieved was not in the scope of the updateTable method. So moving result=db.getResults(); onto the updateTable method, resolved that issue.
The second issue was that the getResults would, if any rows were extracted, return null.
So to fix the issues and also condense the code, instead of (to fix issue 2):-
public ArrayList<Students> getResults()
{
ArrayList<Students> x= new ArrayList<Students>();
Cursor cursor=database.rawQuery("select * from school",null);
if(cursor.getCount()==0)
{
cursor.close();
return x;
}
int lessonsindex=cursor.getColumnIndex("lessons");
int studentindex=cursor.getColumnIndex("student");
int observationsindex=cursor.getColumnIndex("observations");
int gradeindex=cursor.getColumnIndex("grade");
cursor.moveToFirst();
do
{
Students c;
c=new Students(cursor.getString(lessonsindex),
cursor.getString(studentindex),
cursor.getString(observationsindex),
cursor.getDouble(gradeindex));
x.add(c);
}while(cursor.moveToNext());
cursor.close();
return null;
}
It could instead be :-
public ArrayList<Students> getResults()
{
ArrayList<Students> x= new ArrayList<Students>();
Cursor cursor=database.rawQuery("select * from school",null);
while (cursor.moveToNext()) {
x.add(new Students(
cursor.getString(cursor.getColumnIndex("lessons")),
cursor.getString(cursor.getColumnIndex("student")),
cursor.getString(cursor.getColumnIndex("observations")),
cursor.getDouble(cursor.getColumnIndex("grade"))
));
}
cursor.close();
return x;
}
Additionally, to fix (1) in the updateTable method add result=db.getResults(); e.g.
public void updateTable()
{
result=db.getResults(); //<<<< ADDED
resultLayout.removeAllViews();
makeTable();
int i;
for(i=0;i<result.size();i++)
{
Remove the now unecessary result=db.getResults(); from the showRecords.setOnClickListener's onClick method.
This both condenses the code and also will not return a null but rather an ArrayList that is either populated or has a size of 0.
Thus circumventing the java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference

query.addListenerForSingleValueEvent won't run...?

i try to connect to firebase to get display_name and also profile_photo
for my post like instagram
like this one
example image
but when i run my app it says that i have nullPointerException on my variable
mUserAccountSettings cause my app won't run onDataChanged() or onDataCancelled()
function.
i already tried to get data from mUserAccountSettings for Profile class and actually it work perfectly but in ViewFragment class it won't work
it says :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.jesslyn.foodylife, PID: 5655
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String
com.example.jesslyn.foodylife.FoodyLife.models.UserAccountSettings.getProfile_photo()'
on a null object reference
at com.example.jesslyn.foodylife.FoodyLife.Utils.ViewPostFragment.setupWidgets(ViewPostFragment.java:156)
at com.example.jesslyn.foodylife.FoodyLife.Utils.ViewPostFragment.onCreateView(ViewPostFragment.java:117)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
at android.os.Handler.handleCallback(Handler.java:742)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:5544)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
E/MQSEventManagerDelegate: failed to get MQSService.
and this is my code in ViewFragment class:
package com.example.jesslyn.foodylife.FoodyLife.Utils;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.LoginFilter;
import android.util.EventLogTags;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.example.jesslyn.foodylife.FoodyLife.Utils.BottomNavigationViewHelper;
import com.example.jesslyn.foodylife.FoodyLife.Utils.FirebaseMethods;
import com.example.jesslyn.foodylife.FoodyLife.Utils.GridImageAdapter;
import com.example.jesslyn.foodylife.FoodyLife.Utils.SquareImageView;
import com.example.jesslyn.foodylife.FoodyLife.Utils.UniversalImageLoader;
import com.example.jesslyn.foodylife.FoodyLife.models.Photo;
import com.example.jesslyn.foodylife.FoodyLife.models.UserAccountSettings;
import com.example.jesslyn.foodylife.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GetTokenResult;
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.Query;
import com.google.firebase.database.ValueEventListener;
import com.ittianyu.bottomnavigationviewex.BottomNavigationViewEx;
import junit.framework.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.Executor;
/**
* Created by Jesslyn on 12/4/2017.
*/
public class ViewPostFragment extends Fragment {
private static final String TAG = "ViewPostFragment";
private SquareImageView mPostImage;
private BottomNavigationViewEx bottomNavigationViewEx;
private TextView mBackLabel, mCaption, mUsername, mTimeStamp;
private ImageView mBackArrow, mEllipses, mProfileImage;
private RatingBar mStars;
private String photoUrl;
private Photo mPhoto;
private int mActivityNumber = 0;
private String photoUsername = "";
private String profilePhotoUrl = "";
private UserAccountSettings mUserAccountSettings;
// firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private FirebaseMethods mFirebaseMethods;
private String userID;
public ViewPostFragment() {
super();
setArguments(new Bundle());
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_view_post, container, false);
mPostImage = (SquareImageView) view.findViewById(R.id.post_image);
bottomNavigationViewEx = (BottomNavigationViewEx) view.findViewById(R.id.bottomNavViewBar);
mBackArrow = (ImageView) view.findViewById(R.id.backArrow);
mBackLabel = (TextView) view.findViewById(R.id.tvBackLabel);
mCaption = (TextView) view.findViewById(R.id.image_caption);
mUsername = (TextView) view.findViewById(R.id.username);
mTimeStamp = (TextView) view.findViewById(R.id.image_time_posted);
mEllipses = (ImageView) view.findViewById(R.id.iv_ellipses);
mStars = (RatingBar) view.findViewById(R.id.ratingBar);
mStars.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RatingBar bar = (RatingBar) v;
Log.d(TAG,"VALUE IS : "+bar.getRating()+" **************************************************");
}
});
mStars.setRating(0);
mProfileImage = (ImageView) view.findViewById(R.id.profile_photo);
try {
mPhoto = getPhotoFromBundle();
UniversalImageLoader.setImage(mPhoto.getImage_path(), mPostImage, null, "");
} catch (NullPointerException e) {
Log.e(TAG, "onCreateView NullPointerException : " + e.getMessage());
}
setupBottomNavigationView();
setupFirebaseAuth();
getPhotoDetails();
setupWidgets();
return view;
}
private void getPhotoDetails(){
Log.d(TAG, "getPhotoDetails: retrieving photo details.");
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(getString(R.string.dbname_user_account_settings))
.orderByChild(getString(R.string.field_user_id))
.equalTo(mPhoto.getUser_id());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange: ");
for ( DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: " +singleSnapshot.getValue().toString());
mUserAccountSettings = singleSnapshot.getValue(UserAccountSettings.class);
Log.d(TAG, "onDataChange: "+mUserAccountSettings.getUsername());
}
setupWidgets();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "onCancelled: query cancelled.");
}
});
}
private void setupWidgets(){
String timestampDiff = getTimeStampDifference();
if(!timestampDiff.equals("0")){
mTimeStamp.setText(timestampDiff + " DAYS AGO");
}else{
mTimeStamp.setText("TODAY");
}
UniversalImageLoader.setImage(mUserAccountSettings.getProfile_photo(), mProfileImage, null, "");
mUsername.setText(mUserAccountSettings.getUsername());
}
//get how many days ago of post
private String getTimeStampDifference() {
Log.d(TAG, "getTimeStampDifference : getting time difference");
String difference = "";
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy'T'HH:mm:ss'Z'", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Jakarta"));
Date timestamp;
Date today = c.getTime();
sdf.format(today);
final String photoTimestamp = mPhoto.getDate_created();
try {
timestamp = sdf.parse(photoTimestamp);
difference = String.valueOf(Math.round(((today.getTime() - timestamp.getTime()) / 1000 / 60 / 60 / 24)));
} catch (ParseException e) {
Log.e(TAG, "PARSE EXCEPTION : " + e.getMessage());
difference = "0";
}
return difference;
}
private int getActivityFromBundle() {
Log.d(TAG, "getActivityFromBundle arguments : " + getArguments());
Bundle bundle = this.getArguments();
if (bundle != null) {
return bundle.getInt(getString(R.string.activity_number));
} else {
return 0;
}
}
private Photo getPhotoFromBundle() {
Log.d(TAG, "getPhotoFromBundle arguments : " + getArguments());
Bundle bundle = this.getArguments();
if (bundle != null) {
return bundle.getParcelable(getString(R.string.photo));
} else {
return null;
}
}
/**
* BottomNavigationView setup
*/
private void setupBottomNavigationView() {
Log.d(TAG, "setupBottomNavigationView: setting up BottomNavigationView");
BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);
BottomNavigationViewHelper.enableNavigation(getActivity(), getActivity(), bottomNavigationViewEx);
Menu menu = bottomNavigationViewEx.getMenu();
MenuItem menuItem = menu.getItem(mActivityNumber);
menuItem.setChecked(true);
}
/**
* ----------------------------------Firebase stuffs-----------------------------------------
*/
//setup the firebase auth obj
private void setupFirebaseAuth() {
Log.d(TAG, "setupFirebaseAuth : setting up firebase auth");
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
//user is signed in
Log.d(TAG, "user is signed in" + user.getUid());
} else {
//user is signed out
Log.d(TAG, "onAuthStateChanged : signed out");
}
}
};
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
It is because the variable mUserAccountSettings is initialized in onDataChange() method which is a callback and is executed async. Before this it initialized your main thread is trying to access that in setupWidgets()
A possible fix would be to move the below code from setupWidgets() to onDataChange().
UniversalImageLoader.setImage(mUserAccountSettings.getProfile_photo(), mProfileImage, null, "");
NOTE: this is not intend to show you any best practice. This solution is just to show that all UI updates which depends on value from server, should happen ones you get the response from server.

Value of EditText not appearing in my logs

I an new to Android. I have the following code for a Twitter Client search:
package com.michaelnares.twitterclient;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
import twitter4j.*;
import twitter4j.conf.ConfigurationBuilder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* Created by michael on 01/05/2014.
*/
public class SearchActivity extends Activity {
EditText queryEditText = null;
String queryText = null;
private Context context = this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
queryEditText = (EditText) findViewById(R.id.queryEditText);
queryText = (queryEditText.getText().toString());
final Context context = this;
Button queryButton = (Button) findViewById(R.id.queryButton);
queryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.i(LogConstants.LOG, "Text value is " + queryText);
if (queryText.equals(null)) {
Toast.makeText(context, "You did not enter a query", Toast.LENGTH_SHORT).show();
} else {
new SearchAsyncTask().execute();
}
}
});
} // ends onCreate()
private class SearchAsyncTask extends AsyncTask<String, String, ArrayList<String>>
{
private ProgressDialog dialog = new ProgressDialog(SearchActivity.this);
private ArrayList<String> searchResults;
#Override
protected void onPreExecute()
{
super.onPreExecute();
dialog.setMessage("Getting data...");
dialog.setIndeterminate(false);
dialog.setCancelable(true);
dialog.show();
}
#Override
protected ArrayList<String> doInBackground(String... strings) {
APIClient client = new APIClient();
searchResults = client.getQueryResults(queryText);
return searchResults;
}
#Override
protected void onPostExecute(ArrayList<String> results)
{
dialog.dismiss();
results.addAll(searchResults);
if (searchResults == null)
{
Log.w(LogConstants.LOG, "searchResults is null");
}
final ListView searchListView = (ListView) findViewById(R.id.searchListView);
final ArrayAdapter adapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, results);
adapter.notifyDataSetChanged();
searchListView.setAdapter(adapter);
}
}
} //ends class
The issue is, I have tried to log the results of the EditText, however I never see that in the logs. What is going on here? I can't work out why I'm never seeing "Text value is " + queryText in the logs.
The problem is you initialize the String value queryText in the event of the screen being created (onCreate()) and not when you actually type in values (after screen creation & dynamic activity on the screen).
This is why the following would work
#Override
public void onClick(View view) {
queryText = (queryEditText.getText().toString());
Log.i(LogConstants.LOG, "Text value is " + queryText);
if (queryText.equals("")) {
Toast.makeText(context, "You did not enter a query", Toast.LENGTH_SHORT).show();
} else {
new SearchAsyncTask().execute();
}
}
Change
Log.i(LogConstants.LOG, "Text value is " + queryText);
to
Log.i(LogConstants.LOG, "Text value is " + queryEditText.getText().toString());
Move
queryText = (queryEditText.getText().toString());
inside the onClick
queryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
queryText = (queryEditText.getText().toString());
Log.i(LogConstants.LOG, "Text value is " + queryText);
if ("".equals(queryText)) {
Toast.makeText(context, "You did not enter a query", Toast.LENGTH_SHORT).show();
} else {
new SearchAsyncTask().execute();
}
}
});

Making remote server calls in an Android application

I've made an apache thrift server and I have a service which contains several functions.
I'm trying to figure out what is the best way to make calls to the remote server from my android application.
My problem is that I can't make calls from the MainActivity thread (the main thread) - and I need to use most of the remote functions in my main activity methods.
I tried to make a static class with a static member called "Server" equals to the server object, and I set it in another thread and then I tried to call it in the main thread (the main activity class) - but I had errors because of jumping from one thread to another..
To be more specified I want something like that:
public class MainActivity extends Activity {
private service.Client myService;
#Override
protected void onCreate(Bundle savedInstanceState) {
..
... Some stuff that define myService (In a new thread ofcourse) ...
}
...
private void MyFunc1() {
myService.Method1();
}
private void MyFunc2() {
myService.Method2();
}
private void MyFunc3() {
myService.Method3();
}
}
I've got a library for talking to REST APIs. Feel free to slice, dice, and re-use: https://github.com/nedwidek/Android-Rest-API
The code is BSD or GPL.
Here's how I use what I have (I've trimmed MainActivity a bit, hopefully not too much):
package com.hatterassoftware.voterguide.api;
import java.util.HashMap;
public class GoogleCivicApi {
protected final String baseUrl = "https://www.googleapis.com/civicinfo/us_v1/";
protected String apiKey = "AIzaSyBZIP5uY_fMF35SVVrytpKgHtppBbj8J0I";
public static final String DATE_FORMAT = "yyyy-MM-dd";
protected static HashMap<String, String> headers;
static {
headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
}
public String createUrl(String uri, HashMap<String, String> params) {
String url = baseUrl + uri + "?key=" + apiKey;
if (params != null) {
for (String hashKey: params.keySet()) {
url += hashKey + "=" + params.get(hashKey) + "&";
}
url = url.substring(0, url.length());
}
return url;
}
}
package com.hatterassoftware.voterguide.api;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.hatterassoftware.restapi.GetTask;
import com.hatterassoftware.restapi.HttpReturn;
import com.hatterassoftware.restapi.RestCallback;
import com.hatterassoftware.voterguide.api.callbacks.ElectionCallback;
import com.hatterassoftware.voterguide.api.models.Election;
public class ElectionsQuery extends GoogleCivicApi implements RestCallback {
GetTask getTask;
ElectionCallback callback;
final String TAG = "ElectionQuery";
public ElectionsQuery(ElectionCallback callback) {
String url = this.createUrl("elections", null);
this.callback = callback;
Log.d(TAG, "Creating and executing task for: " + url);
getTask = new GetTask(url, this, null, null, null);
getTask.execute();
}
#Override
public void onPostSuccess() {
Log.d(TAG, "onPostSuccess entered");
}
#Override
public void onTaskComplete(HttpReturn httpReturn) {
Log.d(TAG, "onTaskComplete entered");
Log.d(TAG, "httpReturn.status = " + httpReturn.status);
if (httpReturn.content != null) Log.d(TAG, httpReturn.content);
if (httpReturn.restException != null) Log.d(TAG, "Exception in httpReturn", httpReturn.restException);
JsonParser parser = new JsonParser();
JsonElement electionArrayJson = ((JsonObject)parser.parse(httpReturn.content)).get("elections");
Log.d(TAG, electionArrayJson.toString());
Gson gson = new GsonBuilder().setDateFormat(GoogleCivicApi.DATE_FORMAT).create();
Election[] elections = gson.fromJson(electionArrayJson.toString(), Election[].class);
callback.retrievedElection(elections);
}
}
package com.hatterassoftware.voterguide;
import java.util.Calendar;
import java.util.List;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.hatterassoftware.voterguide.api.ElectionsQuery;
import com.hatterassoftware.voterguide.api.VoterInfoQuery;
import com.hatterassoftware.voterguide.api.callbacks.ElectionCallback;
import com.hatterassoftware.voterguide.api.callbacks.VoterInfoCallback;
import com.hatterassoftware.voterguide.api.models.Election;
import com.hatterassoftware.voterguide.api.models.VoterInfo;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends SherlockFragmentActivity implements ElectionCallback, VoterInfoCallback {
private ProgressBar mProgressBar;
public Button submit;
public Spinner state;
public Spinner election;
public EditText address;
public EditText city;
public EditText zip;
private int count=0;
private Object lock = new Object();
private static final String TAG = "MainActivity";
public static final String VOTER_INFO = "com.hatterassoftware.voterguide.VOTER_INFO";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressBar = (ProgressBar) findViewById(R.id.home_progressBar);
Resources res = getResources();
SharedPreferences mPrefs = getApplicationSharedPreferences();
ImageButton gpsButton = (ImageButton) findViewById(R.id.locate);
try {
LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if (!manager.isProviderEnabled(Context.LOCATION_SERVICE)) {
gpsButton.setClickable(false);
}
} catch(Exception e) {
Log.d(TAG, e.getMessage(), e);
gpsButton.setClickable(false);
gpsButton.setEnabled(false);
}
submit = (Button) findViewById(R.id.submit);
submit.setClickable(false);
submit.setEnabled(false);
state = (Spinner) findViewById(R.id.state);
election = (Spinner) findViewById(R.id.election);
address = (EditText) findViewById(R.id.streetAdress);
city = (EditText) findViewById(R.id.city);
zip = (EditText) findViewById(R.id.zip);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doSubmit();
}
});
gpsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doLocate();
}
});
// Let's check for network connectivity before we get down to business.
if (Utils.isNetworkAvailable(this, true)) {
// Show the disclaimer on first run.
if(mPrefs.getBoolean("firstRun", true)) {
AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setCancelable(false);
alert.setTitle(res.getString(R.string.welcome));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog, null);
TextView alertContents = (TextView) layout.findViewById(R.id.custom_dialog_text);
alertContents.setMovementMethod(LinkMovementMethod.getInstance());
alertContents.setText(Html.fromHtml(res.getString(R.string.welcome_dialog_text)));
alert.setView(alertContents);
alert.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences mPrefs = getApplicationSharedPreferences();
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean("firstRun", false);
editor.commit();
dialog.dismiss();
retrieveElections();
}
});
alert.show();
} else {
retrieveElections();
}
}
}
#Override
public void onResume() {
super.onResume();
// Let's check for network connectivity before we get down to business.
Utils.isNetworkAvailable(this, true);
LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if (!(manager.isProviderEnabled(LocationManager.GPS_PROVIDER)
|| manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))) {
Toast.makeText(this, "GPS is not available", 2).show();
ImageButton gpsButton = (ImageButton) findViewById(R.id.locate);
gpsButton.setClickable(false);
}
}
public SharedPreferences getApplicationSharedPreferences() {
Context mContext = this.getApplicationContext();
return mContext.getSharedPreferences("com.hatterassoftware.voterguide", MODE_PRIVATE);
}
private void showSpinner() {
synchronized(lock) {
count++;
mProgressBar.setVisibility(View.VISIBLE);
}
}
private void hideSpinner() {
synchronized(lock) {
count--;
if(count < 0) { // Somehow we're trying to hide it more times than we've shown it.
count=0;
}
if (count == 0) {
mProgressBar.setVisibility(View.INVISIBLE);
}
}
}
public void retrieveElections() {
Log.d(TAG, "Retrieving the elections");
showSpinner();
ElectionsQuery query = new ElectionsQuery(this);
}
#Override
public void retrievedElection(Election... elections) {
Log.d(TAG, "Retrieved the elections");
hideSpinner();
for (int i=0; i<elections.length; i++) {
Log.d(TAG, elections[i].toString());
}
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, elections);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spinner = (Spinner) this.findViewById(R.id.election);
spinner.setAdapter(arrayAdapter);
}
}

Categories