The code below is the class(Checklist.java) I'm trying to open when checklistbutton is clicked:-
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.Toast;
public class Checklist extends AppCompatActivity {
// ExpandableListAdapter listAdapter;
ExpListViewAdapterWithCheckbox listAdapter;
ExpandableListView expListView;
ArrayList<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the listview
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpListViewAdapterWithCheckbox(this, listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
// Listview Group click listener
expListView.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
// Toast.makeText(getApplicationContext(),
// "Group Clicked " + listDataHeader.get(groupPosition),
// Toast.LENGTH_SHORT).show();
return false;
}
});
// Listview Group expanded listener
expListView.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Expanded",
Toast.LENGTH_SHORT).show();
}
});
// Listview Group collasped listener
expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Collapsed",
Toast.LENGTH_SHORT).show();
}
});
// Listview on child click listener
expListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
Toast.makeText(
getApplicationContext(),
listDataHeader.get(groupPosition)
+ " : "
+ listDataChild.get(
listDataHeader.get(groupPosition)).get(
childPosition), Toast.LENGTH_SHORT)
.show();
return false;
}
});
}
/*
* Preparing the list data
*/
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data
listDataHeader.add("Toiletries");
listDataHeader.add("Clothes");
listDataHeader.add("Essentials");
// Adding child data
List<String> toiletries = new ArrayList<String>();
toiletries.add("Bandages");
toiletries.add("Contacts");
toiletries.add("Contacts Solution");
toiletries.add("Cologne");
toiletries.add("Conditioner");
toiletries.add("Cotton Buds");
toiletries.add("Deodorant");
toiletries.add("Hairbrush");
toiletries.add("Nail Clippers");
toiletries.add("Razor");
toiletries.add("Shampoo");
toiletries.add("Shaving Gel");
toiletries.add("Toothbrush");
toiletries.add("Toothpaste");
List<String> clothes = new ArrayList<String>();
clothes.add("Belt ");
clothes.add("Bras");
clothes.add("Casual Pants");
clothes.add("Casual Shirts");
clothes.add("Heavy Coat");
clothes.add("Jumper");
clothes.add("Light Jacket");
clothes.add("Pyjamas");
clothes.add("Scarf");
clothes.add("Shoes");
clothes.add("Shorts");
clothes.add("Socks");
clothes.add("Swimwear");
List<String> essentials = new ArrayList<String>();
essentials.add("Digital Camera");
essentials.add("Headache Pills");
essentials.add("Fever Pills");
essentials.add("Diarrhea Pills");
essentials.add("Flu Pills");
essentials.add("Cough Medicine");
essentials.add("Powerbank");
essentials.add("USB Power Socket");
essentials.add("Sunglasses");
essentials.add("Earphones");
listDataChild.put(listDataHeader.get(0), toiletries); // Header, Child data
listDataChild.put(listDataHeader.get(1), clothes);
listDataChild.put(listDataHeader.get(2), essentials);
}
}
The code below is where the checklistbutton is stored (ContentAdapter.java) :-
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Calendar;
import java.util.List;
import android.util.Log;
import android.widget.Toast;
public class ContentAdapter extends RecyclerView.Adapter<ContentAdapter.ViewHolder>{
private final Drawable[] mPlacePictures;
List<Flights> mainList;
Context context;
public ContentAdapter(Context context , List<Flights> mainList) {
this.context = context;
this.mainList = mainList;
//instantiate resources for images
Resources resources = context.getResources();
//gets images from drawable and recycles images
TypedArray a = resources.obtainTypedArray(R.array.places_picture);
mPlacePictures = new Drawable[a.length()];
for (int i = 0; i < mPlacePictures.length; i++) {
mPlacePictures[i] = a.getDrawable(i);
}
a.recycle();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()), parent);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Flights flight = mainList.get(position);
holder.picture.setImageDrawable(mPlacePictures[position % mPlacePictures.length]);
holder.DestinationTo.setText(String.valueOf(flight.getDestinationto()));
holder.Date.setText("Departs on: " + String.valueOf(flight.getDate()));
holder.Time.setText("Boarding time: " + String.valueOf(flight.getTime()));
}
#Override
public int getItemCount() {
Log.i("sss size",mainList.size()+"");
return mainList.size();
}
//removes item from list
public void removeItem(int position){
mainList.remove(position);
notifyItemRemoved(position);
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView picture;
public TextView DestinationTo;
public TextView Date;
public TextView Time;
public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.homepage_item_card, parent, false));
picture = (ImageView) itemView.findViewById(R.id.card_image);
DestinationTo = (TextView) itemView.findViewById(R.id.card_title);
Date = (TextView) itemView.findViewById(R.id.card_text2);
Time = (TextView) itemView.findViewById(R.id.card_text);
//view details button
Button button = (Button) itemView.findViewById(R.id.action_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra("Position", getAdapterPosition());
context.startActivity(intent);
}
});
//delete button
final ImageButton deletebutton = (ImageButton) itemView.findViewById(R.id.delete_button);
deletebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onShowQuitDialog();
}
});
//edit button
final ImageButton editbutton = (ImageButton) itemView.findViewById(R.id.edit_button);
editbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, UpdateActivity.class);
intent.putExtra("Position", getAdapterPosition());
context.startActivity(intent);
}
});
//open checklist button
final ImageButton checklistbutton = (ImageButton) itemView.findViewById(R.id.checklist_button);
checklistbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, Checklist.class);
intent.putExtra("Position", getAdapterPosition());
context.startActivity(intent);
}
});
}
//shows dialog to double confirm with user whether they really want to delete record
public void onShowQuitDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(false);
builder.setMessage("Are you sure you want to delete this flight record?");
builder.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
DatabaseHelper db = new DatabaseHelper(context);
db.deleteFlight(mainList.get(getAdapterPosition()));
removeItem(getAdapterPosition());
db.close();
Toast.makeText(context, "Flight deleted!", Toast.LENGTH_LONG).show();
}
});
builder.setNegativeButton(android.R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.create().show();
}
}
}
Finally, the Android.xml file which I think is where the problem should be fixed but do not know where or what to modify to make the checklistbutton work :-
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="project.myapplication">
<application
android:allowBackup="true"
android:icon="#drawable/aeroplan"
android:label="#string/app_name"
android:roundIcon="#drawable/aeroplan"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".Main"
android:label="#string/app_name"
android:theme="#style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DetailActivity"
android:theme="#style/AppTheme.NoActionBar"
android:parentActivityName=".Main">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".Main" />
</activity>
<activity
android:name=".UpdateActivity"
android:theme="#style/AppTheme.NoActionBar"
android:parentActivityName=".Main">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".Main" />
</activity>
<activity android:name=".Checklist"
android:theme="#style/AppTheme.NoActionBar"
android:parentActivityName=".Main"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
To all the gurus out there, I did the Checklist feature on a seperate project and it was working fine before I moved everything carefully into my main project as an added feature. There were no error codes that was shown.
Below is the logcat from right before the app crashes until after clicking the checklistbutton :-
--------- beginning of crash
06-20 02:40:46.453 8487-8487/project.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: project.myapplication, PID: 8487
java.lang.RuntimeException: Unable to start activity ComponentInfo{project.myapplication/project.myapplication.Checklist}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ExpandableListView.setAdapter(android.widget.ExpandableListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ExpandableListView.setAdapter(android.widget.ExpandableListAdapter)' on a null object reference
at project.myapplication.Checklist.onCreate(Checklist.java:39)
at android.app.Activity.performCreate(Activity.java:7009)
at android.app.Activity.performCreate(Activity.java:7000)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Related
here is my manifest file
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="sam.ulf.myapplication3">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.MyApplication3"
tools:targetApi="31">
<activity
android:name=".NotificationActivity"
android:exported="false" />
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".FirebaseBackgroundService"
android:exported="false"
android:process=":remote" >
<intent-filter>
<action android:name="sam.ulf.myapplication3.FirebaseBackgroundService"/>
</intent-filter>
</service>
<receiver android:name=".StartFirebaseAtBoot"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" >
</action>
</intent-filter>
</receiver>
</application>
</manifest>
and here is my mainactivity
package sam.ulf.myapplication3;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import android.app.ActivityManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.messaging.FirebaseMessaging;
import java.io.Serializable;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button on,on2;
Button off,off2;
TextView distance;
DatabaseReference dref;
String status;
//FirebaseFirestore firestore;
//Button btn3 ,btn4;
TextView sens1,sens2,sens3,sens4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseApp.initializeApp(this);
// startService(new Intent(FirebaseBackgroundService.class.getName()));
startService(new Intent(this, FirebaseBackgroundService.class));
//FirebaseBackgroundService s= new FirebaseBackgroundService();
// s.addDataToDatabase();
sens1=(TextView)findViewById(R.id.sensor1);
sens2=(TextView)findViewById(R.id.sensor2);
sens3=(TextView)findViewById(R.id.sensor3);
sens4=(TextView)findViewById(R.id.sensor4);
status="";
on2=(Button)findViewById(R.id.on2);
off2=(Button)findViewById(R.id.off2);
on = (Button) findViewById(R.id.on);
off = (Button) findViewById(R.id.off);
distance = (TextView) findViewById(R.id.distance);
dref= FirebaseDatabase.getInstance().getReference();
dref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
checkService();
status=dataSnapshot.child("database").getValue().toString();
distance.setText(status);
status=dataSnapshot.child("sensor1").getValue().toString();
sens1.setText(status);
status=dataSnapshot.child("sensor2").getValue().toString();
sens2.setText(status);
status=dataSnapshot.child("sensor3").getValue().toString();
sens3.setText(status);
status=dataSnapshot.child("sensor4").getValue().toString();
sens4.setText(status);
String msg="ched lheme";
//NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this,"my notifcation").setSmallIcon(R.drawable.ic_msg)
// .setContentTitle("balesh che8el").setContentText(msg).setAutoCancel(true);
//Intent intent = new Intent(MainActivity.this,NotificationActivity.class);
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//intent.putExtra("message",msg);
//PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
// builder.setContentIntent(pendingIntent);
//NotificationManager notificationManager =(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
// NotificationManagerCompat managerCompat =NotificationManagerCompat.from(MainActivity.this);
// managerCompat.notify(1,builder.build());
// NotificationChannel channel = new NotificationChannel("My Notifcation","My Notifcation",NotificationManager.IMPORTANCE_DEFAULT);
// NotificationManager manager =getSystemService(NotificationManager.class);
//manager.createNotificationChannel(channel);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
on.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("LED_STATUS");
myRef.setValue("1");
}
});
on2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("LED_STATUS2");
myRef.setValue("1");
}
});
off.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("LED_STATUS");
myRef.setValue("0");
}
});
off2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("LED_STATUS2");
myRef.setValue("0");
}
});
}
public void checkService(){
if(isServiceRunning(getApplicationContext(),FirebaseBackgroundService.class)){
Toast.makeText(getApplicationContext(),"service is running",Toast.LENGTH_LONG).show();
}
else
Toast.makeText(getApplicationContext(),"service is not running",Toast.LENGTH_LONG).show();
}
public boolean isServiceRunning(Context c,Class<?>serviceClass) {
ActivityManager activityManager = (ActivityManager) c.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);
for (ActivityManager.RunningServiceInfo runningServiceInfo : services) {
if (runningServiceInfo.service.getClassName().equals(serviceClass.getName())) {
return true;
}
;
}
return false;
}
}
and this is my firebasebackground service class
package sam.ulf.myapplication3;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.google.firebase.*;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.DatabaseRegistrar;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.ktx.Firebase;
public class FirebaseBackgroundService extends Service {
private Context mContext;
private DatabaseReference data;
//private Firebase f = new firebase("https://somedemo.firebaseio-demo.com/");
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference orders = database.getReference();
private ValueEventListener handler;
#Override
public IBinder onBind(Intent arg0) {
// FirebaseApp.initializeApp(this);
return null;
}
// #Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// // FirebaseApp.initializeApp(this);
// mContext=getApplicationContext();//Get the context here
// FirebaseDatabase database2 = FirebaseDatabase.getInstance();
//
// DatabaseReference orders2 = database2.getReference("test");
// orders2.setValue("kolol");
// // addDataToDatabase();
// Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show();
//
// new Thread(new Runnable() {
// #Override
// public void run() {
// while(true){
//
// Log.e("service","service is running");
// }
// }
// });
// // return super.onStartCommand(intent, flags, startId);
// return START_STICKY;
// }
#Override
public void onCreate() {
super.onCreate();
// FirebaseApp.initializeApp(this);
addDataToDatabase();
showToast();
Toast.makeText(this,"test", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"test", Toast.LENGTH_SHORT).show();
orders.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
postNotif("ntebeh");
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
handler = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot arg0) {
postNotif(arg0.getValue().toString());
Log.e("service","service eners change");
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
};
orders.addValueEventListener(handler);
}
void postNotif(String notifString) {
Log.e("service","service is running2");
Toast.makeText(this,"test", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"test", Toast.LENGTH_SHORT).show();
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Toast.makeText(this,"test", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"test", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
// build notification
// the addAction re-use the same intent to keep the example short
Notification n = new Notification.Builder(this)
.setContentTitle("My message")
.setContentText("Subject")
.setSmallIcon(R.drawable.ic_msg)
.setContentIntent(pIntent)
.setAutoCancel(true)
.setStyle(new Notification.BigTextStyle().bigText("")).build();
// .addAction(R.drawable.line, "", pIntent).build();
n.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, n);
}
void showToast() {
if (mContext != null) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(mContext, "Display your message here", Toast.LENGTH_LONG).show();
}
});
}
}
public void addDataToDatabase() {
//setValue method is used to add value to RTFD
orders.setValue("kol",1
);
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed by user.", Toast.LENGTH_LONG).show();
}
}
and this is startfirebaseatboot class
package sam.ulf.myapplication3;
import android.content.BroadcastReceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.google.firebase.FirebaseApp;
/**
* Start the service when the device boots.
*
* #author vikrum
*
*/
public class StartFirebaseAtBoot extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, FirebaseBackgroundService.class));
}
}
and this is build.gradle
buildscript {
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
}
dependencies {
// Add this line
classpath 'com.google.gms:google-services:4.3.10'
//classpath 'com.google.gms:google-services:4.0.1'
//classpath 'com.google.gms:google-services:4.2.0'
}
}
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
id 'com.android.application' version '7.2.1' apply false
id 'com.android.library' version '7.2.1' apply false
}
task clean(type: Delete) {
delete rootProject.buildDir
}
i get this error 2022-06-20 03:49:18.983 1417-1417/sam.ulf.myapplication3 E/AndroidRuntime: FATAL EXCEPTION: main
Process: sam.ulf.myapplication3:remote, PID: 1417
java.lang.RuntimeException: Unable to create service sam.ulf.myapplication3.FirebaseBackgroundService: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process sam.ulf.myapplication3:remote. Make sure to call FirebaseApp.initializeApp(Context) first.
i tried to initialize firebase in mainactivity and also tried to initialize it in service class but it didnt work , im trying to send notification when firebase data change even if the app is not running or terminated.
i know firebase has cloud function but they are not free so im trying to use background service i found this code on github https://gist.github.com/vikrum/6170193
I've been trying to get this app to switch activities by simply clicking the button, but the app simply refreshes and I stay on the same activity. Nothing happens. And if I uncomment the lines of code for my second activity, the OnClick ones, I get null pointer errors. I have no idea what I could be doing wrong. Here's my code in main activity:
package com.example.commontaskslite;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.Button;
import android.widget.CompoundButton;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
private TimePicker alarmClock;
private PendingIntent pendingIntent;
private AlarmManager alarmManager;
private Button search;
private Button redial;
private Button address;
boolean checked = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmClock = (TimePicker) findViewById(R.id.timePicker);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton);
search = (Button) findViewById(R.id.search);
redial = (Button) findViewById(R.id.redial);
address = (Button) findViewById(R.id.address);
search.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
openSearch(view);
}
});
redial.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
openRedial(view);
}
});
address.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
openShowAddress(view);
}
});
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
if(isChecked){
checked = true;
onToggleClicked();
}
else{
checked = false;
onToggleClicked();
}
}
});
}
public void openSearch(View V){
Intent _intent = new Intent(MainActivity.this,Search.class);
startActivity(_intent);
}
public void openRedial(View V){
Intent _intent = new Intent(MainActivity.this,Redial.class);
startActivity(_intent);
}
public void openShowAddress(View V){
Intent _intent = new Intent(MainActivity.this,ShowAddress.class);
startActivity(_intent);
}
public void onToggleClicked(){
long time;
if(checked) {
Toast.makeText(MainActivity.this, "ALARM ON", Toast.LENGTH_SHORT).show();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, alarmClock.getHour());
calendar.set(Calendar.MINUTE, alarmClock.getMinute());
Intent intent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
time = (calendar.getTimeInMillis() - (calendar.getTimeInMillis() % 60000));
if (System.currentTimeMillis() > time) {
if (calendar.AM_PM == 0) {
time = time + (1000 * 60 * 60 * 12);
} else {
time = time + (1000 * 60 * 60 * 24);
}
}
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, 10000, pendingIntent);
}
else{
alarmManager.cancel(pendingIntent);
Toast.makeText(MainActivity.this,"ALARM OFF", Toast.LENGTH_SHORT).show();
AlarmReceiver.ringtone.stop();
}
}
}
Here's the code in the second activity:
package com.example.commontaskslite;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Build;
import android.os.Bundle;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
public class Search extends AppCompatActivity {
private PendingIntent pendingIntent;
private Button alarm;
private Button redial;
private Button address;
private SearchView searchView;
private String searchQuery;
private Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = getIntent();/*
address = (Button) findViewById(R.id.address2);
redial = (Button) findViewById(R.id.redial2);
alarm = (Button) findViewById(R.id.alarm);
searchView = (SearchView) findViewById(R.id.searchView);
searchView.setOnQueryTextListener(new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
searchQuery = s;
return true;
}
#Override
public boolean onQueryTextChange(String s) {
return false;
}
});
address.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
openShowAddress(view);
}
});
redial.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
openRedial(view);
}
});
alarm.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
openMainActivity(view);
}
});*/
}
public void openShowAddress(View V){
Intent _intent = new Intent(this,ShowAddress.class);
startActivity(_intent);
}
public void openRedial(View V){
Intent _intent = new Intent(this,Redial.class);
startActivity(_intent);
}
public void openMainActivity(View V){
Intent _intent = new Intent(this,MainActivity.class);
startActivity(_intent);
}
}
And here's the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.commontaskslite">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.CommonTasksLite">
<activity
android:name=".ShowAddress"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.ALL_APPS"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
<activity
android:name=".Redial"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.CALL"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
<activity
android:name=".Search"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.SEARCH"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".AlarmReceiver">
</receiver>
</application>
</manifest>
summarizing the answer that was found in comments.
Change setContentView(R.layout.activity_main); to another layout other than activity_main in Search Activity.
my launcher activity is loginActivity and i want that when the user selects a college and opens the app for the second time he should be moved to another activity TestYip (and not login activity). that is the launcher activty should change once the user has logged in. for this i made a fuction getCollege in Select_Collage activity which is called from the loginActivity .
but its not working.. the code is given :
Select_Collage
package notes.test.firebase;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class Select_Collage extends AppCompatActivity {
// List view
public ListView lv;
public TextView tv;
public String str;
// Listview Adapter
ArrayAdapter<String> adapter;
// Search EditText
EditText inputSearch;
final String products[] = {"Jaypee university Guna", "Delhi university", "Graphics era", "UPES",
"Amity university", "Saradha university",
"ITM gwalior", "RKDF university", "Indraprast university", "IIT delhi"};
// ArrayList for Listview
ArrayList<HashMap<String, String>> productList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.collage);
if (Build.VERSION.SDK_INT >= 21) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
// Listview Data
/* final String products[] = {"Jaypee university Guna", "Delhi university", "Graphics era", "UPES",
"Amity university", "Saradha university",
"ITM gwalior", "RKDF university", "Indraprast university", "IIT delhi"};
*/
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.college_selection_text_view, R.id.product_name, products);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3){
tv = (TextView) arg1.findViewById(R.id.product_name);
str = tv.getText().toString().trim();
if (str.equals(products[0]))
{
Intent int0 = new Intent(Select_Collage.this, TestYip.class);
startActivity(int0);
}
else if(str.equals(products[1])) {
Intent int1 = new Intent(Select_Collage.this, MainListDisplay.class);
startActivity(int1);
}
}
});
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
Select_Collage.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
public void getCollege () {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
if (str.equals(products[0]))
{
editor.putInt("key", 1);
editor.apply();
//Intent int0 = new Intent(getAppl,TestYip.class);
//Intent int0 = new Intent(getApplicationContext(),TestYip.class);
//startActivity(int0);
} else {
editor.putInt("key", 0);
editor.apply();
}
}
}
LoginActivity
package notes.test.firebase;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class LoginActivity extends AppCompatActivity {
private EditText inputEmail, inputPassword;
private FirebaseAuth auth;
private ProgressBar progressBar;
private Button btnSignup, btnLogin, btnReset;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null ) {
Select_Collage s = new Select_Collage();
//s.getCollege();
//startActivity(new Intent(LoginActivity.this, MainActivity.class));
s.getCollege();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
int i = preferences.getInt("key",0);
///startActivity(new Intent(LoginActivity.this, MainActivity.class));
if (i==1)
{
startActivity(new Intent(LoginActivity.this, TestYip.class));
}
else
startActivity(new Intent(LoginActivity.this, MainActivity.class));
}
// set the view now
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnSignup = (Button) findViewById(R.id.btn_signup);
btnLogin = (Button) findViewById(R.id.btn_login);
btnReset = (Button) findViewById(R.id.btn_reset_password);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
btnSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, SignupActivity.class));
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
//authenticate user
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
// there was an error
if (password.length() < 6) {
inputPassword.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
});
}
});
}
}
Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="notes.test.firebase">
<uses-permission android:name="android.permission.INTERNET" />
<!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".LoginActivity"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_profile"
android:theme="#style/AppTheme.NoActionBar">
</activity>
<activity
android:name=".SignupActivity"
android:label="#string/title_activity_login"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".ResetPasswordActivity"
android:label="#string/title_activity_reset_password"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".TestYip"
android:label="#string/title_test"
android:theme="#style/AppTheme.NoActionBar" />
<activity android:name=".Computer_Notes" />
<activity
android:name=".MainListDisplay"
android:label="#string/Select_Subject"
android:theme="#style/AppTheme.NoActionBar" >
<meta-data
android:name="android.app.default_searchable"
android:value=".SearchResulltsActivity" />
</activity>
<activity
android:name=".Select_Collage"
android:label="#string/Select_Collage"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.app.default_searchable"
android:value=".SearchResulltsActivity" />
</activity>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
<activity android:name=".SearchResulltsActivity"
android:theme="#style/AppTheme.NoActionBar">
<meta-data android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity"/>
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
</application>
</manifest>
please tell how i can move from one activity to another based on a condition.
Dont use LoginActivity as your launcher activity. In your LoginActivity, save some flag value to SharedPreferences to indicate the user has logged in, and then in the onCreate of your other Activity(Set this one to launcher), check for this value, if its not present, then go to LoginActivity.
I will recommend the best way around. Whenever you are stuck on such things, Splash screen will help you.
Let me explain how:-
Just make splash screen as Launcher activity. If you don't want that to display it for much longer, just have the handler run for 1-2 seconds. Now look at the code below.
SplashScreen.java
public class SplashScreen extends AppCompatActivity {
private String email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash);
//SharedPreference to Store API Result
SharedPreferences pref = getApplicationContext().getSharedPreferences("CachedResponse", 0);
SharedPreferences.Editor editor = pref.edit();
editor.apply();
email = pref.getString("login", null);
int SPLASH_TIME_OUT = 3000;
if (email != null) {
//It means User is already Logged in so I will take the user to Select_College Screen
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(SplashScreen.this, Select_College.class);
intent.putExtra("Email", email);
startActivity(intent);
finish();
}
}, SPLASH_TIME_OUT);
} else {
//It means User is not Logged in so I will take the user to Login Screen
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(SplashScreen.this, Login.class);
startActivity(intent);
finish();
}
}, SPLASH_TIME_OUT);
}
}
}
Login.java
public class Login extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor_login);
//SharedPreference to Store API Result
pref = getApplicationContext().getSharedPreferences("CachedResponse", 0);
Login();
}
private void login() {
//If login is successfull, before moving to next activity, store something in sharedpreference with name login. It can be email or just a string as "true"
SharedPreferences.Editor editor = pref.edit();
editor.putString("login", email);
editor.apply();
Intent intent = new Intent(DoctorLogin.this, Select_Collage.class);
intent.putExtra("Email", email);
startActivity(intent);
finish();
}
}
Select_Collage.java
public class Select_Collage extends AppCompatActivity {
private SharedPreferences pref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor_message);
//SharedPreference to Store API Result
pref = getApplicationContext().getSharedPreferences("CachedResponse", 0);
//Somewhere on Signout button click, delete the login sharedpreference
signOut();
}
private void signOut() {
SharedPreferences.Editor editor = pref.edit();
editor.remove("login");
editor.apply();
Intent intent = new Intent(Select_Collage.this, Login.class);
startActivity(intent);
finish();
}
}
So that's how you can solve this problem. Keep Coding :)
Try saving a boolean or int in shared preference.
Set the int or boolean in Select_collage
Get its value in LoginAcitivity , and check condition the way you did it.
I guess the problem with your code is when you check condition in LoginAcitivity , the value in Select_collage activity is not set as it is not created.
https://developer.android.com/training/basics/data-storage/shared-preferences.html
You have to start a splashcreen activity.. in that activity u need to check the condition (oncreate function)
for which activity should be launch to the next..
Hello my App crash if I try to open my AddIP.class fragment
My error code says:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{de.kwietzorek.fulcrumwebview/de.kwietzorek.fulcrumwebview.MainActivity$AddIP}: java.lang.InstantiationException: java.lang.Class has no zero argument constructor
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.kwietzorek.fulcrumwebview" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true">
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity$AddIP"></activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
MainActivity.java
package de.kwietzorek.fulcrumwebview;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import java.util.ArrayList;
public class MainActivity extends FragmentActivity {
String selected;
Spinner spinner;
WebView myWebView;
ArrayList<String> server_name_list = null;
/* Menu */
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.add_server:
Intent intent = new Intent(this, AddIP.class);
this.startActivity(intent);
return true;
case R.id.menu_refresh:
myWebView.reload();
return true;
default:
return true;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//WebView
myWebView = (WebView) findViewById(R.id.webView);
myWebView.setWebViewClient(new WebC());
WebSettings webSettings = myWebView.getSettings();
//JavaScript enable
webSettings.setJavaScriptEnabled(true);
//Server name spinner
if (server_name_list != null) {
spinner = (Spinner) findViewById(R.id.server_spinner);
ArrayAdapter<String> server_adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, server_name_list);
server_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(server_adapter);
server_adapter.notifyDataSetChanged();
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
selected = parent.getItemAtPosition(pos).toString();
myWebView.loadUrl(selected);
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
//WebView Client
public class WebC extends WebViewClient {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
}
}
public class AddIP extends Fragment {
Button btn_back, btn_add;
EditText server_ip, server_name;
String new_server_ip, new_server_name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_ip);
server_ip = (EditText) findViewById(R.id.edit_server_address);
server_name = (EditText) findViewById(R.id.edit_server_name);
/* Back Button */
btn_back = (Button) findViewById(R.id.btn_back);
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});
/* Add IP Button */
btn_add = (Button) findViewById(R.id.btn_add);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*new_server_ip = server_ip.getText().toString();
MainActivity.server_array_ip.add(new_server_ip);*/
new_server_name = server_name.getText().toString();
server_name_list.add(new_server_name);
}
});
}
}
}
Add this method to your faragment :
public AddIP() {
}
in some situation you need an empty constructor method for your fragment
As above. I'm to sure what I'm doing wrong. Here is the code for the MainActivity.java and the code for the NoteMain.java When I click on the Notes button on the home screen when the app loads it says Unfortunately,(app name) has stopped.
I don't know why? Any help is appreciated.
Thanks in advance
MainActivity:
package com.qub.buildersbuddy;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button buttonConverter;
Button buttonCalculator;
Button buttonNotePad;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button ConvertBtn = (Button) findViewById(R.id.butonConverter);
ConvertBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,CentInch.class);
startActivity(intent);
}
});
Button CalcBtn = (Button) findViewById(R.id.buttonCalc);
CalcBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Calculator.class);
startActivity(intent);
}
});
Button NoteBtn = (Button) findViewById(R.id.buttonNotes);
NoteBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,NoteMain.class);
startActivity(intent);
}
});
}
public void setupConverterButton(){
buttonConverter = (Button) findViewById(R.id.butonConverter);
// Button messageButton = (Button) findViewById(R.id.butonConverter);
}
public void CentToInch(){
buttonConverter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//opening the
try{
Class centClass = Class
.forName("com.qub.buildersbuddy.CentInch");
Intent myintent = new Intent(MainActivity.this,centClass);
startActivity(myintent);
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
});
}
public void setupCalculatorButton(){
buttonCalculator = (Button) findViewById(R.id.buttonCalc);
// Button messageButton = (Button) findViewById(R.id.butonConverter);
}
public void Calculator(){
buttonCalculator.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//opening the
try{
Class calcClass = Class
.forName("com.qub.buildersbuddy.Calculator");
Intent myintent = new Intent(MainActivity.this,calcClass);
startActivity(myintent);
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
});
}
public void setupNotesButton(){
buttonNotePad = (Button) findViewById(R.id.buttonNotes);
// Button messageButton = (Button) findViewById(R.id.butonConverter);
}
public void Notes(){
buttonNotePad.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//opening the
try{
Class NoteMain = Class
.forName("com.qub.buildersbuddy.NoteMain");
Intent myintent = new Intent(MainActivity.this,NoteMain);
startActivity(myintent);
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
});
}
}
NoteMain
package com.qub.buildersbuddy;
import java.util.ArrayList;
import java.util.Map;
import java.util.Map.Entry;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
public class NoteMain extends Activity implements OnItemClickListener, OnClickListener {
private SharedPreferences spNotes;
private ArrayList<Note> notes;
private Button addNote;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_main);
this.addNote = (Button) findViewById(R.id.addNoteButton);
this.addNote.setOnClickListener(this);
spNotes = getSharedPreferences("notes", Context.MODE_PRIVATE);
}
#Override
protected void onResume() {
super.onResume();
showNotes();
ListView list = (ListView) findViewById(R.id.listNotes);
CustomAdapter aa = new CustomAdapter(this, getLayoutInflater(), this.notes, spNotes);
list.setAdapter(aa);
list.setOnItemClickListener(this);
}
private void showNotes() {
this.notes = new ArrayList<Note>();
Map map = spNotes.getAll();
for (Object o : map.entrySet()) {
Entry e = (Entry<String, String>) o;
this.notes.add(new Note((String)e.getKey(), (String)e.getValue()));
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
Intent intent = new Intent(this, NoteActivity.class);
intent.putExtra("title", this.notes.get(position).getTitle());
intent.putExtra("text", this.notes.get(position).getText());
startActivity(intent);
}
#Override
public void onClick(View arg0) {
Intent intent = new Intent(this, NoteActivity.class);
startActivity(intent);
}
}
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.qub.buildersbuddy"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.qub.buildersbuddy.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.qub.buildersbuddy.CentInch"
android:label="#string/title_activity_cent_inch" >
</activity>
<activity
android:name="com.qub.buildersbuddy.Calculator"
android:label="#string/title_activity_calculator" >
</activity>
<activity
android:name="com.qub.buildersbuddy.NotePad"
android:label="#string/title_activity_note" >
</activity>
</application>
</manifest>
Its probably because you don't have the NoteMain activity defined in your Manifest.
<activity
android:name="com.qub.buildersbuddy.NoteMain"
android:label="#string/title_activity_note" >
</activity>