Dialog box to confirm deletion of row - android

I'm trying to add a dialog box which will pop up when a user selects a delete button which will delete a specified row. However I can't seem to get the appropriate syntax for the program to compile. The error occurs at this line;
MODULEDATABASE.deleteRow(rowId);
Intent intent = new Intent(this, MyCourses.class);
Any suggestions would be much appreciated.
public class ViewCourse extends Activity implements OnClickListener{
Cursor cursor;
database MODULEDATABASE;
String rowId;
Button deleteModule;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_course);
Intent intent = getIntent();
rowId = intent.getStringExtra(MyCourses.TEST);
MODULEDATABASE = new database(ViewCourse.this);
MODULEDATABASE.openToRead(ViewCourse.this);
cursor = MODULEDATABASE.getRow(rowId);
TextView text_modulecode = (TextView)findViewById(R.id.viewModuleCode);
TextView text_modulename = (TextView)findViewById(R.id.viewModuleName);
text_modulecode.setText(cursor.getString(cursor.getColumnIndex(database.KEY_MODULECODE)));
text_modulename.setText(cursor.getString(cursor.getColumnIndex(database.KEY_MODULENAME)));
deleteModule = (Button)findViewById(R.id.deleteButton);
deleteModule.setOnClickListener(this);
}
public void onClick (View deleteModule)
{
Dialog(rowId);
}
public void Dialog (String rowId) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.confirmDelete)
.setPositiveButton(R.string.confirmDelete, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MODULEDATABASE = new database(ViewCourse.this);
MODULEDATABASE.deleteRow(rowId);
Intent intent = new Intent(this, MyCourses.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.confirmDelete, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
}
}

You don't say what the error is, but I suspect you need to change this line:
Intent intent = new Intent(this, MyCourses.class);
to:
Intent intent = new Intent(ViewCourse.this, MyCourses.class);
(The problem is that at that point in the code, this refers to the anonymous OnClickListener class.)
EDIT - Declare the rowId parameter to the method to be final:
public void Dialog (final String rowId) {
. . .

Related

Updating cursor after returning from intent to mainactivity

So i am having this listview in my MainActivity, which is updated every time the main activity is started or resumed.
The code for that is
#Override
public void onResume()
{
super.onResume();
Cursor array_list_patients = mydb.getAllPatientsDetails();
PatientAdapter arrayAdapter = new n
PatientAdapter(this,array_list_patients);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
}
Now for the listview in the MainActivity i have a setOnItemClickListener as shown below, which basically displays the data in another activity "ModifyPatient". Code for that is:
Cursor array_list_patients = mydb.getAllPatientsDetails();
final PatientAdapter arrayAdapter = new PatientAdapter(this,array_list_patients);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
Cursor cur = (Cursor) arrayAdapter.getItem(arg2);
cur.moveToPosition(arg2);
int id_To_Search = cur.getInt(cur.getColumnIndexOrThrow("id"));
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(),ModifyPatient.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
Now in the ModifyPatient class.. i can do Upate/Delete operations on the database entry. Now the problem is, when i do a delete operation and return back to the MainActivity, and click on any item in the listview, i get an OutOfBounds exception for the cursor. The current code for delete button in the ModifyPatient class is as follows:
deleteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(ModifyPatient.this);
builder.setMessage(R.string.deleteContact)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mydb.deletePatient(id_To_Update);
Toast.makeText(getApplicationContext(), "Deleted Successfully",
Toast.LENGTH_SHORT).show();
ModifyPatient.this.finish();
}
})
.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();
}
});
This deletes the entry and returns to the mainactivity, but clicking on any of the items in the listview throws the error which i mentioned before.
I have done a small workaround, where i have replaced the below line:
ModifyPatient.this.finish();
with
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
But the problem with this is, the original activity remains in the background and a new MainActivity is forked. So pressing the back button, goes back to the original activity with the stale listview.
If somebody can help me out, with how to update the cursor, because i could not implement the swapcursor in my case. I am not sure what i am doing wrong.
Thank you in advance.
i set my variable "arrayAdapter" present in the onResume and onItemClickListener in the MainActivity from local to global, and that did the trick.
New code, where arrayAdapter is global:
public void onResume()
{
super.onResume();
Cursor array_list_patients = mydb.getAllPatientsDetails();
arrayAdapter = new PatientAdapter(this,array_list_patients);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
}
and
arrayAdapter = new PatientAdapter(this,array_list_patients);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
Cursor cur = (Cursor) arrayAdapter.getItem(arg2);
cur.moveToPosition(arg2);
int id_To_Search = cur.getInt(cur.getColumnIndexOrThrow("id"));
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(),ModifyPatient.class);
intent.putExtras(dataBundle);
startActivity(intent);
arrayAdapter.notifyDataSetChanged();
}
});

Trying to use getIntent() within a custom dialog comes up as an error. Solution to get around this error?

I am sending a string from an activity to my custom dialog.
This is the activity in which I create a bundle and insert the string, then send it to the dialog activity.
Bundle sendToDialog = new Bundle();
sendToDialog.putString("caloreis", strCalories);
Intent a = new Intent(CaloriesLogMainActivity.this, ActivityDialog.class);
a.putExtras(sendToDialog);
This is the custom dialog activity in which I am trying to receive the intent from the activity.
getIntent(), is coming up as an error. How would I get around this error?
public class ActivityDialog {
Context mContext;
Date mDate;
public ActivityDialog(Context context, CaloriesLogMainActivity caloriesLogMainActivity) {
mContext = context;
}
public void show() {
LayoutInflater factory = LayoutInflater.from(mContext);
View view = factory.inflate(R.layout.dialog_activity, null);
AlertDialog.Builder builder = new AlertDialog.Builder((mContext));
final EditText calories = (EditText) view.findViewById(R.id.etCalories);
Bundle recieveFromActivity = getIntent().getExtras();
String strCaloreis = recieveFromActivity.getString("calories");
calories.setText(strCaloreis);
builder.setTitle(R.string.edit_log_title);
builder.setNegativeButton(R.string.create_log_negative_button,
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNeutralButton(R.string.create_log_neutral_button, null);
builder.setPositiveButton(R.string.create_log_positive_button, null);
builder.create().show();
builder.setView(view);
builder.create().show();
}
}
you have to extend Activity class , then only you can access getIntent()...
so your code should be like this
public class ActivityDialog extends Activity{
Context mContext;
Date mDate;
protected void onCreate(Bundle savedInstanceState){
//here you can call getIntent()
}
public void show() {
// or even from here ,you can call getIntent()
LayoutInflater factory = LayoutInflater.from(mContext);
View view = factory.inflate(R.layout.dialog_activity, null);
AlertDialog.Builder builder = new AlertDialog.Builder((mContext));
final EditText calories = (EditText) view.findViewById(R.id.etCalories);
Bundle recieveFromActivity = getIntent().getExtras();
String strCaloreis = recieveFromActivity.getString("calories");
calories.setText(strCaloreis);
builder.setTitle(R.string.edit_log_title);
builder.setNegativeButton(R.string.create_log_negative_button,
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNeutralButton(R.string.create_log_neutral_button, null);
builder.setPositiveButton(R.string.create_log_positive_button, null);
builder.create().show();
builder.setView(view);
builder.create().show();
}
}
Your ActivityDialog class is an Activity and thus should extend Activity. This is a general rule, but specifically your problem here is due to the fact that getIntent() is defined in Activity, so you must extend that in order to use it.
It might be because of your spelling mistake in sendToDialog.putString("caloreis", strCalories); because you later reference the extra as "calories" not "caloreis". (I tried to put this in an edit but it was uner 6 characters long...)

Android Call Intent Null pointer exception

Im at my wits end here. I have a Class which Implements the OnClickListener cous i need the same action on Buttons accros my Application. This used to work just fine. But since I added some functionality by getting some needed data from the app preferences. startActivity throws a null pointer exception.Here is the class:
//Imports
public class CallClickListener extends Activity implements View.OnClickListener {
protected AppPreferences appPrefs;
String contactPersonName;
String contactPersonTelephone;
String name;
public CallClickListener(Context context){
Log.d("TRACE", "init CallClick");
appPrefs = new AppPreferences(context);
try {
JSONObject object = appPrefs.getConsultantObject();
contactPersonName = object.getString("contactPersonName");
contactPersonTelephone = object.getString("contactPersonTelephone");
name = object.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onClick(View view) {
final View v = view;
AlertDialog.Builder alert = new AlertDialog.Builder(view.getContext());
alert.setTitle("Anrufen");
alert.setMessage("Kontakt für " + name + ", " + contactPersonName + " anrufen");
alert.setPositiveButton("Anrufen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+contactPersonTelephone));
startActivity(callIntent);// this line throws the exception
}
});
alert.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(v.getContext(), "Abbruch", Toast.LENGTH_SHORT).show();
}
});
alert.show();
}
}
The Strings are all there from appPrefs, i also tried with hardcoding a phonenumber just incase. the Alert works fine, but as soon as i hit the positive Button, the app crashes
I add the Listener like this:
bCall.setOnClickListener(new CallClickListener(getApplicationContext()));
I added the necessary Call permissions.
I'm fairly new to Android dev, what am I missing?
Do this.... make the context object that you passed in the constructor into a field variable. and change startActivity to context.startActivity. It will work then.
EDIT: Highlighting the full solution.
bCall.setOnClickListener(new CallClickListener(getApplicationContext()));
should be changed to YourActivityClass.this instead of getApplicationContext.
Start Activity in the same task does not work with a context object that is not an Activity. So you need to either change the context to Activity or you start the activity in a new task. Also without calling startActivity on the context provided to your constructor you were getting the NPE because your CallClickListerner has no context.
Use activity context. Also check if you have initialized bCall. If you have not you will get NullPointerException.
bCall.setOnClickListener(ActivityName.this);
Also check this link to know when to use activity context and when to use application context
When to call activity context OR application context?
Edit:
Make sure you have added permission in manifest file
<uses-permission android:name="android.permission.CALL_PHONE" />
For reference use the below. My Class extends Activity
Button b= (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v1) {
// TODO Auto-generated method stub
final View v = v1;
AlertDialog.Builder alert = new AlertDialog.Builder(v.getContext());
alert.setTitle("Anrufen");
alert.setMessage("Kontakt für " );
alert.setPositiveButton("Anrufen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:8095992052"));
startActivity(callIntent);// this line throws the exception
}
});
alert.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(v.getContext(), "Abbruch", Toast.LENGTH_SHORT).show();
}
});
alert.show();
}
});

Have a Search Activity return a result?

Hi I was wondering how I can get my Search Activity to return a result back to the Activity that started it.
I currently have a Search Dialog implemented (meaning the search Activity starts once the Search button on the phone is clicked).
Here is my code for the Search activity which is a list view.
public class ItemFinder extends ListActivity {
public static final int REQUEST_CODE = 1; // get it?
Vector<String> upcCodes;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
upcCodes = new Vector<String>();
ListView lv = (ListView) findViewById(android.R.id.list);
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
String upc = upcCodes.elementAt(position);
setResult(RESULT_OK);
}
});
// Get the intent, verify the action and get the query
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
ProgressDialog dialog = ProgressDialog.show(ItemFinder.this, "Searching",
"Searching. Please wait...", true);
performSearch(query);
dialog.hide();
dialog.dismiss();
}
}
public void performSearch(String query){
String result = new SmartShopClient().SearchItems(query);
List<String> dataList = new ArrayList<String>();
String _parsedResult[] = result.split("\\n");
for( int i = 0; i<_parsedResult.length; i++){
String _splitData[] = _parsedResult[i].split("\\|");
String itemName = _splitData[0];
String itemUPC = _splitData[1];
dataList.add(itemName);
upcCodes.add(itemUPC);
}
ArrayAdapter<String> arr = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataList);
this.setListAdapter(arr);
}
}
So the search is working all fine and dandy, but I want it so when I click one of the results in the ListView, for it to return data back to the main activity with some data, say the name of the clicked searched result.
Thanks.
What you want to do is launch the search using startActivityForResult. See an explanation here.
This way, you can pass your search results back to the activity which launched it.
That would happen in your setOnItemClickListener method, where you could launch an explicit intent naming the desired activity with extra data.
Edit : I'm not quite sure of how startActivityForResult() would be implemented since we're talking about the search activity of the application, meaning it's launched by the Android search specific module ; that's why i suggested the above solution.
I ended up doing this:
public boolean onSearchRequested() {
askSearchQuery();
return true;
}
public void sendSearchRequest(String query){
Intent mIntent = new Intent(this, ItemFinder.class);
mIntent.setAction(Intent.ACTION_SEARCH);
mIntent.putExtra(SearchManager.QUERY, query);
startActivityForResult(mIntent, ItemFinder.REQUEST_CODE);
}
public void askSearchQuery() {
final EditText input = new EditText(SmartShop.this);
AlertDialog.Builder adb = new AlertDialog.Builder(SmartShop.this);
adb.setTitle("Search Items");
adb.setMessage("Please input the name of the item you are looking for.");
adb.setView(input);
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable upc = input.getText();
sendSearchRequest(upc.toString());
dialog.cancel();
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
adb.create().show();
}
And then I hooked the
protected void onActivityResult (int requestCode, int resultCode, Intent data) {

Cannot refer to a non-final variable db inside an inner class defined in a different method

I'm developing an app for Android but I got stuck on deleting things from my database!
I'm getting an "Cannot refer to a non-final variable db inside an inner class defined in a different method" error! I know what this error means but I can't seem to find a solution to this.
Here is my code
package iwt.ehb.be.capita_selecta;
//my imports
public class RemoveActivity extends Activity {
Context context = this;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.remove_activity);
DBAdapter db = new DBAdapter(this);
db.open();
Cursor c = db.getAllTrips();
if(c.moveToFirst())
{
LinearLayout layout = (LinearLayout) findViewById(R.id.layout_removeTrips);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(5, 5, 5, 5);
do {
Button buttonView = new Button(this);
buttonView.setBackgroundResource(R.layout.btn_blue);
buttonView.setLayoutParams(lp);
buttonView.setText(c.getString(1) + " # " + c.getString(2));
final int id_trip = c.getInt(0);
buttonView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println(id_trip);
AlertDialog.Builder alert = new AlertDialog.Builder(context).setTitle("Attention");
alert.setMessage("Do you wish to delete this trip?");
alert.setIcon(R.drawable.icon);
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
db.deleteSpecificRecord(id_trip);
}
});
alert.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
alert.show();
}
});
layout.addView(buttonView);
} while (c.moveToNext());
}
db.close();
//*******************
//BACK-button
//*******************
Button back = (Button) findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
});
}
}
And I'm getting the error at this line of code db.deleteSpecificRecord(id_trip);
If you have any idea on how I can resolve this that would be awsome ;)
Thx
Kevin
The problem is this line:
AlertDialog.Builder alert = new AlertDialog.Builder(context).setTitle("Attention");
context is a variable from the outer class. Variables like these can only be accessed if they are final.
There are a few possible fixes.
The first one is let your activity implement the onclicklistner
Public class RemoveActivity extends Activity implements OnClickListener { ...
buttonView.setOnClickListener(this);
imho the best solution
Another fix is make the variable context make a constructor with the following code:
Public RemoveActivity (){ this.context = this;}
but this is ugly code
i also think changing the line to
AlertDialog.Builder alert = new AlertDialog.Builder(RemoveActivity.this).setTitle("Attention");
would work.
I had the same error . The thing with this is that java treats each function with an independent scope . I see that you have declared the db Adapter object inside the on Create function . Take the declaration and declare it before the on create function ( rather extending the scope ) this should solve the problem . Your code should look like this :)
public class RemoteActivity extends Activity{
DBAdapter db = new DBAdapter(this);
Context context = this;
onCreate () ...

Categories

Resources