I have a TextView and RatingBar in ListView, and i want to save value of RatingBar on each list in ListView, it is possible with custom adapter??
the code I use to do likes:
PertanyaanAdapter.java
package flix.yudi.pertanyaan3;
import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.RatingBar;
import android.widget.TextView;
import java.util.List;
class PertanyaanAdapter extends ArrayAdapter<Pertanyaan> {
private AppCompatActivity activity;
private List<Pertanyaan> movieList;
PertanyaanAdapter(AppCompatActivity context, int resource, List<Pertanyaan> objects) {
super(context, resource, objects);
this.activity = context;
this.movieList = objects;
}
#Override
public Pertanyaan getItem(int position) {
return movieList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_listview, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
//holder.ratingBar.getTag(position);
}
holder.ratingBar.setOnRatingBarChangeListener(onRatingChangedListener(position));
holder.ratingBar.setTag(position);
holder.ratingBar.setRating(getItem(position).getRatingStar());
holder.movieName.setText(getItem(position).getAsk());
return convertView;
}
private RatingBar.OnRatingBarChangeListener onRatingChangedListener(final int position) {
return new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
Pertanyaan item = getItem(position);
assert item != null;
item.setRatingStar(v);
Log.i("Adapter", "star: " + v);
}
};
}
private static class ViewHolder {
private RatingBar ratingBar;
private TextView movieName;
ViewHolder(View view) {
ratingBar = (RatingBar) view.findViewById(R.id.rate_img);
movieName = (TextView) view.findViewById(R.id.text);
}
}
}
Pertanyaan.java
package flix.yudi.pertanyaan3;
public class Pertanyaan {
private float ratingStar;
private String ask;
Pertanyaan(int ratingStar, String ask) {
this.ratingStar = ratingStar;
this.ask = ask;
}
float getRatingStar() {
return 0;
}
void setRatingStar(float ratingStar) {
this.ratingStar = ratingStar;
}
public String getAsk() {
return ask;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<Pertanyaan> listPertanyaan;
ArrayAdapter<Pertanyaan> adapter2;
ProgressDialog pDialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.list_view);
listPertanyaan = new ArrayList<>();
getpertanyaan get= new getpertanyaan();
get.execute();
adapter2 = new PertanyaanAdapter(this, R.layout.item_listview, listPertanyaan);
listView.setAdapter(adapter2);
}
protected void onStart() {
super.onStart();
}
private class getpertanyaan extends AsyncTask<Void, Void, Integer> {
ArrayList<Pertanyaan> list;
protected void onPreExecute() {
pDialog=new ProgressDialog(MainActivity.this);
pDialog.setTitle("Nama Dosen");
pDialog.setMessage("Menampilkan nama dosen... Mohon tunggu...!");
pDialog.setCancelable(false);
pDialog.show();
super.onPreExecute();
list = new ArrayList<>();
}
#Override
protected Integer doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://flix.16mb.com/send_data.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
} catch (IOException e) {
e.printStackTrace();
}
//convert response to string
try {
BufferedReader reader = null;
if (is != null) {
reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
}
String line;
if (reader != null) {
while ((line = reader.readLine()) != null) {
result += line;
}
}
if (is != null) {
is.close();
}
//result=sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
list.add(new Pertanyaan(0,jsonObject.getString("ask")));
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Integer result) {
if (pDialog.isShowing())
pDialog.dismiss();
listPertanyaan.addAll(list);
adapter2.notifyDataSetChanged();
}
}
}
but when I run the app, the RatingBar is untouchable, just each list of ListView is touch however I want to tap the RatingBar.
did I doing something wrong? help me please.
EDIT :
item_listview.xml
<RatingBar
android:id="#+id/rate_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/text"
android:numStars="5"
android:stepSize="1"
style="#style/Widget.AppCompat.RatingBar.Indicator" />
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold" />
the RatingBar is read-only because of the style you are using.
style="#style/Widget.AppCompat.RatingBar.Indicator"
sets the attribute android:isIndicator to true which makes behave it, in the way are experiencing. You can either get rid of the line, or try to force android:isIndicator to false in your item_listview.xml
Related
I am having a little trouble with listview, I want to get values of listview whose checkbox are selected when button is clicked. till now i have created a listview with checkboxes and fetched all the values from mysql but i am not able to get values of listview which are checked.
This is my class
public class ListViewMultipleSelectionActivity extends Activity{
Button button;
String myJSON;
private static final String TAG_NAME = "cat_name";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
personList = new ArrayList<HashMap<String,String>>();
list1 = (ListView) findViewById(R.id.list);
button = (Button)findViewById(R.id.testbutton);
getlat();
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public void getlat(){
class GetDataJSON extends AsyncTask<String, Void, String> {
public void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
InputStream inputStream = null;
String result = null;
try {
URL url = new URL("http://xxxxxxxxxxxx/category.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder("");
String line="";
while ((line = in.readLine()) != null)
{
sb.append(line).append("\n");
}
result = sb.toString();
}
assert inputStream != null;
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).append("\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("tagconvertstr", "["+result+"]");
System.out.println(e);
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
protected void showList(){
try {
peoples = new JSONArray(myJSON);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String name = c.getString(TAG_NAME);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,name);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
ListViewMultipleSelectionActivity.this, personList, R.layout.result,
new String[]{TAG_NAME},
new int[]{R.id.name}
);
list1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
list1.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
main.xml
<?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" >
<Button
android:id="#+id/testbutton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Submit" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#id/testbutton"
android:layout_alignParentTop="true"/>
</RelativeLayout>
result.xml
<?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="wrap_content"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/cbBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical" >
</CheckBox>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:orientation="vertical"
android:layout_weight="1" >
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textStyle="bold"/>
</LinearLayout>
</LinearLayout>
i have implemented this on testbutton(Button) click please check
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SparseBooleanArray checked = list1.getCheckedItemPositions();
ArrayList<String> selectedItems = new ArrayList<String>();
for (int i = 0; i < checked.size(); i++) {
int position = checked.keyAt(i);
if (checked.valueAt(i))
selectedItems.add((String) adapter.getItem(position));
}
String[] valuess = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
valuess[i] = selectedItems.get(i);
}
Toast.makeText(ListViewMultipleSelectionActivity.this, String.valueOf(valuess), Toast.LENGTH_SHORT).show();
}
});
this is i am getting after click
E/-->>>>: [Ljava.lang.String;#ca01299
What you can do is creating a custom class to store these values along with a custom adapter that supports it. So whenever you click the button you can call the given function to retrieve the statuses of those items. Example architecture given below:
PS: Since I don't know what you want to do with checked values, I left you there with comments which you can change with your need.
MainActivity.java
package com.rencsaridogan.stackoverflow;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<ExampleClass> objects;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
objects = new ArrayList<>();
for (int i = 0; i < 10; i++){
objects.add(new ExampleClass("Example Name " + i));
}
final ListView listView = (ListView) findViewById(R.id.listView);
final Button testButton = (Button) findViewById(R.id.testButton);
final ExampleAdapter exampleAdapter = new ExampleAdapter(this, R.layout.list_cell, objects);
listView.setAdapter(exampleAdapter);
exampleAdapter.notifyDataSetChanged();
testButton.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
getCheckedItems();
}
});
}
private void getCheckedItems(){
for (int i = 0; i < 10; i++) {
if (objects.get(i).isChecked()){
Log.i("MainActivity",i + " is checked");
/**
* Value is checked, do what you need to do here
*/
} else {
Log.i("MainActivity",i + " is NOT checked");
/**
* Value is NOT checked
*/
}
}
}
}
ExampleAdapter.java
package com.rencsaridogan.stackoverflow;
import android.annotation.SuppressLint;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by rencsaridogan on 16/02/2017.
*/
public class ExampleAdapter extends ArrayAdapter<ExampleClass> {
ArrayList<ExampleClass> objects;
Listener listener;
Context context;
public ExampleAdapter(Context context, int resource, ArrayList<ExampleClass> objects) {
super(context, resource);
this.context = context;
this.objects = objects;
}
#Override public int getViewTypeCount() {
return super.getViewTypeCount();
}
#Override public int getCount() {
return objects.size();
}
#SuppressLint("InflateParams") #Override public View getView(int position, View convertView, #NonNull ViewGroup parent) {
if (convertView == null){
Log.i("ExampleAdapter","ConvertView inflated");
convertView = LayoutInflater.from(context).inflate(R.layout.list_cell, null, false);
}
Log.i("ExampleAdapter","Setting of values");
final ExampleClass data = objects.get(position);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.textView = (TextView) convertView.findViewById(R.id.textView);
viewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
viewHolder.textView.setText(data.getName());
viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
data.setChecked(isChecked);
}
});
return convertView;
}
public void setListener(Listener listener) {
this.listener = listener;
}
private class ViewHolder {
TextView textView;
CheckBox checkBox;
}
public ArrayList<ExampleClass> getObjects() {
return objects;
}
public void setObjects(ArrayList<ExampleClass> objects) {
this.objects = objects;
notifyDataSetChanged();
}
#Override public long getItemId(int position) {
return super.getItemId(position);
}
public interface Listener {
void onCheckedChanged(int position);
}
}
ExampleClass.java
package com.rencsaridogan.stackoverflow;
/**
* Created by rencsaridogan on 16/02/2017.
*/
public class ExampleClass {
String name;
boolean isChecked;
public ExampleClass(String name) {
this.name = name;
}
public ExampleClass(String name, boolean isChecked) {
this.name = name;
this.isChecked = isChecked;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean checked) {
isChecked = checked;
}
}
Set checkbox object as tag to your row view that might be your 'convertView' in getView() method of your adapter.
Write on click listener on your row view.
3.Inside that click-listener to row view getTag from view that's parameter in onClick method and cast it to checkbox and then setChecked to true for that checkbox object.
code might look like this,
convertView.setTag(yourCheckBoxObject);
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v.getTag();
cb.setChecked(true);
}
});
Please refer this sight for more information Getting an issue while checking the dynamically generated checkbox through list view
In your Adapter there was one #override method called getView() in that method you will get the current item which you will clicked
holder.checkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
CheckBox checkBox=(CheckBox) view;
String tagName="";
if(checkBox.isChecked()){
tagName=checkBox.getTag().toString();
deleteServices.add(tagName);
checkboxArrayList.add(checkBox);
}else {
checkboxArrayList.remove(checkBox);
tagName=checkBox.getTag().toString();
if(deleteServices.size()>0&&deleteServices.contains(tagName)){
deleteServices.remove(tagName);
}
});
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I can't resolve this problem. I want to add search functionality by EditText. Results should dynamically display after typing letters but now there is no results.
Thanks for Your quick response :)
ParkingActivity.java
public class ParkingActivity extends FragmentActivity {
private final String URL_TO_HIT = "http://www-users.mat.umk.pl/~discordia/dane.json";
private ListView lvParking;
private EditText inputSearch;
public ParkingAdapter adapter;
public ArrayList<ParkingModel> parkingModelList = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_activity);
lvParking = (ListView) findViewById(R.id.lvParking);
inputSearch = (EditText) findViewById(R.id.editText);
new JSONTask().execute(URL_TO_HIT);
}
public class JSONTask extends AsyncTask<String,String, List<ParkingModel> > {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<ParkingModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("parkingInfo");
ArrayList<ParkingModel> parkingModelList = new ArrayList<>();
Gson gson = new Gson();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
/**
* below single line of code from Gson saves you from writing the json parsing yourself which is commented below
*/
ParkingModel parkingModel = gson.fromJson(finalObject.toString(), ParkingModel.class);
parkingModelList.add(parkingModel);
}
return parkingModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(final List<ParkingModel> result) {
super.onPostExecute(result);
if(result != null) {
adapter = new ParkingAdapter(getApplicationContext(), R.layout.row, result);
lvParking.setAdapter(adapter);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
ParkingActivity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
lvParking.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ParkingModel parkingModel = result.get(position);
Intent intent = new Intent(ParkingActivity.this, DetailActivity.class);
intent.putExtra("parkingModel", new Gson().toJson(parkingModel));
startActivity(intent);
}
});
}
}
}
public class ParkingAdapter extends ArrayAdapter {
private List<ParkingModel> parkingModelList;
private int resource;
private LayoutInflater inflater;
public ParkingAdapter(Context context, int resource, List<ParkingModel> objects) {
super(context, resource, objects);
parkingModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
holder = new ViewHolder();
convertView = inflater.inflate(resource, null);
holder.tvLokalizacja = (TextView)convertView.findViewById(R.id.tvLokalizacja);
holder.tvIle_wolnych_zwyklych = (TextView)convertView.findViewById(R.id.tvIle_wolnych_zwyklych);
holder.tvIle_wszystkich_zwyklych = (TextView)convertView.findViewById(R.id.tvIle_wszystkich_zwyklych);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvLokalizacja.setText(parkingModelList.get(position).getLokalizacja());
holder.tvIle_wolnych_zwyklych.setText("Wolne: " + parkingModelList.get(position).getIle_wolnych_zwyklych());
holder.tvIle_wszystkich_zwyklych.setText("Wszystkie:" + parkingModelList.get(position).getIle_wszystkich_zwyklych());
return convertView;
}
class ViewHolder{
private TextView tvLokalizacja;
private TextView tvIle_wolnych_zwyklych;
private TextView tvIle_wszystkich_zwyklych;
}
}
#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_parking, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
}
This is my model which I use to create final array with data.
ParkingModel.java
public class ParkingModel {
private String lokalizacja;
private int ile_wolnych_zwyklych;
private int ile_wszystkich_zwyklych;
public String getLokalizacja() {
return lokalizacja;
}
public void setLokalizacja(String lokalizacja) {
this.lokalizacja = lokalizacja;
}
public int getIle_wolnych_zwyklych() {
return ile_wolnych_zwyklych;
}
public void setIle_wolnych_zwyklych(int ile_wolnych_zwyklych) {
this.ile_wolnych_zwyklych = ile_wolnych_zwyklych;
}
public int getIle_wszystkich_zwyklych() {
return ile_wszystkich_zwyklych;
}
public void setIle_wszystkich_zwyklych(int ile_wszystkich_zwyklych) {
this.ile_wszystkich_zwyklych = ile_wszystkich_zwyklych;
}
}
Here is my xml file.
list_activity.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:orientation="vertical"
tools:context=".ParkingActivity">
<EditText
android:layout_width="319dp"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:inputType="text"
android:layout_gravity="center_horizontal" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lvParking" />
</LinearLayout>
Because in onPostExecute of JSONTask you have created new object of ParkingAdapter class and below that
ParkingActivity.this.adapter.getFilter().filter(cs); you are using this line.
this is always null;
To set adapter just use
adapter = new ParkingAdapter(getApplicationContext(), R.layout.row, result);
lvParking.setAdapter(adapter);
change this line
ParkingAdapter adapter = new ParkingAdapter(getApplicationContext(), R.layout.row, result);
To This
adapter = new ParkingAdapter(getApplicationContext(), R.layout.row, result);
i was tring to load image using url.a single url is working properly. but i need to add a few more images to this page.i need to add this image s to a list view.pls tell me how can i add a string array to this code.
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class FareCrd extends Activity {
String image_url="http://movito.nervov.com/img/ace-hd.png";
String[] mString ={"http://movito.nervov.com/img/ace-hd.png",
"http://movito.nervov.com/img/Movito_Logo_M.png"};
JSONArray jsonary;
ListView list;
private Activity activity;
private String[] data;
private static View inflater=null;
//private String[] mStrings={"http://movito.nervov.com/img/ace-hd.png"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fare_crd);
list=(ListView)findViewById(R.id.farelist);
new ServConn().execute();
}
private void parsedata(String data){
//System.out.println(data);
try {
JSONObject json = new JSONObject(data);
jsonary = json.getJSONArray("data");
ListView list = (ListView) findViewById(R.id.farelist);
list.setAdapter(new DriverOrderList(getApplicationContext(),
R.layout.farecrd, new JSONObject[jsonary.length()]));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class DriverOrderList extends ArrayAdapter<JSONObject> {
int listViewResource;
public DriverOrderList(Context context, int resource, JSONObject[] s) {
super(context, resource, s);
listViewResource = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(listViewResource, parent, false);
ImageLoader imgLoader = new ImageLoader(getApplicationContext());
JSONObject rowdata = new JSONObject();
int loader = R.drawable.stub;
try {
rowdata = jsonary.getJSONObject(position);
System.out.println(rowdata);
ImageLoader imgLoader1 = new ImageLoader(getApplicationContext());
ImageView img=(ImageView) row.findViewById(R.id.imgid);
imgLoader.DisplayImage(image_url, loader, img);
TextView nameTxt = (TextView) row.findViewById(R.id.truckname);
TextView idTxt = (TextView) row.findViewById(R.id.id);
TextView minrttv =(TextView) row.findViewById(R.id.minimumRate);
TextView kmrttxt =(TextView) row.findViewById(R.id.kilometerRate);
TextView mindurtv=(TextView) row.findViewById(R.id.minimumDuration);
TextView freewatintim = (TextView) row.findViewById(R.id.freeWaitingTime);
TextView minuterttxt =(TextView) row.findViewById(R.id.minuteRate);
TextView watingchrttv =(TextView)row.findViewById(R.id.waitingCharge);
double freewt=(Double) rowdata.get("freeWaitingTime");
double kmratetxt=(Double) rowdata.get("kilometerRate");
double mindurtxt=(Double) rowdata.get("minimumDuration");
double mindur= mindurtxt/60;
double minkmrttxt=(Double) rowdata.get("minimumKilometer");
double minrttxt=(Double) rowdata.get("minimumRate");
double mintrate=(Double) rowdata.get("minuteRate");
double minutrat=mintrate/60;
double watingchrtxt=(Double) rowdata.get("waitingCharge");
double waitchgunittxt=(Double) rowdata.get("waitingChargeUnit");
nameTxt.setText(rowdata.getString("truckModel"));
minrttv.setText("Rs."+minrttxt+" /-");
kmrttxt.setText("Rs."+kmratetxt+"/km after "+minkmrttxt+"km");
mindurtv.setText("first"+mindur+"hr and "+minkmrttxt+"km");
//minuterttxt.setText(minutrat+"/-");
freewatintim.setText("first "+freewt+"min free");
watingchrttv.setText("RS"+watingchrtxt+"after every "+waitchgunittxt+"min");
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return row;
}
}
private class ServConn extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
System.out.println("do in backgrnd");
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://movito.nervov.com/v1/trucks/miniTruckCategories");
httpget.setHeader(HTTP.CONTENT_TYPE, "application/json");
String replyString = "";
try {
HttpResponse response = httpclient.execute(httpget);
replyString = EntityUtils.toString(response
.getEntity());
} catch (ClientProtocolException e) {
System.out.println("ex: " + e);
} catch (IOException e) {
System.out.println("e: " + e);
}
return replyString;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
System.out.println(result);
result = "{\"data\":"+result+"}";
parsedata(result);
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
}
Try to use Glide libreries instead od picasso .It might help full for you.Please look at following link which might help you out.
http://inthecheesefactory.com/blog/get-to-know-glide-recommended-by-google/en
try this code I am using Picasso library to populate ImageView,
if you are using android studio add this library using following code into your gradle file
compile 'com.squareup.picasso:picasso:2.5.2'
use following code,
It is complete example of how you can make a custom ListView, I didn't include code where you have to get he JSON data from WebService as i didn't want to make the code complicated, I will write a separate code where i will show how to read the data you are interested in.
XML
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#+id/CustomListViewActivity_listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
single_item.xml layout
<?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="50dp"
android:orientation="horizontal">
<TextView
android:id="#+id/single_item_textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:layout_weight="0.5"
android:text="New Text" />
<ImageView
android:id="#+id/single_item_imageView"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="4dp"
android:layout_weight="0.5" />
</LinearLayout>
Code
public class CustomListViewActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_list_view);
ArrayList<SingleItem> singleItems = new ArrayList<>();
singleItems.add(new SingleItem("http://movito.nervov.com/img/ace-hd.png","first Text"));
singleItems.add(new SingleItem("http://movito.nervov.com/img/Movito_Logo_M.png","Second Text"));
singleItems.add(new SingleItem("http://movito.nervov.com/img/ace-hd.png","third Text"));
singleItems.add(new SingleItem("http://movito.nervov.com/img/Movito_Logo_M.png","fourth Text"));
ListView listView = (ListView)findViewById(R.id.CustomListViewActivity_listView);
MyAdapter adapter = new MyAdapter(getApplicationContext(), R.layout.single_item,singleItems);
listView.setAdapter(adapter);
}
private class MyAdapter extends ArrayAdapter {
private ArrayList<SingleItem> singleItems;
private LayoutInflater layoutInflater;
private Context context;
private View single_View;
public MyAdapter(Context context, int resource, ArrayList<SingleItem> singleItems) {
super(context, resource, singleItems);
this.context = context;
this.singleItems = singleItems;
layoutInflater = LayoutInflater.from(this.context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
row = layoutInflater.inflate(R.layout.single_item, parent, false);
holder = new ViewHolder();
holder.textView = (TextView) row.findViewById(R.id.single_item_textView);
holder.imageView = (ImageView) row.findViewById(R.id.single_item_imageView);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final SingleItem singleItem = singleItems.get(position);
holder.textView.setText("" + singleItem.getText());
Picasso.with(context).load(""+singleItem.getUrl()).into(holder.imageView);
return row;
}
private class ViewHolder {
// Instance Variable (state or data)
TextView textView;
ImageView imageView;
}
}
public class SingleItem {
private String url;
private String text;
public SingleItem() {
}
public SingleItem(String url, String text) {
this.url = url;
this.text = text;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
}
Output
As you will see the loading the images from the URL provided to the appropriate ImageView is taken care by Picasso, do make sure you add the permission for the internet in the AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
I have a custom adapter and I need to use it in onPostExecute method to populate a ListView with an image and a text.
This is the Custom Adapter
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class MyAdapter extends BaseAdapter {
private Activity mActivity;
private ArrayList listaElementi;
private static LayoutInflater infilater = null;
public MyAdapter( Activity a, ArrayList list) {
mActivity = a;
listaElementi = list;
infilater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return listaElementi.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if( convertView == null )
vi = infilater.inflate(R.layout.riga, null);
TextView nome = (TextView) vi.findViewById(R.id.nome);
ImageView immagine = (ImageView) vi.findViewById(R.id.immagine);
Riga rigaCorrente = (Riga) listaElementi.get(position);
nome.setText(rigaCorrente.getNome());
immagine.setImageDrawable(mActivity.getResources().getDrawable(rigaCorrente.getImmagine()));
return vi;
}
}
This is my onPostExecute method:
private class LongOperation extends AsyncTask<String, String, JSONObject> {
//Other methods here
protected void onPostExecute(JSONObject result) {
JSONObject jobj = null;
JSONArray elenco_cartelle = null;
try {
jobj = new JSONObject(String.valueOf(result));
} catch (JSONException e) {
e.printStackTrace();
}
//Provo a recuperare i campi json
try {
elenco_cartelle = jobj.getJSONArray("elenco");
} catch (JSONException e) {
e.printStackTrace();
}
ArrayList<Riga> arrayCartelle = new ArrayList<Riga>();
//DEvo scorrere le'elenco delle cartelle
for (int i = 0; i < elenco_cartelle.length(); i++) {
try {
String nome = elenco_cartelle.getString(i);
arrayCartelle.add( new Riga( nome , R.drawable.ic_launcher ) );
} catch (JSONException e) {
e.printStackTrace();
}
}
MyAdapter myAdapter = new MyAdapter(CartelleActivity.class,arrayCartelle);
mainListView.setAdapter(myAdapter);
// Close progress dialog
Dialog.dismiss();
}
}
And this is my Riga class
public class Riga {
String nome;
Integer idImmagine;
public Riga( String nome, Integer idImmagine ) {
super();
this.nome = nome;
this.idImmagine = idImmagine;
}
public String getNome() {
return this.nome;
}
public Integer getImmagine() {
return this.idImmagine;
}
public void setNome( String nome ) {
this.nome = nome;
}
public void setIdImmagine( Integer idImmagine ) {
this.idImmagine = idImmagine;
}
}
The problem is on this line:
MyAdapter myAdapter = new MyAdapter(CartelleActivity.class,arrayCartelle);
The IDE ( AndroidStudio ) says that I can't use CartelleActivity.
How can I use my Adapter?
SOLVED.
Used:
CartelleActivity.this
instead
CartelleActivity.class
Theres something fishy in your code. Try to define your ArrayList in your adapter by changing it to ArrayList<Riga> :
private Activity mActivity;
private ArrayList<Riga> listaElementi;
private static LayoutInflater infilater = null;
public MyAdapter( Activity a, ArrayList<Riga> list) {
mActivity = a;
listaElementi = list;
infilater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public class LongOperation extends AsyncTask<String, String, JSONObject> {
private Activity a;
public CustomAsync(Activity a) {
this.a = a;
}
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
MyAdapter myAdapter = new MyAdapter(a, new ArrayList());
}
}
Ok this is my first every android app so don't bash me. I am very open to suggestion if I am doing anything wrong or weird so please don't be shy. I'm have a little bit of trouble updating my listview after I click on an item. Anyways here's the code... I just don't understand how it works I think...
[ MainActivity.java ]
package com.mycompany.myapp2;
import android.app.*;
import android.os.*;
import android.text.method.*;
import android.view.*;
import android.widget.*;
import android.content.*;
import java.util.*;
import java.io.*;
public class MainActivity extends ListActivity
{
public CustomAdapter adapterMain;
private FtpConnectionTask ftpTask;
private LayoutInflater mInflater;
private Vector<RowData> data;
private TextView textView;
#Override
public void onCreate( Bundle savedInstanceState )
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView) findViewById(R.id.txtView);
textView.setMovementMethod(new ScrollingMovementMethod());
xBins(textView);
}
/*public void addItems( ListView parent )
{
CustomAdapter adapter = (CustomAdapter) parent.getAdapter();
RowData rd = new RowData("item4", "description4");
data.add(rd);
rd = new RowData("item5", "description5");
data.add(rd);
rd = new RowData("item6", "description6");
data.add(rd);
CustomAdapter adapter = new CustomAdapter(this, R.layout.row, R.id.item, data);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}*/
public void onListItemClick( ListView parent, View v, int position, long id )
{
ftpTask.row = ftpTask.adapter.getItem(position);
String ftpItem = ftpTask.row.mItem;
if ( ftpTask.row.mDescription == "dir" )
{
String[] args = new String[] { ftpItem };
Object[] aObject = new Object[] { "cd", args, this };
//ftpTask.adapter.clear();
//ftpTask.processCmd(aObject);
}
}
private class RowData
{
protected String mItem;
protected String mDescription;
RowData( String item, String description )
{
mItem = item;
mDescription = description;
}
#Override
public String toString( )
{
return mItem + " " + mDescription;
}
}
private class CustomAdapter extends ArrayAdapter<RowData>
{
public CustomAdapter( Context context, int resource,
int textViewResourceId, List<RowData> objects )
{
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView( int position, View convertView, ViewGroup parent )
{
ViewHolder holder = null;
//widgets displayed by each item in your list
TextView item = null;
TextView description = null;
//data from your adapter
RowData rowData= getItem(position);
//we want to reuse already constructed row views...
if ( null == convertView )
{
convertView = mInflater.inflate(R.layout.row, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
//
holder = (ViewHolder) convertView.getTag();
item = holder.getItem();
item.setText(rowData.mItem);
description = holder.getDescription();
description.setText(rowData.mDescription);
return convertView;
}
}
/**
* Wrapper for row data.
*
*/
private class ViewHolder
{
private View mRow;
private TextView description = null;
private TextView item = null;
public ViewHolder( View row )
{
mRow = row;
}
public TextView getDescription( )
{
if ( null == description )
{
description = (TextView) mRow.findViewById(R.id.description);
}
return description;
}
public TextView getItem( )
{
if ( null == item )
{
item = (TextView) mRow.findViewById(R.id.item);
}
return item;
}
}
public void xBins( View view )
{
IrcConnectionTask task = new IrcConnectionTask();
task.execute(new Object[] { "irc.efnet.pl", 6667, "sgd5", this });
}
}
[ IrcConnectionTask.java ]
package com.mycompany.myapp2;
import android.os.*;
import java.io.*;
import java.net.*;
public class IrcConnectionTask extends AsyncTask<Object, String, String>
{
MainActivity callerActivity;
private Socket socket;
#Override
protected String doInBackground(Object... params)
{
String response = "";
String host = (String)params[0];
Integer port = (Integer)(params[1]);
String nick = (String)params[2];
callerActivity = (MainActivity)params[3];
try
{
socket = new Socket(host, port);
String msg1 = "NICK " + nick;
String msg2 = "USER sur 8 * :be";
String messages[] = { msg1, msg2 };
InputDumper task = new InputDumper();
task.execute(new Object[] { socket, messages, nick, callerActivity});
}
catch ( UnknownHostException e )
{
e.printStackTrace();
}
catch ( IOException e )
{
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result)
{
//textView.setText(result);
}
#Override
protected void onProgressUpdate(String result)
{
//textView.setText(result);
}
}
[ InputDumper.java ]
package com.mycompany.myapp2;
import android.os.*;
import android.text.*;
import java.io.*;
import java.net.*;
import android.widget.*;
public class InputDumper extends AsyncTask<Object, String, String>
{
MainActivity callerActivity;
private String response = "";
private Integer i = 0;
private Boolean Connected = false;
protected String doInBackground(Object... params)
{
try
{
Socket socket = (Socket)params[0];
String messages[] = (String[])params[1];
String nickname = (String)params[2];
callerActivity = (MainActivity) params[3];
//Pattern pattern = Pattern.compile("USERNAME: (.*)");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg;
while ((msg = bufferedReader.readLine()) != null)
{
if (msg.indexOf("USERNAME:") > 0)
{
new FtpConnectionTask().execute(new Object[] { nickname, "emulation", callerActivity });
publishProgress("FTP CONNECTION STARTED!!!");
}
if (msg.startsWith("PING"))
{
String PONG = "PONG " + msg.substring(msg.indexOf(":"));
new OutputWriter().execute(new Object[] { socket, PONG, callerActivity });
Connected = true;
}
else if (i == 4)
{
for (String message : messages)
{
new OutputWriter().execute(new Object[] { socket, message, callerActivity });
}
}
else if (i == 13) //msg.endsWith("servers"))
{
new OutputWriter().execute(new Object[] { socket, "JOIN #xbins", callerActivity });
}
else if (i == 20)
{
new OutputWriter().execute(new Object[] { socket, "PRIVMSG #xbins :!list", callerActivity });
}
response += msg;
publishProgress(msg);
i++;
}
}
catch (IOException e )
{
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result)
{
//textView.setText(result);
}
private TextView textView;
#Override
protected void onProgressUpdate(String... progress)
{
textView = (TextView) callerActivity.findViewById(R.id.txtView);
textView.append(Html.fromHtml("<font color='green'>" + progress[0] + "</font><br />"));
final int scrollAmount = textView.getLayout().getLineTop(textView.getLineCount())
- textView.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if (scrollAmount > 0)
textView.scrollTo(0, scrollAmount);
else
textView.scrollTo(0, 0);
}
}
[ OutputWriter.java ]
package com.mycompany.myapp2;
import android.os.*;
import android.text.*;
import java.io.*;
import java.net.*;
import android.widget.*;
public class OutputWriter extends AsyncTask<Object, String, String>
{
MainActivity callerActivity;
private String response = "";
protected String doInBackground(Object... params)
{
try
{
Socket socket = (Socket)params[0];
String message = (String)params[1];
callerActivity = (MainActivity)params[2];
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bufferedWriter.write(message + "\n\r");
bufferedWriter.flush();
publishProgress(message);
}
catch (IOException e )
{
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result)
{
//textView.setText(result);
}
private TextView textView;
#Override
protected void onProgressUpdate(String... progress)
{
textView = (TextView) callerActivity.findViewById(R.id.txtView);
textView.append(Html.fromHtml("<font color='red'>" + progress[0] + "</font><br />"));
final int scrollAmount = textView.getLayout().getLineTop(textView.getLineCount())
- textView.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if (scrollAmount > 0)
textView.scrollTo(0, scrollAmount);
else
textView.scrollTo(0, 0);
}
}
[ FtpConnectionTask.java ]
package com.mycompany.myapp2;
import android.os.*;
import android.text.*;
import android.util.*;
import android.widget.*;
import java.io.*;
import org.apache.commons.io.*;
import org.apache.commons.net.ftp.*;
import java.util.*;
import android.view.*;
import android.content.*;
import android.app.*;
public class FtpConnectionTask extends AsyncTask<Object, String, String>
{
public static CustomAdapter adapter;
public static RowData row;
MainActivity callerActivity;
private LayoutInflater mInflater;
public Vector<RowData> data;
private FTPClient mFTPClient = new FTPClient();
protected String doInBackground( Object... params )
{
try
{
if ( mFTPClient.isConnected() )
{
Log.v("TESTING", "Is connected");
String cmd = (String)params[0];
String[] args = (String[])params[1];
callerActivity = (MainActivity) params[2];
if (cmd == "cd")
{
mFTPClient.changeWorkingDirectory(args[0].toString());
String[] names = mFTPClient.listNames();
listRemote(names);
}
}
else
{
String user = (String)params[0];
String pass = (String)params[1];
callerActivity = (MainActivity) params[2];
mFTPClient.connect("distribution.xbins.org");
mFTPClient.login(user, pass);
mFTPClient.enterLocalActiveMode();
mFTPClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
publishProgress("WORKING DIR: " + mFTPClient.printWorkingDirectory());
publishProgress("LOGGED IN");
String[] names = mFTPClient.listNames();
listRemote(names);
FTPFile[] remoteFiles = mFTPClient.listFiles();
for ( FTPFile remoteFile : remoteFiles ) //int i = 0; i < remoteFiles.length; i++)
{
if ( remoteFile.getType() == FTPFile.FILE_TYPE )
{
String name = remoteFile.getName();
long length = remoteFile.getSize();
String readableLength = FileUtils.byteCountToDisplaySize(length);
publishProgress(name + ":\t\t" + readableLength);
}
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
final void listRemote(final String... params)
{
callerActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
mInflater = (LayoutInflater) callerActivity.getSystemService(callerActivity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
for ( String name : params )
{
row = new RowData(name, "dir");
data.add(row);
}
adapter = new CustomAdapter(callerActivity, R.layout.row, R.id.item, data);
callerActivity.setListAdapter(adapter);
callerActivity.getListView().setTextFilterEnabled(true);
}
});
}
private TextView textView;
#Override
protected void onProgressUpdate( String... progress )
{
textView = (TextView) callerActivity.findViewById(R.id.txtView);
textView.append(Html.fromHtml("<font color='yellow'>" + progress[0] + "</font><br />"));
final int scrollAmount = textView.getLayout().getLineTop(textView.getLineCount())
- textView.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if ( scrollAmount > 0 )
textView.scrollTo(0, scrollAmount);
else
textView.scrollTo(0, 0);
}
public class RowData
{
protected String mItem;
protected String mDescription;
RowData( String item, String description )
{
mItem = item;
mDescription = description;
}
#Override
public String toString( )
{
return mItem + " " + mDescription;
}
}
public class CustomAdapter extends ArrayAdapter<RowData>
{
public CustomAdapter( Context context, int resource,
int textViewResourceId, List<RowData> objects )
{
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView( int position, View convertView, ViewGroup parent )
{
ViewHolder holder = null;
//widgets displayed by each item in your list
TextView item = null;
TextView description = null;
//data from your adapter
RowData rowData= getItem(position);
//we want to reuse already constructed row views...
if ( null == convertView )
{
convertView = mInflater.inflate(R.layout.row, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
//
holder = (ViewHolder) convertView.getTag();
item = holder.getItem();
item.setText(rowData.mItem);
description = holder.getDescription();
description.setText(rowData.mDescription);
return convertView;
}
}
/**
* Wrapper for row data.
*
*/
public class ViewHolder
{
private View mRow;
private TextView description = null;
private TextView item = null;
public ViewHolder( View row )
{
mRow = row;
}
public TextView getDescription( )
{
if ( null == description )
{
description = (TextView) mRow.findViewById(R.id.description);
}
return description;
}
public TextView getItem( )
{
if ( null == item )
{
item = (TextView) mRow.findViewById(R.id.item);
}
return item;
}
}
}
[ row.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="wrap_content"
android:background="#00000000">
<TextView
android:id="#+id/item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"/>
<TextView
android:id="#+id/description"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false" />
</LinearLayout>
[ main.xml ]
<?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" >
<TextView
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
android:id="#+id/txtView"
android:maxLines = "5"
android:scrollbars = "vertical" />
<ListView
android:id="#android:id/list"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_below="#+id/txtView" />
</RelativeLayout>