I am trying to write a notes management app, when I am adding few new notes, delete them and then try to add new note the app is crashing on setcontentview().
I added the log, it can be triggered easily by deleting the first editText and then adding a new one.
public class Mainpage extends AppCompatActivity {
private LinearLayout MyLayout;
private ScrollView sv;
private List<EditText> et = new ArrayList<EditText>();
private List<EditText> ct = new ArrayList<EditText>();
private List<TextView> tv = new ArrayList<TextView>();
private List<CheckBox> cb = new ArrayList<CheckBox>();
private Button btn;
final Context context = this;
private CountDownTimer timer;
boolean isWaiting;
int last_added;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainpage);
last_added = 0;
//btn = (Button) findViewById(R.id.btn);
//btn.setVisibility(View.INVISIBLE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_mainpage, menu);
sv = new ScrollView(this);
MyLayout = new LinearLayout(this);
MyLayout.setOrientation(LinearLayout.VERTICAL);
sv.addView(MyLayout);
timer = new CountDownTimer(500,500) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
isWaiting = false;
}
};
btn = new Button(this);
btn.setText("Accept");
btn.setVisibility(View.INVISIBLE);
MyLayout.addView(btn);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
else if (id == R.id.action_add) {
et.add(new EditText(this)) ;
tv.add(new TextView(this));
ct.add(new EditText(this));
cb.add(new CheckBox(this));
cb.get(ct.size() -1).setVisibility(View.INVISIBLE);
ct.get(ct.size() -1).setVisibility(View.INVISIBLE);
Calendar cal = Calendar.getInstance();
String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
tv.get(tv.size() -1).setText("created on" + date);
et.get(et.size() - 1).setText("weeeeeeeeeee~!");
MyLayout.addView(et.get(et.size() - 1));
MyLayout.addView(ct.get(ct.size() -1));
MyLayout.addView(tv.get(tv.size() - 1));
MyLayout.addView(cb.get(cb.size() - 1));
this.setContentView(sv);
et.get(last_added).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i=0;i<et.size();i++)
{
if(et.get(i) == v)
{
last_added = i + 1;
break;
}
}
if(isWaiting) {
isWaiting = false;
timer.cancel();
// TODO: open a new EditText
if(ct.get(last_added -1).isShown())
{
ct.get(last_added -1).setVisibility(View.INVISIBLE);
}
else
{
ct.get(last_added -1).setVisibility(View.VISIBLE);
}
}
else {
isWaiting = true;
timer.start();
}
}
});
last_added++;
return true;
}
else if (id == R.id.action_delete) {
btn.setVisibility(View.VISIBLE);
for (int i = 0; i < cb.size(); i++) {
cb.get(i).setVisibility(View.VISIBLE);
}
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int j=0; j < cb.size();j++)
{
if(cb.get(j).isChecked())
{
et.get(j).setVisibility(View.GONE);
tv.get(j).setVisibility(View.GONE);
ct.get(j).setVisibility(View.GONE);
cb.get(j).setVisibility(View.GONE);
et.remove(j);
tv.remove(j);
ct.remove(j);
cb.remove(j);
}
}
btn.setVisibility(View.INVISIBLE);
for (int i = 0; i < cb.size(); i++) {
cb.get(i).setVisibility(View.INVISIBLE);
}
}
});
this.setContentView(sv);
return true;
}
else if (id == R.id.action_search) {
return true;
}
else if (id == R.id.action_send) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
log
10-16 11:10:34.203 13030-13030/com.example.user_pc.notes E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.user_pc.notes, PID: 13030
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.example.user_pc.notes.Mainpage.onOptionsItemSelected(Mainpage.java:125)
at android.app.Activity.onMenuItemSelected(Activity.java:2908)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:325)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:147)
at android.support.v7.internal.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:100)
at android.support.v7.app.AppCompatDelegateImplV7.onMenuItemSelected(AppCompatDelegateImplV7.java:609)
at android.support.v7.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:811)
at android.support.v7.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:153)
at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:958)
at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:948)
at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:619)
at android.support.v7.internal.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:139)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
1) Your error
Error shows that in 125 you have IndexOutOfBoundsException exeption.
at com.example.user_pc.notes.Mainpage.onOptionsItemSelected(Mainpage.java:125)
You call get functions on one of your array. There are one item in list. There for maxumum index must be 0 but you call 1 it throws IndexOutOfBoundsException.
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
2)You don't need to create additonal arraylist as yours
private List<EditText> et = new ArrayList<EditText>();
LinearLayout has following methods. And you can get them from your layout.
getChildAt());
getChildCount();
3) You don't need to call following method on ScrollView. It has to automatically
this.setContentView(sv);
4) And finally your code very smashed. Try use standart way. Read android tutorial https://developer.android.com/guide/topics/ui/index.html
fixed it .
The last added was too high when I tried to add new EditText.
public class Mainpage extends AppCompatActivity {
private LinearLayout MyLayout;
private ScrollView sv;
private List<EditText> et = new ArrayList<EditText>();
private List<EditText> ct = new ArrayList<EditText>();
private List<TextView> tv = new ArrayList<TextView>();
private List<CheckBox> cb = new ArrayList<CheckBox>();
private Button btn;
final Context context = this;
private CountDownTimer timer;
boolean isWaiting;
int last_added;
int num_removed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainpage);
last_added = 0;
//btn = (Button) findViewById(R.id.btn);
//btn.setVisibility(View.INVISIBLE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_mainpage, menu);
sv = new ScrollView(this);
MyLayout = new LinearLayout(this);
MyLayout.setOrientation(LinearLayout.VERTICAL);
sv.addView(MyLayout);
timer = new CountDownTimer(500,500) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
isWaiting = false;
}
};
btn = new Button(this);
btn.setText("Accept");
btn.setVisibility(View.INVISIBLE);
MyLayout.addView(btn);
///search shit
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
else if (id == R.id.action_add) {
et.add(new EditText(this)) ;
tv.add(new TextView(this));
ct.add(new EditText(this));
cb.add(new CheckBox(this));
cb.get(ct.size() -1).setVisibility(View.INVISIBLE);
ct.get(ct.size() -1).setVisibility(View.INVISIBLE);
Calendar cal = Calendar.getInstance();
String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
tv.get(tv.size() -1).setText("created on" + date);
et.get(et.size() - 1).setText("weeeeeeeeeee~!");
MyLayout.addView(et.get(et.size() - 1));
MyLayout.addView(ct.get(ct.size() -1));
MyLayout.addView(tv.get(tv.size() - 1));
MyLayout.addView(cb.get(cb.size() - 1));
this.setContentView(sv);
et.get(last_added).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i=0;i<et.size();i++)
{
if(et.get(i) == v)
{
last_added = i + 1;
break;
}
}
if(isWaiting) {
isWaiting = false;
timer.cancel();
// TODO: open a new EditText
if(ct.get(last_added -1).isShown())
{
ct.get(last_added -1).setVisibility(View.INVISIBLE);
}
else
{
ct.get(last_added -1).setVisibility(View.VISIBLE);
}
}
else {
isWaiting = true;
timer.start();
}
}
});
last_added++;
return true;
}
else if (id == R.id.action_delete) {
num_removed = 0;
btn.setVisibility(View.VISIBLE);
for (int i = 0; i < cb.size(); i++) {
cb.get(i).setVisibility(View.VISIBLE);
}
btn.setOnClickListener(new View.OnClickListener() {
int checked =0;
#Override
public void onClick(View v) {
while(true)
{
for(int j=0;j< cb.size();j++)
{
if(cb.get(j).isChecked())
{
checked++;
}
}
if(checked == 0)
{
break;
}
for(int i=0;i<cb.size();i++)
{
if(cb.get(i).isChecked())
{
et.get(i).setVisibility(View.GONE);
tv.get(i).setVisibility(View.GONE);
ct.get(i).setVisibility(View.GONE);
cb.get(i).setVisibility(View.GONE);
et.remove(i);
tv.remove(i);
ct.remove(i);
cb.remove(i);
last_added--;
}
}
checked = 0;
}
btn.setVisibility(View.INVISIBLE);
for (int i = 0; i < cb.size(); i++) {
cb.get(i).setVisibility(View.INVISIBLE);
}
}
});
this.setContentView(sv);
return true;
}
else if (id == R.id.action_search) {
btn.setVisibility(View.VISIBLE);
for (int i = 0; i < cb.size(); i++) {
cb.get(i).setVisibility(View.VISIBLE);
}
return true;
}
else if (id == R.id.action_send)
{
btn.setVisibility(View.VISIBLE);
for (int i = 0; i < cb.size(); i++)
{
cb.get(i).setVisibility(View.VISIBLE);
cb.get(i).setChecked(false);
}
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String [] to = new String[]{};
for(int j=0; j < cb.size();j++)
{
if(cb.get(j).isChecked())
{
sendEmail(et.get(j).getText().toString(),ct.get(j).getText().toString());
}
}
btn.setVisibility(View.INVISIBLE);
for (int i = 0; i < cb.size(); i++)
{
cb.get(i).setVisibility(View.INVISIBLE);
}
}});
this.setContentView(sv);
return true;
}
return super.onOptionsItemSelected(item);
}
protected void sendEmail(String subject,String Context)
{
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_SUBJECT,subject);
emailIntent.putExtra(Intent.EXTRA_TEXT,Context);
emailIntent.setType("message/rfc822");
startActivity(Intent.createChooser(emailIntent,"Email"));
}
}
Related
I'm creating an alarm clock application, and I'd like the homepage to have multiple Alarm objects shown, like the default Android clock application. To do this, I've been trying a ListView to create a button for each Alarm in an ArrayList of Alarms.
Debugging the crashes this caused, I've found that it can't implement Serializable or Parcelable due to the Context object within it, and thus I have no way to pass it from one activity to another. The ListView works fine when I create the alarms from the MainActivity itself, but when I use the CreateAlarmActivity that takes input from the user, the ListView won't pass through and it crashes.
I haven't found this precise problem on StackOverflow. This problem is close (Implementing Parcelable Class That Requires Context) but involves a database, which seems overkill for my needs.
If a ListView is even the best way to go about this, how should I pass the ListView between activities? If there's a better way, what would be a better implementation?
I apologise for the large amount of code. I'm not sure exactly what may prove relevant, so I've erred on the side of too much information rather than too little.
Code:
MainActivity.java:
public class MainActivity extends AppCompatActivity {
ListView alarmListView;
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
int[] testArray = {0, 0, 0, 0, 0, 0, 0};
Alarm testAlarm = new Alarm("testAlarm", 6, 1, true, testArray, 10);
Alarm testAlarm2 = new Alarm("testAlarm2", 6, 1, true, testArray, 10);
AlarmAdapter alarmAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmListView = (ListView) findViewById(R.id.alarmListView);
alarmList.add(testAlarm);
alarmList.add(testAlarm2);
alarmAdapter = new AlarmAdapter(MainActivity.this, alarmList);
alarmListView.setAdapter(alarmAdapter);
alarmAdapter.notifyDataSetChanged();
}
// Create alarm when user presses FAB on activity_main.xml.
public void createNewAlarm(View view) {
Intent createAlarmIntent = new Intent(this, CreateAlarmActivity.class);
createAlarmIntent.putExtra("alarmList", alarmList);
createAlarmIntent.putExtra("alarmAdapter", alarmAdapter);
startActivity(createAlarmIntent);
}
public void testAlarmActivated(View view){
Intent activateAlarmIntent = new Intent(this, AlarmActivatedActivity.class);
startActivity(activateAlarmIntent);
}
}
AlarmAdapter.java:
public class AlarmAdapter extends BaseAdapter implements Parcelable {
private Context alarmContext;
private ArrayList<Alarm> alarmList;
public AlarmAdapter(Context context, ArrayList arrayList) {
super();
alarmContext = context;
alarmList = arrayList;
}
public int getCount() {
return alarmList.size();
}
// getView method is called for each item of ListView
public View getView(int position, View view, ViewGroup parent) {
// inflate the layout for each item of listView
LayoutInflater inflater = (LayoutInflater) alarmContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.alarm_row, parent, false);
// get the reference of textView and button
TextView alarmName = (TextView) view.findViewById(R.id.title);
// Button alarmButton = (Button) view.findViewById(R.id.alarmButton);
// Set the title and button name
Alarm tempAlarm = alarmList.get(position);
alarmName.setText(tempAlarm.name);
// btnAction.setText("Action " + position);
// Click listener of button
/*btnAction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Logic goes here
}
});*/
return view;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
protected AlarmAdapter(Parcel in) {
alarmContext = (Context) in.readValue(Context.class.getClassLoader());
if (in.readByte() == 0x01) {
alarmList = new ArrayList<Alarm>();
in.readList(alarmList, Alarm.class.getClassLoader());
} else {
alarmList = null;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(alarmContext);
if (alarmList == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(alarmList);
}
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<AlarmAdapter> CREATOR = new Parcelable.Creator<AlarmAdapter>() {
#Override
public AlarmAdapter createFromParcel(Parcel in) {
return new AlarmAdapter(in);
}
#Override
public AlarmAdapter[] newArray(int size) {
return new AlarmAdapter[size];
}
};
}
Alarm.java:
public class Alarm implements Serializable {
String name;
int hour;
int minute;
boolean isPm;
int[] daysActive;
int snoozeTimer;
public Alarm(String startName, int startHour, int startMinute,
Boolean startIsPm, int[] startDaysActive, int startSnoozeTimer){
name = startName;
hour = startHour;
minute = startMinute;
isPm = startIsPm;
daysActive = startDaysActive;
snoozeTimer = startSnoozeTimer;
}
}
CreateAlarmActivity.java:
public class CreateAlarmActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_alarm);
alarmList = (ArrayList<Alarm>)getIntent().getSerializableExtra("alarmList");
alarmAdapter = (AlarmAdapter)getIntent().getParcelableExtra("alarmAdapter)");
}
int alarmHour = 6;
int alarmMinute = 0;
boolean isPm = false;
int snoozeTimer = 10;
int [] daysActive = new int[] {0, 0, 0, 0, 0, 0, 0};
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
AlarmAdapter alarmAdapter;
// Add one to the hour of the alarm.
public void changeHour(View view) {
Button btn = findViewById(R.id.buttonHours);
if (alarmHour == 12){
alarmHour = 0;
}
else {
alarmHour++;
}
btn.setText(Integer.toString(alarmHour));
}
// Add one to the minute of the alarm.
public void changeMinute(View view) {
Button btn = findViewById(R.id.buttonMinutes);
if (alarmMinute == 59) {
alarmMinute = 0;
}
else {
alarmMinute++;
}
if (alarmMinute < 10) {
// Ensure minute 1 becomes 01, e.g, 6:01 am.
btn.setText("0" + Integer.toString(alarmMinute));
}
else {
btn.setText(Integer.toString(alarmMinute));
}
}
public void changeAmPm(View view) {
Button btn = findViewById(R.id.buttonAmPm);
if (isPm == true) {
isPm = false;
btn.setText("am");
}
else {
isPm = true;
btn.setText("pm");
}
}
public void changeSnoozeTimer(View view) {
Button btn = findViewById(R.id.buttonSnoozeTimer);
if (snoozeTimer == 15){
snoozeTimer = 1;
}
else {
snoozeTimer++;
}
btn.setText(Integer.toString(snoozeTimer));
}
public void finishAlarm(View view){
EditText alarmName = findViewById(R.id.alarmName);
String name = alarmName.getText().toString();
Alarm alarm = new Alarm(name, alarmHour, alarmMinute, isPm, daysActive, snoozeTimer);
alarmList.add(alarm);
alarmAdapter.notifyDataSetChanged();
Intent finishAlarmIntent = new Intent(this, MainActivity.class);
finishAlarmIntent.putExtra("alarmList", alarmList);
startActivity(finishAlarmIntent);
}
public void cancelAlarm(View view){
Intent cancelAlarmIntent = new Intent(this, MainActivity.class);
startActivity(cancelAlarmIntent);
}
public void changeSunday(View view) {
Button btn = findViewById(R.id.buttonSunday);
if (daysActive[0] == 0){
daysActive[0] = 1;
// Source: https://stackoverflow.com/questions/2173936/how-to-set-background-color-of-a-view
// Credit goes to EddieB for the below line.
btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
}
else {
daysActive[1] = 0;
// Source: https://stackoverflow.com/questions/14802354/how-to-reset-a-buttons-background-color-to-default
// Credit goes to Ivo for the below line.
btn.getBackground().clearColorFilter();
}
}
public void changeMonday(View view) {
Button btn = findViewById(R.id.buttonMonday);
if (daysActive[1] == 0){
daysActive[1] = 1;
btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
}
else {
daysActive[1] = 0;
btn.getBackground().clearColorFilter();
}
}
public void changeTuesday(View view) {
Button btn = findViewById(R.id.buttonTuesday);
if (daysActive[2] == 0){
daysActive[2] = 1;
btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
}
else {
daysActive[2] = 0;
btn.getBackground().clearColorFilter();
}
}
public void changeWednesday(View view) {
Button btn = findViewById(R.id.buttonWednesday);
if (daysActive[3] == 0){
daysActive[3] = 1;
btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
}
else {
daysActive[3] = 0;
btn.getBackground().clearColorFilter();
}
}
public void changeThursday(View view) {
Button btn = findViewById(R.id.buttonThursday);
if (daysActive[4] == 0){
daysActive[4] = 1;
btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
}
else {
daysActive[4] = 0;
btn.getBackground().clearColorFilter();
}
}
public void changeFriday(View view) {
Button btn = findViewById(R.id.buttonFriday);
if (daysActive[5] == 0){
daysActive[5] = 1;
btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
}
else {
daysActive[5] = 0;
btn.getBackground().clearColorFilter();
}
}
public void changeSaturday(View view) {
Button btn = findViewById(R.id.buttonSaturday);
if (daysActive[6] == 0){
daysActive[6] = 1;
btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
}
else {
daysActive[6] = 0;
btn.getBackground().clearColorFilter();
}
}
}
I'm new to Java and Android and am trying to figure out how to write a ListView and load the ListView from where it is saved.
I have ListView and each item on the ListView has a string and bool that changes if a checkbox for the item is checked or unchecked. I have a working method to add items to the ListView and am now trying to figure out how to write the ListView to a textfile.
I got some code for saving the ListView by clicking a menu item and them I'm trying to load it when I re-run the program in my OnCreate, but nothing is loading. I'm not sure if its the write or load that is not working or both.
Here is a class I made that works with my ListView.
Item.java
public class Item {
String name;
boolean isChecked = false;
public Item(String name) {this.name = name;}
public Item(String name, boolean checked){
this.name = name;
this.isChecked = checked;
}
#Override
public String toString(){
return name;
}
}
Here is my MainActivity.java that includes my saveList() and readFile()
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getName();
ArrayList<Item> items = new ArrayList<>();
private ListView lv;
private static final String sFile = "Saved.txt";
protected ListView getListView() {
if (lv == null) {
lv = (ListView) findViewById(android.R.id.list);
}
return lv;
}
protected void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}
protected ListAdapter getListAdapter() {
ListAdapter adapter = getListView().getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
return ((HeaderViewListAdapter) adapter).getWrappedAdapter();
} else {
return adapter;
}
}
private void deleteList()
{
if (!items.isEmpty())
{
items.clear();
}
lv.invalidateViews();
}
private void deleteCheckedItems()
{
SparseBooleanArray checked = lv.getCheckedItemPositions();
for(int i = 0; i < lv.getCount(); i++)
{
if (checked.get(i)==true)
{
items.remove(i);
}
lv.invalidateViews();
}
lv.clearChoices();
}
private void saveList(ArrayList<Item> itemlist) {
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(sFile, 0));
int iCnt = 0;
String allstring = "";
for (Item s : items)
{
if (s.isChecked)
{
iCnt++;
if (iCnt < items.size()) {
String thisstring;
thisstring = s.name + "\r\n";
out.write(thisstring);
allstring += thisstring;
} else {
String thisstring;
thisstring = s.name;
out.write(thisstring);
allstring += thisstring;
}
}
}
out.close();
//Toast.makeText(activity, allstring + " Written", duration).show();
}
catch (java.io.FileNotFoundException e)
{
}
catch (Exception ex)
{
// Toast.makeText(activity, "Write Exception : " + ex.getMessage(), duration).show();
}
}
public String readFile(ArrayList<Item> itemsList)
{
String sRet = "Nothing";
try
{
InputStream is = openFileInput(sFile);
if (is != null)
{
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String sLine;
StringBuffer sb = new StringBuffer();
while ((sLine = br.readLine()) != null)
sb.append(sLine + "\r\n");
is.close();
sRet = sb.toString();
// Toast.makeText(Toast.LENGTH_LONG).show();
}
}
catch (java.io.FileNotFoundException e)
{
}
catch (Exception ex)
{
// Toast.makeText(activi"Read Exception" + ex.getMessage(), Toast.LENGTH_LONG).show();
}
return sRet;
}
private void addItemDialog()
{
LayoutInflater inflater = LayoutInflater.from(this);
final View addView = inflater.inflate(R.layout.add, null);
new AlertDialog.Builder(this)
.setTitle("Add Item")
.setView(addView)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
EditText txtAdd = (EditText) addView.findViewById(R.id.etInput);
String sItem = (txtAdd).getText().toString();
items.add(new Item(sItem));
for (int i = 0; i < items.size(); i++)
{
lv.setItemChecked(i, items.get(i).isChecked);
}
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
}).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setListAdapter(new ArrayAdapter<Item>(this, android.R.layout.simple_list_item_multiple_choice, items));
lv = this.getListView();
for (int i = 0; i < items.size(); i++)
{
lv.setItemChecked(i, items.get(i).isChecked);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
readFile(items);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.add_item:
addItemDialog();
return true;
case R.id.clear_all:
deleteList();
return true;
case R.id.clear_checked:
deleteCheckedItems();
return true;
case R.id.write:
saveList(items);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
put your oncreate method above after declaration that means after this line
private static final String sFile = "Saved.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
.......
.......
//your code
}
//other method
Read Android activity lifecyle for better understanding
I want to show an alertdialog and get some input from user and after that, processing that inputs in an asynctask but the alertdialog become dismissed before get inputs and asynctask start to execute.
What should I do? Please help me. Here is my code;
private String[] newspapers,newspapersUrl,newspapersPath;
private String[] choosed,choosedUrl,choosedPath;
private boolean[] checked;
private int perNewspaper;
private boolean returned = false;
private AlertDialog.Builder builder;
private FetchingNewsByChoice fetchingNewsByChoice;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
returned = AlertDialogCreation();
if(returned)
{
fetchingNewsByChoice = new FetchingNewsByChoice((AppCompatActivity)MainActivity.this,choosed,choosedPath,perNewspaper);
fetchingNewsByChoice.execute();
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//***** Alert Dialog *****//
public boolean AlertDialogCreation()
{
//***** File Control And Creating An Dialog Interface if this is first usage *****//
File file = getApplicationContext().getFileStreamPath("First.txt");
if(!file.exists())
{
writeToFile("First.txt", "0",true);
}
if(readFromFile("First.txt",false)[0].equals("0"))
{
newspapers = readFromFile("Choicable Newspaper.txt",true);
newspapersUrl = readFromFile("Choicable Url.txt",true);
newspapersPath = readFromFile("Choicable Path.txt",true);
checked = new boolean[newspapers.length];
builder = new AlertDialog.Builder(this,R.style.AppCompatAlertDialogStyle);
builder.setTitle("Lütfen Güncel Haberlerini Takip Etmek İstediğiniz Siteleri Seçiniz..");
builder.setItems(newspapers, null);
builder.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
int count = 0;
for (int a = 0; a < newspapers.length; a++) {
if (checked[a]) {
count++;
writeToFile("Choosed.txt", newspapers[a], false);
writeToFile("ChoosedUrl.txt", newspapersUrl[a], false);
writeToFile("ChoosedPath.txt", newspapersPath[a], false);
}
if (a == (newspapers.length - 1) && count == 0) {
Toast.makeText(getApplicationContext(), "En az bir gazete seçmek zorundasınız..", Toast.LENGTH_LONG).show();
builder.show();
}
}
}
});
builder.setMultiChoiceItems(newspapers, checked, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i, boolean isChecked) {
if (isChecked) {
checked[i] = true;
} else {
checked[i] = false;
}
}
});
try
{
builder.show();
}
catch (Exception ex)
{
ex.printStackTrace();
}
writeToFile("First.txt", "1", true);
choosed = readFromFile("Choosed.txt",false);
choosedUrl = readFromFile("ChoosedUrl.txt",false);
choosedPath = readFromFile("ChoosedPath.txt",false);
if(choosed != null)
{
perNewspaper = (int) Math.ceil(newspapers.length / choosed.length);
if(perNewspaper > 15)
{
perNewspaper = 14;
}
}
return true;
}
else if(readFromFile("First.txt",false)[0].equals("1"))
{
newspapers = readFromFile("Choicable Newspaper.txt",true);
newspapersUrl = readFromFile("Choicable Url.txt",true);
newspapersPath = readFromFile("Choicable Path.txt",true);
choosed = readFromFile("Choosed.txt",false);
choosedUrl = readFromFile("ChoosedUrl.txt",false);
choosedPath = readFromFile("ChoosedPath.txt",false);
perNewspaper = (int) Math.ceil(newspapers.length / choosed.length);
if(perNewspaper > 15)
{
perNewspaper = 14;
}
return true;
}
else
{
return false;
}
//***** File Control And Creating An Dialog Interface if this is first usage *****//
}
//*****Files*****//
private void writeToFile(String fileName,String data,boolean isPrivate)
{
try
{
OutputStreamWriter outputStreamWriter;
if(isPrivate)
{
outputStreamWriter = new OutputStreamWriter(getApplicationContext().openFileOutput(fileName, MODE_PRIVATE));
}
else
{
outputStreamWriter = new OutputStreamWriter(getApplicationContext().openFileOutput(fileName, MODE_APPEND));
}
outputStreamWriter.write(data+"\r\n");
outputStreamWriter.close();
}
catch (IOException e)
{
}
}
public String[] readFromFile(String fileName,boolean isAsset)
{
String[] ret=null;
try
{
InputStream inputStream;
if(isAsset)
{
inputStream = getApplicationContext().getAssets().open(fileName);
}
else
{
inputStream = getApplicationContext().openFileInput(fileName);
}
if (inputStream != null)
{
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString;
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString).append(",");
}
inputStream.close();
ret = stringBuilder.toString().split(",");
inputStream.close();
}
}
catch (FileNotFoundException e)
{
}
catch (IOException e)
{
}
return ret;
}
I suppose you have a setpositivebutton click listener.
Start your asynktask in that listener with the desired input.
First Write your own function with parameters.
Call async task inside that function.
Now call that function by pass the form values as parameters to that function after you finish dimiss the dialog box.
So, I am creating a little trivia game for learning purposes, but I ran into a problem.
First, I had a specific Android Fragment obtaining the data from JSON, and I will simply use that data on the callback method and display it on TextViews and Buttons. Everything was working fine, however, every time I returned to that fragment, the same questions would be there. So I decided to handle that in a better way outside of the callback method.
The problem here is that apparently my Arrays are either null or their lengths is zero. Which is weird, because according to my LOG, data is being passed to those arrays on the callback method.
Here's my full fragment code. Thanks!
public class GameFragment extends Fragment {
private TextView txtQuestion;
private Button btnAnswer1;
private Button btnAnswer2;
private Button btnAnswer3;
private Button btnAnswer4;
private Questions[] gameQuestions;
private Questions[] animeQuestions;
private Questions[] techQuestions;
private Questions[] movieQuestions;
private Questions[][] gameCategories = new Questions[4][];
int correctAnswer = -1;
private TransparentProgressDialog progressBar;
private Handler handler;
private Runnable runnable;
Callback cb = new Callback<MyApiData>(){
#Override
public void success(MyApiData myApiData, Response response) {
gameCategories[0] = new Questions[myApiData.getCategory()[0].getQuestions(0).length];
gameCategories[1] = new Questions[myApiData.getCategory()[1].getQuestions(1).length];
gameCategories[2] = new Questions[myApiData.getCategory()[2].getQuestions(2).length];
gameCategories[3] = new Questions[myApiData.getCategory()[3].getQuestions(3).length];
//gameCategories = new Questions[][] {gameQuestions, animeQuestions, techQuestions, movieQuestions};
for(int i = 0; i < 4 ; i++){
for(int j = 0; j < gameCategories[i].length ; j++){
gameCategories[i][j] = myApiData.getCategory()[i].getQuestions(i)[j];
//Log.d("GameFragment", "gameCategories[i][j] - gameCategories["+i+"]["+j+"]: " + gameCategories[i][j].getQuestion());
}
}
//displayQuestion();
progressBar.dismiss();
displayQuestion();
}
#Override
public void failure(RetrofitError error) {
Log.d("GameScreen", "Callback failed!");
}
};
public GameFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_game, container, false);
txtQuestion = (TextView) view.findViewById(R.id.txtQuestion);
btnAnswer1 = (Button) view.findViewById(R.id.btnAnswer1);
btnAnswer2 = (Button) view.findViewById(R.id.btnAnswer2);
btnAnswer3 = (Button) view.findViewById(R.id.btnAnswer3);
btnAnswer4 = (Button) view.findViewById(R.id.btnAnswer4);
btnAnswer1.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) { checkAnswer(view); } });
btnAnswer2.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) { checkAnswer(view); } });
btnAnswer3.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) { checkAnswer(view); } });
btnAnswer4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkAnswer(view);
}
});
handler = new Handler();
progressBar = new TransparentProgressDialog(getActivity(), R.drawable.loading_spinner);
runnable = new Runnable() {
#Override
public void run() {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
};
//launchRingDialog();
//RestClient.get().getQuestions(cb);
// Inflate the layout for this fragment
return view;
}
public void launchRingDialog() {
new Thread(new Runnable() {
public void run(){
try {
Log.d("Thred", "Try");
progressBar.show();
RestClient.get().getQuestions(cb);
//Thread.sleep(10000);
} catch (Exception e) {
}
//progressBar.dismiss();
}
}).start();
}
public void checkAnswer(View v){
switch(v.getId()){
case R.id.btnAnswer1:
if(correctAnswer == 1){
feedback(true, btnAnswer1);
}else {
feedback(false, btnAnswer1);
}
break;
case R.id.btnAnswer2:
if(correctAnswer == 2){
feedback(true, btnAnswer2);
}else {
feedback(false, btnAnswer2);
}
break;
case R.id.btnAnswer3:
if(correctAnswer == 3){
feedback(true, btnAnswer3);
}else {
feedback(false, btnAnswer3);
}
break;
case R.id.btnAnswer4:
if(correctAnswer == 4){
feedback(true, btnAnswer4);
}else {
feedback(false, btnAnswer4);
}
break;
default: txtQuestion.setText("Error");
break;
}
}
public void feedback(Boolean correct, Button btn){
if(correct){
btn.setBackgroundColor(Color.GREEN);
btn.setText("CORRECT!");
}else{
btn.setBackgroundColor(Color.RED);
btn.setText("WRONG!");
}
}
#Override
public void onResume() {
super.onResume();
//displayQuestion();
}
public void displayQuestion(){
Random randomizer = new Random();
int randomQuestion;
int category = GTMain.choosenCategory;
if(category == 5){
category = randomizer.nextInt(4);
}
randomQuestion = randomizer.nextInt(25);
Log.d("displayQuestion", "Before if statements");
if(gameCategories != null && gameCategories.length != 0) {
Log.d("displayQuestion", "First if");
if(gameCategories[category] != null && gameCategories[category].length != 0){
Log.d("displayQuestion", "Second if");
txtQuestion.setText(gameCategories[category][randomQuestion].getQuestion());
correctAnswer = gameCategories[category][randomQuestion].getCorrectAnswer();
Log.d("displayQuestion()", "correctAnswer: " + correctAnswer);
btnAnswer1.setText(gameCategories[category][randomQuestion].getAnswers().getA1());
btnAnswer2.setText(gameCategories[category][randomQuestion].getAnswers().getA2());
btnAnswer3.setText(gameCategories[category][randomQuestion].getAnswers().getA3());
btnAnswer4.setText(gameCategories[category][randomQuestion].getAnswers().getA4());
}
}
}
}
PS: On my main activity, I check to see which fragment should be loaded. If it's the fragment that contains the components to display the questions and answer (the one from the code above), I call the following method: gameFragment.launchRingDialog(); (and yes, I have created an instance of my GameFragment fragment before calling that method!)
When onResume() is called, your RestClient.get().getQuestions(cb) is still running in background, and your call displayQuestion(), so of course nothing is shown.
Can you put displayQuestion() inside success() of your callback?
Callback cb = new Callback<MyApiData>(){
#Override
public void success(MyApiData myApiData, Response response) {
....
for(int i = 0; i < 4 ; i++){
for(int j = 0; j < gameCategories[i].length ; j++){
...
}
}
displayQuestion();
}
....
};
I would also suggest you to remove displayQuestion() in onResume() method.
In my android app it will create a pie chart when a button is clicked. This is my code segment for button clicked.
btnpieChart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SelectDBAdapter selectDBAdapter = SelectDBAdapter
.getDBAdapterInstance(getActivity());
try {
selectDBAdapter.openDataBase();
chartDataMap = selectDBAdapter.getPieChartData(strBusinessUnit,
currentPeriod, currentYear);
} catch (Exception e) {
selectDBAdapter.close();
e.printStackTrace();
} finally {
selectDBAdapter.close();
}
if (chartDataMap.size() > 0) {
Intent chrtIntent = new Intent(getActivity(),
PieChart.class);
chrtIntent.putExtra("chartMap", chartDataMap);
startActivity(chrtIntent);
} else {
Toast.makeText(getActivity(), "No Achievement Progress", Toast.LENGTH_SHORT).show();
}
}
});
And this is my PieChart.java class.
package xont.virtusel.v4.controller;
//imports
public class PieChart extends Activity {
private ArrayList<String> lstBrandNames = new ArrayList<String>();
private ArrayList<Double> lstAchievedVals = new ArrayList<Double>();
private GraphicalView mChartView = null;
protected void onResume() {
super.onResume();
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
public void onBackPressed() {
return;
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
this.finish();
return true;
}
return false;
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.complains, menu);
return true;
}
public boolean onOptionsItemSelected(android.view.MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_cancel:
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.pie_chart);
HashMap<String, Double> chrtMap = (HashMap<String, Double>) getIntent().getSerializableExtra("chartMap");
for (Map.Entry<String, Double> entry : chrtMap.entrySet()) {
//System.out.println(">>>> " + entry.getValue());
if (entry.getValue() > 0) {
lstBrandNames.add(entry.getKey());
lstAchievedVals.add(entry.getValue());
}
}
if (lstBrandNames.size() == 0 || lstAchievedVals.size() == 0) {
Toast.makeText(getApplicationContext(), "No Achievement Progress", Toast.LENGTH_SHORT).show();
finish();
} else {
ArrayList<Double> distribution = calc_Percentage(lstAchievedVals);
System.out.println("distribution === " + distribution);
lstBrandNames = set_lables(lstBrandNames, distribution);
CategorySeries distributionSeries = new CategorySeries(
"Your Achievement Progress");
for (int i = 0; i < distribution.size(); i++) {
distributionSeries.add(lstBrandNames.get(i),
distribution.get(i));
}
DefaultRenderer defaultRenderer = new DefaultRenderer();
defaultRenderer.setApplyBackgroundColor(true);
defaultRenderer.setBackgroundColor(Color.WHITE);
defaultRenderer.setLabelsTextSize(15);
defaultRenderer.setInScroll(true);
for (int i = 0; i < distribution.size(); i++) {
SimpleSeriesRenderer seriesRenderer = new SimpleSeriesRenderer();
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256),
rnd.nextInt(256));
seriesRenderer.setColor(color);
seriesRenderer.setDisplayChartValues(true);
seriesRenderer.setShowLegendItem(false);
defaultRenderer.addSeriesRenderer(seriesRenderer);
}
defaultRenderer.setLabelsColor(Color.BLACK);
defaultRenderer.setChartTitle("Your Achievement Progress");
defaultRenderer.setChartTitleTextSize(25);
defaultRenderer.setZoomButtonsVisible(true);
defaultRenderer.setShowLabels(true);
mChartView = ChartFactory.getPieChartView(this,
distributionSeries, defaultRenderer);
LinearLayout layout = (LinearLayout) findViewById(R.id.chart_container);
layout.removeAllViews();
layout.addView(mChartView);
}
}
public static ArrayList<Double> calc_Percentage(ArrayList<Double> list) {
ArrayList<Double> lstPercentage = new ArrayList<Double>();
double total = 0;
double precentage;
for (int i = 0; i < list.size(); i++) {
total = total + list.get(i);
}
System.out.println(total);
for (int j = 0; j < list.size(); j++) {
precentage = (list.get(j) / total) * 100;
lstPercentage.add(precentage);
}
return lstPercentage;
}
public static ArrayList<String> set_lables(ArrayList<String> lstBrandNames,
ArrayList<Double> distribution) {
String G_lable;
DecimalFormat df = new DecimalFormat("#.00");
ArrayList<String> lstLabels = new ArrayList<String>();
for (int i = 0; i < lstBrandNames.size(); i++) {
G_lable = lstBrandNames.get(i) + " : "
+ df.format(distribution.get(i)) + "%";
lstLabels.add(G_lable);
}
return lstLabels;
}
}
Here is my pie_chart.xml file.
I want to disable the default Back key function of the device and introduce the close button on top of the pic chart. I've added a menu in my PieChart class but no luck. Why it is not adding the menu like other activities? I've introduced my pie chart class in manifest file as follows.
<activity android:name=".PieChart" android:theme="#android:style/Theme.Dialog" android:label="Progress Chart"> </activity>
How should I solve this issue ? Any suggestions are greatly appreciated.
try this
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.exit:
finish();
moveTaskToBack(true);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
try
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
this.finish();
return true;
}
return false;
}
By overriding onBackPressed, you can effectively disable the back button :
#Override
public void onBackPressed() {
// Do nothing, back button is de-activated.
}
The way you create your menu looks fine to me.
try this
it worked for me
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
// return super.onKeyDown(keyCode, event);
if (keyCode ==event.KEYCODE_BACK) {
return true;
}
return false;
}