Android Spinner with POST REQUEST - android

I'm working on some project in which Im getting data from webservice. Now what I have to do is showing that values in Spinner. I have tried but got nothing in the spinner. I have make a custom Adapter for that everything is going fine according to me. But I got nothing in a spinner. Can someone please sort out my problem. Thanks in Advance.
How I tried:
MainActivity:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_teacher_selection);
// teacherNameList = new ArrayList<HashMap<String, String>>();
TeacherNameSpinner = (Spinner) findViewById(R.id.spinner);
teacherNameList = new ArrayList<TeacherNameClass>();
// TeacherNameSpinner.setOnItemSelectedListener(this);
new GettingTeacherName().execute();
}
public class GettingTeacherName extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(GETTING_QUIZ_URL);
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpGet);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity httpEntity = httpResponse.getEntity();
try {
Serv_Response = EntityUtils.toString(httpEntity);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(Serv_Response != null)
{
JSONObject jsonObj = new JSONObject(Serv_Response);
JSONArray quiz = jsonObj.getJSONArray(TAG_NAME);
for(int i= 0 ; i < quiz.length(); i++)
{
JSONObject c = quiz.getJSONObject(i);
String teacherNames = c.getString(TAG_TEACHERNAME);
// HashMap<String, String> hash_teachername = new HashMap<String, String>();
// hash_teachername.put(TAG_TEACHERNAME, teacherNames);
//
TeacherNameClass teacherNameClassObj = new TeacherNameClass();
teacherNameClassObj.setTeacherName(teacherNames);
// teacherNameList.add(teacherNameClassObj);
try {
teacherNameList.add(teacherNameClassObj);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(TeacherSelectionActivity.this, android.R.layout.simple_spinner_item);
CustomTeacherAdapter adapter = new CustomTeacherAdapter(getApplicationContext(),teacherNameList);
// attaching data adapter to spinner
// TeacherNameSpinner.setAdapter(adapter);
TeacherNameSpinner.setAdapter((SpinnerAdapter) adapter);
}
}
file.xml of MainActivity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="10dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<!-- Text Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:text="Category:"
android:layout_marginBottom="5dp"
/>
<!-- Spinner Element -->
<Spinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="#string/app_name"
/>
CustomAdapterActivity
public class CustomTeacherAdapter extends BaseAdapter{
private Context mContext;
ArrayList<TeacherNameClass> teacherNameList;
//ArrayList<Quiz> quizList;
public CustomTeacherAdapter(Context context,ArrayList<TeacherNameClass> teacherNameList)
{
super();
mContext = context;
this.teacherNameList = teacherNameList;
}
public View getDropDownView(int position, View convertView,ViewGroup parent)
{
return getCustomView(position, convertView, parent);
}
public View getView(int position, View convertView, ViewGroup parent)
{
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.activity_custom_teachername_spinner, null);
// LayoutInflater inflater=getLayoutInflater();
// View row=inflater.inflate(R.layout.activity_custom_teachername_spinner, parent, false);
TextView label=(TextView)convertView.findViewById(R.id.textView1);
label.setText(teacherNameList.get(position).getTeacherName());
return convertView;
}
file.xml of CustomAdapter
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="TextView" />
What I got in Output

Just add the getCount and getItem(int pos) methods in your adapter class as below which returns the size of arraylist and item which is going to be inflated into your spinner as below:
#Override
public int getCount() {
return teacherNameList .size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return teacherNameList.get(position);
}

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.

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.

ListView is not appearing - Fetching Data from Server

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.

Blank activity using ListView and Adapter

I am learning to use ListViews with Adapters.
The codes I am posting here are from one of the tutorials from
Here
This is my class(Equivalent to MainActvity class in tutorial) in which I am intialising a ListView and providing data to adapter.
setContentView(R.layout.searchresultrowlayout);
try {
jsonarray1=searchscreen.searchresults();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<HashMap<String, String>> propertylist=new ArrayList<HashMap<String, String>> ();
for(int i=0;i<jsonarray1.length();i++){
HashMap<String,String> propertymap=new HashMap<String,String> ();
try {
jsonobject=jsonarray1.getJSONObject(i);
Log.d("json", jsonobject.getString("id"));
propertymap.put("propertytype",jsonobject.getString("propertytype") );
propertylist.add(propertymap);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
list=(ListView)findViewById(R.id.list);
adapter=new PropertySearchArrayAdapter(this,propertylist);
// Log.d("adapter", propertylist.get(1).get("price").toString());
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
and this is my adapter class
public class PropertySearchArrayAdapter extends BaseAdapter{
private Activity activity;
private ArrayList<HashMap<String,String>> data;
private static LayoutInflater inflater=null;
//public ImageLoader imageloader;
public PropertySearchArrayAdapter(Activity context, ArrayList<HashMap<String,String>> d){
activity=context;
data=d;
inflater=(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position,View convertview, ViewGroup parent){
View rowview=convertview;
if(convertview==null){
rowview=inflater.inflate(R.layout.searchlist_row, null);}
//ViewHolder viewholder=new ViewHolder();
TextView propertyType=(TextView) rowview.findViewById(R.id.propertytype); //propertytype
HashMap<String,String> property= new HashMap<String,String> ();
property= data.get(position);
propertyType.setText(property.get("propertytype"));
Log.d("adaptertext", property.get("propertytype"));
return rowview;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
}
These are XMLs
searchresultrowlayout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector" />
</LinearLayout>
searchlist_row
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:orientation="horizontal"
android:padding="5dip" >
<!-- Property type-->
<TextView
android:id="#+id/propertytype"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#040404"
android:typeface="sans"
android:textSize="15dip"
android:textStyle="bold"/>
</RelativeLayout>
The other XMLs list_selector,gradient_bg.xml,gradient_bg_hover.xml I have taken from the tutorial itself.
My problem is when I am pushing my activity which is supposed to show list view(by intent from previous activity on button click), the screen that appears is completely black and blank.
Please help me out.
If you want the ListView to show the data your adapter must return the number of items it contains(or wants to show) with the getCount() method and not 0(in which case the adapter will be considered empty and nothing will be shown):
#Override
public int getCount() {
return data.size();
}

I have created a dynamic ListView - how do I connect it to my XML layout file?

Hi all and thank you for taking a look at this. I have created a dynamic ListView using android's developer guide. Currently, the ListView activity seems to display itself on screen without the need for an XML file or setContentView...which is a problem.
I would like to use an XML layout, so I can go and add other Views to the screen, rather than dedicating an entire Activity to just displaying the list. I created an XML layout, that contains a blank ListView, amongst other things and I want my list to go into that allotted space...so my question: How do I get my ListActivity to use my layout XML file?
public class MainList extends ListActivity {
static SharedPreferences statusSettings;
String jsonString;
static JSONObject json;
static JSONArray arrayTest;
static int bob = 3;
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
try {
JSONObject e = arrayTest.getJSONObject(position);
Intent intent = new Intent();
intent.putExtra("clientName", e.getString("proj_name"));
intent.putExtra("clientAddress", e.getString("c_address"));
intent.putExtra("clientComments", e.getString("comments"));
intent.putExtra("clientOrder", e.getString("order"));
intent.setClass(MainList.this, ClientDetails.class);
MainList.this.startActivity(intent);
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e("JSON", "Problem creating object from array!");
e.printStackTrace();
}
}
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return arrayTest.length();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.mainlist, null);
holder = new ViewHolder();
holder.textName = (TextView) convertView.findViewById(R.id.tvMainName);
holder.textAddress = (TextView) convertView.findViewById(R.id.tvMainAddress);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
JSONObject e;
try {
e = arrayTest.getJSONObject(position);
holder.textName.setText(e.getString("proj_name"));
holder.textAddress.setText(e.getString("c_address"));
switch (statusSettings.getInt(e.getString("order"), 0)){
case 1:
convertView.setBackgroundColor(0x00000000);
break;
case 2:
if(bob == 3){
convertView.setBackgroundColor(0xFFFF6600);
bob = 5;
}
break;
case 3:
convertView.setBackgroundColor(0xFF00CC00);
break;
case 4:
convertView.setBackgroundColor(0xFFCC0000);
break;
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
Log.e("JSON", "Couldn't put one of JSON arrays into object");
e1.printStackTrace();
}
return convertView;
}
static class ViewHolder {
TextView textName;
TextView textAddress;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
jsonString = getIntent().getExtras().getString("jsonString");
try {
json = new JSONObject(jsonString);
arrayTest = json.getJSONArray("client_list");
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e("JSON", "Couldn't create the JSON Array");
e.printStackTrace();
}
setListAdapter(new EfficientAdapter(this));
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
bob = 3;
statusSettings = getSharedPreferences("status", 0);
setListAdapter(new EfficientAdapter(this));
}
}
XML File:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_weight="1">
</ListView>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
The thing is, they create it without using any XML layout - I don't fully understand how, but I assume it has something to do with the LayoutInflater. I tried:
convertView = mInflater.inflate(R.id.list, null);
instead of
convertView = mInflater.inflate(R.layout.mainlist, null);
and I placed setContentView(R.layout.test);
in my onCreate...but didn't work. Any help you offer would be much appreciated, thank you!
This is pretty Simple. I have quick generated some code for your reference.
public class ListandtextActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String [] str = {"ONE","TWO","THREE"};
final ListView lv = (ListView) findViewById(R.id.listView1);
final TextView tv = (TextView)findViewById(R.id.tv1);
lv.setAdapter(new ArrayAdapter<Object>(getApplicationContext(), android.R.layout.simple_list_item_1, str));
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
tv.setText("You Clicked Something");
}
});
}
}
And in your XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tv1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Feel free to ask if you have any doubts.

Categories

Resources