listview not showing my message after launching activity [duplicate] - android

This question already has answers here:
FirebaseListAdapter not pushing individual items for chat app - Firebase-Ui 3.1
(2 answers)
Closed 4 years ago.
anyone is thier who can help me ? listview not showing my message after launching activity ,i am trying to create chatting application , i have created chat application successfully , then later for advertising i have added some dependencis and it start to give me error in adapter code ..
first i think something problem in list adapter please check my main activity and other classes
package com.intraday.geeks;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.text.format.DateFormat;
import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.database.FirebaseListAdapter;
import com.firebase.ui.database.FirebaseListOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
public class MainActivity extends AppCompatActivity {
private static int SIGN_IN_REQUEST_CODE = 1;
private FirebaseListAdapter<ChatMessage> adapter;
RelativeLayout activity_Main;
FloatingActionButton fab;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.menu_sign_out)
{
AuthUI.getInstance().signOut(this).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Snackbar.make(activity_Main,"You have been signed out.", Snackbar.LENGTH_SHORT).show();
finish();
}
});
}
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == SIGN_IN_REQUEST_CODE)
{
if(resultCode == RESULT_OK)
{
Snackbar.make(activity_Main,"Successfully signed in.Welcome!", Snackbar.LENGTH_SHORT).show();
displayChatMessage();
}
else{
Snackbar.make(activity_Main,"We couldn't sign you in.Please try again later", Snackbar.LENGTH_SHORT).show();
finish();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity_Main = (RelativeLayout)findViewById(R.id.layoutmain);
fab=(FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText input =findViewById(R.id.input);
FirebaseDatabase.getInstance().getReference().push().setValue(new ChatMessage(input.getText().toString(),
FirebaseAuth.getInstance().getCurrentUser().getEmail()));
input.setText("");
}
});
if(FirebaseAuth.getInstance().getCurrentUser()==null) {
startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().build(),SIGN_IN_REQUEST_CODE);
}
else{
Snackbar.make(activity_Main,"Welcome "+FirebaseAuth.getInstance().getCurrentUser().getEmail(),Snackbar.LENGTH_SHORT).show();
//Load content
displayChatMessage();
}
}
private void displayChatMessage() {
ListView listOfMessage = (ListView)findViewById(R.id.list_of_message);
Query query = FirebaseDatabase.getInstance().getReference().child("chats");
FirebaseListOptions<ChatMessage> options =
new FirebaseListOptions.Builder<ChatMessage>()
.setQuery(query, ChatMessage.class)
.setLayout(android.R.layout.simple_list_item_1)
.build();
adapter = new FirebaseListAdapter<ChatMessage>(options)
{
#Override
protected void populateView(View v, ChatMessage model, int position) {
//Get references to the views of list_item.xml
TextView messageText, messageUser, messageTime;
messageText = (TextView) v.findViewById(R.id.message_Text);
messageUser = (TextView) v.findViewById(R.id.message_user);
messageTime = (TextView) v.findViewById(R.id.message_time);
messageText.setText(model.getMessageText());
messageUser.setText(model.getMessageuser());
messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", model.getMessageTime()));
}
};
listOfMessage.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
this is my chatMessage class
package com.intraday.geeks;
import java.util.Date;
/**
* Created by Administrator on 6/8/2018.
*/
public class ChatMessage {
private String MessageText;
private String Messageuser;
private Long MessageTime;
public ChatMessage(String messageText, String messageuser) {
this.MessageText = messageText;
this.Messageuser = messageuser;
MessageTime= new Date().getTime();
}
public ChatMessage() {
}
public String getMessageText() {
return MessageText;
}
public void setMessageText(String messageText) {
MessageText = messageText;
}
public String getMessageuser() {
return Messageuser;
}
public void setMessageuser(String messageuser) {
Messageuser = messageuser;
}
public Long getMessageTime() {
return MessageTime;
}
public void setMessageTime(Long messageTime) {
MessageTime = messageTime;
}
}
this is my MainActivity Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layoutmain"
android:layout_width="match_parent"
android:background="#drawable/gg"
android:layout_height="match_parent"
tools:context="com.intraday.geeks.MainActivity">
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:src="#drawable/ic_send"
android:id="#+id/fab"
android:tint="#android:color/white"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
app:fabSize="mini"/>
<EditText
android:id="#+id/input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textInputLayout"
android:layout_alignParentStart="true"
android:hint="message"
android:textColor="#ffff"
android:textColorHint="#ffff"
/>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="#id/fab"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:id="#+id/textInputLayout" />
<ListView
android:id="#+id/list_of_message"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_above="#id/fab"
android:stackFromBottom="true"
android:dividerHeight="20dp"
android:divider="#android:color/transparent"
android:layout_width="match_parent"
android:layout_marginBottom="16dp"
android:layout_height="match_parent"></ListView>
</RelativeLayout>
**this is my list_iteam . xml**
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scroll"
android:background="#drawable/border_style"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="10dp"
android:id="#+id/message_user"
android:visibility="invisible"/>
<TextView
android:id="#+id/message_time"
android:layout_width="fill_parent"
android:layout_height="18dp"
android:layout_alignParentBottom="#id/message_Text"
android:textColor="#ffff"
android:textSize="15dp"
/>
<TextView
android:id="#+id/message_Text"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_alignParentStart="true"
android:layout_below="#+id/message_time"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#ffff"
android:textSize="20sp"
android:textStyle="bold"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="90dp" />
</RelativeLayout>
this is my Menifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.intraday.geeks">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<!-- This meta-data tag is required to use Google Play Services. -->
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<!-- Include the AdActivity configChanges and theme. -->
<activity
android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
android:theme="#android:style/Theme.Translucent" />
</application>
</manifest>

Add this
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}

Related

Application has stopped working using Android Studio, no errors detected in code

My app should have a button on the main page that navigates to the second page and on the second page, there is some edit text boxes and 2 buttons. Whenever i run the app, I can get to the main page but when I attempt to go to the second page the app stops working. I notice I get this response:
Emulator: emulator: INFO: QtLogger.cpp:68: Critical: Uncaught TypeError: Cannot read property 'update' of undefined (qrc:/html/js/location-mock-web-channel.js:130, (null))
I'm not sure why is doing this. Do i need to update something or am i missing a crucial step in my code?
Please help :(.
Main.java
package com.example.hw2;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view) {
startActivity(new Intent("com.example.hw2.SecondActivity"));
}
}
Second.java
package com.example.hw2;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
public class SecondActivity extends Activity {
DBHandler myDb;
EditText editName, editSName, editEmail, editMobile;
Button btnAddContact,btnViewAll, btnReturn;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DBHandler(this);
editName = (EditText)findViewById(R.id.editText_name);
editSName = (EditText)findViewById(R.id.editText_sname);
editEmail = (EditText)findViewById(R.id.editText_email);
editMobile = (EditText)findViewById(R.id.editText_mobile);
btnAddContact = (Button) findViewById(R.id.button_add);
btnViewAll = (Button) findViewById(R.id.button_viewAll);
btnReturn = (Button) findViewById(R.id.button_goback);
AddData();
ViewAll();
Return();
}
public void AddData(){
btnAddContact.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
boolean isInserted= myDb.insertData(editName.getText().toString(),editSName.getText().toString(),editEmail.getText().toString(),editMobile.getText().toString());
if(isInserted)
Toast.makeText(SecondActivity.this, "Contact Saved", Toast.LENGTH_LONG).show();
else
Toast.makeText(SecondActivity.this, "Failed to Save", Toast.LENGTH_LONG).show();
}
});
}
public void ViewAll(){
btnViewAll.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Cursor res = myDb.displayContacts();
if(res.getCount()==0){
showMessage("Error", "No Contacts");
return;
}
StringBuffer buffer =new StringBuffer();
while(res.moveToNext()){
buffer.append("ID:"+res.getString(0)+"\n");
buffer.append("Name :"+res.getString(1)+"\n");
buffer.append("Last Name:"+res.getString(2)+"\n");
buffer.append( "Mobile:"+res.getString(4)+"\n");
buffer.append("Email:"+res.getString(3)+"\n\n");
}
showMessage("Contact", buffer.toString());
}
});
}
public void Return(){
btnReturn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
finish();
}
});
}
public void showMessage(String Title, String Contact){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(Title);
builder.setMessage(Contact);
builder.show();
}
}
DBhandler.java
package com.example.hw2;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class DBHandler extends SQLiteOpenHelper {
public static final String DATABASE_NAME="main.db";
public static final String TABLE_NAME="CONTACT";
public static final String COL_1="ID";
public static final String COL_2="NAME";
public static final String COL_3="SNAME";
public static final String COL_4="EMAIL";
public static final String COL_5="MOBILE";
public DBHandler(Context context){
super(context, DATABASE_NAME, null, 1);
}
public DBHandler(#Nullable Context context, #Nullable String name, #Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table "+TABLE_NAME+"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, SNAME TEXT, EMAIL VARCHAR(20), MOBILE INTEGER(12) )");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String sname,String email, String mobile) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, name);
contentValues.put(COL_3, sname);
contentValues.put(COL_4, email);
contentValues.put(COL_5, mobile);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor displayContacts() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
return res;
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click the button to add a contact"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginTop="56dp"
android:onClick="onClick"
android:text="Display second activity"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.hw2.SecondActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_margin="5dp"
>
<EditText
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="5dp"
android:text="Name"
android:id="#+id/editText_name"
/>
<EditText
android:layout_marginTop="5dp"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="Last Name"
android:id="#+id/editText_sname"
/>
<EditText
android:layout_marginTop="5dp"
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="#+id/editText_email"
android:inputType="textEmailAddress"
android:text="Email"
/>
<EditText
android:layout_marginTop="5dp"
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="#+id/editText_mobile"
android:inputType="phone"
android:text="Mobile"
/>
<Button
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="#+id/button_add"
android:text="Save"
/>
<Button
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="#+id/button_viewAll"
android:text="View All"
/>
<Button
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="#+id/button_goback"
android:text="Return"
/>
</LinearLayout>
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hw2">
<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/AppTheme">
<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=".SecondActivity">
<intent-filter >
<action android:name="com.example.hw2.SecondActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
You are starting second activity wrong. Instead of
startActivity(new Intent("com.example.hw2.SecondActivity"));
change it to
startActivity(new Intent(this, SecondActivity.class));
Also, the layout attached in your Second activity is of first activity. This would cause NullPointerException when accessing the views in SecondActivity.
Change
setContentView(R.layout.activity_main);
to
setContentView(R.layout.activity_second);
You need two values to move pages, these are origin and destination
The origin is the page you are on and the destination of the page you are redirecting to
try it
startActivity(new Intent(this,SecondActivity.class));
this = activity or context origin page
change
setContentView(R.layout.activity_main);
to
setContentView(R.layout.second);
In your second activity, You are trying to inflate wrong view.

whenever i try to start the webview activity though a button it says the app has stopped

I am trying to create an app that implements the webview activity whenever you press a button but. Whenever I press it gives me an, unfortunately, message instead of going to it. Everything seems to be right and I put it through the debugger and it gave me the error "E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.time_app, PID: 7599
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.time_app/com.example.time_app.Browser}: android.view.InflateException: Binary XML file line #8: Error inflating class android.webkit.WebView".It says the problem is at line 42 in the browser.java file which is "setContentView(R.layout.activity_browser);".Ive checked all of my lines of code and it all seems right.
Browser.java
package com.example.time_app;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.util.Calendar;
import java.util.Date;
public class Browser extends AppCompatActivity {
//creating the webview variable
WebView wb;
//the end variable takes in the finshed load time(it is a long function because of the number length
long end;
//this is just a varibale to be used for the alert code
final Context context = this;
//this is the total number converted as a string because the alert function does not take in float
String numberAsString;
//the start variable takes in the start load time(it is a long function because of the number length
long start;
//The total variable takes in the substraction of the end and start and is a float variale do to its shorter length
float total;
Date end_Time;
Date start_Time;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browser);
wb = (WebView) findViewById(R.id.webview);
wb.setWebViewClient(new WebViewClient() {
//this function records the load time
public void onPageStarted(WebView view, String url, Bitmap favicon) {
start = System.currentTimeMillis();
start_Time = Calendar.getInstance().getTime();
}
//This function will take in the finished load time and create an alert
#RequiresApi(api = Build.VERSION_CODES.O)
public void onPageFinished(WebView view, String url) {
end = System.currentTimeMillis();
total=end-start;
end_Time = Calendar.getInstance().getTime();
// Total is the difference in milliseconds.
// Dividing by 1000, you convert it to seconds
numberAsString = String.valueOf(total/1000);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Your Load Time");
// set dialog message
alertDialogBuilder
.setMessage("Elapsed Time:"+numberAsString+"\n"+"Start Time:"+start_Time+"\n"+"EndTime:"+end_Time+"\n")
.setCancelable(false)
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
//declaring and setting the web setting variable
WebSettings webSettings = wb.getSettings();
//setting up the javascript to allow thw browser to use javascript
webSettings.setJavaScriptEnabled(true);
//loading url
wb.loadUrl("https://www.aa.com");
}
}
activity_browser.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Browser">
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout >
Manual_menu.java
package com.example.time_app;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import android.content.Intent;
import android.os.Bundle;
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 Manual_menu extends AppCompatActivity {
public ListView lv;
public EditText nametxt;
public Button addbtn,updatebtn,deletebtn,submit;
public ArrayList<String> names=new ArrayList<String>();
public ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manual_menu);
lv=(ListView) findViewById(R.id.Listview1);
nametxt=(EditText) findViewById(R.id.nametxt);
addbtn=(Button) findViewById(R.id.addbtn);
updatebtn=(Button) findViewById(R.id.updatebtn);
deletebtn=(Button) findViewById(R.id.deletebtn);
submit=(Button) findViewById(R.id.Submit_btn);
//adapter
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice,names);
lv.setAdapter(adapter);
//Set Selected Item
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
nametxt.setText(names.get(i));
}
});
//add button event
addbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
add();
}
});
//update button event
updatebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
update();
}
});
//delete button event
deletebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
delete();
}
});
//clear button event
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivityDecision();
}
});
}
//add
private void add()
{
String name=nametxt.getText().toString();
if(!name.isEmpty() && name.length()>0)
{
//Add
adapter.add(name);
//Refresh
adapter.notifyDataSetChanged();
nametxt.setText("");
Toast.makeText(getApplicationContext(), "Added " +name,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "!!Nothing to Add " +name,Toast.LENGTH_SHORT).show();
}
}
//Update
private void update()
{
String name=nametxt.getText().toString();
int pos=lv.getCheckedItemPosition();
if(!name.isEmpty() && name.length()>0)
{
//Remove Item
adapter.remove(names.get(pos));
//insert
adapter.insert(name,pos);
//refresh
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Updated " +name,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "!!Nothing to Update " ,Toast.LENGTH_SHORT).show();
}
}
//delete
private void delete()
{
int pos=lv.getCheckedItemPosition();
if(pos > -1)
{
//remove
adapter.remove(names.get(pos));
//refresh
adapter.notifyDataSetChanged();
nametxt.setText("");
Toast.makeText(getApplicationContext(), "Deleted " ,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "!!Nothing to delete " ,Toast.LENGTH_SHORT).show();
}
}
//Submit
private void openActivityDecision()
{
Intent intent=new Intent(this, Browser.class);
startActivity(intent);
}
}
activity_manual_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Manual_menu">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="35dp"
android:text="Name :"
/>
<EditText
android:id="#+id/nametxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView1"
android:ems="10"
/>
<ListView
android:id="#+id/Listview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/addbtn"
android:choiceMode="singleChoice"
android:layout_marginTop="20dp">
</ListView>
<Button
android:id="#+id/addbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Listview1"
android:layout_below="#+id/nametxt"
android:layout_marginTop="19dp"
android:text="add" />
<Button
android:id="#+id/updatebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Listview1"
android:layout_toRightOf="#+id/addbtn"
android:layout_marginTop="19dp"
android:text="Update" />
<Button
android:id="#+id/Submit_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Listview1"
android:layout_alignParentRight="true"
android:layout_marginTop="19dp"
android:text="Submit" />
<Button
android:id="#+id/deletebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Listview1"
android:layout_toRightOf="#+id/updatebtn"
android:layout_marginTop="19dp"
android:text="Delete" />
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.time_app">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<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/AppTheme">
<activity android:name=".File_menu"></activity>
<activity android:name=".Browser" />
<activity android:name=".file_load" />
<activity android:name=".Manual_menu" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Trouble in getting Location in Android SDK

I am new to Android, trying to implement Location Based Service but, I am getting errors. I am getting confused now.
Here are my files:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.om.locationdemo.MainActivity">
<Button
android:text="Get Location"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:id="#+id/button" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="#+id/textView"
android:textStyle="bold"
android:textAlignment="center"
android:textSize="20sp"
android:layout_below="#+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="37dp" />
<Button
android:text="Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="137dp"
android:id="#+id/button2" />
</RelativeLayout>
**AndroidManifest.xml**
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.om.locationdemo">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
</activity>
</application>
</manifest>
MainActivity.java
package com.example.om.locationdemo;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.test.mock.MockContentProvider;
import android.test.mock.MockContext;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button b1, b2;
TextView tv;
LocationManager lmngr;
LocationListener llm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button);
b2 = (Button) findViewById(R.id.button2);
tv = (TextView) findViewById(R.id.textView);
lmngr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
llm = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
tv.setText("Latitude = " + location.getLatitude() + " Longitude's = " + location.getLongitude());
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(MainActivity.this, "Please Enable Location Service", Toast.LENGTH_LONG).show();
}
};
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
lmngr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, llm);
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
lmngr.requestLocationUpdates
(LocationManager.NETWORK_PROVIDER,0, 0, llm);
}
});
}
}

java.lang.NullPointerException: Attempt to invoke virtual method android in OnClickListener

I am new to android. I trying to build a simple application but i have encounter the NullPointerException when trying to invoke my onClickListener. Being stuck for hours to debug but fail to discover where the error. And i need help to fix it. Here are my code.
Exception
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.win8user.kidlearnmath, PID: 2593
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.win8user.kidlearnmath.PlayerActivity.displayDialog(PlayerActivity.java:63)
at com.example.win8user.kidlearnmath.PlayerActivity.access$000(PlayerActivity.java:24)
at com.example.win8user.kidlearnmath.PlayerActivity$1.onClick(PlayerActivity.java:47)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<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=".PlayerActivity"></activity>
</application>
PlayerActivity.java
package com.example.win8user.kidlearnmath;
import android.app.Dialog;
import android.database.Cursor;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.example.win8user.kidlearnmath.mDataObject.Player;
import com.example.win8user.kidlearnmath.mDatabase.PlayerAdapter;
import com.example.win8user.kidlearnmath.mListView.CustomAdapter;
import java.util.ArrayList;
public class PlayerActivity extends AppCompatActivity {
ListView lv;
EditText nameEditText;
Button saveBtn, retrieveBtn;
ArrayList<Player> players = new ArrayList<>();
CustomAdapter adapter;
final boolean forUpdate = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
lv = (ListView) findViewById(R.id.lv);
adapter = new CustomAdapter(this, players);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
displayDialog(false);
}
});
this.getPlayers();
}
private void displayDialog(boolean forUpdate){
final Dialog d = new Dialog(this);
d.setContentView(R.layout.dialog_layout);
nameEditText = (EditText) findViewById(R.id.nameEditTxt);
saveBtn = (Button) findViewById(R.id.saveBtn);
retrieveBtn = (Button) findViewById(R.id.cancelBtn);
if(!forUpdate){
d.setTitle("Add New Player");
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(nameEditText.getText().toString().length() == 0){
nameEditText.setError("Name is required");
}
else{
save(nameEditText.getText().toString());
d.dismiss();
}
}
});
retrieveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getPlayers();
d.dismiss();
}
});
}
else {
d.setTitle("Edit Player Name");
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(nameEditText.getText().toString().length() == 0){
nameEditText.setError("Name is required");
}
else{
update(nameEditText.getText().toString());
d.dismiss();
}
}
});
retrieveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getPlayers();
d.dismiss();
}
});
}
d.show();
}
private void save(String name){
PlayerAdapter db = new PlayerAdapter(this);
db.openDB();
boolean save;
save = db.add(name);
if(save){
nameEditText.setText("");
getPlayers();
}
else{
Toast.makeText(this,"Unable To Save",Toast.LENGTH_SHORT).show();
}
}
private void getPlayers(){
players.clear();
PlayerAdapter db = new PlayerAdapter(this);
db.openDB();
Cursor c = db.retrieve();
Player player = null;
while (c.moveToNext()){
String pid = c.getString(0);
String pname = c.getString(1);
player = new Player();
player.setPlayerId(pid);
player.setPlayerName(pname);
players.add(player);
}
db.closeDB();
lv.setAdapter(adapter);
}
private void update(String newname){
//Get id of player
String pid = adapter.getSelectedItemID();
//UPDATE
PlayerAdapter db = new PlayerAdapter(this);
db.openDB();
boolean updated = db.update(newname,pid);
db.closeDB();
if(updated){
nameEditText.setText(newname);
getPlayers();
}
else {
Toast.makeText(this,"Unable to Update",Toast.LENGTH_SHORT).show();
}
}
private void delete(){
String pid = adapter.getSelectedItemID();
//DELETE
PlayerAdapter db = new PlayerAdapter(this);
db.openDB();
boolean deleted = db.delete(pid);
db.closeDB();
if(deleted){
getPlayers();
}
else {
Toast.makeText(this,"Unable to Delete",Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return true;
}
#Override
public boolean onContextItemSelected(MenuItem item) {
CharSequence title = item.getTitle();
if(title=="New"){
displayDialog(!forUpdate);
}else if(title=="Edit"){
displayDialog(forUpdate);
}else if(title=="Delete"){
delete();
}
return super.onContextItemSelected(item);
}
}
activity_player.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.win8user.kidlearnmath.PlayerActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"
/>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_player" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_input_add" />
dialog_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_margin="1dp"
card_view:cardCornerRadius="10dp"
card_view:cardElevation="5dp"
android:gravity="center"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<android.support.design.widget.TextInputLayout
android:id="#+id/nameLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="#+id/nameEditTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:hint="Name"/>
</android.support.design.widget.TextInputLayout>
<Button android:id="#+id/saveBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Save"
android:clickable="true"
android:background="#color/colorAccent"
android:layout_marginTop="40dp"
android:textColor="#android:color/white"/>
<Button android:id="#+id/cancelBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Cancel"
android:clickable="true"
android:background="#color/colorAccent"
android:layout_marginTop="40dp"
android:textColor="#android:color/white"/>
</LinearLayout>
Thanks in advance.
You are calling findViewById() which is a method on the Activity. The Dialog is not part of the same Window as the Activity. You want to call findViewById() on the Dialog instance.
d.findViewById(R.id.saveBtn)

Android SharedPreferences not removed until app is restarted

I'm stucked with this problem.
In my app I use SharedPrefManager as a singleton class, in order to keep some "session" information. In this simple example app I just save the user's name and a boolean that indicates whether or not the user is logged in to skip the login screen if already logged, or to show it if not.
When starting the app, after the splashscreen, the LoginActivity is started.
At this point, if the user has already logged in before (without logging out later, that means the boolean value of isuseradded SharedPreferences variable is true), the user is redirected to the MainActivity, otherwise he sees the login form, where he can insert username and password and make a REST API request to a remote server.
If the login is correct, the MainActivity starts and simply shows the name of the user, taken from the response JSON obtained by the remote login REST API call.
Now, here is my problem: I want to implement a simple logout feature that deletes (or changes, as in this test app) all the information stored by SharedPreferences and takes the user back to the LoginActivity.
But when I click logout, the values for SharedPreferences are updated only in MainActivity, while in LoginActivity they remain the same as before, so when the user is redirected to LoginActivity, the isusedadded shared preference is still true, and the user is redirected back to MainActivity.
But SharedPrefManager class is a singleton, so its values should be the same in every part of the app, because only one instance of it exists, so why do I have this behavior?
You can test the app by downloading the full app code here and using these credentials for login:
Username: 52346
Password: 32fjueM1 (case sensitive)
Here follows my code.
App.java:
package mypackage.sharedprefapp;
import android.app.Application;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class App extends Application
{
private RequestQueue mRequestQueue;
private static App mInstance;
#Override
public void onCreate()
{
super.onCreate();
mInstance = this;
}
public static synchronized App getInstance()
{
return mInstance;
}
// This method returns the queue containing GET/POST requests
public RequestQueue getRequestQueue()
{
if(mRequestQueue == null)
{
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
// This method adds a GET/POST request to the queue of requests
public <T> void addToRequestQueue(Request<T> req)
{
getRequestQueue().add(req);
}
}
SplashActivity.java
package mypackage.sharedprefapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class SplashActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
}
}
LoginActivity.java
package mypackage.sharedprefapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
public class LoginActivity extends AppCompatActivity
{
private static final String TAG = "LoginActivity";
Button loginButton;
EditText userIDInput, passwordInput;
TextView loginErrorMsg, title;
LinearLayout bgLayout;
SharedPrefManager sharedPrefManager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
sharedPrefManager = SharedPrefManager.getInstance(this);
Log.i("HERE", "LoginActivity onCreate: "+sharedPrefManager.isUserAdded());
}
#Override
protected void onResume()
{
super.onResume();
sharedPrefManager = SharedPrefManager.getInstance(this);
Log.i("HERE", "LoginActivity onResume: "+sharedPrefManager.getUserName());
// if the user is already logged in
if(sharedPrefManager.isUserAdded())
{
Log.i(TAG, "User is logged in");
// if the device is connected to the internet
if(Utils.isDeviceOnline(this))
{
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
// if the device is offline
else
{
Log.i(TAG, "Internet connection is not available");
}
}
// if the user is not logged in
else
{
Log.i(TAG, "User is NOT logged in");
setContentView(R.layout.activity_login);
title = (TextView) findViewById(R.id.title);
loginErrorMsg = (TextView) findViewById(R.id.login_errorText);
userIDInput = (EditText) findViewById(R.id.login_id_paziente);
passwordInput = (EditText) findViewById(R.id.login_password);
loginButton = (Button) findViewById(R.id.login_submitButton);
bgLayout = (LinearLayout) findViewById(R.id.login_parentLayout);
// Bind a custom click listener to the login button
loginButton.setOnClickListener(new LoginButtonClickListener(this));
// Bind a custom click listener to the background layout
// so that the soft keyboard is dismissed when clicking on the background
bgLayout.setOnClickListener(new LoginBackgroundClickListener());
}
}
}
LoginButtonClickListener.java
package mypackage.sharedprefapp;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class LoginButtonClickListener implements View.OnClickListener
{
private Context context;
private SharedPrefManager sharedPrefManager;
public LoginButtonClickListener(Context c)
{
this.context = c;
}
#Override
public void onClick(View v)
{
sharedPrefManager = SharedPrefManager.getInstance(context);
// if internet connection is available
if(Utils.isDeviceOnline(context))
{
// Verify login credentials from DB
doLogin();
}
else {}
}
// check login data with REST API
private void doLogin()
{
final String paziente_id = ((EditText)((Activity)context).findViewById(R.id.login_id_paziente)).getText().toString();
final String paziente_password = ((EditText)((Activity)context).findViewById(R.id.login_password)).getText().toString();
StringRequest stringRequest = new StringRequest
(
Request.Method.POST,
"http://www.stefanopace.net/iCAREServer/api/v1/index.php/login",
new Response.Listener<String>()
{
#Override
public void onResponse(String s)
{
try
{
JSONObject obj = new JSONObject(s);
if(!obj.getBoolean("error"))
{
String name = obj.getString("nome");
sharedPrefManager.addUser(name);
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);
}
else
{
Toast.makeText(context, "Error on JSON response", Toast.LENGTH_LONG).show();
}
}
catch(JSONException e)
{
e.printStackTrace();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError volleyError)
{
Toast.makeText(context, volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError
{
Map<String, String> params = new HashMap<>();
params.put("id_paziente", paziente_id);
params.put("password", paziente_password);
return params;
}
};
App.getInstance().addToRequestQueue(stringRequest);
}
}
LoginBackgroundClickListener.java
package mypackage.sharedprefapp;
import android.view.View;
public class LoginBackgroundClickListener implements View.OnClickListener
{
#Override
public void onClick(View v)
{
Utils.hideSoftKeyboard(v);
}
}
MainActivity.java
package mypackage.sharedprefapp;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
{
private static final String TAG = "MainActivity";
TextView personName;
SharedPrefManager sharedPrefManager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
sharedPrefManager = SharedPrefManager.getInstance(this);
setContentView(R.layout.activity_main);
personName = (TextView) findViewById(R.id.person_name);
Log.i(TAG, "Value: "+sharedPrefManager.isUserAdded());
personName.setText(sharedPrefManager.getUserName());
}
#Override
protected void onResume()
{
super.onResume();
sharedPrefManager = SharedPrefManager.getInstance(this);
Log.w("MainActivity", "onResume");
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
// Logout button has been pressed
case R.id.logout_action:
{
Log.i("Logout pressed", "Logout button has been pressed!");
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Are you sure you want to logout?");
alertDialogBuilder.setPositiveButton
(
"Yes",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1)
{
boolean success = sharedPrefManager.removeDataFromSharedPreference();
// if the operation is OK
if(success)
{
// go to the login activity
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
else
{
Toast.makeText(getApplicationContext(), "Error during logout", Toast.LENGTH_LONG).show();
}
}
}
);
alertDialogBuilder.setNegativeButton
(
"No",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1)
{}
}
);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
return true;
}
}
return super.onOptionsItemSelected(item);
}
}
SharedPrefManager.java
package mypackage.sharedprefapp;
import android.content.Context;
import android.content.SharedPreferences;
public final class SharedPrefManager
{
private static final String TAG = "SharedPrefManager";
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
private static SharedPrefManager mInstance;
private static final String SHARED_PREF = "sharedprefs";
private static final String KEY_IS_USER_ADDED = "isuseradded";
public static final String KEY_USER_NAME = "username";
private SharedPrefManager(Context context)
{
sharedPreferences = context.getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
sharedPreferences.registerOnSharedPreferenceChangeListener(new LocalSharedPreferencesChangeListener());
}
public static SharedPrefManager getInstance(Context context)
{
if(mInstance == null)
{
mInstance = new SharedPrefManager(context);
}
return mInstance;
}
// add an user to the shared preferences
public boolean addUser(String name)
{
editor.putString(KEY_USER_NAME, name);
editor.putBoolean(KEY_IS_USER_ADDED, true);
return editor.commit();
}
public boolean removeDataFromSharedPreference()
{
editor.putString(KEY_USER_NAME, "HELLO");
editor.putBoolean(KEY_IS_USER_ADDED, false);
return editor.commit();
}
public String getUserName()
{
return sharedPreferences.getString(KEY_USER_NAME, "");
}
public boolean isUserAdded()
{
return sharedPreferences.getBoolean(KEY_IS_USER_ADDED, false);
}
}
Utils.java
package mypackage.sharedprefapp;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
public class Utils
{
public static void hideSoftKeyboard(View view)
{
InputMethodManager inputMethodManager = (InputMethodManager) view.getContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
// This method checks if the device is connected to the Internet
public static boolean isDeviceOnline(final Context context)
{
final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager != null)
{
final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
boolean isOnline = (networkInfo != null && networkInfo.isConnectedOrConnecting());
if(!isOnline)
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setCancelable(false);
alertDialog.setTitle("Error");
alertDialog.setMessage("Internet is not available");
alertDialog.setPositiveButton("Try again", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
// Reload the Activity
Intent intent = ((Activity) context).getIntent();
((Activity) context).finish();
context.startActivity(intent);
}
});
alertDialog.show();
}
return isOnline;
}
return false;
}
}
LocalSharedPreferencesChangeListener
package mypackage.sharedprefapp;
import android.content.SharedPreferences;
import android.util.Log;
public class LocalSharedPreferencesChangeListener implements SharedPreferences.OnSharedPreferenceChangeListener
{
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
Log.i("HERE", key);
}
}
activity_login.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".LoginActivity"
android:padding="0dp">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scrollView"
android:layout_gravity="center_horizontal">
<LinearLayout
android:id="#+id/login_parentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:clickable="true">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/ic_launcher"
android:layout_gravity="center_horizontal"
android:layout_marginTop="50dp"
android:layout_marginBottom="30dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:layout_marginBottom="30dp"
android:singleLine="false"
android:padding="5dp"
android:textSize="30sp" />
<EditText
android:id="#+id/login_id_paziente"
android:layout_width="match_parent"
android:layout_height="40dp"
android:inputType="number"
android:ems="10"
android:hint="Username"
android:textColor="#android:color/black"
android:textColorHint="#android:color/darker_gray"
android:singleLine="true"
android:minLines="1"
android:gravity="center_horizontal"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:focusableInTouchMode="true"
android:focusable="true" />
<EditText
android:id="#+id/login_password"
android:layout_width="match_parent"
android:layout_height="40dp"
android:hint="Password"
android:textColorHint="#android:color/darker_gray"
android:inputType="textPassword"
android:ems="10"
android:textColor="#android:color/black"
android:maxLines="1"
android:singleLine="true"
android:layout_marginTop="20dp"
android:gravity="center_horizontal"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:focusableInTouchMode="true"
android:focusable="true" />
<TextView
android:id="#+id/login_errorText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login error"
android:textColor="#android:color/holo_red_dark"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:singleLine="false"
android:padding="5dp"
android:textSize="20sp"
android:layout_margin="10dp"
android:visibility="invisible" />
<Button
android:id="#+id/login_submitButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:textSize="20sp"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp" />
</LinearLayout>
</ScrollView>
</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="mypackage.sharedprefapp.MainActivity">
<TextView
android:id="#+id/person_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="25sp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
splashscreen.xml (in drawable resources folder)
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#android:color/holo_green_dark"/>
<item>
<bitmap
android:gravity="center"
android:src="#mipmap/ic_launcher"/>
</item>
</layer-list>
mainmenu.xml (in res/menu resource folder)
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/logout_action"
android:title="Logout"
app:showAsAction="always" />
</menu>
styles.xml
<resources>
...
<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
<item name="android:windowBackground">#drawable/splashscreen</item>
</style>
</resources>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="mypackage.sharedprefapp">
<!-- Needs internet to connect to Google Services -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Permission to check internet connection state -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name=".App"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".SplashActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#style/AppTheme">
<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/app_name"
android:screenOrientation="portrait"
android:theme="#style/AppTheme" />
<activity
android:name=".LoginActivity"
android:label="#string/app_name"
android:process=":other_process"
android:screenOrientation="portrait"
android:theme="#style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.LOGIN_ACTION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
build.gradle (Module: app)
dependencies {
...
compile 'com.android.volley:volley:1.0.0'
}
Thank you!
Just call editor.clear();
and editor.commit();
is enough to delete all data from shared preference.
Because onResume, you keep on instantiating a new SharedPrefManager
sharedPrefManager = new SharedPrefManager(this);
Modify your SharedPrefManager so that it only gives one instance at all times OR make sure that you are referring to the same object when you return to LoginActivity.
SharedPreferences is permanent storage, you can clear
SharedPreferences.Editor.clear().commit();
alternate solution
you want once app close clear entire values,try Application singleton class
#Ciammarica you can call this code on click of Logout button, hope this can help you..you can set in logout button boolean value false..
SessionManager.setUserLoggedIn(YourActivity.this, false); SessionManager.clearAppCredential(YourActivity.this);
I Changed my code in order to have only one instance of SharedPrefManager class.
This is my App singleton class:
public class App extends Application
{
private static App mInstance;
private SharedPrefManager sharedPrefManager;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
sharedPrefManager = new SharedPrefManager(this);
}
public SharedPrefManager getSharedPrefManager(){
return sharedPrefManager;
}
public static synchronized App getInstance(){
return mInstance;
}
}
Then from other classes I get the instance by calling
SharedPrefManager sharedPrefManager = App.getInstance().getSharedPrefManager();
Now, with this change, the onSharedPreferenceChanged() event is triggered only once, so this is better than before, but the "delayed" behavior is still there... I mean, even if I use editor.clear(); and editor.commit(); methods, the values are updated but I can see them only if I close and open the app again.
I found the problem myself... It didn't like the sharedPrefManager.removeDataFromSharedPreference(); method to be called from inside new DialogInterface.OnClickListener()
I took it in another part of the code and it worked.

Categories

Resources