How to Add Go Back function in WebView inside Fragment ? (duplicate) - android

The current code is not working , I want to add goback feature in webview, when I press back button in mobile . How can I solve it? Below is my current fragment . Guide me :) found some question regarding same ,but didn't get the answer..
SOLVED! THIS IS WHAT I FOUND !!
///MY FRAGMENT
}
public static WebView getWebView(){
return webView;
}
}
----------------------
///MY ACTIVITY
#Override
public void onBackPressed() {
WebView webView = fbfragment.getWebView();
if (webView.canGoBack()) {
webView.goBack();
} else {
Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Exit").setMessage("Are you sure you want to exit?").setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.setCancelable(false);
alert.show();
}
}
}
package XXXX.XXXXXXXXXX.XXXXXXXXXXXX.com;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import XXXX.XXXXXX.XXXXXX..R;
import XXXX.XXXXXX.XXXXXX..R.id;
import XXXX.XXXXXX.XXXXXX.R.layout;
public class FBFragment extends Fragment {
private static final String target_url = "https://XXXXXXXXXX.com/";
private static WebView webView;
final Context context = getActivity();
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.XXXXX_main, container, false);
webView = (WebView) rootView.findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
...........CONT...
.......CODE ENDS WITH..........
}
});
CookieSyncManager.createInstance(getActivity());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
CookieSyncManager.getInstance().startSync();
webView.loadUrl(target_url);
return rootView;
}
#JavascriptInterface
public void processVideo(final String vidData, final String vidID) {
}
public static boolean Back() {
if (webView.canGoBack()) {
webView.goBack();
return true;
} else
return false;
}
}
BELOW IS MY MAIN ACTIVITY
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Exit").setMessage("Are you sure you want to exit?").setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.setCancelable(false);
alert.show();
}
}

Try below solutions
in your activity class's onBackPressed method call your fragment's Back() method.
#Override
public void onBackPressed()
{
yourFragment.Back();
}
in your fragment's Back() method call getActivity().onBackPressed(); like this
public static void Back() {
if (webView.canGoBack()) {
webView.goBack();
} else{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Exit").setMessage("Are you sure you want to exit?").setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
getActivity().finish();
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.setCancelable(false);
alert.show();
}
}

Override the onBackPressed() of your Activity
#Override
public void onBackPressed()
{
//fbFragment is an instance of your FBFragment
WebView webView = fbFragment.getWebView();
if (webView.canGoBack())
{
webView.goBack();
} else{
super.onBackPressed();
}
}
/// this is inside your fragment. NOTE the getWebview method
package XXXX.XXXXXXXXXX.XXXXXXXXXXXX.com;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import XXXX.XXXXXX.XXXXXX..R;
import XXXX.XXXXXX.XXXXXX..R.id;
import XXXX.XXXXXX.XXXXXX.R.layout;
public class FBFragment extends Fragment {
private static final String target_url = "https://XXXXXXXXXX.com/";
private static WebView webView;
final Context context = getActivity();
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.XXXXX_main, container, false);
webView = (WebView) rootView.findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
...........CONT...
.......CODE ENDS WITH..........
}
});
CookieSyncManager.createInstance(getActivity());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
CookieSyncManager.getInstance().startSync();
webView.loadUrl(target_url);
return rootView;
}
#JavascriptInterface
public void processVideo(final String vidData, final String vidID) {
}
public void getWebView(){
return webview;
}

Related

How to add Back Button from an Activity to a Fragment

I'm using a fragment because I used a nav drawer menu. After I click "Category" menu it will take me to "Category" fragment and in that fragment, I have added a floating action bar that will take you to "Add category" activity.
Since fragments can't be viewed in AndroidManifest.xml file, I can't make a fragment as a parent. What I want is to add a "Back Button" from "Add category" activity, display a toast message (If sure to leave without saving changes..etc) and will go back to "Category" fragment.
I have tried using "onBackPressed()" and "getSuppoerActionBar()" that will show a toast but when running the app, the toast message will just show up in a few seconds and will go back to "Category" fragment.
Please help. Thanks!
Here is my code.
CategoriesFragment.java
package com.example.devcash;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class CategoriesFragment extends Fragment {
public CategoriesFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_categories, container, false);
//add floating action button
FloatingActionButton categories_fab = view.findViewById(R.id.addcategories_fab);
categories_fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// when add fab is pressed, go to add product activity
Intent addprod = new Intent(getActivity(), AddCategoryActivity.class);
startActivity(addprod);
}
});
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Categories");
}
}
AddCategoryActivity.java
package com.example.devcash;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
public class AddCategoryActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_category);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Unsaved changes");
builder.setMessage("Are you sure you want to leave without saving changes?");
builder.setPositiveButton("LEAVE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
AddCategoryActivity.super.onBackPressed();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.show();
super.onBackPressed();
}
}
You need to remove below code from onBackPressed() as it is calling super class method and eventually destroying activity.
super.onBackPressed();
To handle toolbar back add following code
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// todo: goto back activity from here
onBackPressed();
default:
return super.onOptionsItemSelected(item);
}
}
Your AddCategoryActivity should be like this
public class AddCategoryActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_category);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onBackPressed() {
quitActivity();
}
private void quitActivity() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Unsaved changes");
builder.setMessage("Are you sure you want to leave without saving changes?");
builder.setPositiveButton("LEAVE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
quitActivity();
return true;
} else
return super.onOptionsItemSelected(item);
}
}
you can use EventBus.
class Activity{
fun backToFragment(){
EventBus.postEvent(BackToFragmentEvent())
}
}
class HomeActivity{
EventBus.register{
fragmentmanager.replace(CategoriesFragment)
}
}

Cast Dialog to AlertDialog

I had the exact same code in antoher project, but it continues to crash here. I have implementation 'com.android.support:design:26.1.0' in my gradle. I'm really unsure of what the problem is. I've tried switching the gradle version, changing from v7 Dialog to the app Dialog. All fails regardless
java.lang.ClassCastException: android.app.Dialog cannot be cast to android.support.v7.app.AlertDialog
at com.example.weather.CreateCityDialog.onResume(CreateCityDialog.java:58)
import android.app.Dialog;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v4.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class CreateCityDialog extends DialogFragment {
public interface NewCityHandler {
void onNewCityCreated(String cityName);
}
private NewCityHandler newCityHandler;
private EditText etName;
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof NewCityHandler)
newCityHandler = (NewCityHandler) context;
else
throw new RuntimeException("Error");
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Add new city");
View rootView = getActivity().getLayoutInflater().inflate(R.layout.activity_create_city_dialog, null);
etName = rootView.findViewById(R.id.etName);
builder.setView(rootView);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
return super.onCreateDialog(savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
final AlertDialog d = (AlertDialog) getDialog();
if (d != null) {
Button positiveButton = d.getButton(Dialog.BUTTON_POSITIVE);
positiveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!TextUtils.isEmpty(etName.getText())) {
newCityHandler.onNewCityCreated(etName.getText().toString());
d.dismiss();
} else {
etName.setError("Empty field");
}
}
});
}
}
}
You have to return AlertDialog from onCreateDialog().
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Add new city");
View rootView = getActivity().getLayoutInflater().inflate(R.layout.activity_create_city_dialog, null);
etName = rootView.findViewById(R.id.etName);
builder.setView(rootView);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder.create();
}

How to make filter work when data is being obtained from firebase

The below code is used to open an AlertDialog which enables one to search for data base on the items in the alert dialog
public void FilterIcon(){
AlertDialog.Builder builder = new
AlertDialog.Builder(getActivity());
selecedItem = new ArrayList<>();
builder.setCancelable(false);
builder.setCustomTitle(LayoutInflater.from(getActivity()).inflate(R.layout.dialog_layout,null))
.setSingleChoiceItems(R.array.Category,-1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
switch (i){
case 0:
Selection = 0;
Toast.makeText(getActivity(),"BOOKS",Toast.LENGTH_SHORT).show();
break;
case 1:
Selection =1;
selecedItem.add("PC GAMES");
Toast.makeText(getActivity(),"PC GAMES",Toast.LENGTH_SHORT).show();
break;
case 2:
Selection = 2;
selecedItem.add("PS3 GAMES");
Toast.makeText(getActivity(),"PS3 GAMES",Toast.LENGTH_SHORT).show();
break;
case 3:
Selection =3;
selecedItem.add("PS4 GAMES");
Toast.makeText(getActivity(),"PS4 GAMES",Toast.LENGTH_SHORT).show();
break;
}
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
selecedItem.clear();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
public int getSelection() {
return Selection;
}
I created the getSelection()method in order to know what the user has selected and pass that value to another activity.So if the user pressed the item which is at index 0 then Selection is set to 0.The other activity is the one responsible for doing the search.The code for the other activity is:
package com.example.database.fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.database.R;
import com.example.database.models.Post;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import java.util.ArrayList;
public class RecentPostsFragment extends PostListFragment {
private RecyclerView mRecycler;
private DatabaseReference myDatabase;
public int selection;
public RecentPostsFragment(){
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
myDatabase = FirebaseDatabase.getInstance().getReference();
mRecycler = (RecyclerView)view.findViewById(R.id.messages_list);
}
#Override
public Query getQuery(DatabaseReference databaseReference) {
Log.d("TAG", "getQuery: Selection"+ getSelection());
if(getSelection()==0){
return databaseReference.child("Book");
}else if(getSelection()==1) {
return databaseReference.child("PC GAMES");
}
else if(getSelection()==2){
return databaseReference.child("PS3 GAMES");
}
else {
return databaseReference.child("PS4 GAMES");
}
}
#Override
public void setLayout() {
super.setLayout();
StaggeredGridLayoutManager mManager = new StaggeredGridLayoutManager(2,1);
mManager.setReverseLayout(true);
mRecycler.setLayoutManager(mManager);
}
}
The problem that im facing is that selection is always zero...I can seem to make the value returned by getSelection() to be another value.It always returns a zero.But after a while when the activity has been created again it calls the correct value how can i make it the filter instant

Error in Alert dialog

There is an error in 'return view' at listview.setOnItemLongClickListener method. The error says cannot return a value from a method with void result type. I am trying to create an alert dialog where it will notify the user whether it wants to delete.
package com.example.user.swen;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import com.example.user.swen.DB.RecordsDataSource;
import com.example.user.swen.Model.Records;
public class Record extends ListActivity {
public Button NewButton;
public RecordsDataSource Recordsdatasource;
ArrayAdapter<Records> RecordAdapter;
List<Records> records;
ListView listview;
Records selectedRecord;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record);
Addrecords();
//Referencing the Database
Recordsdatasource = new RecordsDataSource(this);
Recordsdatasource.open();
LayoutInflater inflater = LayoutInflater.from(Record.this);
View view = inflater.inflate(R.layout.activity_record, null);
//set the listView to use the custom List Adapter
records = (List<Records>) Recordsdatasource.getAll();
RecordAdapter = new RecordAdapter(this, 0, (ArrayList<Records>) records);
listview = (ListView) findViewById(android.R.id.list);
listview.setAdapter(RecordAdapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedRecord = records.get(position);
AlertDialog.Builder a_builder = new AlertDialog.Builder(Record.this);
a_builder.setMessage("Duty: " + selectedRecord.getType())
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alert = a_builder.create();
alert.setTitle(Html.fromHtml("<font color='#08ae9e'>Information</font>"));
alert.show();
}
});
listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
selectedRecord = records.get(position);
AlertDialog.Builder a_builder = new AlertDialog.Builder(Record.this);
a_builder.setMessage("Are you sure you want to delete?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
deleteItem(selectedRecord);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = a_builder.create();
alert.setTitle(Html.fromHtml("<font color='#08ae9e'>Alert!!</font>"));
alert.show();
return true;
}
});
return view;
}
public void Addrecords() {
NewButton = (Button) findViewById(R.id.NewButton);
NewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent addrecords = new Intent(Record.this, NewRecord.class);
startActivity(addrecords);
}
});
}
public static void showToast(Context context, String text) {
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
private void deleteItem(Records selectedRecord) {
Recordsdatasource.removeRecords(selectedRecord);
showToast(this, "Usage deleted");
RecordAdapter.notifyDataSetChanged();
RecordAdapter.notifyDataSetInvalidated();
refreshDisplay();
}
private void refreshDisplay() {
records = Recordsdatasource.getAll();
RecordAdapter.clear();
RecordAdapter.addAll(records);
}
}
You are trying to return a View from your Activity's onCreate() method.
#Override
protected void onCreate(Bundle savedInstanceState) {
LayoutInflater inflater = LayoutInflater.from(Record.this);
View view = inflater.inflate(R.layout.activity_record, null);
//...
return view;
}
As you can see, onCreate() in an Activity has a void return type, meaning you shouldn't be returning anything in this method.
From the looks of your code, you are attempting to use this layout as the Activity's layout, but you are confusing the View inflation code with that used in a Fragment's onCreateView() method, which does indeed require you to return a View.
In an Activity, you need to call setContentView() to set the layout. You can either set the layout using the resource ID via setContentView(R.layout.activity_record), or if you want to inflate the View yourself you can call setContentView(view).
The call return view is actually located in onCreate. The function onCreate is declared to return nothing (void). Therefore, you cannot return an instance of View. You just have to remove that line or replace it with return; Also, onItemLongClick must return a boolean. So you can't move return view there either.

How to fix setOnItemClickListener inside ListView

I have a ListView which has more rows in it. Inside of rows I have two LinearLayouts (deleteItem and editItem) which has setOnClickListener on them. When I'm trying to click on deleteItem or editItem it works only at the second touch, i don't know why.. I've read some answers on stackoverflow but I couldn't find one answer to fix my problem..
This is the code:
import org.json.JSONArray;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.currencymeeting.adapters.GetAllMyCurrencyListViewAdapter;
import com.currencymeeting.beans.User;
import com.currencymeeting.connectors.DeleteCurrencyConnector;
import com.currencymeeting.connectors.MyCurrencyConnector;
import com.currencymeeting.controllers.MessageDialogController;
import com.currencymeeting.controllers.VariableController;
public class MyCurrencyActivity extends FragmentActivity {
private ListView getAllMyCurrencyListView;
private ProgressDialog dialog;
private View view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_currency);
this.dialog = ProgressDialog.show(MyCurrencyActivity.this, MessageDialogController.PROGRESS_DIALOG_TITLE, MessageDialogController.PROGRESS_DIALOG_MESSAGE);
this.getAllMyCurrencyListView = (ListView) findViewById(R.id.getAllMyCurrencyListView);
new GetMyCurrencyResults().execute(new MyCurrencyConnector());
getAllMyCurrencyListView.setOnItemClickListener(
new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
MyCurrencyActivity.this.view = view;
final TextView itemID = (TextView) view.findViewById(R.id.itemID);
final LinearLayout deleteItem = (LinearLayout) view.findViewById(R.id.deleteItem);
final LinearLayout editItem = (LinearLayout) view.findViewById(R.id.editItem);
deleteItem.setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(MyCurrencyActivity.this)
.setMessage("Are you sure do you want to delete it?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String vid = itemID.getText().toString();
String userId = ""+VariableController.getInstance().getUser().getId();
new DeleteCurrencyTask().execute(userId, vid);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
);
editItem.setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),EditCurrencyActivity.class);
startActivity(intent);
}
}
);
}
}
);
final LinearLayout menu = (LinearLayout) findViewById(R.id.menu);
menu.setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MenuLoggedActivity.class);
startActivity(intent);
}
}
);
}
public void setListAdapter(JSONArray jsonArray){
this.getAllMyCurrencyListView.setAdapter(new GetAllMyCurrencyListViewAdapter(jsonArray,this));
this.dialog.dismiss();
};
private class GetMyCurrencyResults extends AsyncTask<MyCurrencyConnector,Void,JSONArray>{
#Override
protected JSONArray doInBackground(MyCurrencyConnector... params) {
User user = VariableController.getInstance().getUser();
return params[0].getAllResults(user);
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
setListAdapter(jsonArray);
}
}
private class DeleteCurrencyTask extends AsyncTask<String,Void,String[]>{
#Override
protected String[] doInBackground(String... params) {
return params;
}
#Override
protected void onPostExecute(String[] result) {
boolean status = new DeleteCurrencyConnector().deleteTransaction(result[0],result[1]);
LinearLayout itemViewId = (LinearLayout) MyCurrencyActivity.this.view.findViewById(R.id.itemViewID);
if(status){
new GetMyCurrencyResults().execute(new MyCurrencyConnector());
} else {
Toast.makeText(MyCurrencyActivity.this, "Error", Toast.LENGTH_LONG).show();
}
}
}
}
Your problem might be caused by the way your program executes. You first thread your adapter initialization, and then your main thread starts attaching onclick listeners before your adapter initialization finishes. This means your listview will have a click listener but not the items in the adapter, and when you click the listview once
new GetMyCurrencyResults().execute(new MyCurrencyConnector());
this fires off in your DeleteCurrencyTask and sets the adapter again. To fix this try putting setOnClick initializaion in the post execute of your
private class GetMyCurrencyResults extends AsyncTask<MyCurrencyConnector,Void,JSONArray>{
I believe I realized why the event of deleteItem and editItem is called only on second click, because deleteItem and editItem clickListeners are atached only when getAllMyCurrencyListView.setOnItemClickListener (when I click on row) is called not when the code is loaded. So I guess I have to find another way to make these events

Categories

Resources