Android clear listview linked to SQLite - android

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();

Related

Logout. back button pressed, again logged in

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();
}

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();
}
});
}
}

Data is not passing through intent

I want to send the integer value from one activity to another but I am not getting the value,There is no error in my project.If I am giving the static value it is working so problem with intent only..
Passing the data
try {
JSONObject jsonobject = new JSONObject(doc);
final String statusCode=jsonobject.get("code").toString();
System.out.print("Code......>>>>>>>>>>>>>>"+statusCode);
switch (statusCode){
case "400":
Toast.makeText(getApplicationContext(), "" + doc, Toast.LENGTH_LONG).show();
break;
case "200":
final Dialog dialog = new Dialog(SecondActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.link_dialog);
Button dialogButtonCustomercare = (Button) dialog
.findViewById(R.id.button_ok);
Button dialogButtonCustomer = (Button) dialog
.findViewById(R.id.button_contact_us);
dialogButtonCustomercare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), SecondActivity.class);
i.putExtra("StatusCode", 200);
startActivity(i);
// dialog.dismiss();
}
});
dialogButtonCustomer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
makeCall(phonenumber);
}
});
dialog.show();
break;
default:
Toast.makeText(getApplicationContext(), "Oops something went wrong! ", Toast.LENGTH_LONG).show();
break;
}
} catch (Exception e) {
Log.i("Error", e.getMessage());
}
Getting the data
int responseCode ;
Intent i = getIntent();
responseCode = i.getIntExtra("StatusCode",0);
System.out.print("Status Code" + responseCode);
if (responseCode==200) {
DetailsImageView.setVisibility(View.VISIBLE);
// textview.settext(bank details verification done)
} else {
DetailImageView.setVisibility(View.INVISIBLE);
}
dialogButtonOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), SecondActivity.class);
i.putExtra("StatusCode", 200);
// Toast.makeText(getApplicationContext(), "sucessful intent" +200, Toast.LENGTH_LONG).show();
startActivity(i);
finish();
dialog.dismiss();
}
});

onclick listview in oncreate()

I am getting the values and setting the adapter on onpostexecute() of my async task and when i click the items of listview in oncraete() Its showing nothing and I am trying to show a toast to test it.
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.list);
new Ftpclient().execute();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == 0) {
Toast.makeText(getApplicationContext(), "clicked on", 500).show;
String f = "FILE54.pdf";
File file = new File(Environment
.getExternalStorageDirectory()
+ "/FtpFiles"
+ f);
if (file.exists()) {
Uri filepath = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(filepath, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"file not found", 500);
Log.e("error", "" + e);
}
}
}
});
class Ftpclient extends AsyncTask<String, Void, ArrayList<String>> {
ArrayList<String> temparrlist = new ArrayList<String>();
ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(MainActivity.this, "Connecting",
"please wait");
}
protected ArrayList<String> doInBackground(String... connection) {
temparrlist = listftpitems();
return temparrlist;
}
protected void onPostExecute(ArrayList<String> result) {
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
MainActivity.this, android.R.layout.simple_list_item_1,
result);
lv.setAdapter(arrayAdapter);
dialog.dismiss();
}
}
Help is always appreciated,Thanks
EDIT
ArrayList<String> temparrlist = new ArrayList<String>();
temparrlist = listftpitems();
String uri = temparrlist.get(position).toString();
File file = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/FtpFiles" + "/" + uri);
if (uri.endsWith(".pdf") || uri.endsWith(".txt")) {
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file), "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open File");
try {
startActivity(intent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"file not found", 500).show();
Log.e("error", "" + e);
}
This code...
Toast.makeText(getApplicationContext(), "clicked on", 500);
Should be like this...
Toast.makeText(getApplicationContext(), "clicked on", Toast.LENGTH_SHORT).show();
You have to use show() method to show toast notification.....
EDIT :
To use SPECIFIED TIME YOU CAN USE BELOW CODE..........
final Toast toast = Toast.makeText(getApplicationContext(), "clicked on", Toast.LENGTH_SHORT);
toast.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
toast.cancel();
}
}, 500);
EDIT :
To Open PDF USE FOLLOWING CODE...THAT WORKS FOR ME...........BUT MAKE SURE THAT YOU HAVE PDF READER IN YOUR MOBILE............
btn_open.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
name = edt_filename.getText().toString(); // name of selected file...
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/documents" +"/"+ name+".pdf"); // going to directory
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file),"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open File");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
// Instruct the user to install a PDF reader here, or something
}
}
});
change you toast:Toast.makeText(getApplicationContext(), "clicked on"+position, 500).show();

SQLite Database not updating properly after deleting row

When I delete any data then listitem click is showing error when opening listitem and data are also not correct on custom listview. After deleting row 0 data is not updating properly. Please help..
mydb = new DBHelper(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
int Value = extras.getInt("id");
if (Value > 0) {
// means this is the view part not the add contact part.
Cursor crs = mydb.getData(Value);
id_To_Update = Value;
crs.moveToFirst();
String nam = crs.getString(crs.getColumnIndex(DBHelper.C_NAME));
String phon = crs.getString(crs
.getColumnIndex(DBHelper.C_PHONE));
String addr = crs.getString(crs
.getColumnIndex(DBHelper.C_ADDRESS));
String dat = crs.getString(crs.getColumnIndex(DBHelper.C_DATE));
String typ = crs.getString(crs.getColumnIndex(DBHelper.C_TYPE));
if (!crs.isClosed()) {
crs.close();
}
Button b = (Button) findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
name.setText((CharSequence) nam);
name.setFocusable(false);
name.setClickable(false);
phone.setText((CharSequence) phon);
phone.setFocusable(false);
phone.setClickable(false);
type.setText((CharSequence) typ);
type.setFocusable(false);
type.setClickable(false);
address.setText((CharSequence) addr);
address.setFocusable(false);
address.setClickable(false);
date.setText((CharSequence) dat);
date.setFocusable(false);
date.setClickable(false);
}
}
}
case R.id.Delete_Contact:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.deleteContact)
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
mydb.deleteContact(id_To_Update);
Toast.makeText(getApplicationContext(),
"Deleted Successfully",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(
getApplicationContext(),
com.example.addressbook.MainActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// User cancelled the dialog
}
});
AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void run(View view) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
int Value = extras.getInt("id");
if (Value > 0) {
if (mydb.updateContact(id_To_Update, name.getText().toString(),
phone.getText().toString(), type.getText().toString(),
address.getText().toString(), date.getText().toString())) {
Toast.makeText(getApplicationContext(), "Updated",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),
com.example.addressbook.MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "not Updated",
Toast.LENGTH_SHORT).show();
}
} else {
if (mydb.insertContact(name.getText().toString(), phone
.getText().toString(), type.getText().toString(),
address.getText().toString(), date.getText().toString())) {
Toast.makeText(getApplicationContext(), "done",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "not done",
Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(),
com.example.addressbook.MainActivity.class);
startActivity(intent);
}
DBHelper.java
public Integer deleteContact(Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts", "id = ? ",
new String[] { Integer.toString(id) });
}
}
Finally I have got the solution. I have a text view in custom list view which has Table id which is unique for every row and after deleting the row it's value does not change so I am opening the data of that row on different activity.

Categories

Resources