What's wrong with my code, it won't recognize position? - android

I am making a simple planner app, with one xml and one activity. Here is MainActivity, where basically I take editText input, turn it into a listView item with button onClick, and save it. The only probmlem is my alert dialog for when you want to delete an item has an error - it won't recognize the word "position". I feel like it's just some dumb typo..? Thank you.
package com.kass.planner2;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends Activity {
EditText et;
ListView lv;
ArrayAdapter<String> adapter;
Button btn;
ArrayList<String> list = new ArrayList<String>();
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText);
lv = (ListView) findViewById(R.id.listView);
btn = (Button) findViewById(R.id.button);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
lv.setAdapter(adapter);
LoadPreferences();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String task = et.getText().toString();
adapter.add(task);
adapter.notifyDataSetChanged();
SavePreferences("LISTS", task);
}
});
// set ListView item listener
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view; final int position, long id) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setTitle("Confirm Delete");
alertDialogBuilder.setMessage("Sure you want to delete?");
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
adapter.remove(adapter.getItem(position));
}
});
alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});}
protected void SavePreferences(String key, String value) {
// TODO Auto-generated method stub
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = data.edit();
editor.putString(key, value);
editor.commit();
}
protected void LoadPreferences(){
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
String dataSet = data.getString("LISTS", " ");
adapter.add(dataSet);
adapter.notifyDataSetChanged();
}
}`

Try this way :
ArrayAdapter<String> adapter = (ArrayAdapter<String>)getListView().getAdapter();
adapter.remove(adapter.getItem(info.position));
adapter.notifyDataSetChanged();

May be, this needed.... adapter.notifyDataSetChanged(); when remove..
alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
adapter.remove(adapter.getItem(position));
adapter.notifyDataSetChanged();
}
});

The position variable needs to be final if you want to access it there.
Do it as follows:
final int p = position; // just before setPositiveButton
alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
adapter.remove(adapter.getItem(p));
}
});

Related

how to display the name after the user inputted it

How to display the name after the user has inputted the data and how to make it a button that i can add something there making it something like a profile i want you add a alarm inside it but first i got to make this database.
i dont really know how to how to fix it i tried this code but it doesnt work or it always resulted to a force close when i try to add a
name = edtName.getText().toString();
AccountInfo a = new AccountInfo(name);
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private TabLayout tabLayout;
private AppBarLayout appBarLayout;
private ViewPager viewPager;
private EditText edtName;
private Button btnAdd;
Spinner spin1;
Spinner spin2;
Spinner spin3;
#SuppressLint("WrongConstant")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout = findViewById(R.id.tablayout);
appBarLayout = findViewById(R.id.bar);
viewPager = findViewById(R.id.viewpager);
edtName = findViewById(R.id.edtName);
spin1 = findViewById(R.id.spinnerFrequency);
spin2 = findViewById(R.id.SpinnerTime);
spin3 = findViewById(R.id.SpinnerQty);
btnAdd = findViewById(R.id.btnAdd);
String name = edtName.getText().toString();
Adapter adapter = new Adapter(getSupportFragmentManager());
/*screen*/
adapter.AddFragment(new Drugfragment(), "Drug");
adapter.AddFragment(new Appointmentfragment(), "Appointment");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
/* DBHelper mDBHlpr = new DBHelper(this);
AccountInfo a = new AccountInfo(name);
mDBHlpr.insertRecord(a);
String account_just_inserted = mDBHlpr.getAccountName();
Log.d(
"ACCOUNT INSERTED",
"The Name of the account just inserted is :-" + account_just_inserted
);*/
final Account c = new Account();
if(c==null) {
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("LOG IN");
LayoutInflater inflater = MainActivity.this.getLayoutInflater();
builder.setView(inflater.inflate(R.layout.account,null));
builder.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = MainActivity.this.getLayoutInflater();
builder.setView(inflater.inflate(R.layout.accountname,null));
builder.setPositiveButton("Yes",new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id) {
}
});
builder.show();
}
});
builder.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
System.exit(0);
}
});
builder.show();
}
}
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String text = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
MAINACTIVITY
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private TabLayout tabLayout;
private AppBarLayout appBarLayout;
private ViewPager viewPager;
private EditText edtName;
private Button btnAdd;
Spinner spin1;
Spinner spin2;
Spinner spin3;
#SuppressLint("WrongConstant")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout = findViewById(R.id.tablayout);
appBarLayout = findViewById(R.id.bar);
viewPager = findViewById(R.id.viewpager);
edtName = findViewById(R.id.edtName);
spin1 = findViewById(R.id.spinnerFrequency);
spin2 = findViewById(R.id.SpinnerTime);
spin3 = findViewById(R.id.SpinnerQty);
btnAdd = findViewById(R.id.btnAdd);
Adapter adapter = new Adapter(getSupportFragmentManager());
/*screen*/
adapter.AddFragment(new Drugfragment(), "Drug");
adapter.AddFragment(new Appointmentfragment(), "Appointment");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
/* DBHelper mDBHlpr = new DBHelper(this);
AccountInfo a = new AccountInfo(name);
mDBHlpr.insertRecord(a);
String account_just_inserted = mDBHlpr.getAccountName();
Log.d(
"ACCOUNT INSERTED",
"The Name of the account just inserted is :-" + account_just_inserted
);*/
final Account c = new Account();
if(c==null) {
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("LOG IN");
LayoutInflater inflater = MainActivity.this.getLayoutInflater();
builder.setView(inflater.inflate(R.layout.account,null));
builder.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = MainActivity.this.getLayoutInflater();
builder.setView(inflater.inflate(R.layout.accountname,null));
builder.setPositiveButton("Yes",new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id) {
}
});
builder.show();
}
});
builder.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
System.exit(0);
}
});
builder.show();
}
}
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String text = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
You can use textwatcher for this , it will change your name String every time when text is changing in EditText field.
et1.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
name = edtName.getText().toString();
//it will change your name String every time when text is changing in EditText fiels
}
});
Hope this is what you want.
Its rather simple. On vb.net is just this... c# is only slightly different.
Dim b As New Button
b.text = "New Button"
b.Location = New Point(0, 0)
AddHandler b.Click, AddressOf handle_click
Private Sub handle_click(sender As Object, e As EventArgs)
'code here to react to the buttons click.
End Sub
Here's a link with lots of info .. Hope it helps
Controls in Java

My spinner onClickListener will not work?

I am trying to make a drop down menu that changes the text of a text view to "Player Selected: " and then a player selected from the drop down menu. However when i test the app on android, i can click a spinner item but it doesn't register anything. The textview doesn't change, and it doesn't log anything as if it wasn't registering the click listener at all. Here's my code
package com.example.buddyfizzturtles.stattracker;
import android.app.Dialog;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.*;
import android.widget.AdapterView.OnItemSelectedListener;
public class MainActivity extends AppCompatActivity {
EditText input;
Button showBtn;
TextView showPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Players p = new Players();
// Pop-Up Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Enter Name");
builder.setIcon(R.drawable.basketball);
builder.setMessage("Enter a name for your player");
input = new EditText(this);
builder.setView(input);
//Set Positive Button
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String text = input.getText().toString();
Player x = new Player(text);
p.addPlayer(x);
Toast.makeText(MainActivity.this, "Added " + text + " to your player list", Toast.LENGTH_SHORT).show();
}
});
//Set Negative Button
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
//Create Builder
final AlertDialog ad = builder.create();
//Button
showBtn = (Button) findViewById(R.id.addPlayerButton);
showBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ad.show();
}
});
//Spinner Items
Spinner dropNames = (Spinner) findViewById(R.id.choosePlayer);
dropNames.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
Log.d("CLICKED:", "Successful Click");
showPlayer = (TextView) findViewById(R.id.showPlayer);
showPlayer.setText("Player Selected: " + );
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
ArrayAdapter<Player> adapter = new ArrayAdapter<Player>(this, android.R.layout.simple_spinner_item, p.returnList());
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropNames.setAdapter(adapter);
}
}
You can try this. Let's see if it resolves
Spinner spinner=(Spinner)findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Log.d("CLICKED:", "Successful Click");
showPlayer = (TextView) findViewById(R.id.showPlayer);
showPlayer.setText("Player Selected: " + );
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Hope this helps
If the spinner is loading data, then I think this will help you (It's good to define showPlayer outside the listener).
Spinner dropNames = (Spinner) findViewById(R.id.choosePlayer);
TextView showPlayer = (TextView) findViewById(R.id.showPlayer);
dropNames.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(
AdapterView<?> parent, View view, int position, long id) {
showPlayer.setText("Player Selected: " + String.valueOf(dropNames.getSelectedItem());
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});

I want to display data from AlertDialog with an editText and then display it to a list view it'snot working, this is my code

package com.example.riplee07.trydialog;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<String> listss = new ArrayList<String>();
ArrayAdapter <String>adapter;
String add1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText tt = (EditText)findViewById(R.id.editText);
final ListView lv = (ListView)findViewById(R.id.listView1);
Button br = (Button)findViewById(R.id.button);
add1 = tt.getText().toString();
adapter=new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,listss);
lv.setAdapter(adapter);
listss.add(add1);
adapter.notifyDataSetChanged();
br.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View ss = LayoutInflater.from(MainActivity.this).inflate(R.layout.textt,null);
final AlertDialog.Builder builderDialog = new AlertDialog.Builder(MainActivity.this);
builderDialog.setView(ss)
.setPositiveButton("Print", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
listss.add(add1);
adapter.notifyDataSetChanged();
}
}).setNegativeButton("Cancel", null)
.setCancelable(false);
AlertDialog alert = builderDialog.create();
alert.show();
}
});
}
}
Try this code below (for getting edittext data):
br.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View ss = LayoutInflater.from(MainActivity.this).inflate(R.layout.textt,null);
final AlertDialog.Builder builderDialog = new AlertDialog.Builder(MainActivity.this);
builderDialog.setView(ss)
.setPositiveButton("Print", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText et = (EditText) ss.findViewById(E.id.editText);
listss.add(et.getText().toString());
adapter.notifyDataSetChanged();
}
}).setNegativeButton("Cancel", null)
.setCancelable(false);
AlertDialog alert = builderDialog.create();
alert.show();
}
});
Here is the method in which i call on Button button.setOnClickListener
public void saveNote(View view){
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.add_new_note_layout);
mTitle = (EditText)dialog.findViewById(R.id.titleID);
mMessage = (EditText)dialog.findViewById(R.id.messageID);
save = (Button)dialog.findViewById(R.id.saveBtn);
setFilePathll();
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int titleLength = mTitle.getText().length();
if(titleLength != 0){
String title = mTitle.getText().toString();
String msg = mMessage.getText().toString();
helper.addNote(title, mFilePath, msg);
dialog.dismiss();
}
else
{
Toast.makeText(MainActivity.this,"Empty Message is not valid",Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
Here helper.addNote(title, mFilePath, msg); is the method which i declared in the database helper class to insert data.
you Should use RecyclerView for what you want instead of using 'ListView'

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