Logout. back button pressed, again logged in - android

From this page I am logging out. It is logging out properly but when back button is pressed it gets logged in again. i have given a proper intent function but yet it is not acting as per my commands. Please advice me a solution for this problem.
WELCOME PAGE CODE:-
public class Welcome extends AppCompatActivity {
Button __btnlogout;
Button btn1;
Button btn2;
DatagramSocketThread mDatagramSocketThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
__btnlogout = (Button)findViewById(R.id.btnLogout);
__btnlogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("isLogin", false);
editor.commit();
Intent intent = new Intent(Welcome.this,
login.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
btn1 = (Button)findViewById(R.id.btn11);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("MainActivity", "22");
mDatagramSocketThread = new DatagramSocketThread();
mDatagramSocketThread.start();
Intent intent = VpnService.prepare(getApplicationContext());
if (intent != null) {
startActivityForResult(intent, 0);
} else {
onActivityResult(0, RESULT_OK, null);
}
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Log.e("MainActivity", "23");
Intent intent = new Intent(Welcome.this, MyClass.class);
Log.e("MainActivity", "24");
startService(intent);
}
btn2 = (Button)findViewById(R.id.btn22);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("MainActivity", "25");
Intent intent;
intent = new Intent(Welcome.this, MyClass.class);
Log.e("MainActivity", "26");
stopService(intent);
}
});
}
}
And i want to be in Login page when logged out and even after pressing back button.
LOGIN PAGE CODE:-
public class login extends AppCompatActivity {
SQLiteDatabase db;
SQLiteOpenHelper openHelper;
Button __btnLogin;
EditText __txtEmail,__txtPass;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Log.d("login","13");
openHelper = new DatabaseHelper(this);
db=openHelper.getReadableDatabase();
__btnLogin = (Button)findViewById(R.id.btnLogins);
__txtEmail = (EditText)findViewById(R.id.txtEmails);
__txtPass = (EditText)findViewById(R.id.txtPasss);
SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("isLogin", true);
editor.commit();
Log.d("login","14");
__btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = __txtEmail.getText().toString();
String pass = __txtPass.getText().toString();
if (pass == "" || email == "") {
Toast.makeText(getApplicationContext(),"No Entry", Toast.LENGTH_LONG).show();
}
Log.d("login","15");
cursor = db.rawQuery("SELECT * FROM "+ DatabaseHelper.TABLE_NAME + " WHERE " + DatabaseHelper.COL_5 + " =? AND " + DatabaseHelper.COL_4 + " =? ", new String[]{email,pass});
Log.d("login","16");
if(cursor!=null) {
Log.d("login","17");
if (cursor.getCount()>0) {
Log.d("login","18");
//cursor.moveToNext();
Log.d("login","19");
startActivity(new Intent(login.this, Welcome.class));
Toast.makeText(getApplicationContext(), "Login Successfully", Toast.LENGTH_LONG).show();
}
else {
Log.d("login","20");
Toast.makeText(getApplicationContext(),"Error", Toast.LENGTH_LONG).show();
Log.d("login","21");
}
}
}
});
}
}
THANK YOU

You can override onBackPressed on login page, then when users click on back, you can handle it your way:
#Override
public void onBackPressed()
{
//super.onBackPressed(); // disable this
}

You need to finish() all previous Activity when logging out. Try the code below You can emit flag Intent.FLAG_ACTIVITY_NEW_TASK.
Intent intent = new Intent(login.this, Welcome.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
About your question you said i want to be in Login page when logged out and even after pressing back button.
Thats not the proper behavior for any app . The app should close when you back press from last Activity on Stack . So do not disable onBackPressed() in Login Activity.

I think you shouldn't clear the shared preferences properly or should check shared preferences value before rendering welcome activity. Then you should add finish(); after startActivity()
SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("isLogin", false);
editor.commit();
Intent intent = new Intent(Welcome.this,login.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
To prevent this accidental login you should check sharedPreferences value is set before. Back button disabling is not a good option.

You have to finish Welcome Activity when you are logging, so user will not be able to come back this activity again except when the log in again. You have to add finish(); on logout
Intent intent = new Intent(Welcome.this,login.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
and in you login page you can also handle what you want to do when you press back button, either exit from app or do something else, by override onBackPressed(); method.
#Override
public void onBackPressed()
{
super.onBackPressed();
}

Changed isLogin Flag after success login ,
Update your Login Activity Code,
public class login extends AppCompatActivity {
SQLiteDatabase db;
SQLiteOpenHelper openHelper;
Button __btnLogin;
EditText __txtEmail,__txtPass;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Log.d("login","13");
openHelper = new DatabaseHelper(this);
db=openHelper.getReadableDatabase();
__btnLogin = (Button)findViewById(R.id.btnLogins);
__txtEmail = (EditText)findViewById(R.id.txtEmails);
__txtPass = (EditText)findViewById(R.id.txtPasss);
Log.d("login","14");
__btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = __txtEmail.getText().toString();
String pass = __txtPass.getText().toString();
if (pass == "" || email == "") {
Toast.makeText(getApplicationContext(),"No Entry", Toast.LENGTH_LONG).show();
}
Log.d("login","15");
cursor = db.rawQuery("SELECT * FROM "+ DatabaseHelper.TABLE_NAME + " WHERE " + DatabaseHelper.COL_5 + " =? AND " + DatabaseHelper.COL_4 + " =? ", new String[]{email,pass});
Log.d("login","16");
if(cursor!=null) {
Log.d("login","17");
if (cursor.getCount()>0) {
Log.d("login","18");
//cursor.moveToNext();
Log.d("login","19");
SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("isLogin", true);
editor.commit();
startActivity(new Intent(login.this, Welcome.class));
Toast.makeText(getApplicationContext(), "Login Successfully", Toast.LENGTH_LONG).show();
}
else {
Log.d("login","20");
Toast.makeText(getApplicationContext(),"Error", Toast.LENGTH_LONG).show();
Log.d("login","21");
}
}
}
});
}
}

Navigate into login activity if click logout button and listen for back pressed on login activity
Intent ...
finish();
onBackPressed();

Solution is
#Override
public void onBackPressed() {
super.onBackPressed();
finishAffinity();
}

Related

Android Studio getIntent from one activity but not from other

I have a question that whatever I search i can't find the answer for.
So I have 3 Activities:StartActivity, LoginActivity and MainActivity
In StartActivity I have 2 buttons:
-Login - it sends me to LoginActivity
-Continue as guest - it sends me to MainActivity
In Login activity i have:
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if(loginUser(false)) {
String username = String.valueOf(userName);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("USERNAME", username);
startActivity(intent);
finish();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
});
and in MainActivity I have :
private String username = getIntent().getStringExtra("USERNAME");
But when I try to login as guest the String username has nothing to get and gives me error. So how can I make String username getIntent only when I open the activity from LoginActivity and don't do anything when I open it from ContinueAsGuest button in StartActivity?
button in StartActivity only take you as guest right?if so code will look like this
guestBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
String username = String.valueOf(userName);
Intent intent = new Intent(StartActivity.this, MainActivity.class);
intent.putExtra("USERNAME", username);
startActivity(intent);
finish();
}
} catch (SQLException e) {
e.printStackTrace();
}
});

How do i set .equals equal to the result of startActivityForResult

im kinda new to programming and would like to make some sort of like a login and register page. so from my login page i click register and it would go to the register page and i want the username/password i get from the register page to be used in the previous login page to login into the app. But i cant seem to set the username/password using the result. Only able to set the textview. pls help heres the code
public class MainActivity extends AppCompatActivity {
private EditText Name;
private EditText Password;
private TextView Info;
private Button Login;
private int counter = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Name = (EditText)findViewById(R.id.etName);
Password = (EditText)findViewById(R.id.etPass);
Info = (TextView) findViewById(R.id.tvInfo);
Login = (Button)findViewById(R.id.btnLogin);
Info.setText("No Of Attempts Remaining: 5");
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
validate(Name.getText().toString(),Password.getText().toString());
}
});
}
private void validate(String userName, String userPassword){
if(userName.equals("") && userPassword.equals("")){
Intent intent = new Intent(MainActivity.this, MenuActivity.class);
startActivity(intent);
}
else{
counter--;
Info.setText("No Of Attempts Remaining: " + String.valueOf(counter));
if(counter == 0){
Login.setEnabled(false);
}
}
}
public void facebooklogin(View myview){
Intent intent = new Intent(this, MenuActivity.class);
startActivity(intent);
}
public void register(View myview) {
Intent i = new Intent(this, RegisterActivity .class);
startActivityForResult(i, 1);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
String reginame = data.getStringExtra("NAME");
String regipass = data.getStringExtra("PASS");
Name.setText("" + reginame);
Password.setText("" + regipass);
}
}
}
How do i set the
private void validate(String userName, String userPassword){
if(userName.equals("") && userPassword.equals("")){
Intent intent = new Intent(MainActivity.this, MenuActivity.class);
startActivity(intent);
}
to be equal to the onActivityResult reginame and regipass
your condition is wrong it should be like this:-
private void validate(String userName, String userPassword){
if(!userName.equals("") && !userPassword.equals("")){
Intent intent = new Intent(MainActivity.this, MenuActivity.class);
startActivity(intent);
}
First Activity.
Send information
Intent send = new Intent(MainActivity.this, Main2Activity.class);
send.putExtra("login",editText.getText());
send.putExtra("password",editText1.getText());
startActivity(send);
Second Activity.
Get Information
if(getIntent()!=null){
Intent intent = getIntent();
editText.setText(intent.getStringExtra("login")) ;
editText1.setText(intent.getStringExtra("password")) ;
}

Login Details using Content Provider, brings many loop

I want to create a Toast Text (about I haven't registered in the database) on the Login Activity. However, there is a problem when I put this Toast text. If I put it inside a while loop Cursor.MoveToNext(), it will loop as many times as many entries it has.
Inside the loop
if(cursor!=null)
{
{
int i = 0;
while(cursor.moveToNext())
{
if(cursor.getString(i).equals(input_email) && cursor.getString(i).equals(input_password))
{
Log.d(TAG, "Udah masuk belum " );
Toast.makeText(getApplicationContext(),"Login Successful!", Toast.LENGTH_SHORT).show();
Intent intent =new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
finish();
i = i + 1;
}
else
{
Toast.makeText(getApplicationContext(),"You haven't Registered yet!", Toast.LENGTH_SHORT).show();
Intent intent =new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
finish();
}
}
cursor.close();
}
}
But when I putted outside of the loop, it brings error. Do you know what is the solution of this one?
Outside the loop
String [] projection ={ServiceProvidersContract.Columns.SEmail, ServiceProvidersContract.Columns.spPassword};
Cursor cursor = contentResolver.query(ServiceProvidersContract.CONTENT_URI, projection, null, null, null);
Log.d(TAG, "Checking Cursor" + cursor );
if(cursor!=null)
{
{
int i = 0;
while(cursor.moveToNext())
{
if(cursor.getString(i).equals(input_email) && cursor.getString(i).equals(input_password))
{
Log.d(TAG, "Udah masuk belum " );
Toast.makeText(getApplicationContext(),"Login Successful!", Toast.LENGTH_SHORT).show();
Intent intent =new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
finish();
i = i + 1;
}
}
cursor.close();
if(!cursor.getString(i).equals(input_email) && cursor.getString(i).equals(input_password))
{
Toast.makeText(getApplicationContext(),"You haven't Registered yet!", Toast.LENGTH_SHORT).show();
Intent intent =new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
finish();
}
}
}
Just want to clarify, I did finally login successfully in my login parts using For and While.
The other problem is coming from the Toast Text ( where I couldn't put the failed Toast Text in the loop). This is my codes :
private static final String TAG = "LoginActivity";
private Button btnLogin, btnLinkToRegister;
private SessionManager session;
private EditText password, email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Defining everything
email = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.password);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegister);
btnLogin = (Button) findViewById(R.id.btnLogin);
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
ContentResolver contentResolver = getContentResolver() ;
String input_email = email.getText().toString().trim();
String input_password = password.getText().toString().trim();
Log.d(TAG, "onClick: " + input_email + input_password);
// Check for empty data in the form
if (!input_email.isEmpty() && !input_password.isEmpty()) {
Log.d(TAG, "onClick: if statement succeseful");
// checking from the database
String [] projection ={ServiceProvidersContract.Columns.SEmail, ServiceProvidersContract.Columns.spPassword};
Cursor cursor = contentResolver.query(ServiceProvidersContract.CONTENT_URI, projection, null, null, null);
Log.d(TAG, "Checking Cursor" + cursor );
if(cursor!=null)
{
cursor.moveToFirst();
while(cursor.moveToNext())
{
Log.d(TAG, "while process");
for(int i=0; i<cursor.getColumnCount(); i++)
{
Log.d(TAG, "for process " + cursor.getString(i));
if (cursor.getString(0).equals(input_email) && cursor.getString(1).equals(input_password)) {
Log.d(TAG, "if process");
Toast.makeText(getApplicationContext(), "Login Successful!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
finish();
break;
}
}
}
if (!cursor.getString(0).equals(input_email) && cursor.getString(1).equals(input_password)) {
Log.d(TAG, "if process");
Toast.makeText(getApplicationContext(), "You haven't registered yet!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
finish();
}
cursor.close();
}
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
Intent i = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(i);
finish();
}
});
}
}

how to properly use intent? Android beginner

I am a beginner in android and I am trying to learn how to use intent.
In my code, I am trying to send 2 integers to a different activity and perform some calculation and return back in the Main activity with the answer.
This is my main activity and with a click of a button it should send 10, 50 to my calculate class and from there I will click operator buttons like add, multiply, divide and send back the answer here in main activity.
So far I am able to received these numbers to my Calculate class and perform operation there but I am not sure how to get back here in main activity with the answers.
Main Activity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(getIntent() != null){
String msg = getIntent().getStringExtra("MSG");
int result = getIntent().getIntExtra("result", 0);
Toast.makeText(this, "" + msg + result, Toast.LENGTH_LONG).show();
}
}
public void onClick(View v){
Intent i = new Intent(this, Calculate.class);
i.putExtra("MSG", "Receive two numbers : ");
i.putExtra("second", 10);
i.putExtra("first", 50);
startActivity(i);
}
}
Calculate class
public class Calculate extends Activity{
private int calc;
private int first;
private int second;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent i = getIntent();
if(getIntent() != null){
String msg = i.getStringExtra("MSG");
first = i.getIntExtra("first", 0);
second = i.getIntExtra("second", 0);
Toast.makeText(this, "" + msg + first + " and " + second, Toast.LENGTH_LONG).show();
}
}
public void add(View v){
calc = first + second;
Intent i = new Intent(this, MainActivity.class);
i.putExtra("MSG", "Answer");
i.putExtra("result",calc);
}
}
you can use startActivityForResult and onActivityResult methods. fist in main activity you call startActivityForResult that means you want to get result from secondActivity (Calculate activity) and then override onActivityResult in main activity to get result.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(getIntent() != null){
String msg = getIntent().getStringExtra("MSG");
int result = getIntent().getIntExtra("result", 0);
Toast.makeText(this, "" + msg + result, Toast.LENGTH_LONG).show();
}
}
public void onClick(View v){
Intent i = new Intent(this, Calculate.class);
i.putExtra("MSG", "Receive two numbers : ");
i.putExtra("second", 10);
i.putExtra("first", 50);
startActivityForResult(i, 1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result");
}
if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
}
}//onActivityResult
}
public class Calculate extends Activity{
private int calc;
private int first;
private int second;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent i = getIntent();
if(getIntent() != null){
String msg = i.getStringExtra("MSG");
first = i.getIntExtra("first", 0);
second = i.getIntExtra("second", 0);
Toast.makeText(this, "" + msg + first + " and " + second, Toast.LENGTH_LONG).show();
}
}
public void add(View v){
calc = first + second;
Intent returnIntent = Intent(this, MainActivity.class);
returnIntent.putExtra("result",calc );
setResult(RESULT_OK,returnIntent);
finish();
}
}
public class Calculate extends Activity{
private int calc;
private int first;
private int second;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent i = getIntent();
if(getIntent() != null){
String msg = i.getStringExtra("MSG");
first = i.getIntExtra("first", 0);
second = i.getIntExtra("second", 0);
Toast.makeText(this, "" + msg + first + " and " + second, Toast.LENGTH_LONG).show();
}
}
public void add(View v){
calc = first + second;
Intent i = new Intent(this, MainActivity.class);
i.putExtra("MSG", "Answer");
i.putExtra("result",calc);
startActivity(i);
}
}
You need a startActivity(i); in add() function.
You can do this by
onActivityResult()
method of android intent.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(data.getExtras().containsKey("widthInfo")){
width.setText(data.getStringExtra("widthInfo"));
}
if(data.getExtras().containsKey("heightInfo")){
height.setText(data.getStringExtra("heightInfo"));
}
}
See these links for more info:
http://developer.android.com/training/basics/intents/result.html
http://www.java2s.com/Code/Android/UI/CheckActivityresultandonActivityResult.htm
http://www.mybringback.com/android-sdk/12204/onactivityresult-android-tutorial/
It looks like you should be using startActivityForResult() here.
So, in your MainActivity, your onClick() would be modified to call startActivityForResult():
public void onClick(View v){
Intent i = new Intent(this, Calculate.class);
i.putExtra("MSG", "Receive two numbers : ");
i.putExtra("second", 10);
i.putExtra("first", 50);
startActivityForResult(i, 100); //modified
}
Then in MainActivity, you would also add onActivityResult to get the result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100 && resultCode == RESULT_OK){
String msg = data.getStringExtra("MSG");
int result = data.getIntExtra("result", 0);
Toast.makeText(this, "" + msg + result, Toast.LENGTH_LONG).show();
}
}
Then, in the Calculate Activity, you would calculate the result, and send it back to MainActivity in an Intent, which will send the the MSG and result to onActivityResult() in MainActivity:
public void add(View v){
calc = first + second;
Intent i = new Intent(); //modified
i.putExtra("MSG", "Answer");
i.putExtra("result",calc);
setResult(RESULT_OK,i); //added
finish(); //added
}
Note that the reason it would be better for you to use startActivityForResult() here is that it would prevent having to add multiple Activities onto the back stack.
Say for example, you do two calculations (two trips from MainActivity to Calculate and back).
If you just used startActivity(), your back stack would then look like this:
MainActivity->Calculate->MainActivity->Calculate->MainActivity
And, it would just keep growing the more calculations you do.
Using startActivityForResult(), you are always just adding an instance of Calculate to the back stack, and then popping it and returning to the same instance of MainActivity. So, your back stack would always be just:
MainActivity
or...
MainActivity->Calculate
depending on which Activity you are currently in. As you can see, this is a huge improvement over the first option, which just keeps growing as you do more calculations.

Android clear listview linked to SQLite

I have the following activity populating listview from SQLite.
When click on empty I delete table content correctly and refresh the CartActivity which appears empty.
If I add new element in my cart then old elements appears again but only in the listview and (correctly) not in my db. If I close the application the listview update itself correctly.
Tried to give a look at similar question, tried with notify but nothing happens. Someone wrote about "you delete the data but not the entries" but I'm not able to.
How could I solve this issue?
Any help would be much appreciated. Thanks in advance.
public class CartActivity extends Activity {
ListView list;
Context context;
SessionManagement session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
Typeface font = Typeface.createFromAsset(this.getAssets(), "font/VarelaRound-Regular.ttf");
context = getApplicationContext();
session = new SessionManagement(context);
final CartHandler db = new CartHandler(this);
Log.d("Reading: ", "Reading all contacts..");
final List<CartRow> products = db.getAllProducts();
for (CartRow cn : products) {
String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Number: " + cn.getNumber() + " ,Pieces: " + cn.getPieces() + " ,Price: " + cn.getPrice() + " ,Tot: " + cn.getTotPrice();
Log.d("Nome: ", log);
}
if(products.isEmpty() ){
//Intent intent = new Intent(getApplicationContext(),MenuActivity.class);
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//startActivity(intent);
Toast.makeText(this, "", Toast.LENGTH_LONG).show();
//finish();
} else {
final CartHandler mdb = new CartHandler(this);
getItemsFromDatabase(mdb);
final CustomCarterList adapter = new CustomCarterList(CartActivity.this);
list = (ListView) findViewById(R.id.cart);
list.setAdapter(adapter);
Button empty = (Button) findViewById(R.id.emptycart);
empty.setTypeface(font);
empty.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
db.deleteAll();
//mdb.deleteAll();
Intent intent = new Intent(CartActivity.this, CartActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
Button proceed = (Button) findViewById(R.id.proceed);
proceed.setTypeface(font);
proceed.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!session.isLoggedIn()) {
Intent intent = new Intent(CartActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
} else {
Intent intent = new Intent(
getApplicationContext(),
CheckoutActivity.class
);
startActivity(intent);
}
}
});
}
}
public void getItemsFromDatabase(CartHandler mdb) {
Cursor cursor = null;
try{
SQLiteDatabase db =mdb.getReadableDatabase();
cursor=db.rawQuery("select * from products", null);
while (cursor.moveToNext()){
Log.e("Cart", cursor.getString(1)+":"+cursor.getString(2)+":"+cursor.getString(3)+":"+cursor.getString(4)+":"+cursor.getString(5));
CartRow.itemIdList.add(cursor.getString(0));
CartRow.itemNameList.add(cursor.getString(1));
CartRow.itemQuantityList.add(cursor.getString(2));
if (cursor.getString(3).equals("0")){
CartRow.itemPiecesList.add("Pieces: 1");}
else{
CartRow.itemPiecesList.add("Pieces: "+cursor.getString(3));}
CartRow.itemPriceList.add(cursor.getString(4) + ".00€");
CartRow.itemTotPriceList.add(cursor.getString(5)+".00€");
}
cursor.close();
}catch (SQLException e){
Log.e("DB Error", e.toString());
e.printStackTrace();
}
}
use adapter.notifyDataSetChanged() instead of notify.
Change the else part of the onCreate method like this...
if(products.isEmpty() ){
//Intent intent = new Intent(getApplicationContext(),MenuActivity.class);
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//startActivity(intent);
Toast.makeText(this, "", Toast.LENGTH_LONG).show();
//finish();
} else {
final CartHandler mdb = new CartHandler(this);
getItemsFromDatabase(mdb);
final CustomCarterList adapter = new CustomCarterList(CartActivity.this);
list = (ListView) findViewById(R.id.cart);
list.setAdapter(adapter);
Button empty = (Button) findViewById(R.id.emptycart);
empty.setTypeface(font);
empty.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
db.deleteAll();
CartRow.itemIdList.clear(); // clears the list
adapter.notifyDataSetChanged(); // notifies adapter about the change.
//mdb.deleteAll();
Intent intent = new Intent(CartActivity.this, CartActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
Button proceed = (Button) findViewById(R.id.proceed);
proceed.setTypeface(font);
proceed.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!session.isLoggedIn()) {
Intent intent = new Intent(CartActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
} else {
Intent intent = new Intent(
getApplicationContext(),
CheckoutActivity.class
);
startActivity(intent);
}
}
});
}
SOLVED:
Calling
CartRow.itemIdList.clear();
CartRow.itemNameList.clear();
CartRow.itemNumberList.clear();
CartRow.itemPiecesList.clear();
CartRow.itemPriceList.clear();
CartRow.itemTotPriceList.clear();
before
getItemsFromDatabase(mdb);
and after
db.deleteAll();

Categories

Resources