I am new to Java and Android.
I am using a custom adapter to fill my list_view, but then got overwritten, and I don't know what I should do.
By searching on the web I found something about "linkedhashset", but I don't know how to use it.
Adapter Class
public class OSFuncionarioListAdapter extends ArrayAdapter<OSFuncionario> {
private List<OSFuncionario> itemList;
private Context context;
public OSFuncionarioListAdapter(List<OSFuncionario> itemList, Context ctx) {
super(ctx,android.R.layout.simple_list_item_1, itemList);
this.itemList = itemList;
this.context = ctx;
}
public int getCount() {
if (itemList != null)
return itemList.size();
return 0;
}
public OSFuncionario getItem(int position) {
if (itemList != null)
return itemList.get(position);
return null;
}
public long getItemId(int position) {
if (itemList != null)
return itemList.get(position).hashCode();
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.osfuncionario_item, parent, false);
OSFuncionario ositem = itemList.get(position);
TextView os = (TextView) v.findViewById(R.id.IDOS);
os.setText("OS Nº " + ositem.OS);
TextView os1 = (TextView) v.findViewById(R.id.datadaos);
os1.setText(ositem.Data);
TextView os2 = (TextView) v.findViewById(R.id.solicitacao);
os2.setText("Solicitado por: "+ositem.Solicitado);
TextView os3 = (TextView) v.findViewById(R.id.textoosfunc);
os3.setText(ositem.Texto+"...");
}
return v;
}
public List<OSFuncionario> getItemList() {
return itemList;
}
public void setItemList(List<OSFuncionario> itemList) {
this.itemList = itemList;
}
}
the fragment code
public class OSFuncionarioFragment extends Fragment {
OSFuncionarioListAdapter adpt;
OSFuncionario item;
protected SharedPreferences userLocalDatabase;
public static final String SP_NOME="UserDetails";
public static final int CONNECTION_TIME = 1000 *30;
public static final String SERVIDOR = "http://www.creativeriopreto.com.br/app/";
public OSFuncionarioFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_osfuncionario, container, false);
userLocalDatabase = getActivity().getSharedPreferences(SP_NOME, 0);
adpt = new OSFuncionarioListAdapter(new ArrayList<OSFuncionario>(), getActivity());
ListView lView = (ListView) rootView.findViewById(R.id.listaOSFuncionario);
int idfuncionario = userLocalDatabase.getInt("id", -1);
lView.setAdapter(adpt);
item = new OSFuncionario(idfuncionario);
(new Carregadados()).execute();
return rootView;
}
private class Carregadados extends AsyncTask<String, Void, List<OSFuncionario>> {
private final ProgressDialog dialog = new ProgressDialog(getActivity());
#Override
protected void onPostExecute(List<OSFuncionario> result) {
super.onPostExecute(result);
dialog.dismiss();
adpt.setItemList(result);
adpt.notifyDataSetChanged();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setCancelable(false);
dialog.setTitle("Carregando");
dialog.setMessage("Por Favor Aguarde");
dialog.show();
}
#Override
protected List<OSFuncionario> doInBackground(String... params) {
List<OSFuncionario> result = new ArrayList<OSFuncionario>();
ArrayList<NameValuePair> data = new ArrayList<>();
data.add(new BasicNameValuePair("id",String.valueOf(item.IDFuncionario)));
HttpParams httprequestparams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httprequestparams, CONNECTION_TIME);
HttpConnectionParams.setSoTimeout(httprequestparams, CONNECTION_TIME) ;
HttpClient cliente = new DefaultHttpClient(httprequestparams);
HttpPost post = new HttpPost(SERVIDOR + "OS/CarregaOSFuncionario");
try {
post.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response = cliente.execute(post);
HttpEntity entity = response.getEntity();
String JSONResp = EntityUtils.toString(entity);
JSONArray arr = new JSONArray(JSONResp);
for (int i=0; i < arr.length(); i++) {
result.add(ConvertDados(arr.getJSONObject(i)));
}
return result;
}
catch(Throwable t) {
t.printStackTrace();
}
return null;
}
public OSFuncionario ConvertDados(JSONObject obj) throws JSONException {
int OS = obj.getInt("ID");
String solicitado = obj.getString("solicitado");
String texto = obj.getString("texto");
String data = obj.getString("data");
return new OSFuncionario(OS, item.IDFuncionario, solicitado, texto, data);
}
}
Class Code
public class OSItinerarioClass implements Serializable {
public int OS, Itinerario, Versao ;
public String Data, Finalidade, Tecnico, Cliente, Situacao;
public OSItinerarioClass(int os, int itinerario, int versao,
String data, String finalidade, String tecnico, String cliente, String situacao)
{
this.OS = os;
this.Itinerario = itinerario;
this.Versao = versao;
this.Data = data;
this.Finalidade = finalidade;
this.Tecnico = tecnico;
this.Cliente = cliente;
this.Situacao = situacao;
}
public OSItinerarioClass(int itinerario)
{
this.OS = -1;
this.Itinerario = itinerario;
this.Versao = -1;
this.Data = "";
this.Finalidade = "";
this.Tecnico = "";
this.Cliente = "";
this.Situacao = "";
}
}
XML Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dp" >
<!-- Thumbnail Image -->
<ImageView
android:layout_width="56dp"
android:layout_height="56dp"
android:background="#drawable/ic_os"
android:contentDescription="icone"
android:id="#+id/thumbnail" />
<!-- Movie Title -->
<TextView
android:id="#+id/IDOS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:text="Numero de OS"
android:textSize="18dp"
android:textColor="#color/colorPrimary"
android:layout_marginTop="5dp"
android:textStyle="bold" />
<TextView
android:id="#+id/solicitacao"
android:text="Solicitacao"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/IDOS"
android:layout_marginTop="5dp"
android:layout_toRightOf="#+id/thumbnail"
android:textColor="#666"
android:textSize="#dimen/genre" />
<!-- Genre -->
<TextView
android:id="#+id/textoosfunc"
android:text="Texto da OS"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/solicitacao"
android:layout_marginTop="5dp"
android:layout_toRightOf="#+id/thumbnail"
android:textColor="#666"
android:textSize="#dimen/genre" />
<!-- Release Year -->
<TextView
android:id="#+id/datadaos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="data da os"
android:layout_alignParentRight="true"
android:textColor="#666"
android:layout_marginTop="5dp"
android:textSize="#dimen/year" />
the json response from the server
[{"ID":42529,"solicitado":"teste","texto":"teste de apresentação para cliente","data":"29/03/2015"},{"ID":40546,"solicitado":"Rdorigo","texto":"Erro liberação cliente SISTEMA/RADIUS","data":"07/02/2015"},{"ID":37450,"solicitado":"Frank","texto":"Cliente solicita visita no local pois alega ","data":"09/12/2014"},{"ID":35825,"solicitado":"Mirian","texto":"Link de 20 megas compartilhados por R$ 189,","data":"04/11/2014"},{"ID":35317,"solicitado":"Thiago Belao(teste de erro PC)","texto":"Cliente disse que o tecnico esteve no local ","data":"08/10/2014"},{"ID":33150,"solicitado":"andrea","texto":"conexão lenta","data":"31/07/2014"},{"ID":22920,"solicitado":"Angélica","texto":"Referente à desenvolvimento de site para Cad","data":"10/11/2013"},{"ID":22692,"solicitado":"SUMAIA","texto":"CLIENTE SOLICITOU ALTERAÇÕES NO SITE, FOI RE","data":"27/10/2013"},{"ID":22324,"solicitado":"ANGÉLICA","texto":"ABRINDO O.S PARA DESENVOLVIMENTO DE SITE COM","data":"05/10/2013"},{"ID":22092,"solicitado":"Guilherme","texto":"Instalar ponto de internet ( Air Gridg ) no ","data":"18/09/2013"},{"ID":21994,"solicitado":"Desenvolvimento","texto":"Desenvolvimento de Web Site . R$ 1.100,00 em","data":"11/09/2013"},{"ID":21910,"solicitado":"Ellus Bruno","texto":"Desenvolvimento de Site Gerenciavel R$ 1500,","data":"04/09/2013"},{"ID":21846,"solicitado":"Fabio","texto":"Cliente solicitou manutenção em seu web site","data":"01/09/2013"},{"ID":18986,"solicitado":"Tcharles","texto":"Instalação de Sistema Operacional, Configura","data":"19/02/2013"}]
In your get view put this line on the top.
convertView = null;
I hope it works, it solved my problem.
Try calling notifyDataSetChanged() within adapter after "this.itemList = itemList;" in setItemList and remove from onPostExecute.
Related
Im creating a RecyclerView using jdbc connection and mysql database. Inside the RecyclerView I am uploading data from my database into one TextView and three radioButtons . Everything works just fine, but my problem is that it only shows the first RadioButton and there is nothing in the second and third one.
Here is my java code :
public class GererVoteInvite extends AppCompatActivity {
private ArrayList<VoteItem> itemArrayList; //List items Array
private MyAppAdapter myAppAdapter; //Array Adapter
private RecyclerView recyclerView; //RecyclerView
private RecyclerView.LayoutManager mLayoutManager;
private boolean success = false; // boolean
private static final String DB_URL = "jdbc:mysql://10.0.2.2/mvoting_db_1.0.0.0";
// private static final String DB_URL = "jdbc:mysql://172.16.24.25/mvoting_db_1.0.0.0"; //"jdbc:mysql://DATABASE_IP/DATABASE_NAME";
private static final String USER = "mootaz";
private static final String PASS = "mootaz";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gerer_vote_invite);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView); //REcyclerview Declaration
recyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayoutManager);
itemArrayList = new ArrayList<VoteItem>(); // Arraylist Initialization
// Calling Async Task
SyncData orderData = new SyncData();
orderData.execute("");
}
// Async Task has three overrided methods,
private class SyncData extends AsyncTask<String, String, String> {
String msg = "Internet/DB_Credentials/Windows_FireWall_TurnOn Error, See Android Monitor in the bottom For details!";
ProgressDialog progress;
//Starts the progress dailog
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(GererVoteInvite.this, "Synchronising",
"RecyclerView Loading! Please Wait...", true);
}
// Connect to the database, write query and add items to array list
#Override
protected String doInBackground(String... strings) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); //Connection Object
if (conn == null) {
success = false;
} else {
// Change below query according to your own database.
String query = "SELECT lib_probleme , lib_solution_1 , lib_solution_2 , lib_solution_3 FROM reunion JOIN probleme JOIN solution WHERE reunion.id_reunion=probleme.id_reunion and probleme.id_probleme=solution.id_probleme ;";
Statement stmt = conn.createStatement();
java.sql.ResultSet rs = stmt.executeQuery(query);
// if resultset not null, I add items to itemArraylist using class created
if (rs != null) {
while (rs.next()) {
try {
itemArrayList.add(new VoteItem(rs.getString("lib_probleme"), rs.getString("lib_solution_1"), rs.getString("lib_solution_2"), rs.getString("lib_solution_3")));
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
success = false;
}
return msg;
}
// disimissing progress dialoge, showing error and setting up my gridview
#Override
protected void onPostExecute(String msg) {
progress.dismiss();
Toast.makeText(GererVoteInvite.this, msg + "", Toast.LENGTH_LONG).show();
if (success == false) {
} else {
try {
myAppAdapter = new MyAppAdapter(itemArrayList, GererVoteInvite.this);
recyclerView.setAdapter(myAppAdapter);
} catch (Exception ex) {
}
}
}
}
public class MyAppAdapter extends RecyclerView.Adapter<MyAppAdapter.ViewHolder> {
private List<VoteItem> values;
public Context context;
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView txtProbleme;
public RadioGroup group;
public RadioButton txtSol1;
public RadioButton txtSol2;
public RadioButton txtSol3;
public View layout;
public ViewHolder(View v) {
super(v);
layout = v;
group = (RadioGroup) v.findViewById(R.id.radio_group);
txtProbleme = (TextView) v.findViewById(R.id.tv_probleme);
txtSol1 = (RadioButton) v.findViewById(R.id.rb_1);
txtSol2 = (RadioButton) v.findViewById(R.id.rb_2);
txtSol3 = (RadioButton) v.findViewById(R.id.rb_3);
}
}
// Constructor
public MyAppAdapter(List<VoteItem> myDataset, Context context) {
values = myDataset;
this.context = context;
}
// Create new views (invoked by the layout manager) and inflates
#Override
public MyAppAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v = inflater.inflate(R.layout.vote_view, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Binding items to the view
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final VoteItem voteItem = values.get(position);
holder.txtProbleme.setText(voteItem.getProbleme());
holder.group.setTag(position);
holder.txtSol1.setText(voteItem.getSol1());
holder.txtSol2.setText(voteItem.getSol2());
holder.txtSol3.setText(voteItem.getSol3());
}
// get item count returns the list item count
#Override
public int getItemCount() {
return values.size();
}
}
}
And here is my layout.xml that containt the item for the RecyclerView
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/ac"
android:layout_width="match_parent"
android:layout_height="205dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:padding="5dp">
<android.support.v7.widget.CardView
android:id="#+id/vote_card"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:layout_marginTop="10dp"
card_view:cardBackgroundColor="#color/white"
card_view:cardCornerRadius="10dp"
card_view:cardElevation="5dp">
<TextView
android:id="#+id/tv_probleme"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_marginTop="30dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:text="Probleme :"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="16dp" />
<RadioGroup
android:id="#+id/radio_group"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioButton
android:id="#+id/rb_1"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_marginTop="60dp"
android:text="Solution 1" />
<RadioButton
android:id="#+id/rb_2"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:text="Solution 2" />
<RadioButton
android:id="#+id/rb_3"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:text="Solution 3" />
</RadioGroup>
</android.support.v7.widget.CardView>
</RelativeLayout>
Here is the screenshot of my app
xml file
the first file is a xml file of the design.
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listviewtask"/>
</LinearLayout>
</RelativeLayout>
rawtask.xml file
this is the raw file and here design of a list view
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#drawable/property_display_box"
android:id="#+id/listview1ll">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Task Name"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:textSize="30dp"
android:id="#+id/lvtaskname" />
<TextView
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:textSize="30dp"
android:hint="Task Details"
android:layout_gravity="center"
android:id="#+id/lvtaskdetails"
/>
<CheckBox
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add Details"
android:layout_marginLeft="40dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:textSize="30dp"
android:id="#+id/lvchkbox"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="10dp"
android:orientation="horizontal"
android:id="#+id/lvl1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:text="Remaining Time:"
android:textSize="20dp"
android:id="#+id/lvrt"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Done"
android:layout_marginLeft="90dp"
android:layout_marginTop="10dp"
android:textSize="20dp"
android:id="#+id/lvdone"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Listviewadapter.java
the listviewadapter.java is shown
public class ListViewAdapter2 extends BaseAdapter {
Context cntx;
AlertDialog.Builder alertDialogBuilder;
//int loader = R.drawable.ic_menu_gallery;
ArrayList<String> t_id=new ArrayList<String>();
ArrayList<String> t_tname=new ArrayList<String>();
ArrayList<String> t_detail=new ArrayList<String>();
// ArrayList<Float> itemRating=new ArrayList<Float>();
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
//ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
/*
* public ListViewAdapter(Context context, ArrayList<HashMap<String,
* String>> arraylist) { this.cntx = context; data = arraylist; imageLoader
* = new ImageLoader(context); }
*/
public ListViewAdapter2(Context context,
ArrayList<String> taskid,
ArrayList<String> taskname,
ArrayList<String> taskdetail) {
// TODO Auto-generated constructor stub
cntx = context;
t_id=taskid;
t_tname = taskname;
t_detail =taskdetail;
//Log.d("xyz", security_id.toString());
//ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).build();
//ImageLoader.getInstance().init(config);
alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setMessage("Do You Want To Call....");
// itemRating=itm_rating;
}
#Override
public int getCount() {
return t_id.size();
}
#Override
public Object getItem(int position) {
return t_id.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressWarnings("deprecation")
public View getView(final int position, View convertView, ViewGroup parent) {
#SuppressWarnings("unused")
final TextView taskname, taskdetail;
inflater = (LayoutInflater) cntx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LayoutInflater inflater = LayoutInflater.from(cntx);
convertView = inflater.inflate(R.layout.rawtask, parent, false);
/*ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(loader)
.showImageOnFail(loader)
.showImageOnLoading(loader).build();*/
taskname= (TextView) convertView.findViewById(R.id.lvtaskname);
taskdetail= (TextView) convertView.findViewById(R.id.lvtaskdetails);
taskname.setText("taskName : "+t_tname.get(position));
taskdetail.setText("taskdetail: "+t_detail.get(position));
return convertView;
}
}
main activity.java
this is the final .java file of the project
package com.example.sachin.listview;
public class Main2Activity extends Fragment {
public Main2Activity(){};
private static final String TAG_SUCCESS = "success";
JSONArray jsonarray;
JSONObject jsonobject;
ListView listview;
String img;
ListViewAdapter2 listadapter;
//ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
private static String url_task = "http://10.0.2.2/portal/aFetchtask.php";
// private static String url_profile ="http://10.0.2.2/myapp/fetchmember.php";
JSONParser jParser = new JSONParser();
ArrayList<String> t_id = new ArrayList<String>();
ArrayList<String> t_tname = new ArrayList<String>();
ArrayList<String> t_detail = new ArrayList<String>();
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
// don't look at this layout it's just a listView to show how to handle the keyboard
View view = inflater.inflate(R.layout.activity_main, container, false);
getActivity().setTitle("tasks");
new DownloadJSON().execute();
return view;
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
//mProgressDialog = new ProgressDialog(getActivity());
//mProgressDialog.setTitle("Please Wait");
// Set progressdialog message
//mProgressDialog.setMessage("Loading...");
//mProgressDialog.setIndeterminate(false);
// Show progressdialog
//mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... args) {
// Create an array
try {
arraylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("abc", "abc"));
JSONObject json = jParser.makeHttpRequest(url_task, "POST", params);
int success1 = Integer.parseInt(json.getString(TAG_SUCCESS));
Log.d("success", json.toString());
if (success1 == 0) {
Snackbar.make(view, "Not Data Found", Snackbar.LENGTH_LONG).show();
}
if (success1 == 1) {
JSONArray ownerObj = json.getJSONArray("tasks");
// arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
// Locate the array name in JSON
// jsonarray = jsonobject.getJSONArray("images");
for (int i = 0; i < ownerObj.length(); i++) {
// HashMap<String, String> map = new HashMap<String, String>();
jsonobject = ownerObj.getJSONObject(i);
// Retrive JSON Objects
//securityId.add(jsonobject.getString("security_id"));
// t_id.add(jsonobject.getString("t_id"));
t_tname.add(jsonobject.getString("t_tname"));
t_detail.add(jsonobject.getString("t_detail"));
// Number.add(jsonobject.getString("number"));
Log.d("DATA", jsonobject.toString());
//img="http://10.0.2.2/momskitchen/image/";
//proImage.add(img + jsonobject.getString("image"));
/* System.out.println(jsonobject.getString(TA));
System.out.println(g);*/
}
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void args) {
listview = (ListView) getActivity().findViewById(R.id.listviewtask);
ListViewAdapter2 listadapter = new ListViewAdapter2(getActivity(), t_id, t_tname, t_detail);
// Set the adapter to the ListView
listview.setAdapter(listadapter);
// Close the progressdialog
//mProgressDialog.dismiss();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
//add the values which need to be saved from the drawer to the bundle
// outState = result.saveInstanceState(outState);
super.onSaveInstanceState(outState);
}
}
and the lastly is the file is my api file..
<?php
include("connection.php");
$response = array();
// get all products from products table
$result = mysql_query("SELECT * FROM task") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["tasks"] = array();
while ($row = mysql_fetch_array($result))
{
$tasks = array();
$tasks["t_id"] = $row["t_id"];
$tasks["t_tname"] = $row["t_tname"];
$tasks["t_udetail"] = $row["t_udetail"];
// push single product into final response array
array_push($response["tasks"], $tasks);
}
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
}
else
{
// no products found
$response["success"] = 0;
$response["message"] = "No picture found";
// echo no users JSON
echo json_encode($response);
}
?>
here the all files are available.
but the data is not fetched from the database.
please help me out for this..
There are lot of coding faults are there.
The Asynchronus class is return types are not in the exact manner to retrive the data.
After protected Void doInBackground(Void... args) {}is returning null then you can get null value to onPostExcute(Void args) you have to write get whole repose in doInBackground() method only if you are not returning any response.
In rawtask.xml file should contains views which are inflating by adapter but in your case other view are mentioned.
So refere this following link to get the data from webservices into listView.
here
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();
I am building an android application where the data is parsing from the JSON volley library.
Now my need is that: there Should be an particular image in front of particular Text in an ListView.
For example, if the data parsing string is ice-cream, then there should be an Ice-cream image in front of it.
Here is the code I am using for parsing data:
package tabsswipe;
public class FragmentPlay extends Fragment implements OnClickListener {
private Button ib;
private Calendar cal;
private int day;
private int month;
private int year;
private EditText et;
// Movies json url
private static final String url = "url";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
String minstring, maxstring,finaldate;
EditText etxt1, etxt2;
String selItem, selItem2, selItem3, selItem4;
int ab, ba;
TextView tv1, tv2, txtsportname;
SeekBarWithTwoThumb swtt;
String firstlist;
public static ArrayList<String> array;
Calendar c = Calendar.getInstance();
int startYear = c.get(Calendar.YEAR);
int startMonth = c.get(Calendar.MONTH);
int startDay = c.get(Calendar.DAY_OF_MONTH);
Spinner spnr;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
listView = (ListView) rootView.findViewById(R.id.list1);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
int Position, long offset) {
// TODO Auto-generated method stub
Movie item = (Movie) adapter.getItem(Position);
viewCategorysportdetails();
// Intent intent = new Intent(rootView.getContext(),
// SingleArticleAfrica.class);
// single.title = item.getTitle();
// single.author = item.getAuthor();
// single.date = item.getDate();
// single.featured_img = item.getFeatured_img();
// single.content = item.getContent();
// single.permalink = item.getPermalink();
firstlist = item.getTitle();
txtsportname.setText(firstlist);
// Toast.makeText(getActivity(), firstlist,
// Toast.LENGTH_LONG).show();
// startActivity(intent);
}
});
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
return rootView;
}
#Override
public void onStart() {
super.onStart();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("foodname"));
// movie.setThumbnailUrl(obj.getString("image"));
// movie.setRating(((Number) obj.get("rating"))
// .doubleValue());
// movie.setYear(obj.getInt("releaseYear"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
Here is code where this parse value is add using CustomListAdapter:
package info.androidhive.customlistviewvolley.adater;
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Movie> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView rating = (TextView) convertView.findViewById(R.id.rating);
//TextView genre = (TextView) convertView.findViewById(R.id.genre);
TextView year = (TextView) convertView.findViewById(R.id.releaseYear);
// getting movie data for the row
Movie m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
// rating
rating.setText((m.getRating()));
// release year
year.setText(String.valueOf(m.getYear()));
return convertView;
}
}
Here is XML code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF">
<ListView
android:id="#+id/list1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_row_selector" />
</RelativeLayout>
Here is ListAdapter 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="wrap_content"
android:background="#drawable/list_row_selector"
android:padding="8dp" >
<!-- Thumbnail Image -->
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/thumbnail"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentLeft="true"
android:layout_marginRight="8dp" />
<!-- Movie Title -->
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:textSize="#dimen/title"
android:textStyle="bold" />
<!-- Rating -->
<TextView
android:id="#+id/rating"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:layout_marginTop="1dip"
android:layout_toRightOf="#+id/thumbnail"
android:textSize="#dimen/rating" />
<!-- Release Year -->
<TextView
android:id="#+id/releaseYear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:textColor="#color/year"
android:textSize="#dimen/year" />
static List<String> foodnames = Arrays.asList((getResources().getStringArray(R.array.food_names)));
int key = foodnames.indexOf(getString(m.getFoodName()));
String[] food_name_drawables = context.getResources().getStringArray(R.array.food_name_drawables);
ImageView foodname = (ImageView) convertView.findViewById(R.id.image_foodname);
background.setBackgroundDrawable(context.getResources().getDrawable(food_name_drawables[key]);
I think it should work...
I hope I understood your need, but I'm not sure. Do you need to set as the background of the element view of the list an image representing the genre of the movie? Is that correct? If so:
If you take the infos from a server that you don't own, take a note of all the genres that the website uses, you put them in an array, and in the adapter depending on which genre is the movie of the list element, you change the background taking it from a drawable array. Let's say there are only 3 genres:
in xml:
<string-array name="movie_genres">
<item>Dramatic</item>
<item>Comedy</item>
<item>Action</item>
</string-array>
<string-array name"movie_genres_drawables">
<item>#drawable/dramatic_image</item>
<item>#drawable/comedy_image</item>
<item>#drawable/action_image</item>
</string-array>
then in the adapter:
static List<String> genres;
...
...
if (genres == null) {
genres = Arrays.asList((getResources().getStringArray(R.array.movie_genres)));
}
int key = genres.indexOf(getString(m.getGenre())); //Of course you should create this getter
String[] movie_genres_drawables = context.getResources().getStringArray(R.array.movie_genres_drawables);
ImageView background = (ImageView) convertView.findViewById(R.id.background);
background.setBackgroundDrawable(context.getResources().getDrawable(movie_genres_drawables[key]);
If you own the website with the movies archive, well you can take image directly from the server and put it on the list...
If I completely misunderstood your question, I'm sorry don't consider my answer at all. ;-)
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.