app crashes when a block of code is included in a loop - android

I have a block of code creating arraylists, adapter and onclickitemlistener and it works great ONLY if it is meant to work once. I want to include the block in a loop so it's performed several times, but when I do so the app crashes when I want to go to that activity so the block does not run even once... what may be the reason?
public class MyClass extends Activity {
int c=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.quiz1);
final ArrayList<String> words = new ArrayList<String>();
TextView tvTo = (TextView) findViewById(R.id.tvTo);
ListView lvLV = (ListView) findViewById(R.id.lvLV);
DataWraper dwF = (DataWraper) getIntent().getSerializableExtra("data");
ArrayList<Word> wordList = dwF.GetWords();
for(Word w : wordList) {
words.add(w.GetSth()+"."+w.GetSthElse());
}
// do {
Generator set = new Generator(words);
ArrayList<String> s = set.GetQuizSet();
final String palabra = s.get(0).substring(s.get(0).indexOf(".")+1);
tvTo.setText(s.get(0).substring(0, s.get(0).indexOf(".")));
Collections.shuffle(s);
final ArrayList<String> sp = new ArrayList<String>();
for(String o : s) {
transl.add(o.substring(o.indexOf(".")+1));
}
MAdapter la = new MAdapter(MyClass.this, sp);
lvLV.setAdapter(la);
lvLV.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(sp.get(position).matches(palabra)) {
Toast.makeText(getBaseContext(), "Good", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Not Good", Toast.LENGTH_LONG).show();
}
// c++;
}
});
// } while(c<5);
}
}

Looks like you're getting a StackOverflowError. You only increment c in the OnItemClickListener, so it's not getting incremented in onCreate(), and your while-loop is running endlessly.
Without knowing exactly what you're trying to accomplish, or what exactly all your classes are, I juggled your code a bit. You might want to structure your code more like this:
public class MyClass extends Activity
{
int c = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.quiz1);
final ArrayList<String> words = new ArrayList<String>();
TextView tvTo = (TextView) findViewById(R.id.tvTo);
ListView lvLV = (ListView) findViewById(R.id.lvLV);
DataWraper dwF = (DataWraper) getIntent().getSerializableExtra("data");
ArrayList<Word> wordList = dwF.GetWords();
for (Word w : wordList)
{
words.add(w.GetSth() + "." + w.GetSthElse());
}
final ArrayList<String> sp = new ArrayList<String>();
MAdapter la = new MAdapter(MyClass.this, sp);
lvLV.setAdapter(la);
lvLV.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//*** Your call to generate() will go in here
//*** depending on where you want it
if (sp.get(position).matches(palabra))
{
Toast.makeText(getBaseContext(), "Good", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getBaseContext(), "Not Good", Toast.LENGTH_LONG).show();
}
}
}
);
}
private void generate()
{
if (c < 5)
{
Generator set = new Generator(words);
ArrayList<String> s = set.GetQuizSet();
final String palabra = s.get(0).substring(s.get(0).indexOf(".") + 1);
tvTo.setText(s.get(0).substring(0, s.get(0).indexOf(".")));
Collections.shuffle(s);
for (String o : s)
{
transl.add(o.substring(o.indexOf(".") + 1));
}
c++;
}
}
}

Related

How to populate autocomplete textview based on the selection of first?

There are 2 autocomplete textview one for the city and one for the state. I want that when a user enters the state in autocomplete textview then based on state selection, city autocomplete text view should be automatically filled. Like the ecommerce app whenever someone enters the postal code in the address section then the city and state get automatically filled and also the user has the option to select.
MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText edtxt_name_address, edtxt_email_address, edtxt_mobile_address, edtxt_alt_mob_address, edtxt_pincode, edtxt_addline1, edtxt_addline2;
Button buttonSaveAddress;
AutoCompleteTextView edtxt_city, edtxt_state;
private static final String KEY_STATE = "state";
private static final String KEY_CITIES = "cities";
private ProgressDialog pDialog;
private String cities_url = "http://api.androiddeft.com/cities/cities_array.json";
final List<State> statesList = new ArrayList<>();
final List<String> states = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtxt_city = findViewById(R.id.edtxt_city);
edtxt_state = findViewById(R.id.edtxt_state);
loadStateCityDetails();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, states);
edtxt_state.setThreshold(1);//will start working from first character
edtxt_state.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView
//edtxt_city.setTextColor(Color.BLACK)
edtxt_state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
buttonSaveAddress = findViewById(R.id.buttonSaveAddress);
buttonSaveAddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveAddress();
}
});
}
private void loadStateCityDetails() {
JsonArrayRequest jsArrayRequest = new JsonArrayRequest
(Request.Method.GET, cities_url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray responseArray) {
try {
//Parse the JSON response array by iterating over it
for (int i = 0; i < responseArray.length(); i++) {
JSONObject response = responseArray.getJSONObject(i);
String state = response.getString(KEY_STATE);
JSONArray cities = response.getJSONArray(KEY_CITIES);
List<String> citiesList = new ArrayList<>();
for (int j = 0; j < cities.length(); j++) {
citiesList.add(cities.getString(j));
}
statesList.add(new State(state, citiesList));
states.add(state);
Log.d("lskd", String.valueOf(statesList));
Log.d("lskd", String.valueOf(states));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//pDialog.dismiss();
//Display error message whenever an error occurs
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsArrayRequest);
}
private void saveAddress() {
if (TextUtils.isEmpty(city)) {
edtxt_city.setError("Please enter your City");
edtxt_city.requestFocus();
return;
}
if (TextUtils.isEmpty(state)) {
edtxt_state.setError("Please enter your State");
edtxt_state.requestFocus();
return;
}
Intent profile_next = new Intent(MainActivity.this, ProfileNextActivity.class);
startActivity(profile_next);
}
}
State.java
public class State {
private String stateName;
private List<String> cities;
public State(String stateName, List<String> cities) {
this.stateName = stateName;
this.cities = cities;
}
public String getStateName() {
return stateName;
}
public List<String> getCities() {
return cities;
}
}
State and city has one to many relation, I didn't particularly understand what you meant by automatically filled. If you want to populate the related cities of the selected state do the following.
Inside your edtxt_state.setOnItemSelectedListener
edtxt_state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
statesList.get(position).getCities(); //get your cities from selected state
//set adapter or notify city list of your `edtxt_city` AutoCompleteTextView
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
try this...
edtxt_state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
List<String> cityList = statesList.get(position).getCities();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, cityList);
edtxt_city.setThreshold(1);//will start working from first character
edtxt_city.setAdapter(adapter);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
set your adapter inside loadStateCityDetails(); after getting stateList
statesList.add(new State(state, citiesList));
states.add(state);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, states);
edtxt_state.setThreshold(1);//will start working from first character
edtxt_state.setAdapter(adapter);
EDIT
edtxt_state.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
int pos = -1;
for (int i = 0; i < statesList.size(); i++) {
if (statesList.get(i).getStateName().equals(selection)) {
pos = i;
break;
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.select_dialog_item, statesList.get(pos).getCities());
edtxt_city.setThreshold(1);//will start working from first character
edtxt_city.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView
}
});
you must get stateList
set city adapter as above

Async and skipping frames

So I've run into an issue where I have an item that I click in a listview, it does a makes a few extras, and moves on the my next activity. I get an issue where my app goes to a black screen and the Console tells me
I/Choreographer: Skipped 630 frames! The application may be doing too much work on its main thread.
I've tried reading up on Async but I'm not sure how to use it in my code. So I'm posting my Main activity since this happens without interacting with the second activity.
public class MainActivity extends AppCompatActivity {
ListView ListofList;
ArrayList<String> Lists;
ArrayAdapter<String> ListAdapter;
Button button;
ArrayList<String> Subject = new ArrayList<>();
int Size = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListofList = findViewById(R.id.LofL);
Lists = new ArrayList<String>();
ListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Lists);
ListofList.setAdapter(ListAdapter);
button = findViewById(R.id.AddList);
Lists.add("Test");
ListofList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getBaseContext(), ItemList.class);
String s = (String) ListofList.getItemAtPosition(position);
i.putExtra("Title", s);
i.putExtra("size", Size);
int a = 0;
for (String t : Subject) {
i.putExtra("Item" + a, t);
a++;
}
startActivityForResult(i, 2);
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getBaseContext(), CreateItem.class);
String message = "Please enter the name of the list below.";
i.putExtra("mess", message);
startActivityForResult(i, 1);
}
});
}
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
Bundle extras = getIntent().getExtras();
if (data == null) {
}
if (data != null) {
if (requestCode == 1) {
String item = (data.getStringExtra("item"));
Lists.add(item);
ListAdapter.notifyDataSetChanged();
}
}
if (requestCode == 2) {
ArrayList<String> subject = new ArrayList<String>();
int i = 0;
assert data != null;
int size = (data.getIntExtra("ListSize", 0));
Size = size;
while (i <= size) {
String item = (data.getStringExtra("item" + i));
subject.add(item);
i++;
}
Subject = subject;
}
}
}
At the request of Ben P.
public class ItemList extends AppCompatActivity {
static ArrayList<String> customItems;
ArrayAdapter<String> adapter;
ListView lvItems;
Button button;
Button button2;
ArrayAdapter<String> trashAdapter;
ArrayList<String> trash;
ListView itemtrash;
static TextView Title;
String Tit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_list);
Title = findViewById(R.id.Title);
//set up Item List
customItems = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, customItems);
lvItems = (ListView) findViewById(R.id.lvItems);
//Set up trash List
trash = new ArrayList<String>();
trashAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, trash);
itemtrash = findViewById(R.id.itemtrash);
//Initialize Buttons
button = findViewById(R.id.AddItem);
button2 = findViewById(R.id.ClearTrash);
Bundle extras = getIntent().getExtras();
if (extras != null) {
((TextView)findViewById(R.id.Title)).setText(extras.getString("Title"));
Tit = extras.getString("Title");
int i = 0;
int size = (extras.getInt("size", 0));
while (i <= size) {
String item = (extras.getString("Item" + i));
if (item == null) {
continue;
}
customItems.add(item);
i++;
}
}
//CharSequence Titlefilter = Title.getText();
//lvItems.setTextFilterEnabled(true);
//ItemList.this.adapter.getFilter().filter(Titlefilter);
//adapter.notifyDataSetChanged();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getBaseContext(), CreateItem.class);
String message = "Please enter new item below.";
i.putExtra("mess", message);
startActivityForResult(i, 1);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
trashAdapter.clear();
trashAdapter.notifyDataSetChanged();
}
});
lvItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String s = adapter.getItem(position);
trashAdapter.add(s);
adapter.remove(s);
assert s != null;
adapter.notifyDataSetChanged();
trashAdapter.notifyDataSetChanged();
}
});
itemtrash.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String s = trashAdapter.getItem(position);
customItems.add(s);
trash.remove(s);
adapter.notifyDataSetChanged();
trashAdapter.notifyDataSetChanged();
}
});
lvItems.setAdapter(adapter);
itemtrash.setAdapter(trashAdapter);
}
#Override
public void onBackPressed() {
Intent i = new Intent();
int a = 0;
for (String s : customItems){
String t = adapter.getItem(a);
i.putExtra("item" + a, t);
a++;
}
int size = customItems.size();
i.putExtra("ListSize", size);
setResult(2, i);
finish();
}
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
Bundle extras = getIntent().getExtras();
if (data == null) {
}
if (data != null) {
String item = (data.getStringExtra("item"));
String title = Tit;
customItems.add(title + "\n\n" + item);
adapter.notifyDataSetChanged();
}
}
}
I figured it out. I accidentally made an infinite loop with while in the ItemList activity.

Activity reloads the whole data from server again when coming back from an other activity in Android

Basically, I'm working on a app which has a tab-activity including 4 tabs and also I'm using the actvityGroup to manage the activities and backKey pressed() method.
When my app first starts it sends a request to server and shows the progress bar (using AsyncTask) as shown in below image.
After this, my complete UI appears as
it loads new actvity on click event of button "GO" (code is given below)
btnGo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent bookSearchResultActivityIntent = new Intent();
bookSearchResultActivityIntent
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
bookSearchResultActivityIntent.setClass(getParent(),
BookSearchResultActivity.class);
bookSearchResultActivityIntent.putExtra("LANG", language);
bookSearchResultActivityIntent.putExtra("SEARCH_KEYWORDS",
edTxt_SearchField.getText().toString());
MyActivityGroup activityStack = (MyActivityGroup) getParent();
activityStack.push("BooksSearchActivity",
bookSearchResultActivityIntent);
also here is my ActivtyGroup.java code
public class MyActivityGroup extends ActivityGroup {
private Stack<String> stack;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (stack == null) {
stack = new Stack<String>();
}
push("1stStackActivity", new Intent(this, Home.class));
}
#Override
public void finishFromChild(Activity child) {
pop();
}
#Override
public void onBackPressed() {
pop();
}
public void push(String id, Intent intent) {
Window window = getLocalActivityManager().startActivity(id,
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
if (window != null) {
stack.push(id);
setContentView(window.getDecorView());
}
}
public void pop() {
if (stack.size() == 1) {
finish();
}
LocalActivityManager manager = getLocalActivityManager();
manager.destroyActivity(stack.pop(), true);
if (stack.size() > 0) {
Intent lastIntent = manager.getActivity(stack.peek()).getIntent()
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Window newWindow = manager.startActivity(stack.peek(), lastIntent);
setContentView(newWindow.getDecorView());
}
}
}
ok now my question is that when i press the backKey(); it should come to the previous actvity.
Yes it comes to the previous activity but it send request to the server again and shows the progress bar again and loads until the server sends response. it wastes my time.
I only want to load the HomeTab just once (when i play the app). not again and again
I am also adding the
setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
while starting the activity
also added following code in menifest.xml file
android:configChanges="keyboard|keyboardHidden|orientation"
but not working yet.
and here is the code of my Home tab(which sends the request to server in onCreate method)
public class Home extends Activity {
/** Called when the activity is first created. */
static final String URL = "http://www.shiaislamiclibrary.com/requesthandler.ashx";
static final String KEY_ITEM = "Book"; // parent node
static final String KEY_BOOKAUTHOR = "BookAuthor";
static final String KEY_BOOKDATEPUBLISHED = "DatePublished";
static final String KEY_BOOKTITLE = "BookTitle";
static final String KEY_BOOKCODE = "BookCode";
static final String KEY_BOOKIMAGE = "BookImage";
String searchLang;
String searchKeywords;
LayoutInflater inflater = null;
ArrayList<String> BookTitle = new ArrayList<String>();
ArrayList<String> BookCoverPhotos = new ArrayList<String>();
ArrayList<String> BookAuther = new ArrayList<String>();
ArrayList<String> BookPublishDate = new ArrayList<String>();
ArrayList<String> ImageByte = new ArrayList<String>();
ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();
Context ctx = this;
Activity act = this;
Context context = Home.this;
URL bookImageURL = null;
Bitmap bitMapImage = null;
Button btnGo;
Spinner spnrLanguage;
Spinner spnrBrowseBy;
String language;
EditText edTxt_SearchField;
GridView gridView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.home_activity);
View viewToLoad = LayoutInflater.from(this.getParent()).inflate(
R.layout.home_activity, null);
this.setContentView(viewToLoad);
gridView = (GridView) findViewById(R.id.gridview);
spnrLanguage = (Spinner) findViewById(R.id.spnrLanguage);
spnrBrowseBy = (Spinner) findViewById(R.id.spnrBrowseBy);
edTxt_SearchField = (EditText) findViewById(R.id.EditTxt_Search);
btnGo = (Button) findViewById(R.id.btn_GO);
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// checking for availbe internet Connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
new UIThread().execute(URL, "Imam Ali");
}
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
Toast.makeText(context, BookTitle.get(pos), Toast.LENGTH_SHORT)
.show();
Intent bookSearchResultActivityIntent = new Intent();
bookSearchResultActivityIntent.setClass(getParent(),
BookOverView.class);
bookSearchResultActivityIntent.putExtra("BITMAP",
bitmapArray.get(pos));
bookSearchResultActivityIntent.putExtra("BOOK_TITLE",
BookTitle.get(pos));
bookSearchResultActivityIntent.putExtra("BOOK_AUTHOR",
BookAuther.get(pos));
bookSearchResultActivityIntent.putExtra("BOOK_PUBLISH_DATE",
BookPublishDate.get(pos));
MyActivityGroup activityStack = (MyActivityGroup) getParent();
activityStack.push("BookOverViewActivity",
bookSearchResultActivityIntent);
}
});
// //////////////////// Spinners handler/////////////////////////
ArrayAdapter<String> adapterLanguage = new ArrayAdapter<String>(
context, android.R.layout.simple_spinner_item, getResources()
.getStringArray(R.array.spnr_language_array));
ArrayAdapter<String> adapterBrowseBy = new ArrayAdapter<String>(
context, android.R.layout.simple_spinner_item, getResources()
.getStringArray(R.array.spnr_browse_array));
spnrLanguage.setAdapter(adapterLanguage);
spnrBrowseBy.setAdapter(adapterBrowseBy);
spnrLanguage.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
Toast.makeText(getParent(),
spnrLanguage.getItemAtPosition(pos) + "",
Toast.LENGTH_SHORT).show();
language = spnrLanguage.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
spnrBrowseBy.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
Toast.makeText(context,
spnrBrowseBy.getItemAtPosition(pos) + "",
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
// ////////////////////Search Button Handler/////////////////
btnGo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!edTxt_SearchField.getText().toString().equals("")) {
Intent bookSearchResultActivityIntent = new Intent();
bookSearchResultActivityIntent
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
bookSearchResultActivityIntent.setClass(getParent(),
BookSearchResultActivity.class);
bookSearchResultActivityIntent.putExtra("LANG", language);
bookSearchResultActivityIntent.putExtra("SEARCH_KEYWORDS",
edTxt_SearchField.getText().toString());
MyActivityGroup activityStack = (MyActivityGroup) getParent();
activityStack.push("BooksSearchActivity",
bookSearchResultActivityIntent);
} else {
Toast.makeText(context, "Search Field Empty",
Toast.LENGTH_SHORT).show();
}
}
});
}
private class UIThread extends AsyncTask<String, Integer, String> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = ProgressDialog.show(getParent(),
"Acumlating Books from server...",
"This may Take a few seconds.\nPlease Wait...");
}
#Override
protected String doInBackground(String... params) {
String URL = params[0];
String searchKeywords = params[1];
XMLParser parser = new XMLParser();
String XMLString = parser.getXmlFromUrl(URL, searchKeywords,
searchLang);
// Log.i("XML Response", XMLString);
Document doc = parser.getDomElement(XMLString);
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
Element e = (Element) nl.item(i);
BookTitle.add(parser.getValue(e, KEY_BOOKTITLE));
BookCoverPhotos.add("http://shiaislamicbooks.com/books_Snaps/"
+ parser.getValue(e, KEY_BOOKCODE) + "/1_thumb.jpg");
BookAuther.add(parser.getValue(e, KEY_BOOKAUTHOR));
BookPublishDate.add(parser.getValue(e, KEY_BOOKDATEPUBLISHED));
Log.i("URLs", BookCoverPhotos.toString());
}
for (int i = 0; i < BookAuther.size(); i++) {
try {
bookImageURL = new URL(BookCoverPhotos.get(i));
} catch (MalformedURLException e) {
e.printStackTrace();
Log.i("URL", "ERROR at image position" + i + "");
}
try {
bitMapImage = BitmapFactory.decodeStream(bookImageURL
.openConnection().getInputStream());
bitmapArray.add(bitMapImage);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("BITMAP", "ERROR" + i);
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
ImageAdapter adapter = new ImageAdapter(getBaseContext(), act);
gridView.setAdapter(adapter);
}
}
public class ImageAdapter extends BaseAdapter {
public ImageAdapter(Context c) {
context = c;
}
// ---returns the number of images---
public int getCount() {
// return imageIDs.length;
return bitmapArray.size();
// return 6;
}
public ImageAdapter(Context ctx, Activity act) {
inflater = (LayoutInflater) act
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// ---returns the ID of an item---
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// ---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent) {
// ImageView bmImage;
final ViewHolder holder;
View vi = convertView;
if (convertView == null) {
vi = inflater.inflate(R.layout.grid_style, parent, false);
holder = new ViewHolder();
holder.txt_BooksTitle = (TextView) vi
.findViewById(R.id.txt_BookTitle);
holder.img_BookCoverPhoto = (ImageView) vi
.findViewById(R.id.imgBookCover);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
holder.txt_BooksTitle.setText(BookTitle.get(position) + "");
holder.img_BookCoverPhoto.setImageBitmap(bitmapArray.get(position));
return vi;
}
}
class ViewHolder {
TextView txt_BooksTitle;
ImageView img_BookCoverPhoto;
}
}
please have a look on my activity group class and tell what should i do.
thanks in advance
When loading your data in the Home Tab activity, put it inside some static arrays.
ArrayList<String> BookTitle = new ArrayList<String>();
ArrayList<String> BookCoverPhotos = new ArrayList<String>();
ArrayList<String> BookAuther = new ArrayList<String>();
ArrayList<String> BookPublishDate = new ArrayList<String>();
ArrayList<String> ImageByte = new ArrayList<String>();
ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();
From a quick glimpse on the code, make them static ArrayList<...> ... = null; and check inside the onCreate() method:
if(BookTitle == null)
{
//needs init
BookTitle = new ArrayList<String>();
//perform connect to server and parse response.
}
When the application activity home tab is stopped then restarted, the data will be in memory already and it will skip the if clause keeping the old data for re-use.
Make sure you will clear the static variables when you really want to kill the app - on a quit button click, call a static method to init them to null again, or if you want them to be valid for let's say 12 hours, memorize the timestamp in a static variable and each time you kill/pause the main activity perform a check on it (wheather is null or has a date, if it has a date, check if 12 hours have passed, if yes, clear the static variable contents)
This is the quick and easy way. Another way is to store them in the application database if you don't want to deal with static variables.
There are a lot of options, the point is you kinda have to mark them as "global persistent" data with static, or store them in a databse / file etc.

the App. Crashs when delete item from ListView

I have an SQLite table and in the certain activity I obtain all the names fom the table and populate a listview with these names.
Inside the listview listener, the user have can delete the selected item.
The problem is when I delete the item the app crashes.
Please take a look on my code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylocations);
tv_counter = (TextView) findViewById(R.id.counter);
tv_testCounter = (TextView) findViewById(R.id.testCounter);
lv = (ListView) findViewById(R.id.mylist);
mpoh = new MP_DB(this);
db = mpoh.getWritableDatabase();
cv = new ContentValues();
if (hasRecords()) {
Toast.makeText(getBaseContext(), getRowsNum()+" row(s)", Toast.LENGTH_SHORT).show();
get_MPNames();
arrayToArrayList();
setListView();
lv.setOnItemClickListener(listViewListener);
} else {
Toast.makeText(getBaseContext(), "NO RECORDS"+","+getRowsNum()+"rows", Toast.LENGTH_SHORT).show();
}
}
Here are the method to convert the array to arraylist, and the listview listener:
private void arrayToArrayList() {
int s = str.length;
al = new ArrayList<String>();
for (int i=0; i < s; i++) {
al.add(str[i]);
}
}
private int getRowsNum() {
return mpoh.getCurrentRowNumber();
}
OnItemClickListener listViewListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
pos = arg2;
showDialoge();
}
};
Here how I delete element from the DB and the ListView:
private void deleteMPfromListView(int pos) {
al.remove(pos);
adapter.notifyDataSetChanged();
Toast.makeText(getBaseContext(), al.size()+" rows left in list view", Toast.LENGTH_SHORT).show();
}
private void deleteMPFromDB(int pos) {
mpoh.deleteMP(pos);
Toast.makeText(getBaseContext(), getRowsNum()+" rows left in DB", Toast.LENGTH_SHORT).show();
}
private Boolean hasRecords() {
if (getRowsNum() == 0) {
return false;
} else {
return true;
}
}
private void setListView() {
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
android.R.id.text1, al);
lv.setAdapter(adapter);
}
private void get_MPNames() {
str = new String[getRowsNum()];
for (int i=0; i <= getRowsNum()-1; i++) {
str[i] = mpoh.getMP_Name(i+1);
} //tv_testCounter.setText(str[87]);
}
Removing from the database has nothing to do with removing them from the ListView. I have not code of your implementation but you may try something like this too dynamically add or remove items:
public class LVDemo extends ListActivity {
// handles the ListView data
ArrayAdapter<String> adapter;
// Items that are displayed
ArrayList<String> listItems=new ArrayList<String>();
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
listItems);
setListAdapter(adapter);
}
/**
* Remove item.
*/
public void removeItem(int index) {
listItems.remove(index);
adapter.notifyDataSetChanged();
}
}
In General: You change the the ArrayList containing the element and then notify the adapter for the ListView

Select Automatically from Item List

I have one class that shows me a list of Items. Right now I am selecting this items with click (setOnItemClickListener), but i don't want that. What i want is: when i open the class automatically is selecting the last item on the list.
Can anyone tell me how I can do it?
Thanks for any help
public class SelectCodIncidence extends Activity {
private ArrayList<String> datos;
protected netAppApplication app;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.codincidence);
datos = new ArrayList<String>();
//datosCod = new ArrayList<String>();
try {
NotesCenter messageCenter = new NotesCenterImpl();
List<CodIncidence> codincidence = messageCenter.getCodIncidence();
for (CodIncidence e : codincidence) {
//datosCod.add("1");
datos.add(e.id);
}
} catch (Exception ex) {
// showMessage(ex);
Log.v("blah", ex.getMessage());
}
ArrayAdapter<String> adaptador =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, datos);
final TextView lblMessage = (TextView)findViewById(R.id.MensajeCodIncidence);
final GridView grdOptions = (GridView)findViewById(R.id.GridCodIncidence);
grdOptions.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, android.view.View v, int position, long id) {
CodIncidence codincidenceSelected = new CodIncidence();
codincidenceSelected.id = datos.get(position);
app = (netAppApplication)getApplicationContext();
app.setcodincidenceActual(codincidenceSelected);
SharedPreferences prefs = getSharedPreferences("netAppSetup",2);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("CODINCIDENCE", codincidenceSelected.id);
editor.commit();
finish();
}
});
grdOptions.setAdapter(adaptador);
}
}
Something like:
Spinner spinner = (Spinner) findViewById(R.id.mySpinner);
int count = spinner.getCount();
if (count > 0){
spinner.setSelection(count-1,true);
}

Categories

Resources