I have retrieved data from a remote db using json and i have created a custom listView with this data. I have three TextView and one CheckBox and it works perfectly. So, i have added a button that would control selected items in list and eventually transfer selected item in another activity. Problem was solved as suggested,but if i scroll list, selected items losts status.I think it depends from horder or adapter. Can someone help me? Here is my code
public class Activity2 extends ActionBarActivity implements OnItemClickListener {
TextView txtLavorante;
TextView txtCodice;
Intent currIntent;
ListView list;
String myJSON;
ArrayList <String> checkedValue;
private ProgressDialog pDialog;
private static final String TAG_RESULTS="result";
private static final String TAG_ID = "ID";
private static final String TAG_NAME = "Descrizione";
private static final String TAG_PRICE ="Costo";
private static final String TAG_TIME ="Durata_m";
JSONArray serv_man = null;
ArrayList<HashMap<String, String>> list_serv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity2);
list = (ListView) findViewById(R.id.listView);
currIntent = getIntent();
txtLavorante = (TextView) findViewById (R.id.Lavorante);
txtCodice = (TextView) findViewById(R.id.CodiceLavorante);
stampaValori();
list_serv = new ArrayList<HashMap<String,String>>();
getData();
}
#Override
public void onItemClick(AdapterView arg0, View v, int position, long arg3) {
CheckBox cb = (CheckBox) v.findViewById(R.id.checkBox);
TextView tv = (TextView) v.findViewById(R.id.textView);
cb.performClick();
if (cb.isChecked()) {
checkedValue.add(tv.getText().toString());
Log.i("Btn Test",""+checkedValue);
} else if (!cb.isChecked()) {
checkedValue.remove(tv.getText().toString());
}
}
private void stampaValori() {
String pkg = getApplicationContext().getPackageName();
String tCode = "ID: " + currIntent.getStringExtra(pkg + "ID") + "\n";
String tNome = "Collaboratore scelto: " + currIntent.getStringExtra(pkg + "LAV") + "\n";
txtLavorante.setText(tNome);
txtCodice.setText(tCode);
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
serv_man = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<serv_man.length();i++){
JSONObject c = serv_man.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String price = c.getString(TAG_PRICE);
String time = c.getString(TAG_TIME);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_ID,id);
persons.put(TAG_NAME,name);
persons.put(TAG_PRICE,price);
persons.put(TAG_TIME,time);
list_serv.add(persons);
}
list = (ListView) findViewById(R.id.listView);
list.setAdapter(new ListatoAdapter(Activity2.this, list_serv));
list.setOnItemClickListener(Activity2.this);
Button b= (Button) findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(Activity2.this, "TEST" + checkedValue, Toast.LENGTH_LONG).show();
Log.i ("Test ",""+checkedValue);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://www.example.com/.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
Log.i ("Servizi","serv:"+result);
} catch (Exception e) {
// Oops
Log.e("log_tag", "Error converting result " + e.toString());
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Activity2.this);
pDialog.setMessage("Obtaining list...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected void onPostExecute(String result){
pDialog.dismiss();
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_activity2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
ListatoAdapter
public class ListatoAdapter extends BaseAdapter {
private LayoutInflater layoutinflater;
private Context context;
ArrayList<HashMap<String, String>> dataList;
boolean [] itemChecked;
public ListatoAdapter(Context context, ArrayList<HashMap<String, String>> list_serv) {
super();
this.context = context;
this.dataList = list_serv;
itemChecked = new boolean [dataList.size()];
}
#Override
public int getCount() {
return dataList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.prenota_serv, null);
holder = new ViewHolder();
holder.service = (TextView)convertView.findViewById(R.id.et_serv);
holder.id = (TextView)convertView.findViewById(R.id.et_id);
holder.costo = (TextView)convertView.findViewById(R.id.et_costo);
holder.durata = (TextView)convertView.findViewById(R.id.et_dur);
holder.Ceck = (CheckBox)convertView.findViewById(R.id.checkBox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.service.setText(dataList.get(position).get("Descrizione"));
holder.id.setText(dataList.get(position).get("ID"));
holder.costo.setText(dataList.get(position).get("Costo"));
holder.durata.setText(dataList.get(position).get("Durata_m"));
holder.Ceck.setChecked(false);
if (itemChecked[position])
holder.Ceck.setChecked(true);
else
holder.Ceck.setChecked(false);
holder.Ceck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (holder.Ceck.isChecked())
itemChecked[position] = true;
else
itemChecked[position] = false;
Log.i("Adapter Test",""+itemChecked[position]);
}
});
return convertView;
}
class ViewHolder {
TextView service;
TextView id;
TextView costo;
TextView durata;
CheckBox Ceck;
}
}
Activity2.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="net.puntosys.www.customadaptertest.Activity2"
android:orientation="vertical">
<TextView android:text="hello_word" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Lavorante"
android:textStyle="bold"
android:textSize="22dp" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_gravity="right" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/CodiceLavorante"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:visibility="invisible" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView" />
prenota_serv.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Servizio:"
android:textSize="7pt"
android:id="#+id/tv_serv"
android:layout_alignBottom="#+id/tv_id"
android:layout_alignLeft="#+id/tv_id"
android:layout_alignStart="#+id/tv_id" />
<EditText
android:background="#android:drawable/editbox_background"
android:layout_height="wrap_content"
android:layout_width="190dip"
android:id="#+id/et_serv"
android:layout_gravity="center_horizontal"
android:textSize="7pt"
android:layout_alignBottom="#+id/et_id"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Costo Euro:"
android:textSize="7pt"
android:id="#+id/tv_cost"
android:layout_below="#+id/et_serv"
android:layout_alignLeft="#+id/tv_serv"
android:layout_alignStart="#+id/tv_serv" />
<EditText
android:background="#android:drawable/editbox_background"
android:layout_height="wrap_content"
android:layout_width="120dip"
android:id="#+id/et_costo"
android:layout_gravity="center_horizontal"
android:layout_below="#+id/et_serv"
android:layout_alignLeft="#+id/et_serv"
android:layout_alignStart="#+id/et_serv"
android:textSize="7pt" />
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Durata min:"
android:textSize="7pt"
android:id="#+id/tv_dur"
android:layout_below="#+id/et_costo"
android:layout_alignLeft="#+id/tv_cost"
android:layout_alignStart="#+id/tv_cost" />
<EditText
android:background="#android:drawable/editbox_background"
android:layout_height="wrap_content"
android:layout_width="70dip"
android:id="#+id/et_dur"
android:layout_gravity="center_horizontal"
android:textSize="7pt"
android:layout_alignTop="#+id/tv_dur"
android:layout_alignLeft="#+id/et_costo"
android:layout_alignStart="#+id/et_costo" />
<TextView
android:layout_marginTop="5dip"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Nr:"
android:layout_marginLeft="5dip"
android:layout_marginRight="9dip"
android:layout_alignParentLeft="true"
android:textSize="10pt"
android:id="#+id/tv_id"
android:visibility="invisible" />
<EditText
android:background="#android:drawable/editbox_background"
android:layout_height="wrap_content"
android:layout_width="70dip"
android:id="#+id/et_id"
android:layout_gravity="center_horizontal"
android:layout_alignTop="#+id/tv_id"
android:layout_alignLeft="#+id/et_serv"
android:layout_alignStart="#+id/et_serv"
android:enabled="false"
android:elegantTextHeight="false"
android:visibility="invisible" />
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="CheckBox"
android:layout_below="#+id/tv_dur"
android:layout_alignRight="#+id/et_serv"
android:layout_alignEnd="#+id/et_serv" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/textView"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/tv_dur"
android:layout_alignStart="#+id/tv_dur" />
when user select a check box, put its corresponding data to a list.and send the list in bundle on button click.and receive it on another activity with the key.
you need to create a list like.
ArrayList<HashMap<String, String>> list_selected;
public ListatoAdapter(Context context, ArrayList<HashMap<String, String>> list_serv) {
super();
this.context = context;
this.dataList = list_serv;
list_selected = new ArrayList<HashMap<String, String>>();
}
change the listener as.
holder.Ceck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
HashMap<String,String> data = dataList.get(position);
if(isChecked){
addToSelected(data);
}else{
removeSelected(data);
}
}
});
private void addToSelected(HashMap contact){
if(!list_selected.contains(contact))list_selected.add(contact);
}
private boolean removeSelected(HashMap contact){
return list_selected.remove(contact);
}
public ArrayList<HashMap<String, String>> getSelectedItems(){
return list_selected;
}
access the list from activity as adapter.getSelectedItems();.
declare it in your activity as global
ListatoAdapter adapter;
set adapter in this way.
adapter = new ListatoAdapter(Activity2.this, list_serv);
list.setAdapter(adapter);
and get the list in button Click as.
ArrayList<HashMap<String,String> list = adapter.getSelectedItems();
Related
This is my screenshot:
This is my adapter class:
public class ListofAddressesAdapter extends ArrayAdapter<ListofAddressesDataModel> {
private Context context;
private int layoutResourceId;
HashMap<Integer, Integer> hashMap;
private List<ListofAddressesDataModel> data;
int selectedPosition = 0;
String name, phone, address;
String customeraddressid;
public ListofAddressesAdapter(Context context, int layoutResourceId,
List<ListofAddressesDataModel> data) {
super(context, R.layout.listofaddresses, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
hashMap = new HashMap<Integer, Integer>();
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
View row = convertView;
final ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.name = (TextView) row.findViewById(R.id.tvsubservices);
holder.description = (TextView) row.findViewById(R.id.tvdesc);
holder.fulladd = (TextView) row.findViewById(R.id.tvfulladdr);
holder.r = (RadioButton) row.findViewById(R.id.radioButton);
holder.delet = (ImageView) row.findViewById(R.id.ivdelete);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final ListofAddressesDataModel item = data.get(position);
holder.name.setText(item.getName());
holder.description.setText(item.getPhone());
holder.fulladd.setText(item.getFulladdress());
holder.r.setChecked(position == selectedPosition);
holder.r.setTag(position);
holder.r.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedPosition = (Integer) view.getTag();
name = data.get(selectedPosition).getName();
phone = data.get(selectedPosition).getPhone();
address = data.get(selectedPosition).getFulladdress();
customeraddressid = data.get(selectedPosition).getCustaddid();
notifyDataSetChanged();
}
});
return row;
}
static class ViewHolder {
TextView name;
TextView description;
TextView fulladd;
RadioButton r;
ImageView delet;
}
public Object getItemAtPosition(int position) {
// TODO Auto-generated method stub
return null;
}
}
This is my activity class:
public class testclass extends Activity implements View.OnClickListener{
List<ListofAddressesDataModel> lstDataModel;
ListView add;
JSONArray _jsonarray;
JSONObject jsonObject;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
add = (ListView) findViewById(R.id.add);
setContentView(R.layout.test);
add=(ListView)findViewById(R.id.add);
lstDataModel=new ArrayList<>();
button=(Button)findViewById(R.id.button);
button.setOnClickListener(this);
new manageaddresses().execute();
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.button)
{
}
}
class manageaddresses extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
String response = JSONfunctions.getJSONfromURL("http://cpanel.smartindiaservice.com/api/CustomerAddresses?CustomerID=4");
try {
_jsonarray = new JSONArray(response);
for (int i = 0; i < _jsonarray.length(); i++) {
ListofAddressesDataModel datamodel = new ListofAddressesDataModel();
jsonObject = _jsonarray.getJSONObject(i);
String customeraddressid = jsonObject.getString("CustomerAddressID");
datamodel.setCustaddid(customeraddressid);
String fullname = jsonObject.getString("FullName");
datamodel.setName(fullname);
String housenumber = jsonObject.getString("HouseNumber");
String phonenumber = jsonObject.getString("PhoneNumber");
datamodel.setPhone(phonenumber);
String area = jsonObject.getString("Area");
String landmark = jsonObject.getString("Landmark");
String city = jsonObject.getString("City");
String fulladdress = housenumber + "," + " " + area + "," + " " + landmark + "," + " " + city;
datamodel.setFulladdress(fulladdress);
lstDataModel.add(datamodel);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
ListofAddressesAdapter adapter = new ListofAddressesAdapter(testclass.this, R.layout.listofaddresses, lstDataModel);
add.setAdapter(adapter);
adapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}
}
This is my item.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal"
android:paddingBottom="20dp">
<RadioButton
android:id="#+id/radioButton"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:buttonTint="#999999"
android:text="New RadioButton" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout4"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:orientation="vertical"
android:paddingBottom="10dp">
<TextView
android:id="#+id/tvsubservices"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/radioButton"
android:layout_marginLeft="50dp"
android:layout_toRightOf="#+id/radioButton"
android:text="TextView"
android:textColor="#000000"
android:textSize="18dp" />
<TextView
android:id="#+id/tvdesc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvsubservices"
android:layout_marginLeft="50dp"
android:layout_toRightOf="#+id/radioButton"
android:text="Description"
android:textColor="#000000"
android:textSize="14dp" />
<TextView
android:id="#+id/tvfulladdr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvdesc"
android:layout_marginLeft="50dp"
android:layout_toRightOf="#+id/radioButton"
android:text="New Text"
android:textColor="#000000"
android:textSize="14dp" />
<TextView
android:id="#+id/custaddidposition"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="position"
android:visibility="gone" />
</LinearLayout>
</RelativeLayout>
I want to get selected radio button position or value and id so that on button click I tried with but it always take first position. Can any one suggest me where am I doing wrong? I have to get selected radio button position so that I can get value from list of Objects. I have to send into next activity.
In adapter create a method which returns the object of selected position. Like :
public ListofAddressesDataModel getSelectedItem() {
return data.get(selectedPosition);
}
In activity, on click of the button call this method. Like :
#Override
public void onClick(View v) {
if(v.getId() == R.id.button) {
//Here you will get the selected item of which the radio button is checked
ListofAddressesDataModel selectedItem = ((ListofAddressesAdapter) add.getAdapter()).getSelectedItem();
}
}
EDIT :
Instead of below lines in getView() in adapter
holder.r.setTag(position);
holder.r.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedPosition = (Integer) view.getTag();
name = data.get(selectedPosition).getName();
phone = data.get(selectedPosition).getPhone();
address = data.get(selectedPosition).getFulladdress();
customeraddressid = data.get(selectedPosition).getCustaddid();
notifyDataSetChanged();
}
});
just replace it with below line
holder.r.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedPosition = position;
}
});
I have an activity with CustomAdapter ListView and TabLayout with three tabs TrainerTab1, TrainerTab2, TrainerTab3. While clicking on an item it should move to next page that is to TrainerTab1 Fragment.
I need to pass the id from ListView onClick() to fragment page. I have used Bundle to pass value but the items are not working. When I click on an item it's not responding and not showing any error.
My custom ListView Class is:
public class Trainer extends AppCompatActivity {
String tabUrl = "http://adoxsolutions.in/numuww/services/trainers";
private GridView gridView;
ArrayList<HashMap<String, String>> alist = new ArrayList<>();
private TrainAdapter adapter;
private ProgressDialog mprogress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trainer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
new Train().execute();
}
private class Train extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
mprogress = new ProgressDialog(Trainer.this);
mprogress.setMessage("Loading...");
mprogress.setIndeterminate(false);
mprogress.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL(tabUrl);
HttpURLConnection connect = (HttpURLConnection) url.openConnection();
connect.setRequestMethod("POST");
//
System.out.println("Response Code:" + connect.getResponseCode());
InputStream in = new BufferedInputStream(connect.getInputStream());
String response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
System.out.println(response);
Log.d("VALUE:", response);
JSONObject obj = new JSONObject(response);
JSONArray jsArray = obj.optJSONArray("Trainers");
for (int k = 0; k < jsArray.length(); k++) {
HashMap<String, String> map = new HashMap<String, String>();
obj = jsArray.getJSONObject(k);
map.put("id", obj.getString("id"));
map.put("name", obj.getString("name"));
map.put("logo", obj.getString("img"));
alist.add(map);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
gridView = (GridView) findViewById(R.id.trainerGrid);
adapter = new TrainAdapter(getBaseContext(), alist);
gridView.setAdapter(adapter);
adapter.notifyDataSetChanged();
mprogress.dismiss();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.newc, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_search) {
return true;
}
else if(id == android.R.id.home){
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
class TrainAdapter extends BaseAdapter {
private Context context;
private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();
public TrainAdapter(Context c, ArrayList<HashMap<String, String>> list){
context = c;
MyArr = list;
}
#Override
public int getCount() {
return MyArr.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.trainer_list, null);
}
TextView id= (TextView) convertView.findViewById(R.id.trainerId);
ImageView image = (ImageView) convertView.findViewById(R.id.trainerImage);
TextView text = (TextView) convertView.findViewById(R.id.trainerTexts);
try {
image.setImageBitmap(loadBitmap(MyArr.get(position).get("logo")));
text.setText(MyArr.get(position).get("name"));
id.setText(MyArr.get(position).get("id"));
if (((position - 9) / 3) % 9 == 0) {
ImageView adimg = (ImageView) convertView.findViewById(R.id.trainadBanner);
adimg.setScaleType(ImageView.ScaleType.FIT_XY);
adimg.getLayoutParams().height=150;
adimg.getLayoutParams().width=300;
adimg.setImageResource(R.drawable.mainad);
}
} catch (Exception e) {
e.printStackTrace();
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle h=new Bundle();
h.putString("id",MyArr.get(position).get("id"));
Fragment tt1=new TrainerTab1();
tt1.setArguments(h);
}
});
// }else{
// convertView=inflater.inflate(R.layout.trainer_list, parent,false);
// ImageView image= (ImageView) convertView.findViewById(R.id.trainerImage);
// TextView text= (TextView) convertView.findViewById(R.id.trainerTexts);
// try{
// image.setImageResource(R.drawable.ic_action_name);
// text.setText(MyArr.get(position).get("name"));
// if(position % 9 == 0){
// ImageView adimg= (ImageView) convertView.findViewById(R.id.trainadBanner);
// adimg.setImageResource(R.drawable.mainad);
// }
//
// } catch(Exception e){
// e.printStackTrace();
// }
return convertView;
}
private static final String TAG = "ERROR";
private static final int IO_BUFFER_SIZE = 4 * 1024;
private static Bitmap loadBitmap(String tabUrl) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(tabUrl).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + tabUrl);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
android.util.Log.e(TAG, "Could not close stream", e);
}
}
}
private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
}
}
My tab fragment:
public class TrainerTab1 extends Fragment {
String turl="http://adoxsolutions.in/numuww/services/trainer";
TextView tname,tplace,tsex;
public TrainerTab1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView= inflater.inflate(R.layout.fragment_trainer_tab1, container, false);
final String tid=getArguments().getString("id");
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
tname= (TextView) rootView.findViewById(R.id.trainerCourse);
tplace= (TextView) rootView.findViewById(R.id.trainerPlace);
tsex= (TextView) rootView.findViewById(R.id.trainerSex);
ImageView photo= (ImageView) rootView.findViewById(R.id.trainer_photo);
}
}
Inside the onClickListener
after adding the bundle to the fragment.
FragmentManager fragmentManager = Trainer.this.getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.someIDForYourFrameLayout, tt1).commit();
can you just ellaborate where to use this exactly. I mean I don't understand how to add id of fragment to transaction.add(R.id.someIDForYourFrameLayout, tt1).commit();
I tried like this:
Bundle h=new Bundle();
h.putString("id",MyArr.get(position).get("id"));
Fragment tt1=new TrainerTab1();
tt1.setArguments(h);
FragmentTransaction transact=getSupportFragmentManager().beginTransaction();
transact.add(R.id.trainerFragment,tt1).commit();
This is my fragment_trainer_tab_1 layout:
<ScrollView 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:scrollbars="vertical"
android:scrollbarSize="1dp"
android:id="#+id/trainerFragment"
tools:context="com.example.anu.numuww.TrainerTab1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="12dp"
android:background="#color/blue">
<ImageView
android:id="#+id/trainer_photo"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_gravity="center"
android:contentDescription="#string/trainers"
android:src="#mipmap/ic_launcher"
android:layout_marginTop="20dp"/>
<TextView
android:id="#+id/trainerCourse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:layout_marginTop="12dp"
android:textColor="#ffffff"
android:textSize="22sp"
android:gravity="center"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:id="#+id/trainerSex"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_marginTop="5dp"
android:textColor="#ffffff"
android:textSize="17sp"
android:layout_gravity="center"/>
<TextView
android:id="#+id/trainerPlace"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textColor="#ffffff"
android:textSize="17sp"
android:gravity="center"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#F5F5F5"
android:gravity="center_horizontal"
android:padding="7dp"
android:orientation="horizontal">
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/global"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/messenger"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/google_plus"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/inst_detail"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/telegram"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/facebook"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/twitter"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/inst_instagram"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="14dp"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:text="About Trainer"
android:textColor="#color/blue"
android:textSize="19sp"
android:textStyle="bold"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/para"
android:layout_marginTop="4dp"
android:layout_marginBottom="2dp"
android:textSize="14sp"/>
</LinearLayout>
</LinearLayout>
</ScrollView>
I know there are a lot of this kind of questions, but here is my problem.
I have a gallery with images and when I click, there is an ImageView to display the selected image in the gallery.
I also have a TextView witch displays a message.
When I click an image in the gallery, my ImageView gets the image and the TextTiew doesnt update its data.
I tried to put the code in a try/catch block and it doesn't throw any exception.
In my Log, the TextView has the exact text I have provided.
I tried using a new thread, but the result is the same: the TextView doesn't update, but my ImageView does.
I tried using runOnUiThread (as far as I know it's the same as a Thread), but still nothing.
I also changed from TextView to EditText, but I have the same problem.
Everyone says: "use a thread" - I did and it didn't work.
I ran out of ideas...
public class VODInterface extends Activity {
public static String[] values;
private static int itemPosition;
public static Activity thisActivity;
public Gallery gallery;
public ListView listView;
public LinearLayout MovieView;
public ImageView imgview;
public boolean submenus=false;
public boolean listviewVisibility = true;
private Handler handler = new Handler() ;
private SharedPreferences ep;
public ArrayList<VODObject> vod;
private ArrayList<Bitmap> tempimg;
private static int MovieSetNumber = 1;
public static int VODIndexPosition = 0;
public VODInterface(){
}
public void onDestroy(){
MainActivity.inChild=false;
super.onDestroy();
}
public void onCreate(Bundle bundle){
super.onCreate(bundle);
this.setContentView(R.layout.listview2);
ep = getSharedPreferences("Settings", 0);
listView = (ListView) this.findViewById(R.id.listView1);
MovieView = (LinearLayout) this.findViewById(R.id.movieView);
imgview = (ImageView)this.findViewById(R.id.imageView2);
// Defined Array values to show in ListView
values = new String[] { "A..Z",
"Category",
"Most Rated",
"Most Watched",
"Recently"
};
//this shows whitch movie should me load images
//we show always only 10 movies
MovieSetNumber = 1;
// Define a new Adapter
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
// ListView Item Click Listener
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
itemPosition = position;
handler.post(goDeep);
}
});
}
private Runnable goDeep = new Runnable(){
public void run(){
new goDeep().execute("");
}
};
class goDeep extends AsyncTask<String, String, String>{
ProgressDialog mProgressDialog = new ProgressDialog(VODInterface.this);
String result="";
boolean failLoadVOD=false;
protected void onPreExecute(){
mProgressDialog.setMessage(getString(R.string.downloading));
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
//START check if servers are Ok
if(!Server.isOnline()){
Server.getAvailableServer();
Log.i("good", "");
}
if(!Server.isOnline()){
Log.i("WEW", "SERVERS are off");
return null;
}
//END check if servers are Ok
//START synchronize local database with online database
try{
if(ep.contains("downloaded")){
Log.i("localDatabase", "is full");
}
else{
Editor ed = ep.edit();
ed.putString("downloaded", "");
ed.commit();
//load data from database
if(!MainActivity.web.parseVODAndVODCategories()){
failLoadVOD=true;
}
}
}
catch(NullPointerException ee)
{
//lets go get datas from Tibodatabase
Editor ed = ep.edit();
ed.putString("downloaded", "");
ed.commit();
if(!MainActivity.web.parseVODAndVODCategories()){
failLoadVOD=true;
}
}
//END synchronize local database with online database
//START handle menus
if(!submenus) //MainMenu
{
if(itemPosition == 1){
//get all movies ordered by name
List<String> val = MainActivity.voddb.selectAllCategories();
values = new String[val.size()+1];
values[0] ="[...]";
for(int i=0;i<val.size();i++){
values[i+1] = val.get(i);
}
listviewVisibility = true;
}
else{
//show movies
listviewVisibility = false;
}
submenus = true;
}
else{
if(itemPosition == 0){
values = new String[] { "A..Z",
"Category",
"Most Rated",
"Most Watched",
"Recently"
};
submenus = false;
listviewVisibility = true;
}
else{
listviewVisibility = false;
}
}
//END handle menu
if(!listviewVisibility){
getData();
for(int i=0;i<vod.size();i++){
if(!FileExciste(vod.get(i).Icon)){
try{
Bitmap bmp ;
URL newurl = new URL(vod.get(i).Icon);
bmp = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
saveImageToSD(bmp,vod.get(i).Icon);
Log.i(i+"", "done");
}
catch(Exception e){
Log.i("exciste", "exciste");
}
}
else{
Log.i(i+"", "exciste");
}
}
}
runOnUiThread(new Runnable() {
#Override
public void run() {
if(!listviewVisibility){
listView.setVisibility(View.GONE);
MovieView.setVisibility(View.VISIBLE);
populateMovieView();
}
else{
ArrayAdapter<String> adapter = new ArrayAdapter<String>(VODInterface.this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
}
}
});
mProgressDialog.dismiss();
return "";
}
protected void onPostExecute(){
//start adding to cache
super.onPostExecute("");
}
}
private void getData(){
vod = new ArrayList<VODObject>();
for(int i=1;i<MainActivity.voddb.getVODCount()+1;i++){
vod.add(MainActivity.voddb.getVOD(i+""));
if(vod.get(i-1).Icon.contains(" ")){
vod.get(i-1).Icon = vod.get(i-1).Icon.replaceAll(" ", "%20");
Log.i("u korrigjua", vod.get(i-1).Icon);
}
}
}
private void populateMovieView(){
gallery = (Gallery) findViewById(R.id.gallery1);
GalleryImageAdapter gia= new GalleryImageAdapter(this,vod);
gallery.setAdapter(gia);
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, final int position, long id) {
// show the selected Image
/*here is the problem
*
*----------------------------/
*/
try{
LayoutInflater factory = getLayoutInflater();
View view = factory.inflate(R.layout.listview2, null);
EditText title = (EditText) view.findViewById(R.id.editText2);
title.setText(vod.get(position).title);
TextView desc = (TextView) view.findViewById(R.id.editText4);
desc.setText(vod.get(position).description);
Log.i("info", title.getText()+" "+desc.getText());
}
catch(Exception ee){
Log.i("info", ee.getMessage()+" nnn");
}
/*----------------------*/
try{
imgview.setImageBitmap(getImageFromSD(vod.get(position).Icon));
}
catch(Exception ee){
imgview.setImageResource(R.drawable.untitled);
}
}
});
}
public static Bitmap getImageFromSD(String url){
String path = Environment.getExternalStorageDirectory().toString();
File imgFile = new File(path+"/"+WebHelper.getFilenameFromUrl(url));
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
return myBitmap;
}
private void saveImageToSD(Bitmap bmp,String url) throws IOException {
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
File file = new File(path, "/"+WebHelper.getFilenameFromUrl(url));
fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName (),file.getName());
}
private boolean FileExciste(String url){
String path = Environment.getExternalStorageDirectory().toString();
File file = new File(path, "/"+WebHelper.getFilenameFromUrl(url));
return file.exists();
}
AND this is my 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="match_parent"
android:background="#drawable/vod"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="top" >
<ListView
android:id="#+id/listView1"
android:layout_width="274dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="20dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:background="#color/translucent_bblack" >
</ListView>
<LinearLayout
android:id="#+id/movieView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/translucent_black"
android:orientation="vertical"
android:visibility="invisible" >
<Gallery
android:id="#+id/gallery1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:background="#color/translucent_bblack" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageButton
android:id="#+id/imageView2"
android:layout_width="400dp"
android:layout_height="fill_parent"
android:layout_marginBottom="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#drawable/bord" />
<LinearLayout
android:id="#+id/MovieDesc"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="20dp"
android:layout_marginRight="20dp"
android:background="#color/translucent_bblack"
android:orientation="vertical" >
<TextView
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="30dp"
android:inputType="textPersonName"
android:text="Title:"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="bold" >
</TextView>
<TextView
android:id="#+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/editText3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="30dp"
android:text="Description:"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/editText4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/editText5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="60dp"
android:text="Duration:"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Declare your TextViews as field as like as ImageView---- "imgview" as follows...
public ImageView imgview;
public TextView title;
public TextView desc;
Initialize them in onCreate method as "imgview"
imgview = (ImageView)this.findViewById(R.id.imageView2);
title = (TextView) view.findViewById(R.id.editText2);
desc = (TextView) view.findViewById(R.id.editText4);
And update your gallery.setOnItemClickListener code as follows...
gallery.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, final int position, long id) {
title.setText(vod.get(position).title);
desc.setText(vod.get(position).description);
Log.i("info", title.getText()+" "+desc.getText());
imgview.setImageBitmap(getImageFromSD(vod.get(position).Icon));
}
});
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.
dear
how to show text above customise list when i extends listactivity in my class file..the code is given below..
public class ServerResponce extends ListActivity {
private ArrayList<listobj> tobj = new ArrayList<listobj>();
static String str1;
PickUpLocation pickup=new PickUpLocation();
String pickuplocid= pickup.locationid;
String des=planner.description;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
**//here not work force close**
// ****setContentView(R.layout.list_item);
**// TextView tv = (TextView)findViewById(R.id.text1);
// tv.setText("i want to book a cab for 4 hr/40km from sushant lok to delhi air port at" +
// "4 pm today"
// +"the cab should be 4 seater compact cab with carriage");
// tv.setBackgroundColor(R.color.black);**
//
new MyTask().execute();
}
private class MyTask extends AsyncTask<Void, Void, Void>
{
private ProgressDialog progressDialog;
protected void onPreExecute() {
progressDialog = ProgressDialog.show(ServerResponce.this,
"", "Loading. Please wait...", true);
}
protected void onProgressUpdate(Integer... integer){
TextView tv = null;
tv.setText("gjh");
}
#Override
protected Void doInBackground(Void... arg0) {
try {
URL url = new URL("http://qrrency.com/mobile/j2me/cab/CabBookingStatus.php?requestid=666");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
int l=0;
int k=0;
StringBuffer buffer=new StringBuffer();
String str=" ";
while ((l=in.read())!=-1)
{
buffer.append((char)l);
str=str+(char)l;
}
in.close();
//
try {
JSONObject json = new JSONObject(str);
JSONArray nameArray=json.getJSONArray("bookings");
JSONObject[] cabListing=new JSONObject[nameArray.length()];
for (int i = 0; i < cabListing.length; i++) {
//JSONObject jSONObject = cabListing[i];
JSONObject jSONObject = nameArray.getJSONObject(i);
listobj tweet = new listobj();
JSONObject temp=jSONObject.getJSONObject("booking");
tweet.cabid = temp.getString("cabbookingid");
tweet.author =temp.getString("CabDriverName");
tweet.content =temp.getString("price");
tweet.cabrat=temp.getString("cabrating");
tobj.add(tweet);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e)
{
} catch (IOException e)
{
}
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
setListAdapter(new tListAdaptor(
ServerResponce.this, R.layout.list_item, tobj));
}
}
private class tListAdaptor extends ArrayAdapter<listobj> {
private ArrayList<listobj> tobj;
public tListAdaptor(Context context,int textViewResourceId,ArrayList<listobj> items)
{
super(context, textViewResourceId, items);
this.tobj = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item, null);
}
listobj o = tobj.get(position);
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView bt = (TextView) v.findViewById(R.id.bottomtext);
TextView bt1 = (TextView) v.findViewById(R.id.bottomtext1);
TextView bt2 = (TextView) v.findViewById(R.id.bottomtext2);
bt.setText("CAB NAME: " +o.author);
bt1.setText("CAB ID: " +o.cabid);
tt.setText("PRICE: " +o.content);
bt2.setText("CAB RATING: " +o.cabrat);
return v;
}
}
public String getItem(int position) {
// TODO Auto-generated method stub
return null;
}
}
xml file is...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<RelativeLayout xmlns:android= "http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dip">
<TextView android:id="#+id/text" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="false"
android:text=" "
android:textStyle="italic"
/>
<Button
android:text="auto book"
android:id="#+id/autobook"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text"/>
<Button
android:text="cancel"
android:id="#+id/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text"
android:layout_toRightOf="#id/autobook"/>
</RelativeLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
<TextView android:id="#+id/toptext" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:text=" " />
<TextView android:id="#+id/bottomtext" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true" />
<TextView android:id="#+id/bottomtext1" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:text=" " />
<TextView android:id="#+id/bottomtext2" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true" />
</LinearLayout>
</LinearLayout>
You can set the header to by a textview. It will still be in the same format as a list view but the top item in the list view will be your text view
Your code is looking for R.id.text1
TextView tv = (TextView)findViewById(R.id.text1);
But your xml does not have any such id.
So you will get a null for tv.