This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have 1 problem and Who can help me?.
I have 1 Activity run when start App
package com.example.khuatduytan.doantotnghiep;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.Serializable;
public class MainActivity extends AppCompatActivity {
DatabaseHelper db;
Button btnLogin, btnRegister, btnFindPassword;
EditText editUsername, editPassword;
private static final int REQUEST_CODE = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHelper(this);
btnLogin = (Button) findViewById(R.id.button_login);
btnRegister = (Button) findViewById(R.id.button_register);
btnFindPassword = (Button) findViewById(R.id.button_findPassword);
editUsername = (EditText) findViewById(R.id.editText_username);
editPassword = (EditText) findViewById(R.id.editText_password);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarActivity);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Đăng nhập");
Login();
Register();
FindPassword();
}
public void Login(){
btnLogin.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = db.getDataTableUser();
int temp = 1;
if (res.getCount() == 0) {
showMessage("Error", "Tài khoản không tồn tại");
return;
}
while (res.moveToNext()) {
String username, password, idUser;
idUser = res.getString(0);
username = res.getString(1);
password = res.getString(2);
if (editUsername.getText().toString().equals(username) == true&&editPassword.getText().toString().equals(password) == true) {
doOpenManagePage(idUser);
temp = 0;
break;
}
}
if (temp==1){
showMessage("Error", "Account does not exist");
}
}
}
);
}
public void Register(){
btnRegister.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v) {
doOpenRegister();
}
}
);
}
public void FindPassword(){
btnFindPassword.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v) {
doOpenFindPasswordStep1();
}
}
);
}
public void doOpenRegister(){
Intent newIntent = new Intent(this, Register.class);
startActivity(newIntent);
}
public void doOpenFindPasswordStep1(){
Intent newIntent = new Intent(this, FindPasswordStep1.class);
startActivity(newIntent);
}
public void doOpenManagePage(String idUser){
Intent newIntent = new Intent(this, ManagePage.class);
newIntent.putExtra("IdUser", idUser);
startActivityForResult(newIntent, REQUEST_CODE);
}
public void showMessage(String title, String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_manage_page, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_logout) {
return true;
}
else if (id==R.id.action_search){
return true;
}
return super.onOptionsItemSelected(item);
}
}
Then it send IdUser to this Activity
package com.example.khuatduytan.doantotnghiep;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
public class ManagePage extends AppCompatActivity{
private static final int REQUEST_CODE = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_page);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.add_note);
Bundle extras = getIntent().getExtras();
final String idUser = extras.getString("IdUser");
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
doOpenInsertNote(idUser);
}
});
}
public String getIdUser(){
Bundle extras = getIntent().getExtras();
String idUser = extras.getString("IdUser");
return idUser;
}
public void doOpenInsertNote(String idUser){
Intent newIntent = new Intent(this, InsertNote.class);
newIntent.putExtra("IdUser", idUser);
startActivityForResult(newIntent, REQUEST_CODE);
}
}
When i run it 1st time, this app is ok, it can go to next Activity
package com.example.khuatduytan.doantotnghiep;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.Calendar;
public class InsertNote extends AppCompatActivity implements View.OnClickListener {
private ImageButton insertDate;
private Calendar cal;
private int day;
private int month;
private int year;
private EditText et, content_InsertNote, money_InsertNote;
private Button btnSubmitNote, btnCancelNote;
private Spinner SelectTypeNote;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_note);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
insertDate = (ImageButton) findViewById(R.id.dateInsert);
cal = Calendar.getInstance();
et = (EditText) findViewById(R.id.dateInsert_editText);
btnSubmitNote = (Button) findViewById(R.id.insertNote);
btnCancelNote = (Button) findViewById(R.id.cancelNote);
content_InsertNote = (EditText) findViewById(R.id.noiDung);
money_InsertNote = (EditText) findViewById(R.id.soTien);
SelectTypeNote = (Spinner) findViewById(R.id.loai);
db = new DatabaseHelper(this);
cal = Calendar.getInstance();
day = cal.get(Calendar.DAY_OF_MONTH);
month = cal.get(Calendar.MONTH);
year = cal.get(Calendar.YEAR);
insertDate.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
final String idUser = extras.getString("IdUser");
setBtnSubmitNote(idUser);
setBtnCancelNote();
}
#Override
public void onClick(View v) {
showDialog(0);
}
#Override
#Deprecated
protected Dialog onCreateDialog(int id) {
return new DatePickerDialog(this, datePickerListener, year, month, day);
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
et.setText(selectedDay + " / " + (selectedMonth + 1) + " / " + selectedYear);
}
};
private void setBtnSubmitNote(final String idUser){
btnSubmitNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
confirmDialog(idUser);
}
});
}
private void setBtnCancelNote(){
Intent newIntent = new Intent(this, ManagePage.class);
startActivity(newIntent);
}
private void confirmDialog(final String idUser) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setMessage("Are you sure?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
String date = null, content = null, money = null, TypeNote_Selected;
int Type_Note = 0, id_User;
id_User = Integer.parseInt(idUser);
date = et.getText().toString();
content = content_InsertNote.getText().toString();
money = money_InsertNote.getText().toString();
TypeNote_Selected = SelectTypeNote.getSelectedItem().toString();
if(TypeNote_Selected.equals("Thu")){
Type_Note = 0;
} else{
Type_Note = 1;
}
if(date.equals("")||content.equals("")||money.equals("")){
Toast.makeText(InsertNote.this, "Bạn chưa nhập đủ dữ liệu", Toast.LENGTH_LONG).show();
}
else {
long isInserted = db.insertNoteTable(date, content, Type_Note, money, id_User);
if (isInserted == -1) {
Toast.makeText(InsertNote.this, "Thêm ghi chú không thành công", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(InsertNote.this, "Thêm ghi chú thành công", Toast.LENGTH_LONG).show();
}
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.show();
}
}
`
But when i run it second time, When i click button to open Activity
InsertNote, I receive a error
03-26 16:12:32.161 2614-2614/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.khuatduytan.doantotnghiep/com.example.khuatduytan.doantotnghiep.ManagePage}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.khuatduytan.doantotnghiep.ManagePage.onCreate(ManagePage.java:21)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
I tried to print what i send from Activity Main to Activity ManagePage by Toast, it display exactly what i want to send.
But i dont know why this error display.
Can you help me?
Sorry about my English
You call setBtnCancelNote() method in the onCreate() method of your InsertNote activity. so as soon as InsertNote starts it tries to launch the ManagePage activity.
The problem is your ManagePage activity expects the value IdUser in the bundle received from the intent. But you do not pass this value to ManagePage activity when you start it from InsertNote activity.
You probably want to add this line to your setBtncancelNote() method in InsertPage activity -
newIntent.putExtra("IdUser", //The Values here);
If you pass this value then ManageNote will not crash.
please add more info like line numbers, otherwise its difficult to debug it remotely ..
Anyway, my guess is you have to check for null pointers when you do stuff like getIntent().getExtras()
just put some breakpoints there, and step by step and you'll figure it out
Related
I am having this following error. I added constructor on DailyVerseFragment. But still it doesn't work.
I am having this issues for more than one week.
Fatal Exception: java.lang.RuntimeException
Unable to start activity ComponentInfo{com.donghyouny.biblecard/com.donghyouny.biblecard.MainActivity}: androidx.fragment.app.Fragment$InstantiationException: Unable to instantiate fragment com.donghyouny.biblecard.DailyVerseFragment: could not find Fragment constructor
package com.donghyouny.biblecard;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.Menu;
import android.view.ViewGroup;
import android.widget.Button;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.core.view.GravityCompat;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, FragmentCallback {
Toolbar toolbar;
CardFragment cardFargment;
DailyVerseFragment dailyVerseFragment;
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dailyVerseFragment = new DailyVerseFragment();
// mAuth = FirebaseAuth.getInstance();
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
contextOfApplication = getApplicationContext();
toolbar.setTitle("Draw Verse Card");
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
drawer.openDrawer(GravityCompat.START);
cardFargment = new CardFragment();
Calendar mCalendar = Calendar.getInstance();
/*mCalendar.set(Calendar.HOUR_OF_DAY, 01);
mCalendar.set(Calendar.MINUTE, 01);
mCalendar.set(Calendar.SECOND, 0);*/
mCalendar.set(Calendar.HOUR_OF_DAY, 0);
if(mCalendar.before(Calendar.getInstance())){ // if it's in the past, increment
mCalendar.add(Calendar.DATE, 1);
}
// PackageManager pm = this.getPackageManager();
// ComponentName receiver = new ComponentName(this, DeviceBootReceiver.class);
Intent alarmIntent = new Intent(this, AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
if (alarmManager != null) {
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), pendingIntent);
}
}
// 부팅 후 실행되는 리시버 사용가능하게 설정
/* pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);*/
// setAlarm(mCalendar);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportFragmentManager().beginTransaction().add(R.id.container, cardFargment).commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if(drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
}else{
// super.onBackPressed();
AlertDialog.Builder alBuilder = new AlertDialog.Builder(this, R.style.AlertDialogCustom);
alBuilder.setMessage("Do you want to exit?");
// "예" 버튼을 누르면 실행되는 리스너
alBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish(); // 현재 액티비티를 종료한다. (MainActivity에서 작동하기 때문에 애플리케이션을 종료한다.)
}
});
// "아니오" 버튼을 누르면 실행되는 리스너
alBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
return; // 아무런 작업도 하지 않고 돌아간다
}
});
alBuilder.setTitle("Program Exit");
alBuilder.show(); // AlertDialog.Bulider로 만든 AlertDialog를 보여준다.
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Bundle bundle = getBundle(menuItem);
// onFragmentSelected(0, bundle);
int id = menuItem.getItemId();
if(id == R.id.menu1){
onFragmentSelected(0, bundle);
}else if(id == R.id.menu2){
onFragmentSelected(1, bundle);
}else if(id == R.id.menu3) {
onFragmentSelected(2, bundle);
}else if(id == R.id.menu4) {
onFragmentSelected(3, bundle);
}else if(id == R.id.menu5) {
onFragmentSelected(4, bundle);
}else if(id == R.id.menu6) {
onFragmentSelected(5, bundle);
}else if(id == R.id.menu7) {
onFragmentSelected(6, bundle);
}else if(id == R.id.menu8) {
onFragmentSelected(7, bundle);
}else if(id == R.id.menu9) {
onFragmentSelected(8, bundle);
}else if(id == R.id.menu10) {
onFragmentSelected(9, bundle);
}else if(id == R.id.menu11) {
onFragmentSelected(10, bundle);
}else if(id == R.id.menu12) {
onFragmentSelected(11, bundle);
}else if(id == R.id.menu13) {
onFragmentSelected(12, bundle);
}else if(id == R.id.menu14) {
onFragmentSelected(13, bundle);
}else if(id == R.id.menu15) {
onFragmentSelected(14, bundle);
}else if(id == R.id.menu16) {
onFragmentSelected(15, bundle);
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private Bundle getBundle(#NonNull MenuItem menuItem) {
Bundle bundle = new Bundle();
bundle.putString("value", menuItem.getTitle().toString());
return bundle;
}
#Override
public void onFragmentSelected(int position, Bundle bundle) {
String value = bundle.getString("value");
Fragment curFragment = null;
if(position == 0){
curFragment = new CardFragment();
toolbar.setTitle(value);
}else if(position==1){
curFragment = new DailyVerseFragment(toolbar);
//toolbar.setTitle(value);
}else if(position>=2){
curFragment = new Fragment1(value);
toolbar.setTitle(value);
}
// toolbar.setTitle(value);
getSupportFragmentManager().beginTransaction().replace(R.id.container, curFragment).commit();
}
// a static variable to get a reference of our application context
public static Context contextOfApplication;
public static Context getContextOfApplication()
{
return contextOfApplication;
}
}
package com.donghyouny.biblecard;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.gms.ads.AdView;
public class DailyVerseFragment extends Fragment {
private ImageView imageView;
private TextView bibleType;
private TextView verse;
private TextView content;
public Bible bible;
private SharedPreferences checkDialog;
private SharedPreferences saveDialog;
private SharedPreferences shareDialog;
private ImageView like;
private ImageView check;
private ImageView save;
private TextView likecount, savecount, link;
public static final int REQUEST_CODE = 101;
private String key;
private Toolbar toolbar;
private boolean flag;
private AdView mAdView;
private String categoryName;
private DrawableImage DrawbleImage;
private AlertReceiver AlertReceivr;
public DailyVerseFragment(){}
public DailyVerseFragment(Toolbar value) {
this.toolbar = value;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Activity a = getActivity();
if (a != null) a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
final ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.fragment_daily_verse, container, false);
// toolbar = rootView.findViewById(R.id.toolbar);
// ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
verse = rootView.findViewById(R.id.verse);
content = rootView.findViewById(R.id.content);
imageView = rootView.findViewById(R.id.imageView);
save = rootView.findViewById(R.id.save);
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("bibleNum", Context.MODE_PRIVATE);
final int bibleNum = sharedPreferences.getInt("bibleNum", 1);
Log.d("DailyVerseNum", String.valueOf(bibleNum));
MyDatabaseHelper db = new MyDatabaseHelper(getActivity());
Cursor cursor = db.readDailyCardData(bibleNum);
cursor.moveToFirst();
bible = new Bible();
Log.d("cursorid", String.valueOf(cursor.getInt(0)));
bible.setId(cursor.getInt(0));
bible.setVerse(cursor.getString(1));
bible.setContent(cursor.getString(2));
bible.setNum(cursor.getInt(3));
bible.setCnum(cursor.getInt(4));
bible.setVnum(cursor.getInt(5));
bible.setImage(cursor.getBlob(6));
bible.setTimestamp(cursor.getString(7));
Log.d("content", bible.getContent());
Log.d("bible.getCnum", String.valueOf(bible.getCnum()));
Cursor cursor1 = db.getCategoryName(bible.getCnum());
cursor1.moveToFirst();
categoryName = cursor1.getString(0);
display();
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveDialog = getActivity().getSharedPreferences("saveDialog", Context.MODE_PRIVATE);
boolean isFirst = saveDialog.getBoolean("first", true);
if(isFirst){
saveDialogPopup();
}else{
onSave(bible);
}
}
});
setHasOptionsMenu(true);
return rootView;
}
private void checkMethod(Bible bible) {
MyDatabaseHelper db = new MyDatabaseHelper(getContext());
db.updateData(bible);
}
private void checkDialogPopup() {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), R.style.AlertDialogCustom);
builder.setTitle("Check Button");
builder.setMessage("If you want to specify which verse is already read, this button will move the one you read to the lowest of the previously show list. But once you click this button, you cannot revert it. Do you want to proceed?");
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(),"You select 'Yes'.",Toast.LENGTH_SHORT).show();
checkMethod(bible);
}
});
builder.setNegativeButton("Don't show this message, again.",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences.Editor editor = checkDialog.edit();
editor.putBoolean("firstTime", false);
editor.commit();
Toast.makeText(getContext(),"You select 'Don't show this message, again.'",Toast.LENGTH_SHORT).show();
}
});
builder.show();
}
private void onSave(Bible bible) {
Log.d("getId", String.valueOf(bible.getId()));
MyDatabaseHelper db1 = new MyDatabaseHelper(getContext());
Cursor cursor = db1.getSaveDataById(bible.getId());
flag=true;
cursor.moveToFirst();
Log.d("countcursor", String.valueOf(cursor.getCount()));
if (cursor != null && cursor.moveToFirst()) {
Toast.makeText(getContext(),"It is already saved.",Toast.LENGTH_SHORT).show();
flag = false;
}else if(flag){
db1.insertToSave(bible);
cursor.close();
}
}
private void saveDialogPopup() {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), R.style.AlertDialogCustom);
builder.setTitle("Save Button");
builder.setMessage("If you select this button, the verse you read will be saved and if you want to see that verse that you saved, you should go to verse list and on the top right, you will see yellow folder icon. If you click that icon. It will take you to 'favorite bible verse'. If you want to save?");
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
onSave(bible);
}
});
builder.setNegativeButton("Don't show this message, again.",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences.Editor editor = saveDialog.edit();
editor.putBoolean("first", false);
editor.commit();
Toast.makeText(getContext(),"You select not \'Don\'t show this message, again\'.",Toast.LENGTH_SHORT).show();
}
});
builder.show();
}
double getScreenInches() {
DisplayMetrics dm = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
double wi = (double) width / (double) dm.xdpi;
double hi = (double) height / (double) dm.ydpi;
double x = Math.pow(wi, 2);
double y = Math.pow(hi, 2);
double screenInches = Math.sqrt(x + y);
return screenInches;
}
private void display(){
DisplayMetrics metrics = new DisplayMetrics();
WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(metrics);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
params.width = metrics.widthPixels;
params.height = (int)(metrics.heightPixels/2.8);
Log.d("width", String.valueOf(params.width));
Log.d("height", String.valueOf(params.height));
imageView.setLayoutParams(params);
Glide.with(getContext()).load(bible.getImage()).apply(new RequestOptions().centerCrop()).into(imageView);
//imageView.setImageResource(R.drawable.church);
verse.setText(bible.getVerse().toString());
content.setText(bible.getContent().toString());
Log.d("content", bible.getContent().toString());
int inch = (int)( getScreenInches()+0.5 );
Log.d("inch", String.valueOf(3*inch));
//content.setTextSize(3*inch);
toolbar.setTitle(categoryName);
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.share_actions, menu);
}
public void shareDialogPopup(){
AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), R.style.AlertDialogCustom);
builder.setTitle("Share Button");
builder.setMessage("You can share bible verse that you read by clicking this button. Do you want to proceed?");
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(),"You select \'Yes\'.",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, bible.getVerse()+"\n"+bible.getContent()+"\n"+"https://play.google.com/store/apps/details?id=the.holy.catholic.bible");
Intent chooser = Intent.createChooser(intent, "Share");
startActivity(chooser);
}
});
builder.setNegativeButton("Don\'t show this message, again",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences.Editor editor = shareDialog.edit();
editor.putBoolean("printMsg", false);
editor.commit();
Toast.makeText(getContext(),"You select not \'Don\'t show this message, again\'.",Toast.LENGTH_SHORT).show();
}
});
/*AlertDialog alert = builder.create();
alert.show();
alert.getWindow().getAttributes();
TextView textView = (TextView) alert.findViewById(android.R.id.message);
textView.setTextSize(15);
Button btn1 = alert.getButton(DialogInterface.BUTTON_NEGATIVE);
Button btn2 = alert.getButton(DialogInterface.BUTTON_POSITIVE);
btn1.setTextSize(12);
btn2.setTextSize(12);*/
builder.show();
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.share:
shareDialog = getActivity().getSharedPreferences("shareDialog", Context.MODE_PRIVATE);
boolean printMsg = shareDialog.getBoolean("printMsg", true);
if(printMsg){
shareDialogPopup();
}else{
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, bible.getVerse()+"\n"+bible.getContent()+"\n"+"https://play.google.com/store/apps/details?id=the.holy.catholic.bible");
Intent chooser = Intent.createChooser(intent, "Share");
startActivity(chooser);
break;
}
}
return super.onOptionsItemSelected(item);
}
}
The Problem that caused your crash is that you want to instantiate your fragment with a constructor with parameter. but you in android you should create fragment with a non parameter constructor.
so how to solve this problem to pass parameters in to your fragment:
in DailyVerseFragment :
public static DailyVerseFragment newInstance(String myString) {
DailyVerseFragment myFragment = new DailyVerseFragment();
Bundle args = new Bundle();
args.putString("key", myString);
myFragment.setArguments(args);
return myFragment;
}
and in onCreate() function of fragment get it like :
getArguments().getString("key");
and if you want to send Objects you can use putParcable/getParcable.
but my suggestion for you to get toolbar in your fragment is to access it in your fragment like this:
((AppCompatActivity) getActivity()).getSupportActionBar()
I have a medicine_activity class
package com.example.shubhmgajra.medikit;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class Medicine_Activity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "Medicine_Activity";
private Button btnAdd;
private ListView listMeds;
private AppDatabase db;
private ArrayAdapter<MedicineRecord> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicine);
btnAdd = findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(this);
listMeds = findViewById(R.id.listMeds);
listMeds.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MedicineRecord medicineRecord = db.medicineRecordDao().findMedicineById(id + 1);
Intent intent = new Intent(getApplicationContext(), MedicineInputActivity.class);
startActivity(intent);
MedicineInputActivity.getInstance().update(medicineRecord, true);
}
});
db = AppDatabase.getInstance(getApplicationContext());
FeedAdapter feedAdapter = new FeedAdapter(Medicine_Activity.this, R.layout.list_record, db.medicineRecordDao().loadAllRecords());
listMeds.setAdapter(feedAdapter);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onClick(View v) {
Intent intent = new Intent(this, MedicineInputActivity.class);
startActivity(intent);
}
}
In this i am trying to call update() method of another activity namely MedicineInputActivity
package com.example.shubhmgajra.medikit;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
public class MedicineInputActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MedicineInputActivity";
static EditText dosage;
static EditText medName;
static TimePicker timePicker;
static Button btnSave;
Button btnInc;
Button btnDec;
private AppDatabase db;
private static MedicineInputActivity instance;
boolean isEdit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicine_input);
isEdit = false;
instance = this;
dosage = findViewById(R.id.dosage);
dosage.setShowSoftInputOnFocus(false);
dosage.setCursorVisible(false);
medName = findViewById(R.id.medName);
timePicker = findViewById(R.id.simpleTimePicker);
btnInc = findViewById(R.id.btnInc);
btnDec = findViewById(R.id.btnDec);
btnInc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = dosage.getText().toString();
int tempVal = Integer.parseInt(val);
tempVal++;
dosage.setText("" + tempVal);
}
});
btnDec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = dosage.getText().toString();
int tempVal = Integer.parseInt(val);
if (tempVal > 0) {
tempVal--;
}
dosage.setText("" + tempVal);
}
});
btnSave = findViewById(R.id.btnSave);
btnSave.setOnClickListener(this);
db = AppDatabase.getInstance(getApplicationContext());
}
#Override
public void onClick(View v) {
String name = medName.getText().toString();
int min = timePicker.getMinute();
int hour = timePicker.getHour();
String val = dosage.getText().toString();
int dose = Integer.parseInt(val);
MedicineRecord medicineRecord = new MedicineRecord(name, dose, min, hour);
if (validate(name)) {
if (isEdit) {
db.medicineRecordDao().updateRecord(medicineRecord);
} else {
db.medicineRecordDao().insertRecord(medicineRecord);
}
Intent intent = new Intent(this, Medicine_Activity.class);
startActivity(intent);
} else {
Toast toast = Toast.makeText(getApplicationContext(), "Medicine name cannot be empty", Toast.LENGTH_SHORT);
toast.show();
}
}
private boolean validate(String name) {
if (name.length() == 0) {
return false;
} else {
return true;
}
}
public static MedicineInputActivity getInstance() {
return instance;
}
public void update(MedicineRecord medicineRecord, boolean isEdit) {
this.isEdit = isEdit;
dosage.setText(medicineRecord.getDosage());
medName.setText(medicineRecord.getMedName());
timePicker.setHour(medicineRecord.getHour());
timePicker.setMinute(medicineRecord.getMinute());
}
}
What i am trying to achieve is when the user taps the list item, the input activity is loaded and the user can update the record. I wasnt able to find an elegant solution other than making an update method in MedicineInputActivity and then getting an instance of MedicineInputActivity in Medicine_Activity and calling update.
I am getting errors like "Attempt to invoke virtual method 'void com.example.shubhmgajra.medikit.MedicineInputActivity.update() on a null object reference".
You can return data from second activity to the first activity when user is done updating the record. You should start second activity by calling startActivityForResult() instead of startActivity() in the first activity. You should also override onActivityResult() in the first activity. You can read more here.
UPDATE:
I think you want to send selected medicine details from Medicine_Activity to MedicineInputActivity. In that case, you can send selected medicine object by binding it to the intent as follows:
public class Medicine_Activity ... {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
listMeds.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MedicineRecord medicineRecord = db.medicineRecordDao().findMedicineById(id + 1);
Intent intent = new Intent(getApplicationContext(), MedicineInputActivity.class);
intent.putExtra("selectedMedicine", medicineRecord);
startActivity(intent);
MedicineInputActivity.getInstance().update(medicineRecord, true);
}
});
...
}
}
Then on MedicineInputActivity, you should be doing this:
public class MedicineInputActivity ... {
MedicineRecord selectedMedicineRecord;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
selectedMedicineRecord = (MedicineRecord) getIntent().getParcelableExtra("selectedMedicine");
...
}
}
To be able to do this, your MedicineRecord class should implement Parcelable interface.
Im trying to get a single value from JSON using Retrofit, i followed a tutorial but i got an error saying that "Class anonymous class derived from Callback must be either declared ...." .
what im specifically trying to achieve is to echo a single json property value in a empty string like String Axe = ""; and i fill it with a specific value from the json file from the server. here is what i tried.
Json format
"axe1": {"test1"}
The ApiInterface
import com.google.gson.JsonObject;
import retrofit2.Call;
import retrofit2.http.GET;
public interface ApiInterface {
#GET("test.json")
Call<JsonObject> readJsonFromFileUri();
}
The MainActivity
import android.graphics.Typeface;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.Response;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends ActionBarActivity {
DataBaseHandler db;
private AlertDialog dialog;
public static final int IntialQteOfDayId = 8;
private ImageView btn_quotes, btn_authors, btn_favorites, btn_categories, btn_qteday, btn_rateus ;
final Context context = this;
SharedPreferences preferences;
private static final int RESULT_SETTINGS = 1;
// URL of object to be parsed
// This string will hold the results
String data = "";
class Myads{
String bnr;
String intt;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://yourdomain.com/s/ ")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
Call<JsonObject> jsonCall = apiInterface.readJsonFromFileUri();
jsonCall.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
JsonObject json = new JsonObject(body().toString());
Gson gson = new Gson();
Myads ad = gson.fromJson(jsonString, Myads.class);
Log.i(LOG_TAG, String.valueOf(ad.bnr));
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.e(LOG_TAG, t.toString());
}
});
Typeface bold = Typeface.createFromAsset(getAssets(),
"fonts/extrabold.otf");
db = new DataBaseHandler(this);
db.openDataBase() ;
TextView cat = (TextView) findViewById(R.id.titlecat);
cat.setTypeface(bold);
TextView alls = (TextView) findViewById(R.id.titlest);
alls.setTypeface(bold);
TextView fav = (TextView) findViewById(R.id.titlefav);
fav.setTypeface(bold);
TextView qday = (TextView) findViewById(R.id.titleqday);
qday.setTypeface(bold);
TextView rate = (TextView) findViewById(R.id.titleqrate);
rate.setTypeface(bold);
btn_quotes = (ImageView) findViewById(R.id.btn_quotes);
//btn_authors= (Button) findViewById(R.id.btn_authors);
btn_categories = (ImageView) findViewById(R.id.btn_categories);
btn_favorites = (ImageView) findViewById(R.id.btn_favorites);
btn_qteday = (ImageView) findViewById(R.id.btn_qteday);
btn_rateus = (ImageView) findViewById(R.id.btn_rateus);
btn_quotes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,
QuotesActivity.class);
intent.putExtra("mode", "allQuotes");
startActivity(intent);
}
});
/*btn_authors.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent author = new Intent(MainActivity.this,
AuteursActivity.class);
startActivity(author);
}
});*/
btn_favorites.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent favorites = new Intent(MainActivity.this,
QuotesActivity.class);
favorites.putExtra("mode", "isFavorite");
startActivity(favorites);
}
});
btn_categories.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent category = new Intent(MainActivity.this,
CategoryActivity.class);
startActivity(category);
}
});
btn_qteday.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
preferences = PreferenceManager
.getDefaultSharedPreferences(context);
Intent qteDay = new Intent(MainActivity.this,
QuoteActivity.class);
qteDay.putExtra("id",
preferences.getInt("id", IntialQteOfDayId));
qteDay.putExtra("mode", "qteday");
startActivity(qteDay);
}
});
btn_rateus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setMessage(getResources().getString(
R.string.ratethisapp_msg));
builder.setTitle(getResources().getString(
R.string.ratethisapp_title));
builder.setPositiveButton(
getResources().getString(R.string.rate_it),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Intent fire = new Intent(
Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())); //dz.amine.thequotesgarden"));
startActivity(fire);
}
});
builder.setNegativeButton(
getResources().getString(R.string.cancel),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog = builder.create();
dialog.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.menu_settings) {
Intent i = new Intent(this, UserSettingActivity.class);
startActivityForResult(i, RESULT_SETTINGS);
}
return super.onOptionsItemSelected(item);
}
}
So, i want the value of Json axe1 which is test1 to be parsed and put in into the empty string
You are using wrong import:
import com.android.volley.Response;
Replace it with
import retrofit2.Response;
Firstly, your JSON format is invalid, it should be {"axe1": "test1"}.
To store it you could do :
JSONObject json = new JSONObject(response.body().toString());
Log.i(LOG_TAG, json.getString("axe1"));
I have an app with several activities. The up button created by
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
works on all the activities except for one. I've checked the manifest and I can see the parent is set correctly.
Code from activity where the up button doesn't work:
package com.icenibees.apiarymanager;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.icenibees.apiarymanager.sample.SampleDataProvider;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.UUID;
public class ApiaryDetails extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {
public static final String LOGTAG="APIARYMANAGER";
public String apiaryIDDelete = "";
AMDBDataSource mDataSource;
EditText updateApiaryNameInput;
EditText updateApiaryLocationInput;
EditText updateApiaryDescriptionInput;
EditText updateApiarySetupDateInput;
EditText updateApiaryNotesInput;
String updateApiaryidInput;
private TextView tvName, tvDescription, tvLocation, tvSetupDate, tvNotes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_apiary_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDataSource = new AMDBDataSource(this);
mDataSource.open();
final AMClasses.Apiary updateApiary = new AMClasses.Apiary();
// String apiaryId = getIntent().getExtras().getString(ApiaryItemAdapter.APIARY_ID_KEY);
// AMClasses.Apiary item = SampleDataProvider.apiaryItemMap.get(apiaryId);
final AMClasses.Apiary item = getIntent().getExtras().getParcelable(ApiaryItemAdapter.APIARY_RECORD);
if (item == null) {
throw new AssertionError("No data record received!?!");
}
tvName = (TextView) findViewById(R.id.tvApiaryName);
tvLocation = (TextView) findViewById(R.id.tvApiaryLocation);
tvSetupDate = (TextView) findViewById(R.id.tvApiarySetupDate);
tvDescription = (TextView) findViewById(R.id.tvApiaryDescription);
tvNotes = (TextView) findViewById(R.id.tvApiaryNotes);
tvName.setText(item.getApiaryname());
tvLocation.setText(item.getApiarylocation());
tvSetupDate.setText(item.getApiarysetupdate());
tvDescription.setText(item.getApiarydescription());
tvNotes.setText(item.getApiarynotes());
apiaryIDDelete = item.getApiaryid();
Button updateApiaryButton = (Button) findViewById(R.id.btnUpdateApiary);
updateApiaryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view){
updateApiaryidInput = item.getApiaryid();
updateApiaryNameInput = (EditText) findViewById(R.id.tvApiaryName);
updateApiaryLocationInput = (EditText) findViewById(R.id.tvApiaryLocation);
updateApiaryDescriptionInput = (EditText) findViewById(R.id.tvApiaryDescription);
updateApiarySetupDateInput = (EditText) findViewById(R.id.tvApiarySetupDate);
updateApiaryNotesInput = (EditText) findViewById(R.id.tvApiaryNotes);
//updateApiary.setApiaryid(UUID.randomUUID().toString());
updateApiary.setApiaryid(updateApiaryidInput);
updateApiary.setApiaryname(updateApiaryNameInput.getText().toString());
updateApiary.setApiarylocation(updateApiaryLocationInput.getText().toString());
updateApiary.setApiarydescription(updateApiaryDescriptionInput.getText().toString());
updateApiary.setApiarysetupdate(updateApiarySetupDateInput.getText().toString());
updateApiary.setApiarynotes(updateApiaryNotesInput.getText().toString());
Log.i(LOGTAG, "Apiary ID to be updated: " + updateApiary.getApiaryid());
Log.i(LOGTAG, "Update Apiary Name: " + updateApiary.getApiaryname());
Log.i(LOGTAG, "Update Apiary Location: " + updateApiary.getApiarylocation());
Log.i(LOGTAG, "Update Apiary Description: " + updateApiary.getApiarydescription());
Log.i(LOGTAG, "Update Apiary Setup Date: " + updateApiary.getApiarysetupdate());
Log.i(LOGTAG, "Update Apiary Notes: " + updateApiary.getApiarynotes());
mDataSource.updateApiary2DB(updateApiary);
Snackbar.make(findViewById(android.R.id.content),
"Apiary updated", Snackbar.LENGTH_LONG)
.setAction("Action",null).show();
thread.start();
}
}
);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
//ACTIVITY TIMER CLOSER
Thread thread = new Thread(){
#Override
public void run() {
try {
Thread.sleep(2500); // As I am using LENGTH_LONG in Toast
ApiaryDetails.this.finish();
} catch (Exception e) {
e.printStackTrace();
}
}
};
//DELETE MENU
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_edit_apiary, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// SETTINGS MENU CASE STATEMENTS
int id = item.getItemId();
switch (id) {
case R.id.action_apiary_delete:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.app_name);
builder.setMessage("Please confirm you want to delete the apiary?");
builder.setIcon(R.drawable.ic_action_delete);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
mDataSource.deleteApiary(apiaryIDDelete); // Delete Apiary Row
Snackbar.make(findViewById(android.R.id.content),
"Apiary deleted", Snackbar.LENGTH_LONG)
.setAction("Action",null).show();
thread.start();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
break;
}
return true;
}
//DATE PICKER CODE
public void datePickerEditApiary(View view){
NewApiary.DatePickerFragment fragment = new NewApiary.DatePickerFragment();
fragment.show(getSupportFragmentManager(), "date");
}
public void setDate(final Calendar calendar){
final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.UK);
((TextView) findViewById(R.id.tvApiarySetupDate)).setText(dateFormat.format(calendar.getTime()));
}
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar cal = new GregorianCalendar(year, month, dayOfMonth);
setDate(cal);
}
public static class DatePickerFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(),
(DatePickerDialog.OnDateSetListener) getActivity(),year, month, day);
}
}
}
Manifest:
<activity
android:name=".EditApiary"
android:label="#string/title_activity_edit__apiary"
android:parentActivityName=".ApiarySetup"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.icenibees.apiarymanager.ApiarySetup" />
</activity>
<activity
android:name=".ApiaryDetails"
android:label="#string/title_activity_apiary_details"
android:parentActivityName=".EditApiary"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.icenibees.apiarymanager.EditApiary" />
</activity>
<activity
android:name=".EditHive"
android:label="#string/title_activity_edit_hive"
android:parentActivityName=".ApiarySetup"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.icenibees.apiarymanager.ApiarySetup" />
</activity>
I see
getSupportActionBar()
So, you are using AppCompatActivity instance
Probably, you should override onOptionsItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home) {
finish();
return true;
//Or another code here
}
return false;
}
Also, you can add parent activity inside AndroidManifest.xml like this:
API 16+
<activity
....
android:parentActivityName="activity_class_name" />
When I run my app it just opens a white screen and stays there, it slows my whole phone down until I'm forced to shut it down. Logcat says that the first error is "Perfoming stop of activity that is not resumed". I don't really have a onResume on my main file. Should I have a onResume or is there another way to fix this problem?
Here is the error I get when it runs:
05-13 05:13:34.124: E/ActivityThread(27498): Performing stop of activity that is not resumed: {com.example.douglas.topic/com.example.douglas.topic.LoginActivity}
05-13 05:13:34.124: E/ActivityThread(27498): java.lang.RuntimeException: Performing stop of activity that is not resumed: {com.example.douglas.topic/com.example.douglas.topic.LoginActivity}
05-13 05:13:34.124: E/ActivityThread(27498): at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3214)
05-13 05:13:34.124: E/ActivityThread(27498): at android.app.ActivityThread.handleStopActivity(ActivityThread.java:3301)
05-13 05:13:34.124: E/ActivityThread(27498): at android.app.ActivityThread.access$1100(ActivityThread.java:139)
05-13 05:13:34.124: E/ActivityThread(27498): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
05-13 05:13:34.124: E/ActivityThread(27498): at android.os.Handler.dispatchMessage(Handler.java:102)
05-13 05:13:34.124: E/ActivityThread(27498): at android.os.Looper.loop(Looper.java:136)
05-13 05:13:34.124: E/ActivityThread(27498): at android.app.ActivityThread.main(ActivityThread.java:5097)
05-13 05:13:34.124: E/ActivityThread(27498): at java.lang.reflect.Method.invokeNative(Native Method)
05-13 05:13:34.124: E/ActivityThread(27498): at java.lang.reflect.Method.invoke(Method.java:515)
05-13 05:13:34.124: E/ActivityThread(27498): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
05-13 05:13:34.124: E/ActivityThread(27498): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
05-13 05:13:34.124: E/ActivityThread(27498): at dalvik.system.NativeStart.main(Native Method)
Here is the code for my main activity:
package com.example.douglas.topic;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.douglas.topic.LoginActivity;
import com.example.douglas.topic.PostActivity;
import com.example.douglas.topic.PostAdapter;
import com.example.douglas.topic.PostDataProvider;
import com.example.douglas.topic.R;
import com.parse.Parse;
import com.parse.ParseObject;
import com.parse.ParseUser;
public class Lorem extends ActionBarActivity {
//private static final String="POST";
ListView listView;
int[] pic_thumbnail_resource = {R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher,
R.mipmap.ic_launcher, R.mipmap.ic_launcher,};
String[] post_ratings;
String[] post_titles;
PostAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Parse
// Enable Local Datastore.
//Parse.enableLocalDatastore(this);
Parse.initialize(getApplicationContext(), "wHN7DSZyAzVXT5xs5ASDFGwOWasUExbeuePvQvL", "SsvjuJ7e97FsScI12VB7dlv8RilgSoFSw5waIOXM");
//ParseObject testObject = new ParseObject("TestObject");
//testObject.put("foo", "bar");
//testObject.saveInBackground();
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null) {
// do stuff with the user
} else {
// show the signup or login screen
Intent takeUsertoLogin = new Intent(this, LoginActivity.class);
startActivity(takeUsertoLogin);
}
// End Parse
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lorem);
listView = (ListView)findViewById(R.id.list_view);
post_ratings = getResources().getStringArray(R.array.post_ratings);
post_titles = getResources().getStringArray(R.array.post_titles);
//populateListView();
registerClickCallback();
int i = 0;
adapter = new PostAdapter(getApplicationContext(),R.layout.row_layout);
listView.setAdapter(adapter);
for(String titles: post_titles)
{
PostDataProvider dataProvider = new PostDataProvider(pic_thumbnail_resource[i], titles, post_ratings[i]);
adapter.add(dataProvider);
i++;
}
}
private void registerClickCallback(){
ListView list = (ListView) findViewById(R.id.list_view);
list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id){
TextView textView = (TextView) viewClicked;
String message = "You clicked # " + position + ",which is string: " + textView.getText().toString();
Toast.makeText(Lorem.this, message, Toast.LENGTH_LONG).show();
}
});
}
/*
#Override
public void onActivityResult(String requestCode, String resultCode, Intent data){
if (requestCode == "POST")
{
myItems.add
}
super.onActivityResult(requestCode, resultCode, data);
}
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_lorem, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()){
case R.id.post:
aboutItemPost();
break;
case R.id.location:
aboutItemLocation();
break;
case R.id.topic:
aboutItemTopic();
break;
case R.id.sort:
aboutItemSort();
break;
case R.id.login:
aboutItemLogin();
case R.id.Register:
aboutItemRegister();
case R.id.Logout:
aboutItemLogout();
}
return true;
}
private void aboutItemPost(){
Intent intent = new Intent(getApplicationContext(), PostActivity.class);
startActivityForResult(intent, 0);
}
private void aboutItemLocation(){
Intent intent = new Intent(getApplicationContext(), LocationActivity.class);
startActivityForResult(intent, 0);
}
private void aboutItemTopic(){
Intent intent = new Intent(getApplicationContext(), TopicActivity.class);
startActivityForResult(intent, 0);
}
private void aboutItemSort(){
new AlertDialog.Builder(this)
.setTitle("Sort")
.setMessage("This is where the user will sort what they want to see")
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
private void aboutItemLogin(){
Intent takeUsertoLogin = new Intent(this, LoginActivity.class);
startActivity(takeUsertoLogin);
}
private void aboutItemRegister(){
Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
startActivityForResult(intent, 0);
}
private void aboutItemLogout() {
// log the user out
ParseUser.logOut();
// take the user back to log in screen
Intent takeUsertoLogin = new Intent(this, LoginActivity.class);
startActivity(takeUsertoLogin);
}
}
Here is the code for my Login activity:
package com.example.douglas.topic;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.parse.LogInCallback;
import com.parse.Parse;
import com.parse.ParseUser;
import java.text.ParseException;
/**
* Created by Douglas on 5/10/2015.
*/
public class LoginActivity extends Lorem {
protected EditText mUsername;
protected EditText mPassword;
protected Button mLoginButton;
protected Button mCreateAccountButton;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//initialize
mUsername = (EditText)findViewById(R.id.LoginUserName);
mPassword = (EditText)findViewById(R.id.LoginPassword);
mLoginButton = (Button)findViewById(R.id.LoginButton);
mCreateAccountButton = (Button)findViewById(R.id.LoginRegisterButton);
// Listen to when mLoginButton is clicked
mLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get the user input from the edit text and convert into string
String username = mUsername.getText().toString().trim();
String password = mPassword.getText().toString().trim();
// Login the user using Parse SDK
ParseUser.logInInBackground(username, password, new LogInCallback() {
#Override
public void done(ParseUser parseUser, com.parse.ParseException e) {
if (e == null) {
// Success, user logged in
Toast.makeText(LoginActivity.this, "Welcome Back!", Toast.LENGTH_SHORT).show();
Intent takeUserHome = new Intent(LoginActivity.this, Lorem.class);
startActivity(takeUserHome);
} else {
// Failure to Log in, advise user
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage(e.getMessage());
builder.setTitle("Sorry!");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// close the dialog window
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
});
}
}
Thank you for your time.
You have made action before Activity has finished loading:
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lorem);
must be on the top in Your onCreate(). Also, the logcat says, that the problem might be in the LoginActivity. Change the order like I said and come back if this was not the problem.