ListView is not appearing - Fetching Data from Server - android

I am trying to Retrieve data from server and want to show that data in a ListView.
Problem: ListView is not Appearing
OrdersActivity.java:
public class OrdersActivity extends Activity
{
public static final String LOG_TAG = "OrdersActivity";
ArrayList<HashMap<String, String>> d = new ArrayList<HashMap<String, String>>();;
ListView list;
OrdersAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_orders);
final ArrayList<HashMap<String, String>> itemsList = new ArrayList<HashMap<String, String>>();
list = (ListView) findViewById(R.id.listView1);
adapter = new OrdersAdapter(this, itemsList);
list.setAdapter(adapter);
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
}
}
activity_orders.java:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff" >
<include
android:id="#+id/header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
layout="#layout/header_orders" />
<ListView
android:layout_width="match_parent"
android:id="#+id/listView1"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/header"
android:cacheColorHint="#00000000"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:layout_alignParentBottom="true" />
</RelativeLayout>
OrdersActivity.java:
public class OrdersAdapter extends BaseAdapter {
TextView tName,tId,tOid ;
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
String strName,strMemberID ;
public OrdersAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
// return (data == null) ? 0 : data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.listrow_orders, null);
tId = (TextView)vi.findViewById(R.id.txtTotalAmount);
tName = (TextView)vi.findViewById(R.id.txtItemDetails);
HashMap<String, String> item = new HashMap<String, String>();
item = data.get(position);
tId.setText(item.get(strName));
tName.setText(item.get(strMemberID));
String url = "http://172.16.0.4/res/order_fetch.php";
Intent intent= activity.getIntent();
String MemberID = intent.getStringExtra("MemberID");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sMemberID", MemberID));
String resultServer = getHttpPost(url,params);
strMemberID = "";
strName = "";
JSONObject c;
try {
c = new JSONObject(resultServer);
strMemberID = c.getString("TotalAmount");
strName = c.getString("ItemDetails");
if(!strMemberID.equals(""))
{
tName.setText(strName);
tId.setText(strMemberID);
}
else
{
tName.setText("-");
tId.setText("-");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return vi;
}
public String getHttpPost(String url,List<NameValuePair> params) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
}
listrow_orders.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:background="#drawable/btn_background"
android:orientation="horizontal"
android:padding="5dip" >
<TextView
android:id="#+id/txtTotalAmount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:textColor="#a60704"
android:text="TextView" />
<TextView
android:id="#+id/txtItemDetails"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView3"
android:layout_below="#+id/textView3"
android:textColor="#a60704"
android:text="Item Details Here" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtTotalAmount"
android:layout_below="#+id/txtTotalAmount"
android:layout_marginTop="17dp"
android:text="Ordered Items:"
android:textColor="#a60704"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Total Amount"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#a60704" />
</RelativeLayout>

You need to store the data within the views itself when comes to customizing of ListView. Trying implementing this:
public class PlacesListAdapter extends BaseAdapter
{
// private Context mContext;
private LayoutInflater mInflater;
private ArrayList<String> AL_id_text = new ArrayList<String>();
private ArrayList<String> AL_text = new ArrayList<String>();
public PlacesListAdapter(Context c, ArrayList<String> AL_name_time, ArrayList<String> AL_name_time1)
{
mInflater = LayoutInflater.from(c);
// mContext = c;
this.AL_id_text = AL_name_time;
this.AL_text = AL_name_time1;
}
public int getCount()
{
return AL_id_text.size();
}
public Object getItem(int position)
{
return AL_id_text.get(position);
}
public long getItemId(int position)
{
return position;
}
static class ViewHolder
{
TextView txt_maintext;
TextView txt_mtext;
}
public View getView(final int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.place_row, null);
holder = new ViewHolder();
holder.txt_maintext = (TextView) convertView.findViewById(R.id.txt_maintext);
holder.txt_mtext = (TextView) convertView.findViewById(R.id.txt_mtext);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txt_maintext.setText(AL_id_text.get(position));
holder.txt_mtext.setText(AL_text.get(position));
return convertView;
}
}

The getView() method is called by android's ListView when it is rendering the view elements on your screen, piece by piece. You shouldn't be fetching your data in your getView() method which, more often than not, will block your UI thread.
The best way to do this would be to fetch your data beforehand, store it in the objects you like and use them to create ListAdapter instances. This way, you wouldn't need to wait for the image fetching to complete while Android is drawing the ListView for you.
So try fetching the data using
getHttpPost()
outside the getView method, preferably Asynchronously.
Populate your itemsList appropriately after fetching data using this method. Create your ListAdapter instance using this itemList data. Set this adapter to your listview.

Related

fragment with tabs don't show listviews

I try to combine tabbed fragment with ListView. I fetch data by JSON and put it in ListView in fragment but when I start app fragment doesn't show the list.
but when I run the activity outside the fragment, the list appears!
I want to know why please
Testactivity.java
public class Testactivity extends AppCompatActivity {
ArrayList<articles> arrayList;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testactivity);
arrayList = new ArrayList<>();
lv = (ListView) findViewById(R.id.ListView1);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute("http://wach.ma/mobile/home.php");
}
});
}
class ReadJSON extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(content);
} catch (JSONException e1) {
e1.printStackTrace();
}
JSONArray jsonArray = null;
try {
jsonArray = jsonObject.getJSONArray("articles");
} catch (JSONException e1) {
e1.printStackTrace();
}
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject articlesobject = null;
try {
articlesobject = jsonArray.getJSONObject(i);
} catch (JSONException e1) {
e1.printStackTrace();
}
try {
arrayList.add(new articles(
articlesobject.getString("picture"),
articlesobject.getString("title")
));
} catch (JSONException e1) {
e1.printStackTrace();
}
CustomListAdaper adaper = new CustomListAdaper(
getApplicationContext(), R.layout.custom_list_layout,
arrayList
);
lv.setAdapter(adaper);
}
}
private String readURL(String theURL) {
StringBuilder content = new StringBuilder();
try {
URL url = new URL(theURL);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line + "\n");
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
return content.toString();
}
}
}
CustomListAdaper.java
public class CustomListAdaper extends ArrayAdapter<articles> {
ArrayList<articles> articles;
Context context;
int resource;
public CustomListAdaper(#NonNull Context context, #LayoutRes int resource,
#NonNull ArrayList<articles> articles) {
super(context, resource, articles);
this.articles = articles;
this.context = context;
this.resource = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull
ViewGroup parent) {
if (convertView == null){
LayoutInflater layoutInflater = (LayoutInflater)
getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.custom_list_layout,
null, true);
}
articles articles = getItem(position);
ImageView imageView = (ImageView) convertView.findViewById(imageView2);
Picasso.with(context).load("http://wach.ma/"+articles.getPicture())
.into(imageVi
ew);
TextView textView = (TextView) convertView.findViewById(R.id.textView);
textView.setText((replacehtml(articles.getNom())));
return convertView;
}
public String replacehtml(String str) {
str = str.replaceAll("é", "é");
return str;
}
}
Accueil.java: (where I want the activity_testactivity.xml show):
public class Accueil extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_testactivity, container,
false);
return rootView;
}
}
activity_testactivity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
tools:context="com.example.lenovo.myapplication.Testactivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/imageView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:srcCompat="#drawable/logo2" />
<ListView
android:id="#+id/ListView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:listitem="#layout/custom_list_layout"/>
</LinearLayout>
</RelativeLayout>
custom_list_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="350dp"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="1">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/imageView2"
android:layout_width="100dp"
android:layout_height="120dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:src="#mipmap/ic_launcher" />
<TextView
android:id="#+id/textView"
android:layout_width="250dp"
android:layout_height="72dp"
android:layout_marginTop="20dp"
android:layout_weight="0.19"
android:paddingLeft="25dp"
android:text="TextView"
android:textColor="#android:color/darker_gray"
android:textSize="20sp" />
</LinearLayout>
Because you left your ListView empty without any data from the ReadJSON task.
To do this, inside your Fragment: Find the ListView instance
lv = (ListView) findViewById(R.id.ListView1);
Copy the class class ReadJSON extends AsyncTask<String, Integer, String> { } to your Fragment.
Execute the task that get data and show on your ListView inside onCreateView() of your Fragment:
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute("http://wach.ma/mobile/home.php");
}
});
If you do NOT want to duplicate code of the ReadJSON task but still want to use it in Activity also Fragment: Bring the ReadJSON to a separate class, store an instance of ListView inside ReadJSON task and set it through the constructor. Then use this local ListView instance to show data.

i want to fetch a data from database and display it on listview.

xml file
the first file is a xml file of the design.
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listviewtask"/>
</LinearLayout>
</RelativeLayout>
rawtask.xml file
this is the raw file and here design of a list view
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#drawable/property_display_box"
android:id="#+id/listview1ll">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Task Name"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:textSize="30dp"
android:id="#+id/lvtaskname" />
<TextView
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:textSize="30dp"
android:hint="Task Details"
android:layout_gravity="center"
android:id="#+id/lvtaskdetails"
/>
<CheckBox
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add Details"
android:layout_marginLeft="40dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:textSize="30dp"
android:id="#+id/lvchkbox"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="10dp"
android:orientation="horizontal"
android:id="#+id/lvl1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:text="Remaining Time:"
android:textSize="20dp"
android:id="#+id/lvrt"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Done"
android:layout_marginLeft="90dp"
android:layout_marginTop="10dp"
android:textSize="20dp"
android:id="#+id/lvdone"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Listviewadapter.java
the listviewadapter.java is shown
public class ListViewAdapter2 extends BaseAdapter {
Context cntx;
AlertDialog.Builder alertDialogBuilder;
//int loader = R.drawable.ic_menu_gallery;
ArrayList<String> t_id=new ArrayList<String>();
ArrayList<String> t_tname=new ArrayList<String>();
ArrayList<String> t_detail=new ArrayList<String>();
// ArrayList<Float> itemRating=new ArrayList<Float>();
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
//ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
/*
* public ListViewAdapter(Context context, ArrayList<HashMap<String,
* String>> arraylist) { this.cntx = context; data = arraylist; imageLoader
* = new ImageLoader(context); }
*/
public ListViewAdapter2(Context context,
ArrayList<String> taskid,
ArrayList<String> taskname,
ArrayList<String> taskdetail) {
// TODO Auto-generated constructor stub
cntx = context;
t_id=taskid;
t_tname = taskname;
t_detail =taskdetail;
//Log.d("xyz", security_id.toString());
//ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).build();
//ImageLoader.getInstance().init(config);
alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setMessage("Do You Want To Call....");
// itemRating=itm_rating;
}
#Override
public int getCount() {
return t_id.size();
}
#Override
public Object getItem(int position) {
return t_id.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressWarnings("deprecation")
public View getView(final int position, View convertView, ViewGroup parent) {
#SuppressWarnings("unused")
final TextView taskname, taskdetail;
inflater = (LayoutInflater) cntx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LayoutInflater inflater = LayoutInflater.from(cntx);
convertView = inflater.inflate(R.layout.rawtask, parent, false);
/*ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(loader)
.showImageOnFail(loader)
.showImageOnLoading(loader).build();*/
taskname= (TextView) convertView.findViewById(R.id.lvtaskname);
taskdetail= (TextView) convertView.findViewById(R.id.lvtaskdetails);
taskname.setText("taskName : "+t_tname.get(position));
taskdetail.setText("taskdetail: "+t_detail.get(position));
return convertView;
}
}
main activity.java
this is the final .java file of the project
package com.example.sachin.listview;
public class Main2Activity extends Fragment {
public Main2Activity(){};
private static final String TAG_SUCCESS = "success";
JSONArray jsonarray;
JSONObject jsonobject;
ListView listview;
String img;
ListViewAdapter2 listadapter;
//ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
private static String url_task = "http://10.0.2.2/portal/aFetchtask.php";
// private static String url_profile ="http://10.0.2.2/myapp/fetchmember.php";
JSONParser jParser = new JSONParser();
ArrayList<String> t_id = new ArrayList<String>();
ArrayList<String> t_tname = new ArrayList<String>();
ArrayList<String> t_detail = new ArrayList<String>();
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
// don't look at this layout it's just a listView to show how to handle the keyboard
View view = inflater.inflate(R.layout.activity_main, container, false);
getActivity().setTitle("tasks");
new DownloadJSON().execute();
return view;
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
//mProgressDialog = new ProgressDialog(getActivity());
//mProgressDialog.setTitle("Please Wait");
// Set progressdialog message
//mProgressDialog.setMessage("Loading...");
//mProgressDialog.setIndeterminate(false);
// Show progressdialog
//mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... args) {
// Create an array
try {
arraylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("abc", "abc"));
JSONObject json = jParser.makeHttpRequest(url_task, "POST", params);
int success1 = Integer.parseInt(json.getString(TAG_SUCCESS));
Log.d("success", json.toString());
if (success1 == 0) {
Snackbar.make(view, "Not Data Found", Snackbar.LENGTH_LONG).show();
}
if (success1 == 1) {
JSONArray ownerObj = json.getJSONArray("tasks");
// arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
// Locate the array name in JSON
// jsonarray = jsonobject.getJSONArray("images");
for (int i = 0; i < ownerObj.length(); i++) {
// HashMap<String, String> map = new HashMap<String, String>();
jsonobject = ownerObj.getJSONObject(i);
// Retrive JSON Objects
//securityId.add(jsonobject.getString("security_id"));
// t_id.add(jsonobject.getString("t_id"));
t_tname.add(jsonobject.getString("t_tname"));
t_detail.add(jsonobject.getString("t_detail"));
// Number.add(jsonobject.getString("number"));
Log.d("DATA", jsonobject.toString());
//img="http://10.0.2.2/momskitchen/image/";
//proImage.add(img + jsonobject.getString("image"));
/* System.out.println(jsonobject.getString(TA));
System.out.println(g);*/
}
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void args) {
listview = (ListView) getActivity().findViewById(R.id.listviewtask);
ListViewAdapter2 listadapter = new ListViewAdapter2(getActivity(), t_id, t_tname, t_detail);
// Set the adapter to the ListView
listview.setAdapter(listadapter);
// Close the progressdialog
//mProgressDialog.dismiss();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
//add the values which need to be saved from the drawer to the bundle
// outState = result.saveInstanceState(outState);
super.onSaveInstanceState(outState);
}
}
and the lastly is the file is my api file..
<?php
include("connection.php");
$response = array();
// get all products from products table
$result = mysql_query("SELECT * FROM task") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["tasks"] = array();
while ($row = mysql_fetch_array($result))
{
$tasks = array();
$tasks["t_id"] = $row["t_id"];
$tasks["t_tname"] = $row["t_tname"];
$tasks["t_udetail"] = $row["t_udetail"];
// push single product into final response array
array_push($response["tasks"], $tasks);
}
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
}
else
{
// no products found
$response["success"] = 0;
$response["message"] = "No picture found";
// echo no users JSON
echo json_encode($response);
}
?>
here the all files are available.
but the data is not fetched from the database.
please help me out for this..
There are lot of coding faults are there.
The Asynchronus class is return types are not in the exact manner to retrive the data.
After protected Void doInBackground(Void... args) {}is returning null then you can get null value to onPostExcute(Void args) you have to write get whole repose in doInBackground() method only if you are not returning any response.
In rawtask.xml file should contains views which are inflating by adapter but in your case other view are mentioned.
So refere this following link to get the data from webservices into listView.
here

Control CheckBox status

I have retrieved data from a remote db using json and i have created a custom listView with this data. I have three TextView and one CheckBox and it works perfectly. So, i have added a button that would control selected items in list and eventually transfer selected item in another activity. Problem was solved as suggested,but if i scroll list, selected items losts status.I think it depends from horder or adapter. Can someone help me? Here is my code
public class Activity2 extends ActionBarActivity implements OnItemClickListener {
TextView txtLavorante;
TextView txtCodice;
Intent currIntent;
ListView list;
String myJSON;
ArrayList <String> checkedValue;
private ProgressDialog pDialog;
private static final String TAG_RESULTS="result";
private static final String TAG_ID = "ID";
private static final String TAG_NAME = "Descrizione";
private static final String TAG_PRICE ="Costo";
private static final String TAG_TIME ="Durata_m";
JSONArray serv_man = null;
ArrayList<HashMap<String, String>> list_serv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity2);
list = (ListView) findViewById(R.id.listView);
currIntent = getIntent();
txtLavorante = (TextView) findViewById (R.id.Lavorante);
txtCodice = (TextView) findViewById(R.id.CodiceLavorante);
stampaValori();
list_serv = new ArrayList<HashMap<String,String>>();
getData();
}
#Override
public void onItemClick(AdapterView arg0, View v, int position, long arg3) {
CheckBox cb = (CheckBox) v.findViewById(R.id.checkBox);
TextView tv = (TextView) v.findViewById(R.id.textView);
cb.performClick();
if (cb.isChecked()) {
checkedValue.add(tv.getText().toString());
Log.i("Btn Test",""+checkedValue);
} else if (!cb.isChecked()) {
checkedValue.remove(tv.getText().toString());
}
}
private void stampaValori() {
String pkg = getApplicationContext().getPackageName();
String tCode = "ID: " + currIntent.getStringExtra(pkg + "ID") + "\n";
String tNome = "Collaboratore scelto: " + currIntent.getStringExtra(pkg + "LAV") + "\n";
txtLavorante.setText(tNome);
txtCodice.setText(tCode);
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
serv_man = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<serv_man.length();i++){
JSONObject c = serv_man.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String price = c.getString(TAG_PRICE);
String time = c.getString(TAG_TIME);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_ID,id);
persons.put(TAG_NAME,name);
persons.put(TAG_PRICE,price);
persons.put(TAG_TIME,time);
list_serv.add(persons);
}
list = (ListView) findViewById(R.id.listView);
list.setAdapter(new ListatoAdapter(Activity2.this, list_serv));
list.setOnItemClickListener(Activity2.this);
Button b= (Button) findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(Activity2.this, "TEST" + checkedValue, Toast.LENGTH_LONG).show();
Log.i ("Test ",""+checkedValue);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://www.example.com/.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
Log.i ("Servizi","serv:"+result);
} catch (Exception e) {
// Oops
Log.e("log_tag", "Error converting result " + e.toString());
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Activity2.this);
pDialog.setMessage("Obtaining list...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected void onPostExecute(String result){
pDialog.dismiss();
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
#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_activity2, 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);
}
}
ListatoAdapter
public class ListatoAdapter extends BaseAdapter {
private LayoutInflater layoutinflater;
private Context context;
ArrayList<HashMap<String, String>> dataList;
boolean [] itemChecked;
public ListatoAdapter(Context context, ArrayList<HashMap<String, String>> list_serv) {
super();
this.context = context;
this.dataList = list_serv;
itemChecked = new boolean [dataList.size()];
}
#Override
public int getCount() {
return dataList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.prenota_serv, null);
holder = new ViewHolder();
holder.service = (TextView)convertView.findViewById(R.id.et_serv);
holder.id = (TextView)convertView.findViewById(R.id.et_id);
holder.costo = (TextView)convertView.findViewById(R.id.et_costo);
holder.durata = (TextView)convertView.findViewById(R.id.et_dur);
holder.Ceck = (CheckBox)convertView.findViewById(R.id.checkBox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.service.setText(dataList.get(position).get("Descrizione"));
holder.id.setText(dataList.get(position).get("ID"));
holder.costo.setText(dataList.get(position).get("Costo"));
holder.durata.setText(dataList.get(position).get("Durata_m"));
holder.Ceck.setChecked(false);
if (itemChecked[position])
holder.Ceck.setChecked(true);
else
holder.Ceck.setChecked(false);
holder.Ceck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (holder.Ceck.isChecked())
itemChecked[position] = true;
else
itemChecked[position] = false;
Log.i("Adapter Test",""+itemChecked[position]);
}
});
return convertView;
}
class ViewHolder {
TextView service;
TextView id;
TextView costo;
TextView durata;
CheckBox Ceck;
}
}
Activity2.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="net.puntosys.www.customadaptertest.Activity2"
android:orientation="vertical">
<TextView android:text="hello_word" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Lavorante"
android:textStyle="bold"
android:textSize="22dp" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_gravity="right" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/CodiceLavorante"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:visibility="invisible" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView" />
prenota_serv.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Servizio:"
android:textSize="7pt"
android:id="#+id/tv_serv"
android:layout_alignBottom="#+id/tv_id"
android:layout_alignLeft="#+id/tv_id"
android:layout_alignStart="#+id/tv_id" />
<EditText
android:background="#android:drawable/editbox_background"
android:layout_height="wrap_content"
android:layout_width="190dip"
android:id="#+id/et_serv"
android:layout_gravity="center_horizontal"
android:textSize="7pt"
android:layout_alignBottom="#+id/et_id"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Costo Euro:"
android:textSize="7pt"
android:id="#+id/tv_cost"
android:layout_below="#+id/et_serv"
android:layout_alignLeft="#+id/tv_serv"
android:layout_alignStart="#+id/tv_serv" />
<EditText
android:background="#android:drawable/editbox_background"
android:layout_height="wrap_content"
android:layout_width="120dip"
android:id="#+id/et_costo"
android:layout_gravity="center_horizontal"
android:layout_below="#+id/et_serv"
android:layout_alignLeft="#+id/et_serv"
android:layout_alignStart="#+id/et_serv"
android:textSize="7pt" />
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Durata min:"
android:textSize="7pt"
android:id="#+id/tv_dur"
android:layout_below="#+id/et_costo"
android:layout_alignLeft="#+id/tv_cost"
android:layout_alignStart="#+id/tv_cost" />
<EditText
android:background="#android:drawable/editbox_background"
android:layout_height="wrap_content"
android:layout_width="70dip"
android:id="#+id/et_dur"
android:layout_gravity="center_horizontal"
android:textSize="7pt"
android:layout_alignTop="#+id/tv_dur"
android:layout_alignLeft="#+id/et_costo"
android:layout_alignStart="#+id/et_costo" />
<TextView
android:layout_marginTop="5dip"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Nr:"
android:layout_marginLeft="5dip"
android:layout_marginRight="9dip"
android:layout_alignParentLeft="true"
android:textSize="10pt"
android:id="#+id/tv_id"
android:visibility="invisible" />
<EditText
android:background="#android:drawable/editbox_background"
android:layout_height="wrap_content"
android:layout_width="70dip"
android:id="#+id/et_id"
android:layout_gravity="center_horizontal"
android:layout_alignTop="#+id/tv_id"
android:layout_alignLeft="#+id/et_serv"
android:layout_alignStart="#+id/et_serv"
android:enabled="false"
android:elegantTextHeight="false"
android:visibility="invisible" />
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="CheckBox"
android:layout_below="#+id/tv_dur"
android:layout_alignRight="#+id/et_serv"
android:layout_alignEnd="#+id/et_serv" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/textView"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/tv_dur"
android:layout_alignStart="#+id/tv_dur" />
when user select a check box, put its corresponding data to a list.and send the list in bundle on button click.and receive it on another activity with the key.
you need to create a list like.
ArrayList<HashMap<String, String>> list_selected;
public ListatoAdapter(Context context, ArrayList<HashMap<String, String>> list_serv) {
super();
this.context = context;
this.dataList = list_serv;
list_selected = new ArrayList<HashMap<String, String>>();
}
change the listener as.
holder.Ceck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
HashMap<String,String> data = dataList.get(position);
if(isChecked){
addToSelected(data);
}else{
removeSelected(data);
}
}
});
private void addToSelected(HashMap contact){
if(!list_selected.contains(contact))list_selected.add(contact);
}
private boolean removeSelected(HashMap contact){
return list_selected.remove(contact);
}
public ArrayList<HashMap<String, String>> getSelectedItems(){
return list_selected;
}
access the list from activity as adapter.getSelectedItems();.
declare it in your activity as global
ListatoAdapter adapter;
set adapter in this way.
adapter = new ListatoAdapter(Activity2.this, list_serv);
list.setAdapter(adapter);
and get the list in button Click as.
ArrayList<HashMap<String,String> list = adapter.getSelectedItems();

Listview with custom adapter overwriting data from my post

I am new to Java and Android.
I am using a custom adapter to fill my list_view, but then got overwritten, and I don't know what I should do.
By searching on the web I found something about "linkedhashset", but I don't know how to use it.
Adapter Class
public class OSFuncionarioListAdapter extends ArrayAdapter<OSFuncionario> {
private List<OSFuncionario> itemList;
private Context context;
public OSFuncionarioListAdapter(List<OSFuncionario> itemList, Context ctx) {
super(ctx,android.R.layout.simple_list_item_1, itemList);
this.itemList = itemList;
this.context = ctx;
}
public int getCount() {
if (itemList != null)
return itemList.size();
return 0;
}
public OSFuncionario getItem(int position) {
if (itemList != null)
return itemList.get(position);
return null;
}
public long getItemId(int position) {
if (itemList != null)
return itemList.get(position).hashCode();
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.osfuncionario_item, parent, false);
OSFuncionario ositem = itemList.get(position);
TextView os = (TextView) v.findViewById(R.id.IDOS);
os.setText("OS Nº " + ositem.OS);
TextView os1 = (TextView) v.findViewById(R.id.datadaos);
os1.setText(ositem.Data);
TextView os2 = (TextView) v.findViewById(R.id.solicitacao);
os2.setText("Solicitado por: "+ositem.Solicitado);
TextView os3 = (TextView) v.findViewById(R.id.textoosfunc);
os3.setText(ositem.Texto+"...");
}
return v;
}
public List<OSFuncionario> getItemList() {
return itemList;
}
public void setItemList(List<OSFuncionario> itemList) {
this.itemList = itemList;
}
}
the fragment code
public class OSFuncionarioFragment extends Fragment {
OSFuncionarioListAdapter adpt;
OSFuncionario item;
protected SharedPreferences userLocalDatabase;
public static final String SP_NOME="UserDetails";
public static final int CONNECTION_TIME = 1000 *30;
public static final String SERVIDOR = "http://www.creativeriopreto.com.br/app/";
public OSFuncionarioFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_osfuncionario, container, false);
userLocalDatabase = getActivity().getSharedPreferences(SP_NOME, 0);
adpt = new OSFuncionarioListAdapter(new ArrayList<OSFuncionario>(), getActivity());
ListView lView = (ListView) rootView.findViewById(R.id.listaOSFuncionario);
int idfuncionario = userLocalDatabase.getInt("id", -1);
lView.setAdapter(adpt);
item = new OSFuncionario(idfuncionario);
(new Carregadados()).execute();
return rootView;
}
private class Carregadados extends AsyncTask<String, Void, List<OSFuncionario>> {
private final ProgressDialog dialog = new ProgressDialog(getActivity());
#Override
protected void onPostExecute(List<OSFuncionario> result) {
super.onPostExecute(result);
dialog.dismiss();
adpt.setItemList(result);
adpt.notifyDataSetChanged();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setCancelable(false);
dialog.setTitle("Carregando");
dialog.setMessage("Por Favor Aguarde");
dialog.show();
}
#Override
protected List<OSFuncionario> doInBackground(String... params) {
List<OSFuncionario> result = new ArrayList<OSFuncionario>();
ArrayList<NameValuePair> data = new ArrayList<>();
data.add(new BasicNameValuePair("id",String.valueOf(item.IDFuncionario)));
HttpParams httprequestparams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httprequestparams, CONNECTION_TIME);
HttpConnectionParams.setSoTimeout(httprequestparams, CONNECTION_TIME) ;
HttpClient cliente = new DefaultHttpClient(httprequestparams);
HttpPost post = new HttpPost(SERVIDOR + "OS/CarregaOSFuncionario");
try {
post.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response = cliente.execute(post);
HttpEntity entity = response.getEntity();
String JSONResp = EntityUtils.toString(entity);
JSONArray arr = new JSONArray(JSONResp);
for (int i=0; i < arr.length(); i++) {
result.add(ConvertDados(arr.getJSONObject(i)));
}
return result;
}
catch(Throwable t) {
t.printStackTrace();
}
return null;
}
public OSFuncionario ConvertDados(JSONObject obj) throws JSONException {
int OS = obj.getInt("ID");
String solicitado = obj.getString("solicitado");
String texto = obj.getString("texto");
String data = obj.getString("data");
return new OSFuncionario(OS, item.IDFuncionario, solicitado, texto, data);
}
}
Class Code
public class OSItinerarioClass implements Serializable {
public int OS, Itinerario, Versao ;
public String Data, Finalidade, Tecnico, Cliente, Situacao;
public OSItinerarioClass(int os, int itinerario, int versao,
String data, String finalidade, String tecnico, String cliente, String situacao)
{
this.OS = os;
this.Itinerario = itinerario;
this.Versao = versao;
this.Data = data;
this.Finalidade = finalidade;
this.Tecnico = tecnico;
this.Cliente = cliente;
this.Situacao = situacao;
}
public OSItinerarioClass(int itinerario)
{
this.OS = -1;
this.Itinerario = itinerario;
this.Versao = -1;
this.Data = "";
this.Finalidade = "";
this.Tecnico = "";
this.Cliente = "";
this.Situacao = "";
}
}
XML Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dp" >
<!-- Thumbnail Image -->
<ImageView
android:layout_width="56dp"
android:layout_height="56dp"
android:background="#drawable/ic_os"
android:contentDescription="icone"
android:id="#+id/thumbnail" />
<!-- Movie Title -->
<TextView
android:id="#+id/IDOS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:text="Numero de OS"
android:textSize="18dp"
android:textColor="#color/colorPrimary"
android:layout_marginTop="5dp"
android:textStyle="bold" />
<TextView
android:id="#+id/solicitacao"
android:text="Solicitacao"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/IDOS"
android:layout_marginTop="5dp"
android:layout_toRightOf="#+id/thumbnail"
android:textColor="#666"
android:textSize="#dimen/genre" />
<!-- Genre -->
<TextView
android:id="#+id/textoosfunc"
android:text="Texto da OS"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/solicitacao"
android:layout_marginTop="5dp"
android:layout_toRightOf="#+id/thumbnail"
android:textColor="#666"
android:textSize="#dimen/genre" />
<!-- Release Year -->
<TextView
android:id="#+id/datadaos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="data da os"
android:layout_alignParentRight="true"
android:textColor="#666"
android:layout_marginTop="5dp"
android:textSize="#dimen/year" />
the json response from the server
[{"ID":42529,"solicitado":"teste","texto":"teste de apresentação para cliente","data":"29/03/2015"},{"ID":40546,"solicitado":"Rdorigo","texto":"Erro liberação cliente SISTEMA/RADIUS","data":"07/02/2015"},{"ID":37450,"solicitado":"Frank","texto":"Cliente solicita visita no local pois alega ","data":"09/12/2014"},{"ID":35825,"solicitado":"Mirian","texto":"Link de 20 megas compartilhados por R$ 189,","data":"04/11/2014"},{"ID":35317,"solicitado":"Thiago Belao(teste de erro PC)","texto":"Cliente disse que o tecnico esteve no local ","data":"08/10/2014"},{"ID":33150,"solicitado":"andrea","texto":"conexão lenta","data":"31/07/2014"},{"ID":22920,"solicitado":"Angélica","texto":"Referente à desenvolvimento de site para Cad","data":"10/11/2013"},{"ID":22692,"solicitado":"SUMAIA","texto":"CLIENTE SOLICITOU ALTERAÇÕES NO SITE, FOI RE","data":"27/10/2013"},{"ID":22324,"solicitado":"ANGÉLICA","texto":"ABRINDO O.S PARA DESENVOLVIMENTO DE SITE COM","data":"05/10/2013"},{"ID":22092,"solicitado":"Guilherme","texto":"Instalar ponto de internet ( Air Gridg ) no ","data":"18/09/2013"},{"ID":21994,"solicitado":"Desenvolvimento","texto":"Desenvolvimento de Web Site . R$ 1.100,00 em","data":"11/09/2013"},{"ID":21910,"solicitado":"Ellus Bruno","texto":"Desenvolvimento de Site Gerenciavel R$ 1500,","data":"04/09/2013"},{"ID":21846,"solicitado":"Fabio","texto":"Cliente solicitou manutenção em seu web site","data":"01/09/2013"},{"ID":18986,"solicitado":"Tcharles","texto":"Instalação de Sistema Operacional, Configura","data":"19/02/2013"}]
In your get view put this line on the top.
convertView = null;
I hope it works, it solved my problem.
Try calling notifyDataSetChanged() within adapter after "this.itemList = itemList;" in setItemList and remove from onPostExecute.

ListView is not appearing in Activity

I am making an app in which i want to show all previous Order Details to user in a ListView using Server from PHPMYADMIN.
Problem: Not getting ListView in Activity, getting blank activity instead of ListView
OrdersAdapter.java:
public class OrdersAdapter extends BaseAdapter {
TextView tName,tId,tOid ;
String MemberID,resultServer,strMemberID,strName,strOrderID;
Activity activity;
LayoutInflater inflater;
ListView listView;
public OrdersAdapter(Activity a) {
// TODO Auto-generated constructor stub
activity = a;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return 0;
// TODO Auto-generated method stub
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.listrow_orders, null); // listrow_cart
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
tId = (TextView)activity.findViewById(R.id.txtTotalAmount);
tName = (TextView)activity.findViewById(R.id.txtItemDetails);
String url = "http://172.16.0.4/res/order_fetch.php";
Intent intent= activity.getIntent();
MemberID = intent.getStringExtra("MemberID");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sMemberID", MemberID));
resultServer = getHttpPost(url,params);
strMemberID = "";
strName = "";
JSONObject c;
try {
c = new JSONObject(resultServer);
strMemberID = c.getString("TotalAmount");
strName = c.getString("ItemDetails");
if(!strMemberID.equals(""))
{
tName.setText(strName);
tId.setText(strMemberID);
}
else
{
tName.setText("-");
tId.setText("-");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return vi;
}
String getHttpPost(String url,List<NameValuePair> params) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
}
OrdersActivity.java:
public class OrdersActivity extends Activity
{
ListView mLstView1;
OrdersAdapter mViewOrdersAdpt;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_orders);
mLstView1 = (ListView) findViewById(R.id.listView1);
mViewOrdersAdpt = new OrdersAdapter(OrdersActivity.this);
mLstView1.setAdapter(mViewOrdersAdpt);
mLstView1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
final int position, long id)
{
}
});
}
}
activity_orders.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff" >
<include
android:id="#+id/header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
layout="#layout/header_orders" />
<ListView
android:layout_width="match_parent"
android:id="#+id/listView1"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/header"
android:cacheColorHint="#00000000"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:layout_alignParentBottom="true" />
</RelativeLayout>
listrow_orders.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:background="#drawable/btn_background"
android:orientation="horizontal"
android:padding="5dip" >
<TextView
android:id="#+id/txtTotalAmount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:textColor="#a60704"
android:text="TextView" />
<TextView
android:id="#+id/txtItemDetails"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView3"
android:layout_below="#+id/textView3"
android:textColor="#a60704"
android:text="Item Details Here" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtTotalAmount"
android:layout_below="#+id/txtTotalAmount"
android:layout_marginTop="17dp"
android:text="Ordered Items:"
android:textColor="#a60704"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Total Amount"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#a60704" />
</RelativeLayout>
It is good if you parse json inside Activity instead of BaseAdapter , getView() will be called multiple times so json will be parsed multiple times too
Inside Activity write json fetching code inside AsyncTask store data in ArrayList , if you have single ArrayList than use like follow else you need to pass multiple ArrayList to BaseAdapter constructor
onPostExecute use setAdapter();
Here,
mArrayList is a ArrayList<String>
OrdersAdapter ordersAdapter = new OrdersAdapter(MyAct.this,mArrayList);
Inside BaseAdapter
ArrayList<String> mMyList;
public OrdersAdapter(Activity a, ArrayList<String> mList)
{
activity = a;
mMyList = mList;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
getCount method
public int getCount() {
return mMyList.size();
}
your adapter says it has no items as getCount() returns 0
Problem in your OrdersAdapter.java class
you must need to override adapter getCount() method in proper way like
public int getCount() {
return SIZE_OF_ARRAYLIST;
}
if you write return 0 then list will not display. So you need to return size of arrayList
Pass a Collection, lets say strings in constructor
public OrdersAdapter(Activity a, List stringsToShow) {
// TODO Auto-generated constructor stub
activity = a;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.stringsToShow = stringsToShow;
}
and then
public int getCount() {
return stringsToShow.size();
}
And avoid doing so many things in getView().. Kamal karte ho Pande ji..
Don't try to load data in getView() method because it is called by systems many times. You can check this two link to know better
Yet another getView called multiple times
and the second link
custom listview adapter getView method being called multiple times, and in no coherent order
So now what you have to do to overcome this problem. You load data from web so you can use asynctask that will be used to load the data and pass it in a class. Check this to know about asynctask http://developer.android.com/reference/android/os/AsyncTask.html
From asynctask class you can pass this data in a class. This class holds the data and then you can use this data in main activity. It is best to parse json data in asynctask class.
Actually you did not pass any data in your adapter class. That's why your listview did not show any data. Hope this will work.

Categories

Resources