Trying to put a search functionality in my application - android

Hi, guys! First of all, I'm newbie! I'm trying to create a search functionality (Search BY CITY) in my application. But something is wrong! It don't work!
The error message is: 'The method filter(String) is undefined for the type BinderData'
adapter.filter(text);
Could someone help me in details? I included the "TextWatcher" function in my main activity (WeatherActivity).
This is my code:
WeatherActivity
public class WeatherActivity extends Activity {
// XML node keys
static final String KEY_TAG = "weatherdata"; // parent node
static final String KEY_ID = "id";
static final String KEY_CITY = "city";
static final String KEY_TEMP_C = "tempc";
static final String KEY_TEMP_F = "tempf";
static final String KEY_CONDN = "condition";
static final String KEY_SPEED = "windspeed";
static final String KEY_ICON = "icon";
EditText editsearch;
// List items
ListView list;
BinderData adapter = null;
List<HashMap<String,String>> weatherDataCollection;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (getAssets().open("weatherdata.xml"));
weatherDataCollection = new ArrayList<HashMap<String,String>>();
// normalize text representation
doc.getDocumentElement ().normalize ();
NodeList weatherList = doc.getElementsByTagName("weatherdata");
HashMap<String,String> map = null;
for (int i = 0; i < weatherList.getLength(); i++) {
map = new HashMap<String,String>();
Node firstWeatherNode = weatherList.item(i);
if(firstWeatherNode.getNodeType() == Node.ELEMENT_NODE){
Element firstWeatherElement = (Element)firstWeatherNode;
//-------
NodeList idList = firstWeatherElement.getElementsByTagName(KEY_ID);
Element firstIdElement = (Element)idList.item(0);
NodeList textIdList = firstIdElement.getChildNodes();
//--id
map.put(KEY_ID, ((Node)textIdList.item(0)).getNodeValue().trim());
//2.-------
NodeList cityList = firstWeatherElement.getElementsByTagName(KEY_CITY);
Element firstCityElement = (Element)cityList.item(0);
NodeList textCityList = firstCityElement.getChildNodes();
//--city
map.put(KEY_CITY, ((Node)textCityList.item(0)).getNodeValue().trim());
//3.-------
NodeList tempList = firstWeatherElement.getElementsByTagName(KEY_TEMP_C);
Element firstTempElement = (Element)tempList.item(0);
NodeList textTempList = firstTempElement.getChildNodes();
//--city
map.put(KEY_TEMP_C, ((Node)textTempList.item(0)).getNodeValue().trim());
//4.-------
NodeList condList = firstWeatherElement.getElementsByTagName(KEY_CONDN);
Element firstCondElement = (Element)condList.item(0);
NodeList textCondList = firstCondElement.getChildNodes();
//--city
map.put(KEY_CONDN, ((Node)textCondList.item(0)).getNodeValue().trim());
//5.-------
NodeList speedList = firstWeatherElement.getElementsByTagName(KEY_SPEED);
Element firstSpeedElement = (Element)speedList.item(0);
NodeList textSpeedList = firstSpeedElement.getChildNodes();
//--city
map.put(KEY_SPEED, ((Node)textSpeedList.item(0)).getNodeValue().trim());
//6.-------
NodeList iconList = firstWeatherElement.getElementsByTagName(KEY_ICON);
Element firstIconElement = (Element)iconList.item(0);
NodeList textIconList = firstIconElement.getChildNodes();
//--city
map.put(KEY_ICON, ((Node)textIconList.item(0)).getNodeValue().trim());
//Add to the Arraylist
weatherDataCollection.add(map);
}
}
BinderData bindingData = new BinderData(this,weatherDataCollection);
list = (ListView) findViewById(R.id.list);
adapter = new BinderData(WeatherActivity.this,
weatherDataCollection);
editsearch = (EditText) findViewById(R.id.search);
editsearch.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString()
.toLowerCase(Locale.getDefault());
adapter.filter(text);
}
});
Log.i("BEFORE", "<<------------- Before SetAdapter-------------->>");
list.setAdapter(bindingData);
Log.i("AFTER", "<<------------- After SetAdapter-------------->>");
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent();
i.setClass(WeatherActivity.this, SampleActivity.class);
// parameters
i.putExtra("position", String.valueOf(position + 1));
/* selected item parameters
* 1. City name
* 2. Weather
* 3. Wind speed
* 4. Temperature
* 5. Weather icon
*/
i.putExtra("city", weatherDataCollection.get(position).get(KEY_CITY));
i.putExtra("weather", weatherDataCollection.get(position).get(KEY_CONDN));
i.putExtra("windspeed", weatherDataCollection.get(position).get(KEY_SPEED));
i.putExtra("temperature", weatherDataCollection.get(position).get(KEY_TEMP_C));
i.putExtra("icon", weatherDataCollection.get(position).get(KEY_ICON));
// start the sample activity
startActivity(i);
}
});
}
catch (IOException ex) {
Log.e("Error", ex.getMessage());
}
catch (Exception ex) {
Log.e("Error", "Loading exception");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
BlinderData
public class BinderData extends BaseAdapter {
// XML node keys
static final String KEY_TAG = "weatherdata"; // parent node
static final String KEY_ID = "id";
static final String KEY_CITY = "city";
static final String KEY_TEMP_C = "tempc";
static final String KEY_TEMP_F = "tempf";
static final String KEY_CONDN = "condition";
static final String KEY_SPEED = "windspeed";
static final String KEY_ICON = "icon";
LayoutInflater inflater;
ImageView thumb_image;
List<HashMap<String,String>> weatherDataCollection;
ViewHolder holder;
public BinderData() {
// TODO Auto-generated constructor stub
}
public BinderData(Activity act, List<HashMap<String,String>> map) {
this.weatherDataCollection = map;
inflater = (LayoutInflater) act
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
// TODO Auto-generated method stub
// return idlist.size();
return weatherDataCollection.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null){
vi = inflater.inflate(R.layout.list_row, null);
holder = new ViewHolder();
holder.tvCity = (TextView)vi.findViewById(R.id.tvCity); // city name
holder.tvWeather = (TextView)vi.findViewById(R.id.tvCondition); // city weather overview
holder.tvTemperature = (TextView)vi.findViewById(R.id.tvTemp); // city temperature
holder.tvWeatherImage =(ImageView)vi.findViewById(R.id.list_image); // thumb image
vi.setTag(holder);
}
else{
holder = (ViewHolder)vi.getTag();
}
// Setting all values in listview
holder.tvCity.setText(weatherDataCollection.get(position).get(KEY_CITY));
holder.tvWeather.setText(weatherDataCollection.get(position).get(KEY_CONDN));
holder.tvTemperature.setText(weatherDataCollection.get(position).get(KEY_TEMP_C));
//Setting an image
String uri = "drawable/"+ weatherDataCollection.get(position).get(KEY_ICON);
int imageResource = vi.getContext().getApplicationContext().getResources().getIdentifier(uri, null, vi.getContext().getApplicationContext().getPackageName());
Drawable image = vi.getContext().getResources().getDrawable(imageResource);
holder.tvWeatherImage.setImageDrawable(image);
return vi;
}
/*
*
* */
static class ViewHolder{
TextView tvCity;
TextView tvTemperature;
TextView tvWeather;
ImageView tvWeatherImage;
}
}
SampleActivity
public class SampleActivity extends Activity {
String position = "1";
String city = "";
String weather = "";
String temperature = "";
String windSpeed = "";
String iconfile = "";
ImageButton imgWeatherIcon;
TextView tvcity;
TextView tvtemp;
TextView tvwindspeed;
TextView tvCondition;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detailpage);
try {
//handle for the UI elements
imgWeatherIcon = (ImageButton) findViewById(R.id.imageButtonAlpha);
//Text fields
tvcity = (TextView) findViewById(R.id.textViewCity);
tvtemp = (TextView) findViewById(R.id.textViewTemperature);
tvwindspeed = (TextView) findViewById(R.id.textViewWindSpeed);
tvCondition = (TextView) findViewById(R.id.textViewCondition);
// Get position to display
Intent i = getIntent();
this.position = i.getStringExtra("position");
this.city = i.getStringExtra("city");
this.weather= i.getStringExtra("weather");
this.temperature = i.getStringExtra("temperature");
this.windSpeed = i.getStringExtra("windspeed");
this.iconfile = i.getStringExtra("icon");
String uri = "drawable/"+ "d" + iconfile;
int imageBtnResource = getResources().getIdentifier(uri, null, getPackageName());
Drawable dimgbutton = getResources().getDrawable(imageBtnResource);
//text elements
tvcity.setText(city);
tvtemp.setText(temperature);
tvwindspeed.setText(windSpeed);
tvCondition.setText(weather);
//thumb_image.setImageDrawable(image);
imgWeatherIcon.setImageDrawable(dimgbutton);
}
catch (Exception ex) {
Log.e("Error", "Loading exception");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
XParser
public class XParser extends DefaultHandler {
ArrayList<String> idlist = new ArrayList<String>();
ArrayList<String> citylist = new ArrayList<String>();
ArrayList<String> condilist = new ArrayList<String>();
ArrayList<String> templist = new ArrayList<String>();
ArrayList<String> speedlist = new ArrayList<String>();
ArrayList<String> iconlist = new ArrayList<String>();
//temp variable to store the data chunk read while parsing
private String tempStore = null;
public XParser() {
// TODO Auto-generated constructor stub
}
/*
* Clears the tempStore variable on every start of the element
* notification
*
* */
public void startElement (String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if (localName.equalsIgnoreCase("id")) {
tempStore = "";
} else if (localName.equalsIgnoreCase("city")) {
tempStore = "";
}
else if (localName.equalsIgnoreCase("tempc")) {
tempStore = "";
}
else if (localName.equalsIgnoreCase("condition")) {
tempStore = "";
}
else if (localName.equalsIgnoreCase("windspeed")) {
tempStore = "";
}
else if (localName.equalsIgnoreCase("icon")) {
tempStore = "";
}
else {
tempStore = "";
}
}
/*
* updates the value of the tempStore variable into
* corresponding list on receiving end of the element
* notification
* */
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
if (localName.equalsIgnoreCase("id")) {
idlist.add(tempStore);
}
else if (localName.equalsIgnoreCase("city")) {
citylist.add(tempStore);
}
else if (localName.equalsIgnoreCase("tempc")) {
templist.add(tempStore);
}
else if (localName.equalsIgnoreCase("condition")) {
condilist.add(tempStore);
}
else if (localName.equalsIgnoreCase("windspeed")) {
speedlist.add(tempStore);
}
else if (localName.equalsIgnoreCase("icon")) {
iconlist.add(tempStore);
}
tempStore = "";
}
/*
* adds the incoming data chunk of character data to the
* temp data variable - tempStore
*
* */
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
tempStore += new String(ch, start, length);
}
}``
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

Related

How to get edit text values from a listview

I am not able to get edittext value from dynamic listview. When I am scrolling listview, entered values in edit text is going invisible
Below is My Activity file -
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_servic_homepage);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
url = getResources().getString(R.string.webservice);
aq = new AQuery(ServicHomepage.this);
cd = new ConnectionDetector(ServicHomepage.this);
findviewbyId();
progressdialog();
if (cd.isConnectingToInternet()) {
getintentData();
} else {
Toast.makeText(ServicHomepage.this, "CheckIternet connection", Toast.LENGTH_SHORT).show();
}
}
private void progressdialog() {
pd = new ProgressDialog(ServicHomepage.this);
pd.setMessage("Loading...");
}
public void findviewbyId() {
recyclerview = (ListView) findViewById(R.id.service_recycler_view);
update_descrptn = (TextView) findViewById(R.id.update_descrptn);
uploadimages = (TextView) findViewById(R.id.uploadimages);
}
public void getintentData() {
SharedPreferences prefs = getSharedPreferences(Constants.PREFS_NAME, 0);
catid = prefs.getString(Constants.CATID, "");
subcatid = prefs.getString(Constants.SUBCATID, "");
user_id = prefs.getString(Constants.USERID, "");
isappointment = prefs.getString(Constants.IS_APPOINTMENT, "");
clicklistener();
}
public void clicklistener() {
uploadimages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), GalleryAlbumActivity.class);
startActivity(i);
}
});
update_descrptn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(ServicHomepage.this, "" + serv_adapter.getItem(POSITION), Toast.LENGTH_SHORT).show();
for (int i = 0; i < serv_adapter.getCount(); i++) {
View view = serv_adapter.getView(i,null,null);
EditText edittext = (EditText)view.findViewById(R.id.et_amount);
EditText et_description = (EditText)view.findViewById(R.id.et_description);
String str = edittext.getText().toString();
String str1 = et_description.getText().toString();
Toast.makeText(ServicHomepage.this, str + "==" + str1, Toast.LENGTH_SHORT).show();
}
updateList();
}
});
}
private void updateList() {
String substring = null, msgString = "";
String MAIN_CART = null;
MAIN_CART = "{\"service\":[%s]}";
String temstring = "";
for (int i = 0; i < arrayList.size(); i++) {
substring = "{\"title\":\"" + arrayList.get(i).getTitle() + "\",\"subcatid\":\"" + arrayList.get(i).getSubcatid()
+ "\",\"amount\":\"" + "" + "\",\"description\":\"" + "" + "\"}" + ",";
temstring = temstring + substring;
}
temstring = temstring.substring(0, temstring.length() - 1);
msgString = msgString + String.format(MAIN_CART, temstring);
Log.e("msgString=============", msgString);
}
This is the method where all the items are adding in the list
public String parseanimcat(String object) {
try {
JSONObject json = new JSONObject(object);
JSONObject jsonobj = json.getJSONObject("data");
status1 = jsonobj.getString("status");
message = jsonobj.getString("message");
arrayList = new ArrayList<>();
JSONArray jarray = jsonobj.getJSONArray("dataFound");
for (int i = 0; i <= jarray.length(); i++) {
JSONObject jobj = jarray.getJSONObject(i);
String category = jobj.getString("category");
String subsubcat_id = jobj.getString("subsubcat_id");
Toast.makeText(ServicHomepage.this, category + "==" + subsubcat_id, Toast.LENGTH_SHORT).show();
model = new Data_Model();
model.setTitle(category);
model.setSubcatid(subsubcat_id);
arrayList.add(model);
}
} catch (JSONException e) {
e.printStackTrace();
}
return object;
}
This is my adapter class-
private class service_list_adapter extends ArrayAdapter<Data_Model>{
private ArrayList<Data_Model> array_list;
Context context;
String[] etValArr;
ViewHolder holder;
String[] totalValue;
Data_Model model;
HashMap<String, String> hm = new HashMap<>();
ArrayList<HashMap<String, String>> list = new ArrayList<>();
public service_list_adapter(Context context,int resourceId,ArrayList<Data_Model> arrayList) {
super(context,resourceId,arrayList);
this.context = context;
this.array_list = arrayList;
etValArr = new String[array_list.size()];
totalValue = new String[array_list.size()];
}
private class ViewHolder {
public TextView serv_title;
public EditText serv_descrptn, serv_amount;
}
public View getView(int position, View convertView, ViewGroup parent) {
model = array_list.get(position);
POSITION = position;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.serv_cat_rowitem, null);
holder = new ViewHolder();
holder.serv_title = (TextView) convertView.findViewById(R.id.serv_txt);
holder.serv_descrptn = (EditText) convertView.findViewById(R.id.et_description);
holder.serv_amount = (EditText) convertView.findViewById(R.id.et_amount);
convertView.setTag(holder);
holder.serv_title.setTag(position);
holder.serv_descrptn.setTag(position);
holder.serv_amount.setTag(position);
} else
holder = (ViewHolder) convertView.getTag();
holder.serv_title.setText(model.getTitle());
holder.serv_descrptn.setText(model.getServdescription());
holder.serv_amount.setText(model.getServamount());
holder.serv_amount.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
model.setServamount(s.toString());
}
});
holder.serv_descrptn.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
model.setServdescription(s.toString());
}
});
return convertView;
}
}
be more specific exactly which editText value you want.
you can implement onScrollListner on list and save the value of the editText on that event and later use it

Saving/Storeing an external image into SQLite Database

I have a book-App, where I scan a book with barcodescanner and retrieving the information from googlebooksapi.
At the moment I can save the general bookinfos, title, author, date, rating and shelf (where i want to display the book) in my SQLite database
Now I want to save the bookcover, which comes with the googleapi, too.
Can you tell me how I can save the image in my SQlite Database. By looking for solution I realized that I have to blob the image. but I dont know how.
Following my activties.
ScanActivity.java -> at the end of the code, I save the book data into sql db
public class ScanActivity extends AppCompatActivity implements OnClickListener {
private Button scanBtn, previewBtn, linkBtn, addBookBtn, librarybtn;
public TextView authorText, titleText, descriptionText, dateText, ratingCountText;
public EditText shelfText;
private LinearLayout starLayout;
private ImageView thumbView;
private ImageView[] starViews;
private Bitmap thumbImg;
public BookDBHelper bookDBHelper;
public SQLiteDatabase sqLiteDatabase1;
public Context context1 = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
//Fonts
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
Button myButtonViewScan = (Button) findViewById(R.id.scan_button);
myButtonViewScan.setTypeface(myTypeface);
TextView myWheretoSaveTextView = (TextView) findViewById(R.id.textView_wheretosave);
myWheretoSaveTextView.setTypeface(myTypeface);
//Scanbutton
scanBtn = (Button) findViewById(R.id.scan_button);
scanBtn.setOnClickListener(this);
//Preview Button
previewBtn = (Button) findViewById(R.id.preview_btn);
previewBtn.setVisibility(View.GONE);
previewBtn.setOnClickListener(this);
//Weblink Button
linkBtn = (Button) findViewById(R.id.link_btn);
linkBtn.setVisibility(View.GONE);
linkBtn.setOnClickListener(this);
/* //AddBookBtn
addBookBtn= (Button)findViewById(R.id.btn_savebook);
addBookBtn.setVisibility(View.GONE);
addBookBtn.setOnClickListener(this);
//LibraryButton
librarybtn = (Button) findViewById(R.id.btn_maps);
librarybtn.setVisibility(View.GONE);
librarybtn.setOnClickListener(this);
*/
authorText = (TextView) findViewById(R.id.book_author);
titleText = (TextView) findViewById(R.id.book_title);
descriptionText = (TextView) findViewById(R.id.book_description);
dateText = (TextView) findViewById(R.id.book_date);
starLayout = (LinearLayout) findViewById(R.id.star_layout);
ratingCountText = (TextView) findViewById(R.id.book_rating_count);
thumbView = (ImageView) findViewById(R.id.thumb);
shelfText = (EditText) findViewById(R.id.editText_wheretosave);
starViews = new ImageView[5];
for (int s = 0; s < starViews.length; s++) {
starViews[s] = new ImageView(this);
}
starViews = new ImageView[5];
for (int s = 0; s < starViews.length; s++) {
starViews[s] = new ImageView(this);
}
}
public void onClick(View v) {
if (v.getId() == R.id.scan_button) {
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
} else if (v.getId() == R.id.link_btn) {
//get the url tag
String tag = (String) v.getTag();
//launch the url
Intent webIntent = new Intent(Intent.ACTION_VIEW);
webIntent.setData(Uri.parse(tag));
startActivity(webIntent);
} else if (v.getId() == R.id.preview_btn) {
String tag = (String) v.getTag();
Intent intent = new Intent(this, EmbeddedBook.class);
intent.putExtra("isbn", tag);
startActivity(intent);
//launch preview
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve result of scanning - instantiate ZXing object
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
//check we have a valid result
if (scanningResult != null) {
String scanContent = scanningResult.getContents();
//get format name of data scanned
String scanFormat = scanningResult.getFormatName();
previewBtn.setTag(scanContent);
if (scanContent != null && scanFormat != null && scanFormat.equalsIgnoreCase("EAN_13")) {
String bookSearchString = "https://www.googleapis.com/books/v1/volumes?" +
"q=isbn:" + scanContent + "&key=AIzaSyDminlOe8YitHijWd51n7-w2h8W1qb5PP0";
new GetBookInfo().execute(bookSearchString);
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"Not a valid scan!", Toast.LENGTH_SHORT);
toast.show();
}
Log.v("SCAN", "content: " + scanContent + " - format: " + scanFormat);
} else {
//invalid scan data or scan canceled
Toast toast = Toast.makeText(getApplicationContext(),
"No book scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
private class GetBookInfo extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... bookURLs) {
StringBuilder bookBuilder = new StringBuilder();
for (String bookSearchURL : bookURLs) {
HttpClient bookClient = new DefaultHttpClient();
try {
HttpGet bookGet = new HttpGet(bookSearchURL);
HttpResponse bookResponse = bookClient.execute(bookGet);
StatusLine bookSearchStatus = bookResponse.getStatusLine();
if (bookSearchStatus.getStatusCode() == 200) {
HttpEntity bookEntity = bookResponse.getEntity();
InputStream bookContent = bookEntity.getContent();
InputStreamReader bookInput = new InputStreamReader(bookContent);
BufferedReader bookReader = new BufferedReader(bookInput);
String lineIn;
while ((lineIn = bookReader.readLine()) != null) {
bookBuilder.append(lineIn);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return bookBuilder.toString();
}
protected void onPostExecute(String result) {
try {
previewBtn.setVisibility(View.VISIBLE);
JSONObject resultObject = new JSONObject(result);
JSONArray bookArray = resultObject.getJSONArray("items");
JSONObject bookObject = bookArray.getJSONObject(0);
JSONObject volumeObject = bookObject.getJSONObject("volumeInfo");
try {
titleText.setText(volumeObject.getString("title"));
} catch (JSONException jse) {
titleText.setText("");
jse.printStackTrace();
}
StringBuilder authorBuild = new StringBuilder("");
try {
JSONArray authorArray = volumeObject.getJSONArray("authors");
for (int a = 0; a < authorArray.length(); a++) {
if (a > 0) authorBuild.append(", ");
authorBuild.append(authorArray.getString(a));
}
authorText.setText(authorBuild.toString());
} catch (JSONException jse) {
authorText.setText("");
jse.printStackTrace();
}
try {
dateText.setText(volumeObject.getString("publishedDate"));
} catch (JSONException jse) {
dateText.setText("");
jse.printStackTrace();
}
try {
descriptionText.setText("DESCRIPTION: " + volumeObject.getString("description"));
} catch (JSONException jse) {
descriptionText.setText("");
jse.printStackTrace();
}
try {
double decNumStars = Double.parseDouble(volumeObject.getString("averageRating"));
int numStars = (int) decNumStars;
starLayout.setTag(numStars);
starLayout.removeAllViews();
for (int s = 0; s < numStars; s++) {
starViews[s].setImageResource(R.drawable.star);
starLayout.addView(starViews[s]);
}
} catch (JSONException jse) {
starLayout.removeAllViews();
jse.printStackTrace();
}
try {
ratingCountText.setText(volumeObject.getString("ratingsCount") + " ratings");
} catch (JSONException jse) {
ratingCountText.setText("");
jse.printStackTrace();
}
try {
boolean isEmbeddable = Boolean.parseBoolean
(bookObject.getJSONObject("accessInfo").getString("embeddable"));
if (isEmbeddable) previewBtn.setEnabled(true);
else previewBtn.setEnabled(false);
} catch (JSONException jse) {
previewBtn.setEnabled(false);
jse.printStackTrace();
}
try {
linkBtn.setTag(volumeObject.getString("infoLink"));
linkBtn.setVisibility(View.VISIBLE);
} catch (JSONException jse) {
linkBtn.setVisibility(View.GONE);
jse.printStackTrace();
}
try {
JSONObject imageInfo = volumeObject.getJSONObject("imageLinks");
new GetBookThumb().execute(imageInfo.getString("smallThumbnail"));
} catch (JSONException jse) {
thumbView.setImageBitmap(null);
jse.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
titleText.setText("NOT FOUND");
authorText.setText("");
descriptionText.setText("");
dateText.setText("");
starLayout.removeAllViews();
ratingCountText.setText("");
thumbView.setImageBitmap(null);
previewBtn.setVisibility(View.GONE);
shelfText.setText("");
}
}
}
private class GetBookThumb extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... thumbURLs) {
try {
URL thumbURL = new URL(thumbURLs[0]);
URLConnection thumbConn = thumbURL.openConnection();
thumbConn.connect();
InputStream thumbIn = thumbConn.getInputStream();
BufferedInputStream thumbBuff = new BufferedInputStream(thumbIn);
thumbImg = BitmapFactory.decodeStream(thumbBuff);
thumbBuff.close();
thumbIn.close();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
protected void onPostExecute(String result) {
thumbView.setImageBitmap(thumbImg);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void showMaps(View view) {
Intent intent = new Intent(this, MapsActivity.class);
startActivity(intent);
}
//HERE I SAVE THE RETRIEVED DATA
public void saveBook(View view) { //Click on save Book
String title = titleText.getText().toString();
String author = authorText.getText().toString();
String date = dateText.getText().toString();
String rating = ratingCountText.getText().toString();
String shelf = shelfText.getText().toString();
bookDBHelper = new BookDBHelper(context1);
sqLiteDatabase1 = bookDBHelper.getWritableDatabase();
bookDBHelper.addInformations(title, author, date, rating, shelf, sqLiteDatabase1);
Toast.makeText(getBaseContext(), "Data Saved", Toast.LENGTH_LONG).show();
bookDBHelper.close();
}
}
BookDBHelper.java
public class BookDBHelper extends SQLiteOpenHelper{
private static final String DATABASE_BOOKS_NAME = "BookINFO.DB";
private static final int DATABASE_BOOKS_VERS = 2;
private static final String CREATE_QUERY_BOOKS =
"CREATE TABLE "
+ BookContent.NewBookInfo.TABLE_NAME_BOOKS
+"("
+ BookContent.NewBookInfo.BOOK_ID + "INTEGER PRIMARY KEY, "
+ BookContent.NewBookInfo.BOOK_IMAGE +" BLOB, "
+ BookContent.NewBookInfo.BOOK_IMAGE_TAG +" TEXT, "
+ BookContent.NewBookInfo.BOOK_TITLE+" TEXT, "
+ BookContent.NewBookInfo.BOOK_AUTHOR+" TEXT, "
+ BookContent.NewBookInfo.BOOK_DATE+" TEXT, "
+ BookContent.NewBookInfo.BOOK_RATING+" TEXT, "
+ BookContent.NewBookInfo.BOOK_SHELF+" TEXT);";
public BookDBHelper(Context context){
super(context, DATABASE_BOOKS_NAME, null, DATABASE_BOOKS_VERS);
Log.e("DATABASE OPERATIONS", " DATABASE CREATED");
}
#Override
public void onCreate(SQLiteDatabase bookdb) {
bookdb.execSQL(CREATE_QUERY_BOOKS);
Log.e("DATABASE OPERATIONS", " DATABASE CREATED");
}
#Override
public void onUpgrade(SQLiteDatabase bookdb, int oldVersion, int newVersion) {
bookdb.execSQL(" DROP TABLE IS EXISTS " + BookContent.NewBookInfo.TABLE_NAME_BOOKS);
onCreate(bookdb);
}
public void addInformations( String booktitle, String bookauthor, String bookdate, String bookrating, String bookshelf, SQLiteDatabase bookdb)
{
ContentValues contentValues = new ContentValues();
contentValues.put(BookContent.NewBookInfo.BOOK_TITLE, booktitle);
contentValues.put(BookContent.NewBookInfo.BOOK_AUTHOR, bookauthor);
contentValues.put(BookContent.NewBookInfo.BOOK_DATE, bookdate);
contentValues.put(BookContent.NewBookInfo.BOOK_RATING, bookrating);
contentValues.put(BookContent.NewBookInfo.BOOK_SHELF, bookshelf);
bookdb.insert(BookContent.NewBookInfo.TABLE_NAME_BOOKS, null, contentValues);
Log.e("DATABASE OPERATIONS", "ON ROW INSERTED");
}
public Cursor getInformations(SQLiteDatabase bookdb){
Cursor cursor2;
String[] projections = {
BookContent.NewBookInfo.BOOK_TITLE,
BookContent.NewBookInfo.BOOK_AUTHOR,
BookContent.NewBookInfo.BOOK_DATE,
BookContent.NewBookInfo.BOOK_RATING,
BookContent.NewBookInfo.BOOK_SHELF};
cursor2 = bookdb.query(BookContent.NewBookInfo.TABLE_NAME_BOOKS, projections,null, null, null, null, null);
return cursor2;
}
Afterwards the infos will be displayed in a liestview.
BookDataListActivity
public class BookDataListActivity extends Activity {
public ListView booklistView;
private EditText inputSearch = null;
public SQLiteDatabase sqLiteDatabaseBooks = null;
public BookDBHelper bookDBHelper;
public Cursor cursor2;
public BookListDataAdapter bookListDataAdapter;
public final static String EXTRA_MSG1 = "title";
public final static String EXTRA_MSG2 = "author";
public final static String EXTRA_MSG3 = "date";
public final static String EXTRA_MSG4 = "rating";
public final static String EXTRA_MSG5 = "shelf";
public TextView editTextBooktitle;
public TextView editTextBookauthor;
public TextView editTextBookdate;
public TextView editTextBookrating;
public TextView editTextBookshelf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.book_data_list_layout);
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
TextView myTextView = (TextView) findViewById(R.id.text_yourbooks);
myTextView.setTypeface(myTypeface);
booklistView = (ListView) findViewById(R.id.book_list_view);
inputSearch = (EditText) findViewById(R.id.search_bar);
bookListDataAdapter = new BookListDataAdapter(getApplicationContext(), R.layout.row_book_layout);
booklistView.setAdapter(bookListDataAdapter);
//onItemClickListener
booklistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), BookInfoActivity.class);
editTextBooktitle = (TextView) view.findViewById(R.id.text_book_title);
String book_title = editTextBooktitle.getText().toString();
intent.putExtra(EXTRA_MSG1, book_title);
editTextBookauthor = (TextView) view.findViewById(R.id.text_book_author);
String bookauthor = editTextBookauthor.getText().toString();
intent.putExtra(EXTRA_MSG2, bookauthor);
editTextBookdate = (TextView) view.findViewById(R.id.text_book_date);
String bookdate = editTextBookdate.getText().toString();
intent.putExtra(EXTRA_MSG3, bookdate);
editTextBookrating = (TextView) view.findViewById(R.id.text_book_rating);
String bookrating = editTextBookrating.getText().toString();
intent.putExtra(EXTRA_MSG4, bookrating);
editTextBookshelf = (TextView) view.findViewById(R.id.text_book_shelf);
String bookshelf = editTextBookshelf.getText().toString();
intent.putExtra(EXTRA_MSG5, bookshelf);
startActivity(intent);
}
});
bookDBHelper = new BookDBHelper(getApplicationContext());
sqLiteDatabaseBooks = bookDBHelper.getReadableDatabase();
cursor2 = bookDBHelper.getInformations(sqLiteDatabaseBooks);
if (cursor2.moveToFirst()) {
do {
String booktitle, bookauthor, bookdate, bookrating, bookshelf;
booktitle = cursor2.getString(0);
bookauthor = cursor2.getString(1);
bookdate = cursor2.getString(2);
bookrating = cursor2.getString(3);
bookshelf = cursor2.getString(4);
BookDataProvider bookDataProvider = new BookDataProvider(booktitle, bookauthor, bookdate, bookrating, bookshelf);
bookListDataAdapter.add(bookDataProvider);
} while (cursor2.moveToNext());
}
}
}
And I think you will need the DataAdapter
DataListDataAdapter
public class BookListDataAdapter extends ArrayAdapter implements Filterable{
List booklist = new ArrayList();
public SQLiteDatabase sqLiteDatabaseBooks;
public BookListDataAdapter(Context context,int resource) {
super(context, resource);
}
static class BookLayoutHandler {
TextView BOOKTITLE, BOOKAUTHOR, BOOKDATE, BOOKRATING, BOOKSHELF;
}
#Override
public void add (Object object){
super.add(object);
booklist.add(object);
}
#Override
public int getCount() {
return booklist.size();
}
#Override
public Object getItem(int position) {
return booklist.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row1= convertView;
BookLayoutHandler bookLayoutHandler;
if(row1 == null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row1 = layoutInflater.inflate(R.layout.row_book_layout, parent, false);
bookLayoutHandler = new BookLayoutHandler();
bookLayoutHandler.BOOKTITLE = (TextView) row1.findViewById(R.id.text_book_title);
bookLayoutHandler.BOOKAUTHOR = (TextView) row1.findViewById(R.id.text_book_author);
bookLayoutHandler.BOOKDATE = (TextView) row1.findViewById(R.id.text_book_date);
bookLayoutHandler.BOOKRATING = (TextView) row1.findViewById(R.id.text_book_rating);
bookLayoutHandler.BOOKSHELF = (TextView) row1.findViewById(R.id.text_book_shelf);
row1.setTag(bookLayoutHandler);
}else{
bookLayoutHandler = (BookLayoutHandler) row1.getTag();
}
BookDataProvider bookDataProvider = (BookDataProvider) this.getItem(position);
bookLayoutHandler.BOOKTITLE.setText(bookDataProvider.getBooktitle());
bookLayoutHandler.BOOKAUTHOR.setText(bookDataProvider.getBookauthor());
bookLayoutHandler.BOOKDATE.setText(bookDataProvider.getBookdate());
bookLayoutHandler.BOOKRATING.setText(bookDataProvider.getBookrating());
bookLayoutHandler.BOOKSHELF.setText(bookDataProvider.getBookshelf());
return row1;
}
BookDataProvider:
public class BookDataProvider {
private Bitmap bookimage;
private String booktitle;
private String bookauthor;
private String bookdate;
private String bookrating;
private String bookshelf;
public Bitmap getBookimage() {
return bookimage;
}
public void setBookimage(Bitmap bookimage) {
this.bookimage = bookimage;
}
public String getBooktitle() {
return booktitle;
}
public void setBooktitle(String booktitle) {
this.booktitle = booktitle;
}
public String getBookauthor() {
return bookauthor;
}
public void setBookauthor(String bookauthor) {
this.bookauthor = bookauthor;
}
public String getBookdate() {
return bookdate;
}
public void setBookdate(String bookdate) {
this.bookdate = bookdate;
}
public String getBookrating() {
return bookrating;
}
public void setBookrating(String bookrating) {
this.bookrating = bookrating;
}
public String getBookshelf() {
return bookshelf;
}
public void setBookshelf(String bookshelf) {
this.bookshelf = bookshelf;
}
public BookDataProvider ( Bitmap bookimage, String booktitle, String bookauthor, String bookdate, String bookrating, String bookshelf)
{
this.bookimage = bookimage;
this.booktitle = booktitle;
this.bookauthor = bookauthor;
this.bookdate = bookdate;
this.bookrating = bookrating;
this.bookshelf = bookshelf;
}
}
BookContent
public class BookContent {
public static abstract class NewBookInfo{ //Tabllenspalten deklaration
public static final String BOOK_IMAGE = "book_image";
public static final String BOOK_IMAGE_TAG ="image_tag";
public static final String BOOK_TITLE = "book_title";
public static final String BOOK_AUTHOR = "book_author";
public static final String BOOK_DATE = "book_date";
public static final String BOOK_RATING = "book_rating";
public static final String BOOK_SHELF = "book_shelf";
public static final String TABLE_NAME_BOOKS = "book_info";
public static final String BOOK_ID = "_id";
}
}
If I get your question right, you need to convert your image to a blob.
Well, blob is a byte array, so the following code would help you to convert your Bitmap to a byte[]
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, thumbImg);
byte[] blob = stream.toByteArray();
You can also get the whole implementation from another question here:
how to store Image as blob in Sqlite & how to retrieve it?
EDIT:
Of course, you have to edit your BookDBHelper.addInformations function and add one additional parameter for your image:
public void addInformations( String booktitle, String bookauthor, String bookdate, String bookrating, String bookshelf, byte[] image, SQLiteDatabase bookdb)
{
ContentValues contentValues = new ContentValues();
contentValues.put(BookContent.NewBookInfo.BOOK_TITLE, booktitle);
contentValues.put(BookContent.NewBookInfo.BOOK_AUTHOR, bookauthor);
contentValues.put(BookContent.NewBookInfo.BOOK_DATE, bookdate);
contentValues.put(BookContent.NewBookInfo.BOOK_RATING, bookrating);
contentValues.put(BookContent.NewBookInfo.BOOK_SHELF, bookshelf);
contentValues.put(YOUR_IMAGE_CONSTANT, image);
bookdb.insert(BookContent.NewBookInfo.TABLE_NAME_BOOKS, null, contentValues);
Log.e("DATABASE OPERATIONS", "ON ROW INSERTED");
}
Now you can save your Book through ScanActivity.saveBook:
public void saveBook(View view) { //Click on save Book
// ...
BitmapDrawable bitmapDrawable = (BitmapDrawable) thumbView.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
byte[] blob = stream.toByteArray();
sqLiteDatabase1 = bookDBHelper.getWritableDatabase();
bookDBHelper.addInformations(title, author, date, rating, shelf, blob, sqLiteDatabase1);
Toast.makeText(getBaseContext(), "Data Saved", Toast.LENGTH_LONG).show();
bookDBHelper.close();
}

How to add search functionality in custom listview

I have a problem to add search function in a listview in my simple android app. I was followed this article [https://workspaces.codeproject.com/vatsag/customized-android-listview-with-image-and-text][1], but i can't figure how to add search functionality.
This is xparser.java:
public class XParser extends DefaultHandler {
ArrayList<String> idlist = new ArrayList<String>();
ArrayList<String> namalist = new ArrayList<String>();
ArrayList<String> menulist = new ArrayList<String>();
ArrayList<String> alamatlist = new ArrayList<String>();
ArrayList<String> iconlist = new ArrayList<String>();
//temp variable to store the data chunk read while parsing
private String tempStore = null;
public XParser() {
// TODO Auto-generated constructor stub
}
/*
* Clears the tempStore variable on every start of the element
* notification
*
* */
public void startElement (String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if (localName.equalsIgnoreCase("id")) {
tempStore = "";
} else if (localName.equalsIgnoreCase("nama")) {
tempStore = "";
}
else if (localName.equalsIgnoreCase("menu")) {
tempStore = "";
}
else if (localName.equalsIgnoreCase("alamat")) {
tempStore = "";
}
else if (localName.equalsIgnoreCase("icon")) {
tempStore = "";
}
else {
tempStore = "";
}
}
/*
* updates the value of the tempStore variable into
* corresponding list on receiving end of the element
* notification
* */
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
if (localName.equalsIgnoreCase("id")) {
idlist.add(tempStore);
}
else if (localName.equalsIgnoreCase("nama")) {
namalist.add(tempStore);
}
else if (localName.equalsIgnoreCase("menu")) {
menulist.add(tempStore);
}
else if (localName.equalsIgnoreCase("alamat")) {
alamatlist.add(tempStore);
}
else if (localName.equalsIgnoreCase("icon")) {
iconlist.add(tempStore);
}
tempStore = "";
}
/*
* adds the incoming data chunk of character data to the
* temp data variable - tempStore
*
* */
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
tempStore += new String(ch, start, length);
}
}
This is BinderData.java
public class BinderData extends BaseAdapter {
// XML node keys
static final String KEY_TAG = "rmdata"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAMA = "nama";
static final String KEY_MENU = "menu";
static final String KEY_ALAMAT = "alamat";
static final String KEY_ICON = "icon";
LayoutInflater inflater;
ImageView thumb_image;
List<HashMap<String,String>> rmDataCollection;
ViewHolder holder;
public BinderData() {
// TODO Auto-generated constructor stub
}
public BinderData(Activity act, List<HashMap<String,String>> map) {
this.rmDataCollection = map;
inflater = (LayoutInflater) act
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
// TODO Auto-generated method stub
return idlist.size();
return rmDataCollection.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null){
vi = inflater.inflate(R.layout.list_row, null);
holder = new ViewHolder();
holder.tvNama = (TextView)vi.findViewById(R.id.tvNama); // city name
holder.tvMenu = (TextView)vi.findViewById(R.id.tvMenu); // city weather overview
holder.tvRMImage =(ImageView)vi.findViewById(R.id.list_image); // thumb image
vi.setTag(holder);
}
else{
holder = (ViewHolder)vi.getTag();
}
// Setting all values in listview
holder.tvNama.setText(rmDataCollection.get(position).get(KEY_NAMA));
holder.tvMenu.setText(rmDataCollection.get(position).get(KEY_MENU));
//Setting an image
String uri = "drawable/"+ rmDataCollection.get(position).get(KEY_ICON);
int imageResource = vi.getContext().getApplicationContext().getResources().getIdentifier(uri, null, vi.getContext().getApplicationContext().getPackageName());
Drawable image = vi.getContext().getResources().getDrawable(imageResource);
holder.tvRMImage.setImageDrawable(image);
return vi;
}
/*
*
* */
static class ViewHolder{
TextView tvNama;
TextView tvMenu;
ImageView tvRMImage;
}
}
This is WeatherActiviy.java:
public class WeatherActivity extends Activity implements OnQueryTextListener {
// XML node keys
static final String KEY_TAG = "rmdata"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAMA = "nama";
static final String KEY_MENU = "menu";
static final String KEY_ALAMAT = "alamat";
static final String KEY_ICON = "icon";
// List items
ListView list;
EditText inputSearch;
BinderData adapter = null;
List<HashMap<String,String>> rmDataCollection;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (getAssets().open("weatherdata.xml"));
rmDataCollection = new ArrayList<HashMap<String,String>>();
// normalize text representation
doc.getDocumentElement ().normalize ();
NodeList weatherList = doc.getElementsByTagName("rmdata");
HashMap<String,String> map = null;
for (int i = 0; i < weatherList.getLength(); i++) {
map = new HashMap<String,String>();
Node firstWeatherNode = weatherList.item(i);
if(firstWeatherNode.getNodeType() == Node.ELEMENT_NODE){
Element firstWeatherElement = (Element)firstWeatherNode;
//-------
NodeList idList = firstWeatherElement.getElementsByTagName(KEY_ID);
Element firstIdElement = (Element)idList.item(0);
NodeList textIdList = firstIdElement.getChildNodes();
//--id
map.put(KEY_ID, ((Node)textIdList.item(0)).getNodeValue().trim());
//2.-------
NodeList cityList = firstWeatherElement.getElementsByTagName(KEY_NAMA);
Element firstCityElement = (Element)cityList.item(0);
NodeList textCityList = firstCityElement.getChildNodes();
//--city
map.put(KEY_NAMA, ((Node)textCityList.item(0)).getNodeValue().trim());
//3.-------
NodeList tempList = firstWeatherElement.getElementsByTagName(KEY_MENU);
Element firstTempElement = (Element)tempList.item(0);
NodeList textTempList = firstTempElement.getChildNodes();
//--city
map.put(KEY_MENU, ((Node)textTempList.item(0)).getNodeValue().trim());
/*
//4.-------
NodeList condList = firstWeatherElement.getElementsByTagName(KEY_ALAMAT);
Element firstCondElement = (Element)condList.item(0);
NodeList textCondList = firstCondElement.getChildNodes();
//--city
map.put(KEY_ALAMAT, ((Node)textCondList.item(0)).getNodeValue().trim());
//5.-------
NodeList speedList = firstWeatherElement.getElementsByTagName(KEY_SPEED);
Element firstSpeedElement = (Element)speedList.item(0);
NodeList textSpeedList = firstSpeedElement.getChildNodes();
//--city
map.put(KEY_SPEED, ((Node)textSpeedList.item(0)).getNodeValue().trim());
*/
//6.-------
NodeList iconList = firstWeatherElement.getElementsByTagName(KEY_ICON);
Element firstIconElement = (Element)iconList.item(0);
NodeList textIconList = firstIconElement.getChildNodes();
//--city
map.put(KEY_ICON, ((Node)textIconList.item(0)).getNodeValue().trim());
//Add to the Arraylist
rmDataCollection.add(map);
}
}
BinderData bindingData = new BinderData(this,rmDataCollection);
list = (ListView) findViewById(R.id.list);
Log.i("BEFORE", "<<------------- Before SetAdapter-------------->>");
list.setAdapter(bindingData);
Log.i("AFTER", "<<------------- After SetAdapter-------------->>");
list.setTextFilterEnabled(true);
// search
inputSearch = (EditText) findViewById (R.id.inputSearch);
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
((Filterable) WeatherActivity.this.rmDataCollection).getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = inputSearch.getText().toString().toLowerCase(Locale.getDefault());
}
});
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent();
i.setClass(WeatherActivity.this, SampleActivity.class);
// parameters
i.putExtra("position", String.valueOf(position + 1));
/* selected item parameters
* 1. City name
* 2. Weather
* 3. Wind speed
* 4. Temperature
* 5. Weather icon
*/
i.putExtra("city", rmDataCollection.get(position).get(KEY_NAMA));
i.putExtra("weather", rmDataCollection.get(position).get(KEY_MENU));
i.putExtra("windspeed", rmDataCollection.get(position).get(KEY_ALAMAT));
i.putExtra("icon", rmDataCollection.get(position).get(KEY_ICON));
// start the sample activity
startActivity(i);
}
});
}
catch (IOException ex) {
Log.e("Error", ex.getMessage());
}
catch (Exception ex) {
Log.e("Error", "Loading exception");
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#SuppressLint("NewApi")
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
searchView.setSubmitButtonEnabled(true);
searchView.setOnQueryTextListener(this);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onQueryTextChange(String newText)
{
// this is your adapter that will be filtered
if (TextUtils.isEmpty(newText))
{
list.clearTextFilter();
}
else
{
list.setFilterText(newText.toString());
}
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
}

Insert new data in Custom Adapter and update list

I have an list with an custom adapter, and upon refresh I want to add new data to be displayed(if any available).
But the list isn't being update. I tried all the methods with notifyDataSetChanged for the adapter but it's not updated.
Please help. I lost so much time with this and I feel like I'm loosing my mind with this one.
Here is the code:
NewsFeedArrayAdapter
public class NewsFeedArrayAdapter extends ArrayAdapter<FeedItem> {
private final String TAG_DEBUG = this.getClass().getName();
private LayoutInflater inflator;
public final static String PREFS_NAME = "shared_pref_eid";
ImageLoader imageLoader;
Utils utils;
public NewsFeedArrayAdapter(Activity context) {
super(context, R.layout.feed_story_content);
this.utils = new Utils(context);
inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = ImageLoader.getInstance(context);
}
/**
* Static Inner class.
*
* Makes the ListView more efficient since Android recycles views in a ListView.
*/
public static class ViewHolder {
public ImageView profilePicture, image;
public TextView author, timePast, message, likes, comments;
public LinearLayout like, comment, share, likesCommentsCounter;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = null;
FeedItem feedItem = FeedItemParser.FEEDS.get(position);
ViewHolder holder = null;
if (convertView == null) {
rowView = inflator.inflate(R.layout.feed_story_content, parent, false);
holder = new ViewHolder();
holder.profilePicture = (ImageView) rowView.findViewById(R.id.feed_story_profile_picture);
holder.author = (TextView) rowView.findViewById(R.id.feed_story_author);
holder.timePast = (TextView) rowView.findViewById(R.id.feed_story_time_past);
holder.message = (TextView) rowView.findViewById(R.id.feed_story_message);
holder.image = (ImageView) rowView.findViewById(R.id.feed_story_image);
holder.like = (LinearLayout) rowView.findViewById(R.id.feed_feedback_like_container);
holder.comment = (LinearLayout) rowView.findViewById(R.id.feed_feedback_comment_container);
holder.share = (LinearLayout) rowView.findViewById(R.id.feed_feedback_share_container);
holder.likes = (TextView) rowView.findViewById(R.id.feed_story_likes);
holder.comments = (TextView) rowView.findViewById(R.id.feed_story_comments);
rowView.setTag(holder);
} else {
rowView = convertView;
holder = ((ViewHolder) rowView.getTag());
}
Log.i(TAG_DEBUG, "feedItem = " + feedItem);
if (feedItem != null) {
if (!TextUtils.isEmpty(feedItem.feed_story_from_name)) {
holder.author.setText(feedItem.feed_story_from_name);
} else {
holder.author.setText("Unknown");
}
if (!TextUtils.isEmpty(feedItem.feed_story_created_time)) {
// Convert the date to calendar date
Calendar calendarDate = null;
try {
calendarDate = ISO8601.toCalendar(feedItem.feed_story_created_time);
} catch (ParseException e) {
e.printStackTrace();
}
CharSequence relativeTimeSpan = DateUtils.getRelativeTimeSpanString(
calendarDate.getTimeInMillis(),
System.currentTimeMillis(),
DateUtils.SECOND_IN_MILLIS);
holder.timePast.setText(relativeTimeSpan);
} else {
holder.timePast.setText("Unknown");
}
Log.i(TAG_DEBUG, "feedItem.feed_story_message = " + feedItem.feed_story_message);
if (!TextUtils.isEmpty(feedItem.feed_story_message)) {
holder.message.setText(feedItem.feed_story_message);
} else {
holder.message.setText("Unkown");
// holder.message.setVisibility(View.GONE);
}
// Display the icon of the feed
int defaultResourceIcon = R.drawable.no_avatar;
if (feedItem.feed_story_from_id != null) {
String iconUrl = "https://graph.facebook.com/" + feedItem.feed_story_from_id + "/picture?type=normal";
if (Session.getActiveSession() != null &&
Session.getActiveSession().getAccessToken() != null) {
iconUrl += "&access_token=" + Session.getActiveSession().getAccessToken();
}
Log.i(TAG_DEBUG, "iconUrl = " + iconUrl);
imageLoader.displayImage(iconUrl, holder.profilePicture, 70, defaultResourceIcon);
} else {
imageLoader.cancelDisplayTaskFor(holder.profilePicture);
holder.profilePicture.setImageResource(defaultResourceIcon);
}
// Display the picture of the feed
int defaultResourcePicture = R.drawable.empty;
if (!TextUtils.isEmpty(feedItem.feed_story_picture)) {
holder.image.setVisibility(View.VISIBLE);
Log.i(TAG_DEBUG, "feed_picture = " + feedItem.feed_story_picture + "\nfeed_picture_height = " + feedItem.feed_story_picture_height);
imageLoader.displayImage(feedItem.feed_story_picture, holder.image, -1, defaultResourcePicture);
} else {
imageLoader.cancelDisplayTaskFor(holder.image);
// holder.image.setImageResource(defaultResourcePicture);
holder.image.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(feedItem.feed_story_likes)) {
holder.likes.setVisibility(View.VISIBLE);
String likes = feedItem.feed_story_likes + " like";
if (!feedItem.feed_story_likes.contentEquals("1")) {
likes += "s";
}
holder.likes.setText(likes);
} else {
holder.likes.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(feedItem.feed_story_comments)) {
holder.comments.setVisibility(View.VISIBLE);
String comments = feedItem.feed_story_comments + " comment";
if (!feedItem.feed_story_comments.contentEquals("1")) {
comments += "s";
}
holder.comments.setText(comments);
} else {
holder.comments.setVisibility(View.GONE);
}
holder.like.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
utils.customToast("Like content - TBA");
}
});
holder.comment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
utils.customToast("Comment section - TBA");
}
});
holder.share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
utils.customToast("Sharing content - TBA");
}
});
}
return rowView;
}
#Override
public int getCount() {
return FeedItemParser.FEEDS.size();
}
}
The adapter on the list is set after the first request, when I get my first results, like this:
ListView actualListView = mPullRefreshListView.getRefreshableView();
// Need to use the Actual ListView when registering for Context Menu
registerForContextMenu(actualListView);
// Sort the list before displaying
Collections.sort(FeedItemParser.FEEDS, Comparators.CREATED_TIME);
// Set the custom adapter
customAddapter = new NewsFeedArrayAdapter(activity);
// Populate the fragment with the data from JSON
actualListView.setAdapter(customAddapter);
FeedItemParser is an custom class where I store my custom objects:
public class FeedItemParser {
// JSON Node names
public static final String
TAG_DATA = "data", // Array
TAG_ID = "id", // String
TAG_FROM = "from", // Object
TAG_FROM_ID = "id", // String
TAG_FROM_CATEGORY = "category", // String
TAG_FROM_NAME = "name", // String
TAG_TO = "to", // Object
TAG_TO_DATA = "data", // Array
TAG_TO_DATA_ID = "id", // String
TAG_TO_DATA_NAME = "name", // String
TAG_MESSAGE = "message", // String
TAG_PICTURE = "picture", // String
TAG_ACTIONS = "actions", // Array
TAG_ACTIONS_NAME = "name", // String
TAG_ACTIONS_LINK = "link", // String
TAG_PRIVACY = "privacy", // Object
TAG_PRIVACY_VALUE = "value", // String
TAG_TYPE = "type", // String
TAG_STATUS_TYPE = "status_type", // String
TAG_CREATED_TIME = "created_time", // String
TAG_UPDATED_TIME = "updated_time", // String
TAG_LIKES = "likes", // Object
TAG_LIKES_COUNT = "count", // String
TAG_COMMENTS = "comments", // Object
TAG_COMMENTS_DATA = "data", // Array
TAG_PAGING = "paging", // Object
TAG_PAGING_PREVIOUS = "previous",// String
TAG_PAGING_NEXT = "next"; // String
/**
* An array of Shelter items.
*/
public static List<FeedItem> FEEDS = new ArrayList<FeedItem>();
/**
* A map of Array items, by ID.
*/
public static Map<String, FeedItem> FEED_MAP = new HashMap<String, FeedItem>();
public static void addItem(FeedItem item) {
FEEDS.add(FEEDS.size(), item);
FEED_MAP.put(item.feed_story_id, item);
}
public static void addPicture (String feed_story_id, String picture, String height) {
FeedItem feedItem = FEED_MAP.get(feed_story_id);
feedItem.feed_story_picture = picture;
feedItem.feed_story_picture_height = height;
}
public static class FeedItem {
public String feed_story_id, feed_story_from_id, feed_story_from_category,
feed_story_from_name, feed_story_message, feed_story_picture, feed_story_picture_height,
feed_story_privacy, feed_story_type, feed_story_status_type, feed_story_created_time,
feed_story_updated_time, feed_story_likes, feed_story_comments;
/**
* #param feed_story_id
* #param feed_story_from_id
* #param feed_story_from_category
* #param feed_story_from_name
* #param feed_story_message
* #param feed_story_picture
* #param feed_story_privacy
* #param feed_story_type
* #param feed_story_status_type
* #param feed_story_created_time
* #param feed_story_updated_time
*/
public FeedItem(String feed_story_id, String feed_story_from_id, String feed_story_from_category,
String feed_story_from_name, String feed_story_message, String feed_story_picture,
String feed_story_picture_height, String feed_story_privacy, String feed_story_type,
String feed_story_status_type, String feed_story_created_time, String feed_story_updated_time,
String feed_story_likes, String feed_story_comments) {
this.feed_story_id = feed_story_id;
this.feed_story_from_id = feed_story_from_id;
this.feed_story_from_category = feed_story_from_category;
this.feed_story_from_name = feed_story_from_name;
this.feed_story_message = feed_story_message;
this.feed_story_picture = feed_story_picture;
this.feed_story_picture_height = feed_story_picture_height;
this.feed_story_privacy = feed_story_privacy;
this.feed_story_type = feed_story_type;
this.feed_story_status_type = feed_story_status_type;
this.feed_story_created_time = feed_story_created_time;
this.feed_story_updated_time = feed_story_updated_time;
this.feed_story_likes = feed_story_likes;
this.feed_story_comments = feed_story_comments;
}
#Override
public String toString() {
return feed_story_message;
}
}
}
When I request new data(refresh), I add the new data in my object (the same way I do the first time):
FeedItemParser.addItem(new FeedItem(
id,
from_id,
from_category,
from_name,
message,
null, // Will be gotten through another request
null,
privacy_value,
type,
status_type,
created_time,
updated_time,
likes,
comments));
After that I call
ListView actualListView = mPullRefreshListView.getRefreshableView();
// Need to use the Actual ListView when registering for Context Menu
registerForContextMenu(actualListView);
// Sort the list before displaying
Collections.sort(FeedItemParser.FEEDS, Comparators.CREATED_TIME);
// Notify list adapter to update the list
customAddapter.notifyDataSetChanged();
SOLUTION
Based on the recommendations of #Selvin I have managed to update my list after adding more data. Basically I changed my adapter(I'm not using an filtered list anymore, but I'm directly using my custom objects). And after I add new Object, I update the list by calling notifyDataSetChanged() on the existing adapter.
I have also update my code, maybe it will help someone else that is stuck is this situation.
Thanks again #Selvin.

Getting only the last item data from hashmap arraylist

I have parsed json data in which there is a main json array and it contains sub json array. But the main json array not containing the sub json array in every item. So i have parsed all the data accroding to it. and i am getting perfect data from it. But the problem is that the main json array data is displaying in listview and after click on list view item the sub json array is display accroding to main json array item but its only get the last element of sub json array from hash map array list. So i can't get proper way to display so please find out some standard solution.
Here is My Code
public class MainCategories extends Fragment {
WebserviceClass wservice = new WebserviceClass();
Context c;
View v;
String data = "";
String User_id, countryid;
JSONObject jobj;
JSONArray datas;
int currentpage = 1;
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
// testAdapter adapter
ArrayList<Allcategories> listing = new ArrayList<Allcategories>();;
public static ArrayList<subCateData> subList = new ArrayList<subCateData>();
int limit = 3, id;
Button bt1, bt2, bt3;
String img, img1;
String name, count;
String subname, subcount, subCategoryId;
View fragmentview;
ListView lv1, lv2, lv3;
JSONObject ca;
MainTest test;
String url, main, subnameData, subCountData, subID, cateGoryID;
LinearLayout ll;
ProgressDialog pDialog;
HashMap<String, String> map;
JSONArray dataa;
// SimpleAdapter adp;
Button b1, b2, b3;
public MainCategories(Context mainActivity, int id) {
// TODO Auto-generated constructor stub
this.c = mainActivity;
this.id = id;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
SharedPreferences sp = c.getSharedPreferences("key", 0);
User_id = sp.getString("userid=", User_id);
countryid = sp.getString("countryid", countryid);
v = inflater.inflate(R.layout.categories_tab, container, false);
lv2 = (ListView) v.findViewById(android.R.id.list);
if (FirstTab.adp == null) {
new CategoryTest().execute();
} else {
lv2.setAdapter(FirstTab.adp);
}
lv2.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
for (int i = 0; i < subList.size(); i++) {
subID = subList.get(i).getsubcatId();
subnameData = subList.get(i).getsubcatname();
subCountData = subList.get(i).getsubcatcount();
Log.v("ALLDATA", subnameData + "/" + "/" + "/"
+ subCountData);
}
String catid = listing.get(position).getCategoryid();
int mycatID = Integer.parseInt(catid);
Log.v("CAtegory ID", mycatID + "");
addfragment(new CategoriesListClick(c, subID, mycatID,
subnameData, subCountData, position), true,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
});
return v;
}
public class CategoryTest extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
url = String.format(Common.view_main_category + "country_id=%s",
countryid);
Log.v("CateGory URL:", url);
jobj = wservice.getjson(url);
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
JSONObject jdata = jobj.getJSONObject("data");
datas = jdata.getJSONArray("allcategories");
for (int i = 0; i < datas.length(); i++) {
Log.e("length", "" + datas.length());
ca = datas.getJSONObject(i);
cateGoryID = ca.getString("categoryid");
name = ca.getString("categoryname");
count = ca.getString("categorystorecount");
// map = new HashMap<String, String>();
// map.put("categoryname", name);
// map.put("categorystorecount", "(" + count + ")");
// String countc=c.getString("categoryid");
Log.e(name, count);
if (ca.has("subcategories")) {
dataa = ca.getJSONArray("subcategories");
for (int j = 0; j < dataa.length(); j++) {
JSONObject d = dataa.getJSONObject(j);
// subList = new ArrayList<subCateData>();
subCategoryId = d.getString("subcategoryid");
subname = d.getString("subcategoryname");
subcount = d.getString("subcategorystorecount");
// map.put("subcategoryid", subCategoryId);
// map.put("subcategoryname", subname);
// map.put("subcategorystorecount", "(" + subcount
// + ")");
subList.add(new subCateData(subCategoryId, subname,
subcount));
/*
* Log.v("This is Data for Sub:",
* map.get("subcategoryname").toString());
*/
}
} else {
System.out.println("JSONArray is null");
}
listing.add(new Allcategories(cateGoryID, name, count));
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.v("Size", listing.size() + "");
FirstTab.adp = new MyCustom(c, listing);
lv2.setAdapter(FirstTab.adp);
}
}
void addfragment(Fragment fragment, boolean addBacktoStack, int transition) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.simple_fragment, fragment);
ft.setTransition(transition);
if (addBacktoStack)
ft.addToBackStack(null);
ft.commit();
}
class MyCustom extends BaseAdapter {
Context Mcontext;
ArrayList<Allcategories> thisCatList;
LayoutInflater inflater;
public MyCustom(Context c, ArrayList<Allcategories> listing) {
// TODO Auto-generated constructor stub
this.Mcontext = c;
this.thisCatList = listing;
inflater = LayoutInflater.from(Mcontext);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return thisCatList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int position, View v, ViewGroup parent) {
if (v == null) {
v = inflater.inflate(R.layout.list_categories, parent, false);
TextView catName = (TextView) v.findViewById(R.id.txtcname);
TextView catCount = (TextView) v.findViewById(R.id.txtccount);
catName.setText(thisCatList.get(position).getCategoryname());
catCount.setText("(" + ""
+ thisCatList.get(position).getCategorystorecount()
+ "" + ")");
Log.v("CatCount", catCount.getText().toString());
}
// TODO Auto-generated method stub
return v;
}
}
class AllCategories Data:
public class Allcategories {
private String arabicname;
private String categoryid;
private String categoryname;
private String categorystorecount;
private String fatherid;
private String order;
private String status;
// private List subcategories;
public Allcategories(String name, String count) {
// TODO Auto-generated constructor stub
this.categoryname = name;
this.categorystorecount = count;
}
public String getCategoryname() {
return this.categoryname;
}
public void setCategoryname(String categoryname) {
this.categoryname = categoryname;
}
public String getCategorystorecount() {
return this.categorystorecount;
}
public void setCategorystorecount(String categorystorecount) {
this.categorystorecount = categorystorecount;
}
SubCategory Data Class:
public class subCateData {
String subcatId, subcategoryname, subcategorystorecount;
public subCateData(String id, String name, String count) {
// TODO Auto-generated constructor stub
this.subcatId = id;
this.subcategoryname = name;
this.subcategorystorecount = count;
}
public String getsubcatId() {
return this.subcatId;
}
public void setsubcatId(String subID) {
this.subcatId = subID;
}
public String getsubcatname() {
return this.subcategoryname;
}
public void setsubcatname(String name) {
this.subcategoryname = name;
}
public String getsubcatcount() {
return this.subcategorystorecount;
}
public void setsubcatcount(String count) {
this.subcategorystorecount = count;
}
This is My Json parsing URL:
http://www.sevenstarinfotech.com/projects/demo/okaz/API/view_categories.php?country_id=4
Stack Trace:
06-27 12:23:34.361: V/ALLDATA(8533): High School///0
06-27 12:24:02.001: I/Adreno200-EGLSUB(8533): <ConfigWindowMatch:2218>: Format RGBA_8888.
06-27 12:24:02.011: D/memalloc(8533): /dev/pmem: Mapped buffer base:0x53153000 size:1536000 offset:0 fd:74
06-27 12:24:02.041: D/memalloc(8533): /dev/pmem: Mapped buffer base:0x54048000 size:15683584 offset:14147584 fd:80
06-27 12:24:02.091: D/OpenGLRenderer(8533): Flushing caches (mode 0)
06-27 12:24:02.111: D/memalloc(8533): /dev/pmem: Unmapping buffer base:0x51b26000 size:3072000 offset:1536000
06-27 12:24:02.121: D/memalloc(8533): /dev/pmem: Unmapping buffer base:0x552a2000 size:9093120 offset:7557120
06-27 12:24:02.121: D/memalloc(8533): /dev/pmem: Unmapping buffer base:0x55b4e000 size:17219584 offset:15683584
06-27 12:24:03.081: D/CLIPBOARD(8533): Hide Clipboard dialog at Starting input: finished by someone else... !
06-27 12:24:03.141: D/OpenGLRenderer(8533): Flushing caches (mode 0)
06-27 12:24:03.141: D/memalloc(8533): /dev/pmem: Unmapping buffer base:0x53153000 size:1536000 offset:0
06-27 12:24:03.141: D/memalloc(8533): /dev/pmem: Unmapping buffer base:0x54048000 size:15683584 offset:14147584
06-27 12:24:03.441: D/OpenGLRenderer(8533): Flushing caches (mode 2)
you should have to put new HashMap inside your current HasHMap so you can get subcategories items for particular index.
see this for how to use nested HashMap? and use it in subcategories loop.
i am using ArrayList of getter setter class to bind the data. so if you can convert your code into arraylist and edit the question that will be a great..
and see below code
import java.util.ArrayList;
public class MainCategories extends Fragment {
WebserviceClass wservice = new WebserviceClass();
Context c;
View v;
String data = "";
String User_id, countryid;
JSONObject jobj;
JSONArray datas;
int currentpage = 1;
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
// testAdapter adapter
ArrayList<Allcategories> listing = new ArrayList<Allcategories>();;
public static ArrayList<subCateData> subList = new ArrayList<subCateData>();
int limit = 3, id;
Button bt1, bt2, bt3;
String img, img1;
String name, count;
String subname, subcount, subCategoryId;
View fragmentview;
ListView lv1, lv2, lv3;
JSONObject ca;
MainTest test;
String url, main, subnameData, subCountData, subID, cateGoryID;
LinearLayout ll;
ProgressDialog pDialog;
HashMap<String, String> map;
JSONArray dataa;
// SimpleAdapter adp;
Button b1, b2, b3;
/// sanket
ArrayList<Allcategories> list = new ArrayList<Allcategories>();
public MainCategories(Context mainActivity, int id) {
// TODO Auto-generated constructor stub
this.c = mainActivity;
this.id = id;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
SharedPreferences sp = c.getSharedPreferences("key", 0);
User_id = sp.getString("userid=", User_id);
countryid = sp.getString("countryid", countryid);
v = inflater.inflate(R.layout.categories_tab, container, false);
lv2 = (ListView) v.findViewById(android.R.id.list);
if (FirstTab.adp == null) {
new CategoryTest().execute();
} else {
lv2.setAdapter(FirstTab.adp);
}
lv2.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
for (int i = 0; i < subList.size(); i++) {
subID = list.get(position).get(i).getList().getsubcatId();
subnameData = list.get(position).get(i).getList().getsubcatname();
subCountData = list.get(position).get(i).getList().getsubcatcount();
Log.v("ALLDATA", subnameData + "/" + "/" + "/"
+ subCountData);
}
String catid = listing.get(position).getCategoryid();
int mycatID = Integer.parseInt(catid);
Log.v("CAtegory ID", mycatID + "");
addfragment(new CategoriesListClick(c, subID, mycatID,
subnameData, subCountData, position), true,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
});
return v;
}
public class CategoryTest extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
url = String.format(Common.view_main_category + "country_id=%s",
countryid);
Log.v("CateGory URL:", url);
jobj = wservice.getjson(url);
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
JSONObject jdata = jobj.getJSONObject("data");
datas = jdata.getJSONArray("allcategories");
for (int i = 0; i < datas.length(); i++) {
// sanket
Allcategories binAll = new Allcategories();
Log.e("length", "" + datas.length());
ca = datas.getJSONObject(i);
cateGoryID = ca.getString("categoryid");
name = ca.getString("categoryname");
count = ca.getString("categorystorecount");
// map = new HashMap<String, String>();
// map.put("categoryname", name);
// map.put("categorystorecount", "(" + count + ")");
// String countc=c.getString("categoryid");
//sanket
binAll.setcategoryid(cateGoryID);
binAll.setcategoryname(name);
binAll.setcategorystorecount(count);
Log.e(name, count);
if (ca.has("subcategories")) {
dataa = ca.getJSONArray("subcategories");
for (int j = 0; j < dataa.length(); j++) {
JSONObject d = dataa.getJSONObject(j);
// subList = new ArrayList<subCateData>();
subCategoryId = d.getString("subcategoryid");
subname = d.getString("subcategoryname");
subcount = d.getString("subcategorystorecount");
// map.put("subcategoryid", subCategoryId);
// map.put("subcategoryname", subname);
// map.put("subcategorystorecount", "(" + subcount
// + ")");
//// sanket
ArrayList<subCateData> sublist = new ArrayList<subCateData>();
subCateData binSub = new subCateData();
binSub.setsubcatId(subCategoryId);
binSub.setsubcatname(subname);
binSub.setsubcatcount(subcount);
subList.add(new subCateData(subCategoryId, subname,
subcount));
/*
* Log.v("This is Data for Sub:",
* map.get("subcategoryname").toString());
*/
sublist.add(binSub);
}
/// sanket note : make arraylist of subdata in Allcategories class and generate getter and settter
binAll.setList(sublist);
} else {
System.out.println("JSONArray is null");
}
listing.add(new Allcategories(cateGoryID, name, count));
list.add(binAll);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.v("Size", listing.size() + "");
FirstTab.adp = new MyCustom(c, listing);
lv2.setAdapter(FirstTab.adp);
}
}
void addfragment(Fragment fragment, boolean addBacktoStack, int transition) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.simple_fragment, fragment);
ft.setTransition(transition);
if (addBacktoStack)
ft.addToBackStack(null);
ft.commit();
}
class MyCustom extends BaseAdapter {
Context Mcontext;
ArrayList<Allcategories> thisCatList;
LayoutInflater inflater;
public MyCustom(Context c, ArrayList<Allcategories> listing) {
// TODO Auto-generated constructor stub
this.Mcontext = c;
this.thisCatList = listing;
inflater = LayoutInflater.from(Mcontext);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return thisCatList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int position, View v, ViewGroup parent) {
if (v == null) {
v = inflater.inflate(R.layout.list_categories, parent, false);
TextView catName = (TextView) v.findViewById(R.id.txtcname);
TextView catCount = (TextView) v.findViewById(R.id.txtccount);
catName.setText(thisCatList.get(position).getCategoryname());
catCount.setText("(" + ""
+ thisCatList.get(position).getCategorystorecount()
+ "" + ")");
Log.v("CatCount", catCount.getText().toString());
}
// TODO Auto-generated method stub
return v;
}
}

Categories

Resources