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.
Related
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'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);
}
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.
From what I can gather it appears that this might be because my ListView is not being displayed, I've verified that getCount is returning a value not zero, but I can't see what I'm doing wrong.
Everything loads and acts like it's working but the ListView never appears, I put a background color on the fragment reference in mixed.xml and it is there and taking up the full screen, but when I set a background color on my ListView it does not appear, it's like it's not being rendered at all.
More odd, getView is not being called in my adapter, and this is all working code from regular activities that I ported to fragments.
I've tried calling notifyDataSetChanged which didn't changed anything, debugging shows the adapter is filled with data and getCount is indeed returning an accurate count greater than 0.
Thanks for any help, I'm stuck.
Project is open and can be viewed here http://code.google.com/p/shack-droid/source/browse/#svn%2FTrunk but I'm also including the pertinent code here.
This is the ListFragment:
public class FragmentTopicView extends ListFragment implements ShackGestureEvent {
private ArrayList<ShackPost> posts;
private String storyID = null;
private String errorText = "";
private Integer currentPage = 1;
private Integer storyPages = 1;
private String loadStoryID = null;
private Boolean threadLoaded = true;
private Hashtable<String, String> postCounts = null;
private AdapterLimerifficTopic tva;
public FragmentTopicView() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.topics, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final ShackGestureListener listener = Helper.setGestureEnabledContentView(R.layout.topics, getActivity());
if (listener != null) {
listener.addListener(this);
}
if (savedInstanceState == null) {
// get the list of topics
GetChattyAsyncTask chatty = new GetChattyAsyncTask(getActivity());
chatty.execute();
}
ListView lv = getListView();
lv.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// start loading the next page
if (threadLoaded && firstVisibleItem + visibleItemCount >= totalItemCount && currentPage + 1 <= storyPages) {
// get the list of topics
currentPage++;
GetChattyAsyncTask chatty = new GetChattyAsyncTask(getActivity());
chatty.execute();
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
});
}
class GetChattyAsyncTask extends AsyncTask<String, Void, Void> {
protected ProgressDialog dialog;
protected Context c;
public GetChattyAsyncTask(Context context) {
this.c = context;
}
#Override
protected Void doInBackground(String... params) {
threadLoaded = false;
try {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
final String feedURL = prefs.getString("shackFeedURL", getString(R.string.default_api));
final URL url;
if (loadStoryID != null) {
if (currentPage > 1)
url = new URL(feedURL + "/" + loadStoryID + "." + currentPage.toString() + ".xml");
else
url = new URL(feedURL + "/" + loadStoryID + ".xml");
}
else {
if (currentPage > 1)
url = new URL(feedURL + "/" + storyID + "." + currentPage.toString() + ".xml");
else
url = new URL(feedURL + "/index.xml");
}
// Get a SAXParser from the SAXPArserFactory.
final SAXParserFactory spf = SAXParserFactory.newInstance();
final SAXParser sp = spf.newSAXParser();
// Get the XMLReader of the SAXParser we created.
final XMLReader xr = sp.getXMLReader();
// Create a new ContentHandler and apply it to the XML-Reader
SaxHandlerTopicView saxHandler = new SaxHandlerTopicView(c, "topic");
xr.setContentHandler(saxHandler);
// Parse the xml-data from our URL.
xr.parse(new InputSource(HttpHelper.HttpRequestWithGzip(url.toString(), c)));
// Our ExampleHandler now provides the parsed data to us.
if (posts == null) {
posts = saxHandler.GetParsedPosts();
}
else {
ArrayList<ShackPost> newPosts = saxHandler.GetParsedPosts();
newPosts.removeAll(posts);
posts.addAll(posts.size(), newPosts);
}
storyID = saxHandler.getStoryID();
storyPages = saxHandler.getStoryPageCount();
if (storyPages == 0) // XML returns a 0 for stories with only
// one page
storyPages = 1;
}
catch (Exception ex) {
// TODO: implement error handling
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (currentPage == 1)
dialog = ProgressDialog.show(getActivity(), null, "Loading Chatty", true, true);
else
SetLoaderVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ShowData();
SetLoaderVisibility(View.GONE);
try {
dialog.dismiss();
}
catch (Exception e) {
}
}
}
private void ShowData() {
if (posts != null) {
Hashtable<String, String> tempHash = null;
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
final String login = prefs.getString("shackLogin", "");
final int fontSize = Integer.parseInt(prefs.getString("fontSize", "12"));
try {
postCounts = GetPostCache();
}
catch (Exception ex) {
}
if (postCounts != null)
tempHash = new Hashtable<String, String>(postCounts);
if (tva == null) {
tva = new AdapterLimerifficTopic(getActivity(), R.layout.lime_topic_row, posts, login, fontSize, tempHash);
setListAdapter(tva);
}
else {
tva.SetPosts(posts);
tva.notifyDataSetChanged();
}
final ListView lv = getListView();
lv.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Options");
menu.add(0, 1, 0, "Copy Post Url to Clipboard");
menu.add(0, 2, 0, "Watch Thread");
menu.add(0, 3, 0, "Thread Expires In?");
menu.add(0, 4, 0, "Shacker's Chatty Profile");
}
});
// update the reply counts for the listing of topics
try {
UpdatePostCache();
}
catch (Exception e) {
}
}
else {
if (errorText.length() > 0) {
try {
new AlertDialog.Builder(getActivity()).setTitle("Error").setPositiveButton("OK", null).setMessage(errorText).show();
}
catch (Exception ex) {
// could not create a alert for the error for one reason
// or another
Log.e("ShackDroid", "Unable to create error alert ActivityTopicView:468");
}
}
}
threadLoaded = true;
}
}
Here's my FragmentActivity:
public class FragmentActivityTopic extends FragmentActivity {
#Override
protected void onCreate(Bundle arg) {
// TODO Auto-generated method stub
super.onCreate(arg);
setContentView(R.layout.mixed);
}
}
This is the Adapter I'm using, and as mentioned above getView is not being called:
public class AdapterLimerifficTopic extends BaseAdapter {
// private Context context;
private List<ShackPost> topicList;
private final int rowResouceID;
private final String shackLogin;
private final Typeface face;
private final int fontSize;
private final Hashtable<String, String> postCache;
private final String showAuthor;
private final Resources r;
private int totalNewPosts = 0;
LayoutInflater inflate;// = LayoutInflater.from(context);
public AdapterLimerifficTopic(Context context, int rowResouceID, List<ShackPost> topicList, String shackLogin, int fontSize, Hashtable<String, String> postCache) {
this.topicList = topicList;
this.rowResouceID = rowResouceID;
this.shackLogin = shackLogin;
this.fontSize = fontSize;
this.postCache = postCache;
this.r = context.getResources();
face = Typeface.createFromAsset(context.getAssets(), "fonts/arial.ttf");
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
showAuthor = prefs.getString("showAuthor", "count");
inflate = LayoutInflater.from(context);
}
public void SetPosts(List<ShackPost> posts)
{
topicList = posts;
}
#Override
public int getCount() {
return topicList.size();
}
#Override
public Object getItem(int position) {
return topicList.get(position);
}
#Override
public long getItemId(int position) {
// return position;
final ShackPost post = topicList.get(position);
return Long.parseLong(post.getPostID());
}
static class ViewHolder {
TextView posterName;
TextView datePosted;
TextView replyCount;
TextView newPosts;
TextView postText;
TextView viewCat;
RelativeLayout topicRow;
ImageView postTimer;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TextView tmp;
// final View v;
ViewHolder holder;
final ShackPost post = topicList.get(position);
if (convertView == null) {
convertView = inflate.inflate(rowResouceID, parent, false);
holder = new ViewHolder();
holder.posterName = (TextView) convertView.findViewById(R.id.TextViewLimeAuthor);
holder.datePosted = (TextView) convertView.findViewById(R.id.TextViewLimePostDate);
holder.replyCount = (TextView) convertView.findViewById(R.id.TextViewLimePosts);
holder.newPosts = (TextView) convertView.findViewById(R.id.TextViewLimeNewPosts);
holder.postText = (TextView) convertView.findViewById(R.id.TextViewLimePostText);
holder.viewCat = (TextView) convertView.findViewById(R.id.TextViewLimeModTag);
// holder.topicRow = (RelativeLayout) convertView.findViewById(R.id.TopicRow);
// holder.postTimer = (ImageView) convertView.findViewById(R.id.ImageViewTopicTimer);
// holder.posterName.setTypeface(face);
// holder.datePosted.setTypeface(face);
// holder.replyCount.setTypeface(face);
// holder.newPosts.setTypeface(face);
holder.postText.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize);
// holder.postText.setTypeface(face);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
// holder.postTimer.setImageResource(Helper.GetTimeLeftDrawable(post.getPostDate()));
//
holder.posterName.setText(post.getPosterName());
//
// if (shackLogin.equalsIgnoreCase(post.getPosterName()))
// holder.posterName.setTextColor(Color.parseColor("#00BFF3"));
// else
// holder.posterName.setTextColor(Color.parseColor("#ffba00"));
//
holder.datePosted.setText(Helper.FormatShackDateToTimePassed(post.getPostDate()));
holder.replyCount.setText(post.getReplyCount());
//
// if (showAuthor.equalsIgnoreCase("count") && post.getIsAuthorInThread())
// holder.replyCount.setTextColor(Color.parseColor("#0099CC"));
// else
// holder.replyCount.setTextColor(Color.parseColor("#FFFFFF"));
// clipped code
holder.postText.setText(preview);
// if (showAuthor.equalsIgnoreCase("topic") && post.getIsAuthorInThread()) {
// final Drawable d = r.getDrawable(R.drawable.background_gradient_blue);
// holder.topicRow.setBackgroundDrawable(d);
// }
// else
// holder.topicRow.setBackgroundDrawable(null);
// TODO: clean this up a little / also replicated in ShackDroidThread ick
final String postCat = post.getPostCategory();
holder.viewCat.setVisibility(View.VISIBLE);
if (postCat.equals("offtopic")) {
holder.viewCat.setText("offtopic");
holder.viewCat.setBackgroundColor(Color.parseColor("#444444"));
}
else if (postCat.equals("nws")) {
holder.viewCat.setText("nws");
holder.viewCat.setBackgroundColor(Color.parseColor("#CC0000"));
}
else if (postCat.equals("political")) {
holder.viewCat.setText("political");
holder.viewCat.setBackgroundColor(Color.parseColor("#FF8800"));
}
else if (postCat.equals("stupid")) {
holder.viewCat.setText("stupid");
holder.viewCat.setBackgroundColor(Color.parseColor("#669900"));
}
else if (postCat.equals("informative")) {
holder.viewCat.setText("interesting");
holder.viewCat.setBackgroundColor(Color.parseColor("#0099CC"));
}
else
holder.viewCat.setVisibility(View.GONE);
return convertView;
}
public int getTotalNewPosts() {
return totalNewPosts;
}
}
And related XML:
mixed.xml (this is the layout for the fragments, only the one for now)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:id="#+id/LinearLayoutMixed">
<fragment
android:id="#+id/MixedThreads"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="com.stonedonkey.shackdroid.FragmentTopicView"
>
</fragment>
</LinearLayout>
Topics.xml (this contains the ListView as well as a sliding tray and some other stuff.
<?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="fill_parent" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/TopicLoader"
android:divider="#333333"
android:dividerHeight="1dip"
android:textColor="#FFFFFF"
/>
<RelativeLayout
android:id="#+id/TopicLoader"
android:layout_width="fill_parent"
android:layout_height="35dip"
android:layout_alignParentBottom="true"
android:gravity="center_horizontal"
android:visibility="gone"
android:layout_marginTop="5dip" >
<TextView
android:id="#+id/TextViewTopicLoaderText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Loading"
>
</TextView>
<ImageView
android:id="#+id/ImageViewTopicLoader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/TextViewTopicLoaderText"
android:src="#drawable/ic_action_refresh"
android:layout_alignBottom="#+id/TextViewTopicLoaderText"
/>
</RelativeLayout>
<SlidingDrawer
android:id="#+id/SlidingDrawer01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/TopicLoader"
android:animateOnClick="true"
android:content="#+id/bookMarkParent"
android:handle="#+id/TextViewTrayHandle"
android:orientation="vertical"
android:paddingTop="200dip"
android:visibility="gone" >
<TextView
android:id="#+id/TextViewTrayHandle"
android:layout_width="fill_parent"
android:layout_height="35dip"
android:background="#drawable/darkgrey_gradient"
android:focusable="false"
android:focusableInTouchMode="false"
android:gravity="center_vertical" >
</TextView>
<RelativeLayout
android:id="#id/bookMarkParent"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ListView
android:id="#+id/ListViewWatchedThreads"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#333333"
android:dividerHeight="1dip"
android:textColor="#FFFFFF" >
</ListView>
</RelativeLayout>
</SlidingDrawer>
</RelativeLayout>
and finally lime_topic_row which is my custom row layout for the ListView in the above layout:
<?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="match_parent"
android:orientation="vertical"
android:background="#FF0000" >
<TextView
android:id="#+id/TextViewLimeModTag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FF0000"
android:layout_alignParentLeft="true"
android:layout_marginLeft="10dip"
android:textColor="#000000"
android:padding="2dip"
android:textSize="10dip"
/>
<TextView
android:id="#+id/TextViewLimePostText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minHeight="20dip"
android:padding="10dip"
android:layout_below="#+id/TextViewLimeModTag"
android:textColor="#FFFFFF" />
<TextView
android:id="#+id/TextViewLimeAuthor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/TextViewLimePostText"
android:paddingBottom="10dip"
android:paddingLeft="10dip"
android:textColor="#0099CC" />
<TextView
android:id="#+id/TextViewPosted"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/TextViewLimePostText"
android:layout_toRightOf="#+id/TextViewLimeAuthor"
android:paddingBottom="10dip"
android:text=" posted " />
<TextView
android:id="#+id/TextViewLimePostDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/TextViewLimePostText"
android:layout_toRightOf="#+id/TextViewPosted"
android:paddingBottom="10dip"
android:paddingRight="10dip"
android:textColor="#FF8800" />
<TextView
android:id="#+id/TextViewLimePosts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/TextViewLimePostDate"
android:layout_marginRight="3dip"
android:layout_below="#+id/TextViewLimePostText"
android:layout_marginBottom="15dip"
android:layout_toLeftOf="#+id/TextViewLimeNewPosts"
android:background="#BBBBBB"
android:padding="3dip"
android:minWidth="25dip"
android:gravity="center"
android:textColor="#000000" />
<TextView
android:id="#+id/TextViewLimeNewPosts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/TextViewLimePostDate"
android:layout_below="#+id/TextViewLimePostText"
android:layout_marginBottom="15dip"
android:layout_marginRight="10dip"
android:background="#669900"
android:padding="3dip"
android:minWidth="25dip"
android:gravity="center"
android:layout_alignParentRight="true"
android:textColor="#000000" />
</RelativeLayout>
I think I found the problem. The issue appears because of the ShackGestureListener that you setup at the start of the onActivityCreated method in the FragmentTopicView:
final ShackGestureListener listener = Helper.setGestureEnabledContentView(R.layout.topics, getActivity());
if (listener != null) {
listener.addListener(this);
}
In the setGestureEnabledContentView() method you check to see if the user enabled the gestures in the preferences or if the android version is bigger then 3. Either way, true or false you set the content view for the FragmentActivityTopic again(with the layout of the FragmentTopicView). Setting the content view again will, unfortunately, cover the current layout which holds the ListView with data(ListView that populates with no problems). When you run those AsyncTasks to get the data, at the end you set the data on the correct ListView(returned by getListView) because the getListView will hold a reference to the old correct ListView which was set in the onCreateView method, but you don't see anything because in the setGestureEnabledContentView you cover this ListView.
This behavior is easy to see if you simple comment out(or remove) the lines that set the content view for the activity in the Helper and HelperAPI4 classes. Another way to see that your ListView is covered is, for example to set the adapter for the ListView(tva) using getListView and using the getActivity().findViewById(android.R.id.list)(I've done this on selecting one of your menus items, so I can control when I replace the adapter):
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId())
{
case R.id.topic_menu_newpost: // Launch post form
//this doesn't work as the getListView will return a reference to the old ListView
ListView lv = getListView();
lv.setAdapter(tva);
// this will work as you get a reference to the new ListView on top
ListView lv = (ListView) getActivity().findViewById(android.R.id.list);
lv.setAdapter(tva);
I don't know what to recommend as a solution as I don't quite understand what you're doing, but I doubt that it requires to set the content view for the activity again(and you should work from this).
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.