recycling listview with checkbox - android

i have already searched high and low on the net.
tried several tips and tutorials but none is really working for me.
What i am trying to do is using a multiple choicelist to delete more than 1 entry in my list.
everything is working, and the list is set to multiplechoice in the xml, but when trying to update my custom list i can't seem to fix that recycling.
I am using a resourcecursoradapter, no idea if that is the problem or not, but i'm at a loss right now, so if any body could help me that would be great.
Now for the code of my Activity.
package com.ShaHar91.ivlibrary;
import java.io.IOException;
import java.io.InputStream;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.SQLException;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
#SuppressWarnings("deprecation")
public class DeleteMultiPoke extends ListActivity {
public static final String ROW_ID = "row_id"; // Intent extra key
private long rowID;
MyAdapter mListAdapter;
Menu menu;
MenuItem delete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
DatabaseConnector myDbHelper = new DatabaseConnector(
DeleteMultiPoke.this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
DatabaseConnector.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
Cursor myCur = null;
myCur = myDbHelper.getAllPokes();
mListAdapter = new MyAdapter(DeleteMultiPoke.this, myCur);
setListAdapter(mListAdapter);
}
private class MyAdapter extends ResourceCursorAdapter {
public MyAdapter(Context context, Cursor cur) {
super(context, R.layout.poke_list_remove_item, cur);
}
#Override
public View newView(Context context, Cursor cur, ViewGroup parent) {
LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return li.inflate(R.layout.poke_list_remove_item, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cur) {
TextView pokeTv = (TextView) view.findViewById(R.id.pokeTv);
TextView genderTv = (TextView) view.findViewById(R.id.genderTv);
RadioButton hpRb = (RadioButton) view.findViewById(R.id.hpRb);
RadioButton attRb = (RadioButton) view.findViewById(R.id.attRb);
RadioButton defRb = (RadioButton) view.findViewById(R.id.defRb);
RadioButton spAttRb = (RadioButton) view.findViewById(R.id.spAttRb);
RadioButton spDefRb = (RadioButton) view.findViewById(R.id.spDefRb);
RadioButton speedRb = (RadioButton) view.findViewById(R.id.speedRb);
ImageView pokeSprite = (ImageView) view
.findViewById(R.id.pokeSpriteIV);
pokeTv.setText(cur.getString(cur.getColumnIndex("name")));
genderTv.setText(cur.getString(cur.getColumnIndex("gender")));
hpRb.setChecked((cur.getInt(cur.getColumnIndex("hp")) == 0 ? false
: true));
attRb.setChecked((cur.getInt(cur.getColumnIndex("att")) == 0 ? false
: true));
defRb.setChecked((cur.getInt(cur.getColumnIndex("def")) == 0 ? false
: true));
spAttRb.setChecked((cur.getInt(cur.getColumnIndex("sp_att")) == 0 ? false
: true));
spDefRb.setChecked((cur.getInt(cur.getColumnIndex("sp_def")) == 0 ? false
: true));
speedRb.setChecked((cur.getInt(cur.getColumnIndex("speed")) == 0 ? false
: true));
AssetManager assetManager = getAssets();
int imageIndex = cur.getColumnIndex("nat_dex");
try {
InputStream ims = assetManager.open("pokes/"
+ cur.getString(imageIndex) + ".gif");
Drawable d = Drawable.createFromStream(ims, null);
pokeSprite.setImageDrawable(d);
} catch (IOException ex) {
return;
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.poke_menu_remove, menu);
delete = menu.findItem(R.id.deletepokes);
delete.setEnabled(false);
delete.setVisible(false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.canceldeleting:
finish();
return true;
case R.id.deletepokes:
// create a new AlertDialog Builder
AlertDialog.Builder builder = new AlertDialog.Builder(
DeleteMultiPoke.this);
builder.setTitle(R.string.confirmTitle); // title bar string
builder.setMessage(R.string.confirmMessage); // message to display
// provide an OK button that simply dismisses the dialog
builder.setPositiveButton(R.string.button_delete,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int button) {
final DatabaseConnector databaseConnector = new DatabaseConnector(
DeleteMultiPoke.this);
ListView listView = (ListView) findViewById(android.R.id.list);
SparseBooleanArray checked = listView
.getCheckedItemPositions();
for (int i = checked.size() - 1; i >= 0; i--) {
final int position = checked.keyAt(i);
if (checked.valueAt(i)) {
AsyncTask<Long, Object, Object> deleteTask = new AsyncTask<Long, Object, Object>() {
#Override
protected Object doInBackground(
Long... params) {
databaseConnector.deletePoke(mListAdapter
.getItemId(position));
return null;
}
#Override
protected void onPostExecute(
Object result) {
finish(); // return to the
// BookLibrary Activity
}
};
// delete the AsyncTask to delete book at
// rowID
deleteTask.execute(new Long[] { rowID });
}
}
} // end method onClick
});
builder.setNegativeButton(R.string.button_cancel, null);
builder.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onResume() {
super.onResume();
mListAdapter.getCursor().requery();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String selected = "";
int cntChoice = l.getCount();
SparseBooleanArray sparseBooleanArray = l.getCheckedItemPositions();
for (int i = 0; i < cntChoice; i++) {
if (sparseBooleanArray.get(i)) {
selected += l.getItemAtPosition(i).toString() + "\n";
}
}
Toast.makeText(DeleteMultiPoke.this,
selected,
Toast.LENGTH_LONG).show();
if (l.getCheckedItemCount() == 0) {
delete.setEnabled(false);
delete.setVisible(false);
} else {
delete.setEnabled(true);
delete.setVisible(true);
}
}
Ty in advance,
Christiano Bolla

You should notify the list that the underlying data source has changed by calling notifyDataSetChanged() on your list adapter after deleting any item.

Related

Using Android back button after delete an item with SwipeDismissListViewTouchListener

I have a problem when using the back-button in my app (API 17). There are two activities in my project:
The main activity with a ListView reading items from a xml-file.
A second activity which is reading the same xml-file but using only the items which has been checked and saved by the main activity.
If I remove an item from the ListView in the second activity and use the app's menu to go back to the main-activity after saving the xml-file when swiping, this item is now unchecked. It's because the xml-file has been altered after swiping and the value for "isDone" was set from true to false.
So far so good!
But if I go back using the Android back-button the deleted item has is still checked.
What went wrong?
I guess it has something to do with the lifecycle of the activities. But I can not figure it out. Do I have to read the altered and saved xml-file in onResume again? I assumed it will be read again when the main-activity starts after using the back-button from the second activity.
And what I really do not understand is this:
When I debug the code I can see that the xml-file was not altered after swipping the item in the second activity and save the changed isDone value to the xml. This seems a little bit strange to me.
Any help would be fine!
Main-Activity:
package com.wbapps.wbshoppinglist;
/**
* Created by Andreas on 9/4/2017.
*/
import android.support.v7.app.ActionBar;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.xmlpull.v1.XmlPullParserException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MainActivity extends AppCompatActivity {
/*wb, 19Sep,2017: not yet
public static final int REQUEST_ID = 1;
*/
ImageButton imgbtnAddItem;
Button btn_create_shopping_list;
EditText input;
//object for the ListView from activity_main.xml
ListView list_view;
List<Task> tasks;
TodoListAdapter adapter;
XmlParser parser;
File file;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
file = new File(Environment.getExternalStorageDirectory(), "tasks.xml");
parser = new XmlParser();
tasks = new ArrayList<Task>();
//file.delete();
if (file.exists()) {
try {
tasks = parser.read(file);
if (tasks.isEmpty()) {
file.delete();
file.createNewFile();
}else {sortList();}
} catch (XmlPullParserException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileNotFoundException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
try {
file.createNewFile();
} catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}
}
//Initialize the variables
imgbtnAddItem = (ImageButton) findViewById(R.id.add_task_button);
btn_create_shopping_list = (Button) findViewById(R.id.create_shopping_list);
/* findViewById(R.id.list_view).requestFocus(); */
input = (EditText) findViewById(R.id.input_task);
/* id list_view identifies the listview from the activity_main.xmll */
list_view = (ListView) findViewById(R.id.list_view);
registerForContextMenu(list_view);
//tasks = new ArrayList<Task>();
adapter = new TodoListAdapter(tasks, this);
list_view.setAdapter(adapter);
//To swipe away an litem from the list
SwipeDismissListViewTouchListener touchListener =
new SwipeDismissListViewTouchListener(
list_view,
new SwipeDismissListViewTouchListener.DismissCallbacks() {
#Override
public boolean canDismiss(int position) {
return true;
}
#Override
public void onDismiss(ListView listView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
tasks.remove(position);
adapter.notifyDataSetChanged();
}
}
});
list_view.setOnTouchListener(touchListener);
//set the onClickListener for the button
imgbtnAddItem.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (input.getText().length() > 0) {
/* wb, 16Sep2017: look if the new item is already in the list */
Boolean itemfound = false;
for (int i = 0; i<tasks.size(); i++){
if (tasks.get(i).getTaskContent().equalsIgnoreCase(input.getText().toString())){
itemfound = true;
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("This item is already in the list!");
AlertDialog dialog = builder.create();
dialog.show();
break;
}
}
if (itemfound == false){
tasks.add(new Task(input.getText().toString(), false));
adapter.notifyDataSetChanged();
sortList();
input.setText("");
}
}
}
});
btn_create_shopping_list.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//startActivity(new Intent(MainActivity.this, ShoppingListActivity.class));
Boolean selected = false;
Task taskTmp;
for (int i = 0; i < tasks.size(); i++) {
taskTmp = tasks.get(i);
if (taskTmp.isDone()) {
selected = true;
break;
}
}
if (selected) {
Intent intent = new Intent(getApplicationContext(), ShoppingListActivity.class);
startActivity(intent);
/* startActivityForResult(intent, REQUEST_ID); */
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("No items for shopping list selected!");
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
#Override
protected void onPause() {
super.onPause();
//wb, Sep 13, 2017:
//before doing something else - like calling a new activity - write the altered list to
//the data sourc file tasks.xml file
try {
parser.write(tasks, file);
} catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
protected void onResume() {
super.onResume();
/* Do I have to do the same here like in onCreate? It does not work yet!*/
if (file.exists()) {
try {
tasks = parser.read(file);
if (tasks.isEmpty()) {
file.delete();
file.createNewFile();
}else {sortList();}
} catch (XmlPullParserException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileNotFoundException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
try {
file.createNewFile();
} catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_clear_all:
clearDonetasks();
this.adapter.notifyDataSetChanged();
break;
case R.id.action_delete_done_tasks:
deleteDonetasks();
this.adapter.notifyDataSetChanged();
break;
case R.id.action_delete_all:
this.tasks.clear();
this.adapter.notifyDataSetChanged();
break;
}
return super.onOptionsItemSelected(item);
}
//wb, 15 Sep, 2017: take out the hook from checkbox
public void clearDonetasks() {
for (int i = 0; i < tasks.size(); i++) {
if (tasks.get(i).isDone()) {
tasks.get(i).setIsDone(false);
}
}
}
public void deleteDonetasks() {
for (int i = 0; i < tasks.size(); i++) {
if (tasks.get(i).isDone()) {
tasks.remove(i);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int position = (int) info.id;
switch (item.getItemId()) {
case R.id.context_delete:
this.tasks.remove(position);
this.adapter.notifyDataSetChanged();
return true;
case R.id.context_edit:
createEditDialog(tasks.get(position));
return true;
default:
return super.onContextItemSelected(item);
}
}
public void createEditDialog(final Task task) {
LayoutInflater li = LayoutInflater.from(MainActivity.this);
View dialogView = li.inflate(R.layout.edit_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setView(dialogView);
final EditText inputText = (EditText) dialogView.findViewById(R.id.edit_dialog_input);
inputText.setText(task.getTaskContent());
final TextView dialogMessage = (TextView) dialogView.findViewById(R.id.edit_dialog_message);
alertDialogBuilder
.setCancelable(true)
.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
task.setTaskContent(inputText.getText().toString());
sortList();
adapter.notifyDataSetChanged();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
final AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
/* wb, 18Sep2017: sort the tasks list */
public void sortList() {
Collections.sort(tasks, new Comparator<Task>() {
#Override
public int compare(Task content1, Task content2) {
/* return o1.getTaskContent().compareTo(o2.getTaskContent()); */
/* ignore case sentsitivity */
return content1.getTaskContent().compareToIgnoreCase(content2.getTaskContent());
}
});
}
}
Second Activity:
package com.wbapps.wbshoppinglist;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.xmlpull.v1.XmlPullParserException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Created by Andreas on 9/4/2017.
*/
public class ShoppingListActivity extends AppCompatActivity {
/*wb, 19Sep2017: Not yet
public static final String RETVAL_KEY = "RETURN STRING";
*/
ListView shopping_list_view;
List<Task> tasks, shoppingTasks;
TodoListAdapter adapter;
XmlParser parser;
File file;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shoppinglist);
file = new File(Environment.getExternalStorageDirectory(), "tasks.xml");
parser = new XmlParser();
tasks = new ArrayList<Task>();
shoppingTasks = new ArrayList<Task>();
if (file.exists()) {
try {
tasks = parser.read(file);
if (tasks.isEmpty()) {
Toast.makeText(this, "No Items in Shopping List", Toast.LENGTH_SHORT).show();
//file.delete();
//file.createNewFile();
} else {
/*
Collections.sort(tasks, new Comparator<Task>() {
#Override
public int compare(Task o1, Task o2) {
return o1.getTaskContent().compareTo(o2.getTaskContent());
}
});
*/
addDonelistitems();
}
} catch (XmlPullParserException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileNotFoundException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
try {
file.createNewFile();
} catch (IOException ex) {
Toast.makeText(this, "Task File not existing!", Toast.LENGTH_SHORT).show();
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}
}
//create an instance for the view of the lauout
shopping_list_view = (ListView) findViewById(R.id.shoppingListView);
registerForContextMenu(shopping_list_view);
adapter = new TodoListAdapter(shoppingTasks, this);
shopping_list_view.setAdapter(adapter);
SwipeDismissListViewTouchListener touchListener =
new SwipeDismissListViewTouchListener(
shopping_list_view,
new SwipeDismissListViewTouchListener.DismissCallbacks() {
#Override
public boolean canDismiss(int position) {
return true;
}
#Override
public void onDismiss(ListView listView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
//wb, 15Sep: With swipe an item uncheck the checkbox for this item in the file for the shopping items
for (int i = 0; i < tasks.size(); i++) {
if (tasks.get(i).getTaskContent() == shoppingTasks.get(position).getTaskContent()) {
tasks.get(i).setIsDone(false);
try {
parser.write(tasks, file);
} catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
shoppingTasks.remove(position);
adapter.notifyDataSetChanged();
}
}
});
shopping_list_view.setOnTouchListener(touchListener);
}
#Override
public void onBackPressed() {
/* I jaust added a toas there to see if I will reach here */
Toast.makeText(this, "we are in onBackPressed", Toast.LENGTH_SHORT).show();
finish();
}
public void addDonelistitems() {
for (int i = 0; i < tasks.size(); i++) {
if (tasks.get(i).isDone() == true) {
shoppingTasks.add(tasks.get(i));
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int position = (int) info.id;
switch (item.getItemId()) {
case R.id.context_delete:
this.tasks.remove(position);
this.adapter.notifyDataSetChanged();
return true;
case R.id.context_edit:
createEditDialog(tasks.get(position));
return true;
default:
return super.onContextItemSelected(item);
}
}
public void createEditDialog(final Task task) {
LayoutInflater li = LayoutInflater.from(ShoppingListActivity.this);
View dialogView = li.inflate(R.layout.edit_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ShoppingListActivity.this);
alertDialogBuilder.setView(dialogView);
final EditText inputText = (EditText) dialogView.findViewById(R.id.edit_dialog_input);
inputText.setText(task.getTaskContent());
final TextView dialogMessage = (TextView) dialogView.findViewById(R.id.edit_dialog_message);
alertDialogBuilder
.setCancelable(true)
.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
task.setTaskContent(inputText.getText().toString());
adapter.notifyDataSetChanged();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
final AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
after trying a little bit around today it seems I solved my problem with the back-button. It seems to be I forgot to set the adapter to the list_view in onResume when comming back from the second activity. After changing the code to this
#Override
protected void onResume() {
super.onResume();
/* Do I have to do the same here like in onCreate? It does not work yet!*/
Toast.makeText(this, "onResume is reached!", Toast.LENGTH_SHORT).show();
if (file.exists()) {
try {
tasks = parser.read(file);
if (tasks.isEmpty()) {
file.delete();
file.createNewFile();
}else {
==>>new code here adapter = new TodoListAdapter(tasks, this);
==>>new code here list_view.setAdapter(adapter);
sortList();}
} catch (XmlPullParserException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileNotFoundException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
try {
file.createNewFile();
} catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
everything worked fine.
I guess without the new code the adapter put the values from the old xml-file to the list_view.
Guess I have to learn a lot of more with android!
Many thanks to all who are trying to help me!
Have a nice day wherever you are
Andreas

Two activities sending data to each other

Two activities are sending data to each other.
The first activity has a custom list view. The second has one text view and three buttons to increase and decrease a value.
When I click on the first activity, the second activity opens. The second activity increases the text view value and clicked the button. Data goes to the first activity. Same process again.
My problem is that the total value is not displayed in the first activity.
How can i show all increase and decrease values from the second activity in the first activity?
First activity's code:
package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;
import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.json.JSONfunctions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
public class DetaisRESTActivity extends Activity {
String messagevaluename,valueid,valueid1,valuename,pos;
public String countString=null;
String nameofsubmenu;
public int count=0;
public String message=null;
public String message1=null;
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ArrayList aa;
public SharedPreferences.Editor edit;
public TextView mTitleTextView;
public ImageButton imageButton;
ListAdapterAddItems adapter;
public TextView restaurantname = null;
public TextView ruppees = null;
ProgressDialog mProgressDialog;
ArrayList<ListModel> arraylist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detais_rest);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));
SharedPreferences preferences=getSharedPreferences("temp1", 1);
// SharedPreferences.Editor editor = preferences.edit();
int na=preferences.getInt("COUNTSTRING1",0);
Log.i("asasassas",""+na);
LayoutInflater mInflater = LayoutInflater.from(this);
View mCustomView = mInflater.inflate(R.layout.titlebar, null);
mTitleTextView = (TextView) mCustomView.findViewById(R.id.textView123456789);
imageButton = (ImageButton) mCustomView
.findViewById(R.id.imageButton2);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Refresh Clicked!",
Toast.LENGTH_LONG).show();
Intent i=new Intent(DetaisRESTActivity.this,TotalPriceActivity.class);
startActivity(i);
}
});
actionBar.setCustomView(mCustomView);
actionBar.setDisplayShowCustomEnabled(true);
// SqliteControllerSqliteController db = new SqliteControllerSqliteController(QuentityActivity.this);
// Reading all contacts
/*
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Phone: " +
cn.getPhoneNumber();
// Writing Contacts to log
Log.d("Name: ", log);
}
*/
Intent intent = getIntent();
// get the extra value
valuename = intent.getStringExtra("restaurantmenuname");
valueid = intent.getStringExtra("restaurantmenunameid");
valueid1 = intent.getStringExtra("idsrestaurantMenuId5");
//totalamount = intent.getStringExtra("ruppees");
Log.i("valueid",valueid);
Log.i("valuename",valuename);
Log.i("valueid1",valueid1);
// Log.i("totalamount",totalamount);
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void,Void,Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(DetaisRESTActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
Toast.makeText(DetaisRESTActivity.this, "Successs", Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<ListModel>();
// Retrieve JSON Objects from the given URL address
// Log.i("123",value1);
jsonobject = JSONfunctions.getJSONfromURL("http://firstchoicefood.in/fcfapiphpexpert/phpexpert_restaurantMenuItem.php?r=" + URLEncoder.encode(valuename) + "&resid=" + URLEncoder.encode(valueid1) + "&RestaurantCategoryID=" + URLEncoder.encode(valueid) + "");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("RestaurantMenItems");
Log.i("1234",""+jsonarray);
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
ListModel sched = new ListModel();
sched.setId(jsonobject.getString("id"));
sched.setProductName(jsonobject.getString("RestaurantPizzaItemName"));
sched.setPrice(jsonobject.getString("RestaurantPizzaItemPrice"));
arraylist.add(sched);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listViewdetails);
adapter = new ListAdapterAddItems();
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
adapter.notifyDataSetChanged();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
// Get Person "behind" the clicked item
ListModel p =(ListModel)listview.getItemAtPosition(position);
// Log the fields to check if we got the info we want
Log.i("SomeTag",""+p.getId());
//String itemvalue=(String)listview.getItemAtPosition(position);
Log.i("SomeTag", "Persons name: " + p.getProductName());
Log.i("SomeTag", "Ruppees: " + p.getPrice());
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
Log.i("postititi",""+position);
Intent intent=new Intent(DetaisRESTActivity.this,QuentityActivity.class);
intent.putExtra("quentity",countString);
intent.putExtra("valueid",valueid);
intent.putExtra("valuename",valuename);
intent.putExtra("valueid1",valueid1);
intent.putExtra("id",p.getId());
intent.putExtra("name",p.getProductName());
intent.putExtra("price",p.getPrice());
startActivityForResult(intent,2);
// startActivity(intent);
}
});
}
}
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
pos=data.getStringExtra("POSITION");
message=data.getStringExtra("MESSAGE");
message1=data.getStringExtra("COUNTSTRING");
messagevaluename=data.getStringExtra("VALUENAME");
nameofsubmenu=data.getStringExtra("name");
Log.i("xxxxxxxxxxx",message);
Log.i("xxxxxxxxxxx1234",pos);
Log.i("xxxxxxxxxxx5678count",message1);
Log.i("messagevaluename",messagevaluename);
Log.i("submenu",nameofsubmenu);
//ruppees.setText(message);
//editor.putInt("count",na);
//editor.commit();
//Log.i("asasassasasdsasdasd",""+na);
// mTitleTextView.setText(Arrays.toString(message1));
mTitleTextView.setText(message1);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
Intent i=new Intent(DetaisRESTActivity.this,TotalPriceActivity.class);
i.putExtra("count",message1);
i.putExtra("submenu",nameofsubmenu);
i.putExtra("ruppees",message);
i.putExtra("id",pos);
i.putExtra("messagevaluename",messagevaluename);
startActivity(i);
}
});
}
}
//==========================
class ListAdapterAddItems extends ArrayAdapter<ListModel>
{
ListAdapterAddItems(){
super(DetaisRESTActivity.this,android.R.layout.simple_list_item_1,arraylist);
//imageLoader = new ImageLoader(MainActivity.this);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.cartlistitem, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.populateFrom(arraylist.get(position));
// arraylist.get(position).getPrice();
return convertView;
}
}
class ViewHolder {
ViewHolder(View row) {
restaurantname = (TextView) row.findViewById(R.id.rastaurantnamedetailsrestaurant);
ruppees = (TextView) row.findViewById(R.id.rastaurantcuisinedetalsrestaurant);
}
// Notice we have to change our populateFrom() to take an argument of type "Person"
void populateFrom(ListModel r) {
restaurantname.setText(r.getProductName());
ruppees.setText(r.getPrice());
}
}
//=============================================================
#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_detais_rest, 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.
return super.onOptionsItemSelected(item);
}
public void OnPause(){
super.onPause();
}
}
Second activity's code:
package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.CARTBean;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.database.SqliteController;
public class QuentityActivity extends Activity {
String value=null;
public String TotAmt=null;
String[] cccc;
ImageButton positive,negative;
String position;
static int count = 1;
int tot_amt = 0;
public String countString=null;
String name,price;
String valueid,valueid1,valuename;
public TextView ruppees,submenuname,totalruppees,quantity,addtocart;
SharedPreferences preferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quentity);
ActionBar actionBar = getActionBar();
// Enabling Up / Back navigation
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));
preferences = getSharedPreferences("temp1",1);
editor = preferences.edit();
Intent intent = getIntent();
// get the extra value
value = intent.getStringExtra("quentity");
valuename = intent.getStringExtra("valuename");
valueid = intent.getStringExtra("valueid");
valueid1 = intent.getStringExtra("valueid1");
name=intent.getStringExtra("name");
price=intent.getStringExtra("price");
position=intent.getStringExtra("id");
quantity=(TextView)findViewById(R.id.rastaurantcuisinedetalsrestaurantquantity);
totalruppees=(TextView)findViewById(R.id.rastaurantnamequentitytotal1);
submenuname=(TextView)findViewById(R.id.rastaurantnamesubmenuquentity);
ruppees=(TextView)findViewById(R.id.rastaurantnamequentity1);
positive=(ImageButton)findViewById(R.id.imageButtonpositive);
negative=(ImageButton)findViewById(R.id.imageButtonnegative);
addtocart=(TextView)findViewById(R.id.textViewaddtocart);
buttonclick();
addtocart();
submenuname.setText(name);
ruppees.setText(price);
totalruppees.setText(price);
// new DownloadJSON().execute();
}
public void buttonclick(){
positive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String totalAmtString = ruppees.getText().toString();
int totAmount = Integer.parseInt(totalAmtString);
//count = Integer.parseInt(getString);
count++;
editor.putInt("COUNTSTRING1", count);
editor.commit();
editor.clear();
Log.i("sunder sharma",""+count);
countString= String.valueOf(count);
tot_amt = totAmount * count;
TotAmt = String.valueOf(tot_amt);
totalruppees.setText(TotAmt);
quantity.setText(countString);
}
});
negative.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String totalAmtString = ruppees.getText().toString();
int totAmount = Integer.parseInt(totalAmtString);
if (count > 1)
count--;
editor.putInt("COUNTSTRING1", count);
editor.commit();
countString = String.valueOf(count);
tot_amt = totAmount * count;
TotAmt = String.valueOf(tot_amt);
totalruppees.setText(TotAmt);
quantity.setText(countString);
}
});
}
public void addtocart(){
addtocart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* Log.i("valueid",valueid);
Log.i("valuename",valuename);
Log.i("valueid1",valueid1);
Log.i("name",name);
Log.i("price",price);
Log.i("id1",position);
SqliteController db = new SqliteController(QuentityActivity.this);
db.insertStudent(new CARTBean(position,name,price,countString,TotAmt));
*/
Intent intent=new Intent();
intent.putExtra("MESSAGE",TotAmt);
intent.putExtra("POSITION",position);
intent.putExtra("COUNTSTRING",countString);
intent.putExtra("VALUENAME",valuename);
intent.putExtra("name",name);
setResult(2,intent);
finish();//finishing activity
}
});
}
#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_quentity, 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);
}
}
Collect the data from second activity and put into below intent .Then you will receive first activity.
Intent myIntent = new Intent(secondActivity.this, firstActivity.class);
myIntent.putExtra("COUNTSTRING", CountString); //add data
startActivity(myIntent);

Regarding migrating searchview on appcompat

I am migrating search view Item provided in action bar using support library .Here I have done as mentioned in doc but still it is giving error while creating options menu.Please tell me where I have done wrong.Here is my code.
contacts_list_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:com.utteru.ui="http://schemas.android.com/apk/res-auto"
xmlns:yourapp="http://schemas.android.com/tools">
<!-- The search menu item. Honeycomb and above uses an ActionView or specifically a SearchView
which expands within the Action Bar directly. Note the initial collapsed state set using
collapseActionView in the showAsAction attribute. -->
<group
android:id="#+id/main_menu_group">
<item
android:id="#+id/menu_search"
android:actionViewClass="android.widget.SearchView"
android:icon="#drawable/ic_action_search"
yourapp:showAsAction="ifRoom|collapseActionView"
yourapp:actionViewClass="android.support.v7.widget.SearchView"
android:title="#string/menu_search" />
</group>
<group
android:id="#+id/refresh_group">
<item
android:id="#+id/refresh"
android:icon="#android:drawable/ic_popup_sync"
yourapp:showAsAction="ifRoom|collapseActionView"
yourapp:actionViewClass="android.support.v7.widget.SearchView"
android:title="#string/menu_search" />
</group>
</menu>
ContactsListFragment.java
import android.accounts.Account;
import android.app.SearchManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Contacts.Photo;
import android.support.v4.BuildConfig;
import android.support.v4.app.ListFragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class ContactsListFragment extends ListFragment {
private static final String TAG = "ContactsAccessFragment";
private static final String STATE_PREVIOUSLY_SELECTED_KEY =
"com.Utteru.ui.SELECTED_ITEM";
ArrayList<AccessContactDto> allcontacts;
ArrayList<AccessContactDto> databasecontacts;
TextView textempty;
public Context mContext;
private AccessContactAdapter mAdapter;
private ImageLoader mImageLoader; // Handles loading the contact image in a background thread
// Stores the previously selected search item so that on a configuration change the same item
// can be reselected again
private int mPreviouslySelectedSearchItem = 0;
// Whether or not the search query has changed since the last time the loader was refreshed
private boolean mSearchQueryChanged;
// Whether or not this fragment is showing in a two-pane layout
private boolean mIsTwoPaneLayout;
// Whether or not this is a search result view of this fragment, only used on pre-honeycomb
// OS versions as search results are shown in-line via Action Bar search from honeycomb onward
private boolean mIsSearchResultView = false;
/**
* Fragments require an empty constructor.
*/
public ContactsListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mIsTwoPaneLayout = getResources().getBoolean(R.bool.has_two_panes);
getActivity().setTitle("");
if (savedInstanceState != null) {
// If we're restoring state after this fragment was recreated then
// retrieve previous search term and previously selected search
// result.
mPreviouslySelectedSearchItem =
savedInstanceState.getInt(STATE_PREVIOUSLY_SELECTED_KEY, 0);
}
mImageLoader = new ImageLoader(getActivity(), CommonUtility.getListPreferredItemHeight(getActivity())) {
#Override
protected Bitmap processBitmap(Object data) {
// This gets called in a background thread and passed the data from
// ImageLoader.loadImage().
return loadContactPhotoThumbnail((String) data, getImageSize());
}
};
// Set a placeholder loading image for the image loader
mImageLoader.setLoadingImage(R.drawable.ic_contact_picture_holo_light);
// Add a cache to the image loader
mImageLoader.addImageCache(getActivity().getSupportFragmentManager(), 0.1f);
mContext = getActivity().getBaseContext();
new loadData().execute();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the list fragment layout
View all_contacts_view = inflater.inflate(R.layout.contact_list_fragment, container, false);
textempty = (TextView)all_contacts_view.findViewById(android.R.id.empty);
textempty.setText("No contacts found");
return all_contacts_view;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
AccessContactDto cdto = (AccessContactDto) l.getItemAtPosition(position);
Log.e("number on click",""+cdto.getMobile_number());
cdto=UserService.getUserServiceInstance(mContext).getAccessConDataByNumber(cdto.getMobile_number());
if(cdto==null)
cdto = (AccessContactDto) l.getItemAtPosition(position);
else
Log.e("mumber not mull from db","number not null from db");
Intent detailsActivity = new Intent(mContext, ContactDetailActivity.class);
detailsActivity.putExtra("selected_con", cdto);
startActivity(detailsActivity);
getActivity().overridePendingTransition(R.anim.animation1, R.anim.animation2);
super.onListItemClick(l, v, position, id);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Let this fragment contribute menu items
setHasOptionsMenu(true);
// Set up ListView, assign adapter and set some listeners. The adapter was previously
// created in onCreate().
setListAdapter(mAdapter);
getListView().setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
// Pause image loader to ensure smoother scrolling when flinging
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {
mImageLoader.setPauseWork(true);
} else {
mImageLoader.setPauseWork(false);
}
}
#Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
}
});
if (mIsTwoPaneLayout) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
if (mPreviouslySelectedSearchItem == 0) {
}
}
#Override
public void onPause() {
super.onPause();
mImageLoader.setPauseWork(false);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
menu.clear();
getActivity().getMenuInflater().inflate(R.menu.contact_list_menu, menu);
MenuItem searchItem = menu.findItem(R.id.menu_search);
menu.setGroupVisible(R.id.main_menu_group, true);
if (mIsSearchResultView) {
searchItem.setVisible(false);
}
if (Utils.hasHoneycomb()) {
final SearchManager searchManager =
(SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getActivity().getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String queryText) {
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
Log.e("on query text change ","on query text change");
if (newText != null && !newText.equals(""))
{
ArrayList<AccessContactDto> filterList = new ArrayList<AccessContactDto>();
for (AccessContactDto a : allcontacts) {
if (a.getDisplay_name().toLowerCase().startsWith(newText.toLowerCase())) {
filterList.add(a);
continue;
}
getListView().setAdapter(new AccessContactAdapter(filterList, getActivity(), mImageLoader));
}
return true;
}
else{
getListView().setAdapter(new AccessContactAdapter(allcontacts, getActivity(), mImageLoader));
return true;
}
}
});
}
super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_search:
if (!Utils.hasHoneycomb()) {
getActivity().onSearchRequested();
}
break;
case R.id.refresh:
if (CommonUtility.isNetworkAvailable(getActivity())) {
final Account account = new Account(Constants.ACCOUNT_NAME, Constants.ACCOUNT_TYPE);
Bundle bundle = new Bundle();
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
ContentResolver.requestSync(account, ContactsContract.AUTHORITY, bundle);
mAdapter.notifyDataSetChanged();
// new CountDownTimer(5000, 1000) {
// #Override
// public void onTick(long millisUntilFinished) {
// }
//
// #Override
// public void onFinish() {
//
// }
// }.start();
} else {
Toast.makeText(getActivity(), "Internet Connection Required!!", Toast.LENGTH_SHORT).show();
}
break;
}
return super.onOptionsItemSelected(item);
}
private Bitmap loadContactPhotoThumbnail(String photoData, int imageSize) {
if (!isAdded() || getActivity() == null) {
return null;
}
AssetFileDescriptor afd = null;
try {
Uri thumbUri;
if (Utils.hasHoneycomb()) {
thumbUri = Uri.parse(photoData);
} else {
final Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_URI, photoData);
thumbUri = Uri.withAppendedPath(contactUri, Photo.CONTENT_DIRECTORY);
}
afd = getActivity().getContentResolver().openAssetFileDescriptor(thumbUri, "r");
FileDescriptor fileDescriptor = afd.getFileDescriptor();
if (fileDescriptor != null) {
return ImageLoader.decodeSampledBitmapFromDescriptor(
fileDescriptor, imageSize, imageSize);
}
} catch (FileNotFoundException e) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Contact photo thumbnail not found for contact " + photoData
+ ": " + e.toString());
}
} finally {
if (afd != null) {
try {
afd.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
public ArrayList<AccessContactDto> readContactsNew() {
ArrayList<AccessContactDto> list = new ArrayList<AccessContactDto>();
AccessContactDto adto;
Cursor phones = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String photouri= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
String contact_id= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
Uri con_uri= Contacts.getLookupUri(phones.getLong(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID)), phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY)));
adto = new AccessContactDto(contact_id, name, null, phoneNumber, null, photouri, con_uri.toString(),null,null,null);
list.add(adto);
}
phones.close();
return list;
}
public class loadData extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPostExecute(Void aVoid) {
mAdapter = new AccessContactAdapter(allcontacts, getActivity(), mImageLoader);
if(getActivity()!=null)
getListView().setAdapter(mAdapter);
super.onPostExecute(aVoid);
}
#Override
protected Void doInBackground(Void... params) {
allcontacts = readContactsNew();
// databasecontacts = UserService.getUserServiceInstance(mContext).getAllAccessContacts();
// allcontacts.removeAll(databasecontacts);
// allcontacts.addAll(databasecontacts);
Collections.sort(allcontacts, new Comparator<AccessContactDto>() {
#Override
public int compare(AccessContactDto lhs, AccessContactDto rhs) {
return lhs.getDisplay_name().compareToIgnoreCase(rhs.getDisplay_name());
}
});
return null;
}
}
}
ContactsListActivity.java
import android.accounts.AccountManager;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import com.viewpagerindicator.IconPagerAdapter;
public class ContactsListActivity extends ActionBarActivity {
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
ViewPager mViewPager;
private ContactDetailFragment mContactDetailFragment;
private boolean isTwoPaneLayout;
AccountManager mAccountManager;
Boolean checkAccount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager());
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(R.color.purple));
getSupportActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
isTwoPaneLayout = getResources().getBoolean(R.bool.has_two_panes);
PagerTabStrip pagerTabStrip = (PagerTabStrip) findViewById(R.id.pager_title_strip);
pagerTabStrip.setTextSpacing(0);
pagerTabStrip.setPadding(0, 0, 0, 10);
pagerTabStrip.setTextSize(1, 20);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.remove("android:support:fragments");
}
#Override
public void onBackPressed() {
startActivity(new Intent(ContactsListActivity.this, MenuScreen.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK));
this.finish();
overridePendingTransition(R.anim.card_rotate_in, R.anim.card_rotate_out);
}
#Override
protected void onDestroy() {
if(CommonUtility.dialog!=null){
CommonUtility.dialog.dismiss();
}
super.onDestroy();
}
#Override
public boolean onSearchRequested() {
boolean isSearchResultView = false;
return !isSearchResultView && super.onSearchRequested();
}
public static class DemoCollectionPagerAdapter extends FragmentPagerAdapter implements IconPagerAdapter {
protected static final String[] CONTENT = new String[]{"All Contacts", "Access Contacts"};
protected final int[] ICONS = new int[]{
R.drawable.all_contact,
R.drawable.access_contacts
};
private int mCount = CONTENT.length;
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// All Contacts Fragment
return new ContactsListFragment();
case 1:
// Access Contacts Fragment
return new ContactsAccessFragment();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return DemoCollectionPagerAdapter.CONTENT[position % CONTENT.length];
}
#Override
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
#Override
public int getCount() {
return mCount;
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
}
Error Log:
java.lang.NullPointerException
at com.hello.ContactsListFragment.onPrepareOptionsMenu(ContactsListFragment.java:236)
at android.support.v4.app.Fragment.performPrepareOptionsMenu(Fragment.java:1882)
at android.support.v4.app.FragmentManagerImpl.dispatchPrepareOptionsMenu(FragmentManager.java:2020)
at android.support.v4.app.FragmentActivity.onPreparePanel(FragmentActivity.java:459)
at android.support.v7.app.ActionBarActivity.superOnPreparePanel(ActionBarActivity.java:280)
at android.support.v7.app.ActionBarActivityDelegate$1.onPreparePanel(ActionBarActivityDelegate.java:84)
at android.support.v7.app.ActionBarActivityDelegateBase.preparePanel(ActionBarActivityDelegateBase.java:1006)
at android.support.v7.app.ActionBarActivityDelegateBase.doInvalidatePanelMenu(ActionBarActivityDelegateBase.java:1182)
at android.support.v7.app.ActionBarActivityDelegateBase.access$100(ActionBarActivityDelegateBase.java:79)
at android.support.v7.app.ActionBarActivityDelegateBase$1.run(ActionBarActivityDelegateBase.java:115)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5520)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)

How do I maintain ListView state between activity loads in android

I'm doing some background processing in my activity and have a ListView that shows the progress. I 'update' the listView with
adapter.notifyDataSetChanged();
However when I leave the activity and then come back, the background processes are still running, but the list view isn't updated. This is presumably because it's a new object, not the previous one. How do I maintain my list view object between activity loads?
This is my activity. I think the issue is that the 'adapter' variable that the download uses to bind to to show updates, is recreated in the onCreate method of the activity, and the 'adapter' variable that the download originally bound to is not in the activity anymore.
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.model.ProgressEvent;
import com.amazonaws.services.s3.model.ProgressListener;
import com.amazonaws.services.s3.transfer.TransferManager;
//import com.amazonaws.auth.AWSCredentials;
//import com.amazonaws.auth.BasicAWSCredentials;
public class VideosActivity extends Activity {
ListView video_list;
CustomList adapter;
File storage_dir;
SharedPreferences completed_downloads; //http://developer.android.com/guide/topics/data/data-storage.html
SharedPreferences downloaded_data; //maps position to percent downloaded
SharedPreferences queue; //holds which fiiles are awaiting download
String images[]; //holds references to all thumnails for vids
String volume; //something like vol1 or vol2
String s3_dir; //the directory after the boucket that the files are stored in (do not add first slash)
String s3_bucket = "com--apps";
Handler handler = new Handler(); //'tunnel' through whci other threads communicate with main thread
Map<String, String[][]> video_config = new HashMap<String, String[][]>(); //holds info about video thumbs and filenames for all apps
ArrayList<String> arr_videos = new ArrayList<String>(); //holds video names
DownloadQueue queue_manager = new DownloadQueue();
#Override
public void onCreate(Bundle savedInstanceState) {
Log.v("dev", "onCreateCalled");
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
volume = getPackageName().split("\\.")[2]; //something like vol1 or vol2
s3_dir = "android/" + volume + "/"; //the directory after the boucket that the files are stored in (do not add first slash)
completed_downloads = getSharedPreferences("completed_downloads", 0);
downloaded_data = getSharedPreferences("downloaded_data", 0);
queue = getSharedPreferences("queue", 0);
storage_dir = getApplicationContext().getExternalFilesDir(null); //private to app, removed with uninstall
adapter = new CustomList(this, R.layout.customlist, arr_videos);
video_list = (ListView)findViewById(R.id.list);
video_list.setAdapter(adapter); //set adapter that specifies list contents
ensureStorageDirExists( storage_dir ); //make sure storage dir exists
set_video_data(); //store vid dat in array
ensure_connection_or_warn();
}
public boolean ensure_connection_or_warn()
{
if(have_connection())
{
return true;
}
else
{
Toast.makeText(this, "No Internet connection", Toast.LENGTH_LONG).show();
return false;
}
}
protected void ensureStorageDirExists( File dir )
{
if (!dir.exists())
{
dir.mkdirs();
}
}
public void set_video_data()
{
config_video_data(); //run config
images = video_config.get(getPackageName())[0]; //set images
for (String name : video_config.get(getPackageName())[1] ) { //set video info, this should be streamlined but is due to legacy code and my crap Java skills, consider doing like this: http://developer.android.com/guide/topics/resources/more-resources.html#TypedArray
arr_videos.add(name);
}
}
public SharedPreferences stored_vals()
{
return PreferenceManager.getDefaultSharedPreferences(this);
}
public boolean have_connection()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if(cm.getActiveNetworkInfo()!=null && cm.getActiveNetworkInfo().isConnected() && cm.getActiveNetworkInfo().isAvailable())
{
Log.v("dev", "have internet connection");
return true;
}
else
{
Log.v("dev", "No internet connection");
return false;
}
}
public class DownloadQueue
{
protected void process()
{
if (queue.size() > 0 && queue.get(0).download_status == "queued") //this is meant to force one download at a time
{
queue.get(0).start();
adapter.notifyDataSetChanged();
}
}
protected void add(Integer position)
{
queue.edit.putInt(position+"");
d.download_status = "queued";
adapter.notifyDataSetChanged();
}
protected boolean position_is_queued(Integer position)
{
for (Download d : queue ) {
if(d.position == position)
{
return true;
}
}
return false;
}
protected void remove(Download d)
{
queue.remove(d);
adapter.notifyDataSetChanged();
}
}
public class CustomList extends ArrayAdapter<String>
{
View view;
int position;
Button btn;
public CustomList(Context context, int layout_id, ArrayList<String> objects)
{
super(context, layout_id, objects);
}
#Override
public View getView(final int position, View convertView, ViewGroup view_group)
{
set_view(convertView);
this.position = position;
TextView text_view = (TextView) view.findViewById(R.id.name);
ImageView image = (ImageView) view.findViewById(R.id.img);
btn = (Button) view.findViewById(R.id.play);
prepare_btn();
text_view.setText( list_text() );
image.setImageResource(
getResources().getIdentifier(images[position], "drawable", getPackageName())
);
return view;
}
public String list_text()
{
String s = arr_videos.get( position ).replace("_", " ").replace(".m4v", "");
s = s.substring(2, s.length());
return s;
}
public void set_view(View convertView)
{
if(convertView == null)
{
LayoutInflater inflater = getLayoutInflater();
view = inflater.inflate(R.layout.customlist, null);
}
else
{
view = convertView;
}
}
public Boolean is_downloaded()
{
return completed_downloads.getBoolean(position + "", false);
}
public void prepare_btn()
{
btn.setTag((Integer) position);
if(is_downloaded() == true)
{
btn.setText("Play ");
btn.setEnabled(true);
btn.setOnClickListener( new OnClickListener()
{
public void onClick(View btn)
{
int position = (Integer) btn.getTag();
Intent i = new Intent(VideosActivity.this, PlayVideoActivity.class);
String video_path = storage_dir + "/" + arr_videos.get(position);
Log.v("video_path", video_path);
i.putExtra("video_path", video_path);
startActivity(i);
}
});
}
else if( downloaded_data.contains(position+"") ) //it it's currently being downloaded
{
btn.setText(downloaded_data.getInt(position+"", 0) + "%");
btn.setEnabled(false);
}
else if( queue_manager.position_is_queued(position) ) //it's in the queue
{
btn.setText("Queued");
btn.setEnabled(false);
}
else
{
btn.setText("Download");
btn.setEnabled(true);
btn.setOnClickListener( new OnClickListener()
{
public void onClick(View btn)
{
int position = (Integer) btn.getTag();
btn.setEnabled(false);
queue_manager.add(position);
}
});
}
}
}
public class Download
{
File new_video_file;
int position;
String download_status;
com.amazonaws.services.s3.transfer.Download download;
protected void queue(int position)
{
this.position = position;
queue_manager.add(this);
queue_manager.process();
//put this download in the queue
//start downloading if it's the only one in the queue
}
protected void start()
{
if(!ensure_connection_or_warn())
{
return;
}
this.download_status = "started";
this.new_video_file = new File(storage_dir, arr_videos.get(position)); //local file to be writtent to
TransferManager tx = new TransferManager(credentials);
//http://stackoverflow.com/questions/6976317/android-http-connection-exception
this.download = tx.download(s3_bucket, s3_dir + arr_videos.get(position), new_video_file);
download.addProgressListener(new ProgressListener()
{
public void progressChanged(final ProgressEvent pe)
{
handler.post( new Runnable()
{
#Override
public void run()
{
if ( pe.getEventCode() == ProgressEvent.COMPLETED_EVENT_CODE )
{
Download.this.onComplete();
}
else
{
Download.this.onProgressUpdate();
}
}
});
}
});
}
//protected void onProgressUpdate(Double progress)
protected void onProgressUpdate()
{
this.download_status = "downloading";
Double progress = this.download.getProgress().getPercentTransfered();
Integer percent = progress.intValue();
//Log.v("runnable", percent + "");
downloaded_data.edit().putInt(position+"", percent).commit();
adapter.notifyDataSetChanged();
}
protected void onComplete()
{
Log.v("dev", "download complete!!!");
//downloaded_data.remove(position);
this.download_status = "complete";
completed_downloads.edit().putBoolean(position + "", true).commit();
queue_manager.remove(this);
queue_manager.process();
adapter.notifyDataSetChanged();
// this.download.abort();
}
}
}
Not exactly sure what happens during background processing and what do you mean by ListView state, but my suggestion would be:
try the following:
#Override
protected void onResume() {
super.onResume();
yourAdapter.clear();
yourAdapter.addAll(yourData); // API level [1..10] use for(..){ yourAdapter.add(yourData.get(index)) }
yourAdapter.notifyDataSetChanged();
}
Reason:
An adapter keeps a copy of all the elements, so when you call notifyDataSetChanged, it checks its own copy of the elements

What is the correct way implement switch case statement in Android?

It didn't showing up any error. however when I run my application, there is no result appear from my listView. I think,the mistake is because of i didn't use the correct way doing switch case statement. here is my code.
QuickSearch.java
package com.example.awesome;
import java.io.IOException;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.SQLException;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class QuickSearch extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
//-------------------------------------------------------------------------
// Initiate database data
initiateDb();
//---------------------------------------------------------------------------
// Declaration of view
final Button qsfaculty, qscollege;
super.onCreate(savedInstanceState);
setContentView(R.layout.quick_search);
//---------------------------------------------------------------------------
// Get reference
qsfaculty = (Button) this.findViewById(R.id.button1);
qsfaculty.setOnClickListener(this);
qscollege = (Button) this.findViewById(R.id.button2);
qscollege.setOnClickListener(this);
}
public void onClick(View v) {
char ch = 0;
View qsfaculty = null;
View qscollege = null;
if(v == qsfaculty){
ch = 'a';
}
else if (v == qscollege)
{ch = 'b';}
Intent i = new Intent(this,SearchLocation.class);
i.putExtra("value",ch);
startActivity(i);
}
//---------------------------------------------------------------------------
// Initiate database data
public void initiateDb() {
DatabaseHandler myDbHandler = new DatabaseHandler(this);
try {
myDbHandler.createDataBase();
}
catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHandler.openDataBase();
}
catch(SQLException sqle) {
throw sqle;
}
Log.d("Initiate", "UKM Location Count: " + myDbHandler.getUkmLocationCount());
myDbHandler.close();
}
//------------------------------------------------------------------------------
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quick_search, menu);
return true;
}
}
SearchLocation.java
package com.example.awesome;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class SearchLocation extends ListActivity {
//------------------------------------------------------------------
// Declaration
public static UkmLocation selectedPOI = null;
final DatabaseHandler db = new DatabaseHandler(this);
private EditText filterText = null;
ArrayAdapter<String> adapter = null;
final ArrayList<String> results = new ArrayList<String>();
final ArrayList<String> results_id = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_location);
final Intent c = new Intent(SearchLocation.this, LocationDetail.class);
//------------------------------------------------------------------
// Link editText to layout item
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
//------------------------------------------------------------------
// Reading Poi
Log.d("Reading", "Reading all Kategori ..");
int value = 0;
switch(value) {
case 'a' :
List<UkmLocation> faculty = db.getCategoryFaculty();
for(UkmLocation k : faculty) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
case 'b' :
List<UkmLocation> college = db.getCategoryCollege();
for(UkmLocation k : college) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
}
//------------------------------------------------------------------
// Set list arrayAdapter to adapter
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.textView1,results);
setListAdapter(adapter);
//------------------------------------------------------------------
// Set ListView from ListActivity
ListView lv = getListView();
lv.setTextFilterEnabled(true);
//------------------------------------------------------------------
// Set click event from listView
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
Log.d("test", "position:" + position);
Log.d("test", "actualname:" + db.getUkmLocationByName(adapter.getItem(position)).getName());
// String poiID = results_id.get(position);
String poiID = db.getUkmLocationByName(adapter.getItem(position)).getID();
setSelectedPoi(poiID);
startActivity(c);
}
});
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
}
};
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
public UkmLocation getSelectedPoi() {
return selectedPOI;
}
public void setSelectedPoi(String poiID) {
selectedPOI = db.getUkmLocation(poiID);
Log.d("test2", "_id:" + db.getUkmLocation(poiID).getID());
Log.d("test2", "Name:" + db.getUkmLocation(poiID).getName());
// Closing db
db.close();
}
}
i think,the if else statement inside QuickSearch.java is already correct. the problem at the switch case statement at SearchLocation.java
please help me solve this.
int value = 0;
switch(value) {
You are setting the value over which you switch to 0 so it is equivalent to doing switch(0) {...
Find out what that value is supposed to be and initialise it properly.
Also, value is of type int but your switch uses chars ('a', 'b'), so you need to either have value be a char and initialise it properly or have it be an int, initialise it properly and change your switch cases to use ints.
First you do int value = 0; so value is 0. So it is not 'a' nor 'b'.
You have to get the value from the intent as you put it in extras. i.putExtra("value",ch);
something like
char value;
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getIntgetChar("value");
}
here, i already solve my problem..
QuickSearch.java
public void onClick(View v) {
int ch = 0;
/*View qsfaculty = null;
View qscollege = null;*/
if(v == qsfaculty){
ch = '1';
}
else if (v == qscollege)
{ch = '2';}
Intent i = new Intent(this,SearchLocation.class);
i.putExtra("value",ch);
startActivity(i);
}
SearchLocation.java
Bundle extras = getIntent().getExtras();
int value = extras.getInt("value");
switch(value) {
case '1' :
List<UkmLocation> faculty = db.getCategoryFaculty();
for(UkmLocation k : faculty) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
case '2' :
List<UkmLocation> college = db.getCategoryCollege();
for(UkmLocation k : college) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
}

Categories

Resources