I have lots of questions that I didn't find answers to.
First of all, I have two tables in MS Sql server, one is called country that contains country id and country name, and one is called family which contains country id, family id, family name and family info. The problem I am facing is how can I write a query in Java Android that gets the id of the country and compare it with the id of the country in the families table and then for each country there is its own family.
I have tried inner joins but couldn't know how to do it.
Here is my code so far:
public class InsideCountries extends AppCompatActivity {
private ArrayList<ClassListItems> itemArrayList; //List items Array
private MyAppAdapter myAppAdapter; //Array Adapter
private ListView listView;
private TextView ttl;// Listview
private boolean success = false; // boolean
private ConnectionClass connectionClass; //Connection Class Variable
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inside_countries);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
ttl = (TextView) findViewById(R.id.title) ;
ttl.setText(getIntent().getStringExtra("CountriesName"));
listView = (ListView) findViewById(R.id.listvieww); //Listview Declaration
connectionClass = new ConnectionClass(); // Connection Class Initialization
itemArrayList = new ArrayList<ClassListItems>(); // Arraylist Initialization
// Calling Async Task
SyncData orderData = new SyncData();
orderData.execute("");
}
// Async Task has three overrided methods,
private class SyncData extends AsyncTask<String, String, String> {
String msg = "No Data Found";
ProgressDialog progress;
#Override
protected void onPreExecute() //Starts the progress dailog
{
progress = ProgressDialog.show(InsideCountries.this, "Synchronising",
"Please Wait...", true);
}
#Override
protected String doInBackground(String... strings) // Connect to the database, write query and add items to array list
{
try {
Connection conn = connectionClass.CONN(); //Connection Object
if (conn == null) {
msg = "Please Check Your Connection";
success = false;
} else {
// Change below query according to your own database.
String query = "query here";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) // if resultset not null, I add items to itemArraylist using class created
{
while (rs.next()) {
try {
itemArrayList.add(new ClassListItems(rs.getString("name")));
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch(Exception e)
{
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
success = false;
}
return msg;
}
#Override
protected void onPostExecute (String
msg) // disimissing progress dialoge, showing error and setting up my listview
{
progress.dismiss();
Toast.makeText(InsideCountries.this, msg + "", Toast.LENGTH_LONG).show();
if (success == false) {
} else {
try {
myAppAdapter = new MyAppAdapter(itemArrayList, InsideCountries.this);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(myAppAdapter);
} catch (Exception ex) {
}
}
}
}
public class MyAppAdapter extends BaseAdapter //has a class viewholder which holds
{
public class ViewHolder
{
TextView textName;
}
public List<ClassListItems> parkingList;
public Context context;
ArrayList<ClassListItems> arraylist;
private MyAppAdapter(List<ClassListItems> apps, Context context)
{
this.parkingList = apps;
this.context = context;
arraylist = new ArrayList<ClassListItems>();
arraylist.addAll(parkingList);
}
#Override
public int getCount() {
return parkingList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) // inflating the layout and initializing widgets
{
View rowView = convertView;
ViewHolder viewHolder= null;
if (rowView == null)
{
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.list_content, parent, false);
viewHolder = new ViewHolder();
viewHolder.textName = (TextView) rowView.findViewById(R.id.textName);
rowView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder) convertView.getTag();
}
// here setting up names and images
viewHolder.textName.setText(parkingList.get(position).getName()+"");
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(InsideCountries.this,Inside_Families.class);
intent.putExtra("Family",parkingList.get(position).getName());
startActivity(intent);
}
});
return rowView;
}
}
}
Any help would be apreciated!?
Related
I am getting data from the SQL database to the android Expandable listview.
All of my data is correct except the listview group is repeated the same amount of the listview children.
I have no idea why and I have tried everything that came into my mind.
Anyways I am using 2 queries!
one to get the group and one to get the group children!
Here is my code: AsyncTask:
private class SyncData extends AsyncTask<String, String, String> {
String msg;
#Override
protected void onPreExecute() //Starts the progress dailog
{
System.out.println("Start");
//lottieAnimationView.playAnimation();
progressDialog.show();
}
#Override
protected String doInBackground(String... strings) // Connect to the database, write query and add items to array list
{
try {
Connection conn = connectionClass.CONN(); //Connection Object
if (conn == null) {
success = false;
msg = "Sorry something went wrong,Please check your internet connection";
} else {
// Change below query according to your own database.
String query = "SELECT SalesInvoice.SalesInvoiceID,SalesInvoice.SalesInvoiceSerial,SalesInvoice.SalesInvoiceDate,SalesInvoice.SalesInvoiceItemCount,SalesInvoice.SalesInvoiceTotal,SalesInvoice.SalesInvoiceTaxs,SalesInvoice.SalesInvoiceLastTotal,SalesInvoice.SalesInvoiceBranchID FROM SalesInvoice where SalesInvoiceID = '321' AND SalesInvoiceBranchID = '2'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) // if resultset not null, I add items to itemArraylist using class created
{
while (rs.next()) {
try {
ClassListItems classListItems = new ClassListItems(rs.getString("SalesInvoiceSerial"),rs.getString("SalesInvoiceDate"),rs.getString("SalesInvoiceItemCount"),rs.getString("salesInvoiceTotal"),rs.getString("SalesInvoiceTaxs"),rs.getString("SalesInvoiceLastTotal"));
String query2 = "SELECT SalesProductName FROM SalesInvoiceDetail WHERE SalesInvoiceID = '"+rs.getString("SalesInvoiceID")+"'";
Statement stmt2 = conn.createStatement();
ResultSet rs2 = stmt2.executeQuery(query2);
if (rs2 != null){
while (rs2.next()){
System.out.println("ssss");
classListItems.getChildItemList().add(new ChildItem(rs2.getString("SalesProductName")));
itemArrayList.add(classListItems);
}
msg = "Found";
success = true;
}else {
msg = "Not Found";
success = false;
}
//Picasso.with(agzakhana_mainAr.this).load(rs.getString("SpecialityIcon")).into(specialityicon);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
Log.d("Error", writer.toString());
success = false;
}
return msg;
}
#Override
protected void onPostExecute(String msg) // disimissing progress dialoge, showing error and setting up my listview
{
//progress2.hideProgress();
progressDialog.hide();
if (msg!=null){
Toast.makeText(MainActivity.this, msg + "", Toast.LENGTH_LONG).show();
}
if (!success) {
System.out.println("EndNotSuccess");
} else {
try {
myAppAdapter = new MyAppAdapter(itemArrayList, MainActivity.this);
exlistView21.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
exlistView21.setAdapter(myAppAdapter);
System.out.println("End");
} catch (Exception ex) {
}
}
}
}
Adapter:
public class MyAppAdapter extends BaseExpandableListAdapter//has a class viewholder which holds
{
public class ViewHolder {
TextView invoicenum;
TextView date;
TextView itemscount;
TextView total;
TextView tax;
TextView lasttotal;
TextView textchild;
}
public List<ClassListItems> parkingList;
public Context context;
ArrayList<ClassListItems> arraylist;
private MyAppAdapter(List<ClassListItems> apps, Context context) {
this.parkingList = apps;
this.context = context;
arraylist = new ArrayList<ClassListItems>();
arraylist.addAll(parkingList);
System.out.println("called");
}
#Override
public int getGroupCount() {
return parkingList.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return parkingList.get(groupPosition).getChildItemList().size();
}
#Override
public Object getGroup(int groupPosition) {
return null;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return parkingList.get(groupPosition).getChildItemList().get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return 0;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
View rowView = convertView;
MyAppAdapter.ViewHolder viewHolder = null;
if (rowView == null) {
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.list_items, parent, false);
viewHolder = new MyAppAdapter.ViewHolder();
//initialize our labels
viewHolder.invoicenum = (TextView) rowView.findViewById(R.id.invoicenum);
viewHolder.date = (TextView) rowView.findViewById(R.id.date);
viewHolder.itemscount = (TextView) rowView.findViewById(R.id.itemcount);
viewHolder.total = (TextView) rowView.findViewById(R.id.total);
viewHolder.tax = (TextView) rowView.findViewById(R.id.tax);
viewHolder.lasttotal = (TextView) rowView.findViewById(R.id.lasttotal);
rowView.setTag(viewHolder);
} else {
viewHolder = (MyAppAdapter.ViewHolder) convertView.getTag();
}
// here setting up names and images
viewHolder.invoicenum.setText(parkingList.get(groupPosition).getSalesInvoiceSerial());
viewHolder.itemscount.setText(parkingList.get(groupPosition).getSalesInvoiceItemCount());
viewHolder.date.setText(parkingList.get(groupPosition).getSalesInvoiceDate());
viewHolder.total.setText(parkingList.get(groupPosition).getSalesInvoiceTotal());
viewHolder.lasttotal.setText(parkingList.get(groupPosition).getSalesInvoiceLastTotal());
viewHolder.tax.setText(parkingList.get(groupPosition).getSalesInvoiceTax());
System.out.println("PARENT IS: "+parkingList.get(groupPosition).getSalesInvoiceSerial());
// Picasso.with(context).load(parkingList.get(position).getDiscountimage()).into(viewHolder.imagediscount);
exlistView21.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//What happens when you click on a place!
// Intent intent = new Intent(LoggedIn.this,MapsActivity.class);
// startActivity(intent);
}
});
return rowView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
View resultView = convertView;
ViewHolder holder;
LayoutInflater inflater = getLayoutInflater();
if (resultView == null) {
resultView = inflater.inflate(R.layout.listchildren, null); //TODO change layout id
holder = new ViewHolder();
holder.textchild = (TextView) resultView.findViewById(R.id.child); //TODO change view id
resultView.setTag(holder);
} else {
holder = (ViewHolder) resultView.getTag();
}
System.out.println("CHILD IS: "+parkingList.get(childPosition).getChildItemList().get(childPosition).getSs());
holder.textchild.setText(parkingList.get(childPosition).getChildItemList().get(childPosition).getSs());
return resultView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
// public void filter(String charText) {
// charText = charText.toLowerCase(Locale.getDefault());
// itemArrayList.clear();
// if (charText.length() == 0) {
// itemArrayList.addAll(arraylist);
//
// } else {
// for (ClassListItems2 st : arraylist) {
// if (st.getSpecialityname().toLowerCase(Locale.getDefault()).contains(charText)) {
// itemArrayList.add(st);
// }
//
// }
// }
// notifyDataSetChanged();
// }
}
}
Im new on java and im doing a app for finish my university. This app have a SearchView filtering on a ListView getting data from a JSON. Im almost finishing that but im stuck after the filter part.
After input on the SearchBar and filter returns the result I cant open a new intent getting the ID from the JSON. I only can open the intent using the position ListView number (that doesn't work for my necessity because of filter process).
The image below shows exactly the issue:
Image
So my necessity is: Open a intent using the ID stored on the JSON for avoid the issue of changing position ID after filter result.
I dont have any idea how I fix this.
Bean:
public class Model {
private String description;
private int id;
public Model(int id, String description) {
this.setId(id);
this.setDescription(description);
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
Main:
public class MainActivity extends Activity implements SearchView.OnQueryTextListener, SearchView.OnCloseListener {
private ListView list;
private ListViewAdapter adapter;
private SearchView editsearch;
public static ArrayList<Model> modelArrayList = new ArrayList<Model>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listview);
loadDataJSON();
adapter = new ListViewAdapter(this);
list.setAdapter(adapter);
editsearch = (SearchView) findViewById(R.id.search);
editsearch.setOnQueryTextListener(this);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int a = position;
Intent myIntent = new Intent(MainActivity.this, Info.class);
myIntent.putExtra("valor", a);
startActivity(myIntent);
}
});
}
public String loadJSON(String arq) {
String json = null;
try {
InputStream is = getAssets().open(arq);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
private void loadDataJSON() {
String arquivo = loadJSON("lista.json");
try {
JSONObject obj = new JSONObject(arquivo);
JSONArray a = obj.getJSONArray("locais");
for (int i = 0; i < a.length(); i++) {
JSONObject item = a.getJSONObject(i);
Model model = new Model(item.getInt("id"),item.getString("description"));
modelArrayList.add(model);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
String text = newText;
adapter.filter(text);
return false;
}
#Override
public boolean onClose() {
// TODO Auto-generated method stub
return false;
}
Adapter:
public class ListViewAdapter extends BaseAdapter {
Context mContext;
LayoutInflater inflater;
public ArrayList<Model> arraylist;
public ListViewAdapter(Context context ) {
mContext = context;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<Model>();
this.arraylist.addAll(MainActivity.modelArrayList);
}
public class ViewHolder {
TextView name;
}
#Override
public int getCount() {
return MainActivity.modelArrayList.size();
}
#Override
public Model getItem(int position) {
return MainActivity.modelArrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
holder.name = (TextView) view.findViewById(R.id.name);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.name.setText(MainActivity.modelArrayList.get(position).getDescription());
return view;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
MainActivity.modelArrayList.clear();
if (charText.length() == 0) {
MainActivity.modelArrayList.addAll(arraylist);
} else {
for (Model mp : arraylist) {
if (mp.getDescription().toLowerCase(Locale.getDefault()).contains(charText)) {
MainActivity.modelArrayList.add(mp);
}
}
}
notifyDataSetChanged();
}
Info:
public class Info extends Activity {
TextView aaa, bbb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
aaa = (TextView) findViewById(R.id.aaa);
bbb = (TextView) findViewById(R.id.bbb);
Intent mIntent = getIntent();
int id = mIntent.getIntExtra("valor",0);
String arquivo = loadJSON("lista.json");
try {
JSONObject obj = new JSONObject(arquivo);
JSONArray a = obj.getJSONArray("locais");
JSONObject item = a.getJSONObject(id);
aaa.setText(item.getString("id"));
bbb.setText("Base: "+item.getString("description"));
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
public String loadJSON(String arq) {
String json = null;
try {
InputStream is = getAssets().open(arq);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
JSON:
{ "locais": [{
"id": "1",
"description": "Text A"
}, {
"id": "2",
"description": "Text B"
}]}
use int a = modelArrayList.get(position).getId() instead. So you will get id from JSON
You need to use that intent in ListViewAdapter
Hope its works fine
I'm trying to update data for clicked row with dialog box. I can updated but when i scroll down some row will also updated. Then, when i scroll up again the data will random updated to other row.
Below is my adapter code:
public class ViewHolder {
TextView productid, productname, pcs, cs;
ImageView dist;
}
public List<Product_List> parkingList;
public Context context;
ArrayList<Product_List> arrayList;
private MyAppAdapter(List<Product_List> apps, Context context) {
this.parkingList = apps;
this.context = context;
arrayList = new ArrayList<Product_List>();
arrayList.addAll(parkingList);
}
#Override
public int getCount() {
return parkingList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
View rowView = convertView;
final MyAppAdapter.ViewHolder viewHolder;
if (rowView == null) {
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.productlist, parent, false);
viewHolder = new MyAppAdapter.ViewHolder();
viewHolder.productid = (TextView) rowView.findViewById(R.id.productid);
viewHolder.productname = (TextView) rowView.findViewById(R.id.productname);
viewHolder.pcs = (TextView) rowView.findViewById(R.id.pcs);
viewHolder.cs = (TextView) rowView.findViewById(R.id.cs);
viewHolder.dist = (ImageView) rowView.findViewById(R.id.dist);
rowView.setTag(viewHolder);
} else {
viewHolder = (MyAppAdapter.ViewHolder) convertView.getTag();
}
viewHolder.productid.setText(parkingList.get(position).getInvtID() + "");
viewHolder.productname.setText(parkingList.get(position).getDescr() + "");
final String a = viewHolder.productid.getText().toString();
final String b = viewHolder.productname.getText().toString();
if ( position % 2 == 0) {
rowView.setBackgroundColor(Color.parseColor("#FFFFFF"));
} else {
rowView.setBackgroundColor(Color.parseColor("#ECEAEA"));
}
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
final Dialog dialog = new Dialog(context);
dialog.setTitle("Inventory Checking");
dialog.setContentView(R.layout.inventory);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
final TextView productids = (TextView) dialog.findViewById(R.id.productids);
productids.setText(a);
final TextView productdesc = (TextView) dialog.findViewById(R.id.productdesc);
productdesc.setText(b);
final EditText pcss = (EditText) dialog.findViewById(R.id.pcss);
final EditText css = (EditText) dialog.findViewById(R.id.css);
final RadioButton btnyes = (RadioButton) dialog.findViewById(R.id.btnyes);
final RadioButton btnno = (RadioButton) dialog.findViewById(R.id.btnno);
btnno.setChecked(true);
Button btnsave = (Button) dialog.findViewById(R.id.btnsave);
btnsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewHolder.pcs.setText(pcss.getText().toString());
viewHolder.cs.setText(css.getText().toString());
if (btnyes.isChecked()) {
viewHolder.dist.setImageResource(R.drawable.done);
} else {
viewHolder.dist.setImageResource(R.drawable.no);
}
notifyDataSetChanged();
dialog.dismiss();
}
});
dialog.show();
}
});
return rowView;
}
}
This is my adapter code.
String msg="Found";
ProgressDialog progress;
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(InventoryChecking1.this, "Synchronising",
"Listview Loading! Please Wait...", true);
}
#Override
protected String doInBackground(String... strings) {
try {
Connection conn = connectionClass.CONN();
if (conn == null) {
success = false;
} else {
String query = "SELECT * FROM Inventory";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) {
while (rs.next()) {
try {
if (rs.getString("Status").equals("A") || rs.getString("Status").equals("AC")) {
itemsArrayList.add(new Product_List(rs.getString("InvtID"), rs.getString("Descr"), rs.getString("Brand"),
rs.getString("Category")));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
success = false;
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
progress.dismiss();
// Toast.makeText(SellerActivity.this, msg + "", Toast.LENGTH_LONG).show();
if (success == false) {
} else {
try {
myAppAdapter = new MyAppAdapter(itemsArrayList, InventoryChecking1.this);
listView.setAdapter(myAppAdapter);
} catch (Exception ex) {
}
}
}
}
Change data in list instead of UI Views just change in list and notify
the adapter:
btnsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Product_List product_list = new Product_List(pcss.getText().toString(),css.getText().toString());
parkingList.set( position,product_list );
notifyDataSetChanged();
dialog.dismiss();
}
});
I am getting data from an XML uploaded on a website. I want to display the text from the XML in a custom ListView, which has two TextViews. The 'title' should go into the upper TextView and the 'guid' into the lower TextView. I'm not sure how I should go about doing this. I've written the following Custom Adapter.
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
private ArrayList list;
private LayoutInflater layoutInflater;
public CustomAdapter(Context context, ArrayList list) {
this.list= list;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.layout_list_row, null);
holder = new ViewHolder();
holder.backgroundImage = (ImageView) convertView.findViewById(R.id.backgroundImage);
holder.topText = (TextView) convertView.findViewById(R.id.topText);
holder.bottomText = (TextView) convertView.findViewById(R.id.bottomText);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
DiscourseItem discourseItem = (DiscourseItem) discourseList.get(position);
holder.topText.setText(discourseItem.getTopText());
holder.bottomText.setText(discourseItem.getBottomText());
return convertView;
}
static class ViewHolder {
ImageView backgroundImage;
TextView topText; //This should display the text in the 'title' field
TextView bottomText; //This should display the text in the 'guid' field
}
}
I'm currently able to display the two separately in separate ListViews with normal ArrayAdapters. Here's the code I've written.
XMLParser.java
public class XMLParser extends AsyncTask {
private URL url;
public ArrayList<String> title = new ArrayList<>();
public ArrayList<String> guid = new ArrayList<>();
#Override
protected Object doInBackground(Object[] objects) {
try {
url = new URL(removed);
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(getInputStream(url), null);
boolean insideItem = false;
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("item")){
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("title")){
if (insideItem)
title.add(xpp.nextText());
} else if (xpp.getName().equalsIgnoreCase("guid")){
if (insideItem)
guid.add(xpp.nextText());
}
} else if (eventType == XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){
insideItem = false;
}
eventType = xpp.next();
}
} catch (MalformedURLException e){
e.printStackTrace();
} catch (XmlPullParserException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return title;
}
public InputStream getInputStream(URL url){
try {
return url.openConnection().getInputStream();
} catch (IOException e){
e.printStackTrace();
}
return null;
}
public ArrayList<String> titles(){
return title;
}
public ArrayList<String> guids(){
return guid;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
parser = new XMLParser();
parser.execute();
title = parser.titles();
guid = parser.guids();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
discourseList = getDiscourseList();
}
}, 2000);
}
});
ListView listView = (ListView) findViewById(R.id.discourseList);
listView.setAdapter(new CustomAdapter(this, discourseList));
}
private ArrayList<DiscourseItem> getDiscourseList() {
ArrayList<DiscourseItem> listData = new ArrayList<DiscourseItem>();
String[] topText = new String[title.size()];
topText = title.toArray(topText);
String[] bottomText = new String[guid.size()];
bottomText = guid.toArray(bottomText);
for (int i = 0; i <= title.size(); i++) {
try {
DiscourseItem discourseItem = new DiscourseItem();
discourseItem.setTopText(topText[i]);
discourseItem.setBottomText(bottomText[i]);
listData.add(discourseItem);
} catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
}
return listData;
}
}
Edit :
I've made the above changes. Now when the parser runs and calls getDiscourseList(), it throws the following error at discourseItem.setTopText(topText[i]); :
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
You can create wrapper class for your upper and bottom values ( something like this, consider another name as I don't know the context of your data):
public class TitleGuidPair {
private final String title;
private final String guid;
public TitleGuidPair(String title, String guid) {
this.title = title;
this.guid = guid;
}
//getters
}
And then parse your result to ArrayList of TitleGuidPair. If you want to keep your parsing algorithm you can make some post-processing and build your TitleGuidPairs afterwards from the two lists that you have.
Having that step behind just pass to your adapter List of TitleGuidPairs and in the getView method set top and bottom text like
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.layout_list_row, null);
holder = new ViewHolder();
holder.backgroundImage = (ImageView) convertView.findViewById(R.id.backgroundImage);
holder.topText = (TextView) convertView.findViewById(R.id.topText);
holder.bottomText = (TextView) convertView.findViewById(R.id.bottomText);
TitleGuidPair titleGuidPair = list.get(position);
holder.topText.setText(titleGuidPair.getTitle());
holder.bottomText.setText(titleGuidPair.getGuid());
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
What I want to do is to append a list item at the bottom Just Like "Load More" functionality.
What I've performed i appended an extra items with empty values into adapter for ArrayList.
It's working fine for the first time but when i load more items it's adding Load More ItemView two times after every 15 items While i didn't make any changes into original ArrayList. The Changes has been made only into adapter class's constructor.
Here's the adapter class:
public class ContactListAdaptor extends BaseAdapter {
private Context context;
private ArrayList<DirectroyDetails> items = new ArrayList<DirectroyDetails>();
private Activity activity = null;
boolean isSearch = false;
private View currentView = null;
private String categoryName = null;
private HashMap< String, String> bannerHash = new HashMap<String, String>();
ContactList ACTIVITY;
public ContactListAdaptor(Context context, final ArrayList<DirectroyDetails> items2, Activity activity, String categoryName, HashMap< String, String> bannerHash, ContactList ACTIVITY, boolean expand) {
// super(context, textViewResourceId, items);
items = items2;
if(expand)
{
DirectroyDetails dummy = new DirectroyDetails();
dummy.setId("-1");
items.add(dummy);
}
this.context = context;
this.activity = activity;
this.categoryName = categoryName;
this.bannerHash = bannerHash;
this.ACTIVITY = ACTIVITY;
}
/*public ContactListAdaptor(Context context, Vector<Directory> items,
Activity activity, boolean isSearch) {
// TODO Auto-generated constructor stub
this.items = items;
this.context = context;
this.activity = activity;
this.isSearch = isSearch;
}*/
// #Override
public View getView(final int position, View convertView, ViewGroup parent) {
final DirectroyDetails directroyDetails = items.get(position);
System.out.println("id======="+directroyDetails.getId().toString());
try {
if(convertView == null)
{
System.out.println("##THE POSITION IS=="+position);
LayoutInflater vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.item_directory, null);
if(directroyDetails.getId().toString().equals("-1"))
convertView.setId(-1);
else
convertView.setId(1);
}else {
currentView = convertView;
}
//To fatch the values from the Event object
TextView titleText = (TextView)convertView.findViewById(R.id.title);
TextView nameText = (TextView)convertView.findViewById(R.id.name);
TextView numberText = (TextView)convertView.findViewById(R.id.number);
ImageView profilePic = (ImageView)convertView.findViewById(R.id.eventimage);
System.out.println("the position is ==== " +position);
titleText.setText(directroyDetails.getCompanyname());
nameText.setText(directroyDetails.getFirstname() + " " + directroyDetails.getSurname());
numberText.setText(directroyDetails.getMobile());
System.out.println("id at position======="+directroyDetails.getId().toString()+" at=="+position);
RelativeLayout overlay = (RelativeLayout)convertView.findViewById(R.id.overlay);
if(directroyDetails.getId().toString().equals("-1"))
{
overlay.setVisibility(View.VISIBLE);
System.out.println("at here to make the Overl;ay visible");
}else {
overlay.setVisibility(View.INVISIBLE);
}
} catch (Exception e) {
// TODO: handle exception
System.out.println("the exception occurs at:-" + e.getMessage());
}
return convertView;
}
public int getCount() {
System.out.println("the item size====="+items.size());
return items.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
}
private void onScrollUpdateList() {
// TODO Auto-generated method stub
Handler onScrollList = new Handler();
onScrollList.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
setContactList();
}
}, 200);
}
& here is my calling code:-
if(contactDb.size()>0 && contactDb!=null)
{
System.out.println("theh responseData1 before new additions==="+responseData1.size());
responseData1 = addMoreData(contactDb,responseData1);
System.out.println("theh responseData1==="+responseData1.size());
if(responseData1 != null)
{
if(responseData1.size()>0)
{
ContactListAdaptor contactAdaptor = new ContactListAdaptor(getApplicationContext(), responseData1, this, CategoryName, bannerHash, ContactList.this, expand);
contactAdaptor.notifyDataSetChanged();
listview.setAdapter(contactAdaptor);
try {
listview.setSelection(getSelectedItems());
} catch (Exception e) {
// TODO: handle exception
System.out.println("the exception at scrolling and set :- " + e.getMessage());
}
}else
{
Toast.makeText(ContactList.this, "No Item found.", Toast.LENGTH_LONG).show();
}
}}
Please review below link code and try to resolve your issue with load more data dynamically with list view..
http://www.developerfusion.com/article/145373/android-listviews-with-dynamic-data/
If you have any query then let me know..