I'm using an adapter in a list, and the view of the buttons,
Some buttons are blocked, but if you scroll the drop-down list of this button is enabled with another wrong position that does not match, is there any way to solve this?
this is my Adapter
/**
* Created by Isai on 15/03/17.
*/
public class AdapterFood extends ArrayAdapter<Charola.Producto> {
ImageView imgFood;
private String nameService = "AgregarItemCharola";
private String usuarioId = "UsuarioId";
private String productoId = "ProductoId";
private String cantidad = "Cantidad";
private String especificaciones = "Especificaciones";
private String urlComplete = Constantes.URLMAIN + nameService + "?";
private Fragment fragment;
private List<Charola.Producto> productoList;
private int contador;
private String totalCharola;
public AdapterFood(Context context, List<Charola.Producto> productoList, Fragment fragment) {
super(context, 0, productoList);
this.fragment = fragment;
this.productoList = productoList;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater)
getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View listViewInflate = convertView;
if (convertView == null) {
listViewInflate = inflater.inflate(R.layout.item_menu, viewGroup, false);
}
imgFood = (ImageView) listViewInflate.findViewById(R.id.imageFood);
TextView tituloFood = (TextView) listViewInflate.findViewById(R.id.tittleFood);
TextView descricionFood = (TextView) listViewInflate.findViewById(R.id.descriptionFood);
TextView precio = (TextView) listViewInflate.findViewById(R.id.priceFood);
final Button btnAnadir = (Button) listViewInflate.findViewById(R.id.buttonAnadir);
final Charola.Producto producto = getItem(position);
tituloFood.setText(producto.getNombre().toString());
descricionFood.setText(producto.getDescripcion());
precio.setText("$" + producto.getPrecio() + ".00");
if(producto.isExistencia()){
if (producto.getCantidad() != 0) {
btnAnadir.setText("+ Añadir (" + producto.getCantidad() + ")");
btnAnadir.setBackgroundResource(R.drawable.btns_dialogs);
} else {
btnAnadir.setText("+ Añadir");
btnAnadir.setBackgroundResource(R.drawable.btn_anadir);
}
btnAnadir.setTag(position);
btnAnadir.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("La etiqueta cambio del siguiente forma: "+ btnAnadir.getTag());
btnAnadir.setBackgroundResource(R.drawable.btns_dialogs);
new consumeServiceAgregarProductoACharola().execute(urlComplete + "#" + producto.getIdProducto());
System.out.println("+ Añadir("+(producto.getCantidad()+1)+")");
btnAnadir.setText("+ Añadir("+(producto.getCantidad()+1)+")");
producto.setCantidad((producto.getCantidad()+1));
//notifyDataSetChanged();
}
});
}else{
btnAnadir.setBackgroundResource(R.drawable.btn_agotado);
btnAnadir.setBackgroundResource(R.drawable.btn_agotado);
btnAnadir.setText("Agotado");
}
Glide.with(getContext()).
load(producto.getUrlFoto()).placeholder(R.drawable.place_holder)
.into(imgFood);
//Escalar Vistas
/* GuiTools guiTools = GuiTools.getCurrent();
guiTools.scale(tituloFood);
guiTools.scale(descricionFood);
guiTools.scale(precio);
guiTools.scale(btnAnadir);*/
notifyDataSetChanged();
return listViewInflate;
}
//recuperar id usuario
public int recuperarIdUsario() {
SharedPreferences sharedPreferences = getContext().getSharedPreferences("MIS_PREFRENCIAS", Context.MODE_PRIVATE);
int valor = sharedPreferences.getInt("id", 1);
return valor;
}
//Consume service AgregarProducto
class consumeServiceAgregarProductoACharola extends AsyncTask<String, Void, Void> {
private AlertDialogLoading loading;
#Override
protected Void doInBackground(String... params) {
String delimiter = "#";
String[] arrayLink = params[0].split("#");
URL url = null;
try {
url = new URL(arrayLink[0]);
Log.d("URL ---------->", url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");// La conexión es por el metodo POST
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.connect();
JSONObject jsonParam = new JSONObject();
jsonParam.put("UsuarioId", recuperarIdUsario());
jsonParam.put("ProductoId", arrayLink[1]);
jsonParam.put("Cantidad", 1);
jsonParam.put("Especificaciones", "");
// Send POST output.
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(jsonParam.toString());
out.close();
StringBuilder sb = new StringBuilder();
int HttpResult = urlConnection.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream(), "utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
JSONObject jsonObject = new JSONObject(sb.toString());
Log.d("RESPUESTA ----->",jsonObject.toString());
Log.d("TAMAÑO DEL CH------>", String.valueOf(jsonObject.getInt("TotalCharola")));
totalCharola = String.valueOf(jsonObject.getInt("TotalCharola"));
} else {
Log.e("NO SUCCESS", urlConnection.getResponseMessage());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = new AlertDialogLoading(fragment.getActivity());
loading.messageDialog("", "");
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
PrincipalViewController principalViewController = new PrincipalViewController();
principalViewController.ahBottomNavigation.setNotification(totalCharola,2);
loading.closeMessage();
}
}
}
Related
I need some help, I am developing an app with php and android. I'm using the recycler view, but I'm having problems because my list has 3 items and is showing only one, could you help me? I will add my adapter and my main.
AdapterLocalPersonalizado
public class AdapterLocalPersonalizado extends RecyclerView.Adapter<AdapterLocalPersonalizado.MeuViewHolder> {
Context ctx;
List<Local> listaLocal;
connection con = new connection();
public AdapterLocalPersonalizado(List<Local> locais,Context ctx1) {
this.ctx = ctx1;
this.listaLocal = locais;
}
public class MeuViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView nome,categoria,endereco,valor;
#SuppressLint("WrongViewCast")
public MeuViewHolder(#NonNull View view) {
super(view);
nome = (TextView) view.findViewById(R.id.namec);
categoria = (TextView) view.findViewById(R.id.categoria);
valor = (TextView) view.findViewById(R.id.valor);
endereco = (TextView) view.findViewById(R.id.ende);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Local objSelecionado = listaLocal.get(position);
if(position != RecyclerView.NO_POSITION){
Intent intent = new Intent(ctx.getApplicationContext(), tela_lista_local.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle bundle = new Bundle();
bundle.putInt("ID",objSelecionado.getId());
ctx.startActivity(intent);
}
}
}
#NonNull
#Override
public MeuViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
Local local = listaLocal.get(i);
Context context = viewGroup.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View linhaView = inflater.inflate(R.layout.activity_tela_lista_local_personalizada, viewGroup, false);
MeuViewHolder viewHolder = new MeuViewHolder(linhaView);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull AdapterLocalPersonalizado.MeuViewHolder meuViewHolder, int i) {
Local local = listaLocal.get(i);
TextView nome = meuViewHolder.nome;
nome.setText(local.getNome());
}
#Override
public int getItemCount() {
return listaLocal.size();
}
}
tela_lista_local (main)
public class tela_lista_local extends AppCompatActivity {
AdapterLocalPersonalizado adapterLocalPersonalizado;
List<Local> localList;
Local local;
String endereco,categoria,token;
connection con = new connection();
ListarLocalAsyncTask listarLocaisAsyncTask;
RecyclerView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tela_lista_local);
token = "tcc";
Intent it = getIntent();
categoria = it.getStringExtra("categoria");
endereco = it.getStringExtra("endereco");
listView = findViewById(R.id.recyclerViewLocal);
listarLocaisAsyncTask = new ListarLocalAsyncTask();
listarLocaisAsyncTask.execute();
}
public class ListarLocalAsyncTask extends AsyncTask<String, String, String> {
String api_token, query;
HttpURLConnection conn;
URL url = null;
Uri.Builder builder;
final String URL_WEB_SERVICES = "http://192.168.0.110/Controller/APIListarLocal.php";
final int READ_TIMEOUT = 10000; // MILISSEGUNDOS
final int CONNECTION_TIMEOUT = 30000;
int response_code;
public ListarLocalAsyncTask( ){
this.builder = new Uri.Builder();
builder.appendQueryParameter("api_categoria", categoria);
}
#Override
protected void onPreExecute() {
Log.i("APIListar", "onPreExecute()");
}
#Override
protected String doInBackground(String... strings) {
Log.i("APIListar", "doInBackground()");
// Gerar o conteúdo para a URL
try {
url = new URL(URL_WEB_SERVICES);
} catch (MalformedURLException e) {
Log.i("APIListar", "MalformedURLException --> " + e.getMessage());
} catch (Exception e) {
Log.i("APIListar", "doInBackground() --> " + e.getMessage());
}
// Gerar uma requisição HTTP - POST - Result será um ArrayJson
// conn
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setRequestProperty("charset", "utf-8");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
} catch (Exception e) {
Log.i("APIListar", "HttpURLConnection --> " + e.getMessage());
}
// Adicionar o TOKEN e/ou outros parâmetros como por exemplo
// um objeto a ser incluido, deletado ou alterado.
// CRUD completo
try {
query = builder.build().getEncodedQuery();
OutputStream stream = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(stream, "utf-8"));
writer.write(query);
writer.flush();
writer.close();
stream.close();
conn.connect();
} catch (Exception e) {
Log.i("APIListar", "BufferedWriter --> " + e.getMessage());
}
// receber o response - arrayJson
// http - código do response | 200 | 404 | 503
try {
response_code = conn.getResponseCode();
if (response_code == HttpURLConnection.HTTP_OK) {
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(input)
);
StringBuilder result = new StringBuilder();
String linha = null;
while ((linha = reader.readLine()) != null) {
result.append(linha);
}
return result.toString();
} else {
return "HTTP ERRO: " + response_code;
}
} catch (Exception e) {
Log.i("APIListar", "StringBuilder --> " + e.getMessage());
return "Exception Erro: " + e.getMessage();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
Log.i("APIListar", "onPostExecute()--> Result: " + result);
try {
Local local;
JSONArray jsonArray = new JSONArray(result);
localList = new ArrayList<>();
if (jsonArray.length() != 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
local = new Local(jsonObject.getInt("id"),
jsonObject.getString("nome"),
jsonObject.getString("endereco"),
jsonObject.getString("categoria"),
jsonObject.getString("valor"));
localList.add(local);
Log.i("APIListar", "Estado: -> " + local.getId() + " - " +local.getNome());
}
Toast.makeText(tela_lista_local.this, localList.size() + " local Listados no LogCat", Toast.LENGTH_LONG)
.show();
initial();
}
} catch (Exception e) {
Log.i("APIListar", "onPostExecute()--> " + e.getMessage());
}
}
public void initial(){
adapterLocalPersonalizado = new AdapterLocalPersonalizado(localList, getApplicationContext());
listView.setAdapter(adapterLocalPersonalizado);
listView.setLayoutManager(new LinearLayoutManager(tela_lista_local.this));
}
}
}
It just returns one item but my bank has 3. There are no problems with my API because in debug mode I can see the three items, the problem is when interacting with the list.
Thanks
I guess each item of your recycle view is taking the entire screen and you are only able to see only one item. As #Mike M suggested you can try to scroll and see other item are showing up or not.
If so then make sure your recycle view layout item are not android:layout_width="match_parent" android:layout_height="match_parent".
If you want specific reason, you must post activity_tela_lista_local_personalizada layout.
Happy Coding !
I cannot figure why I getting null listview from it as i tried my url with postman. I think my Android part has some problem with it but i have no idea where the problem.
View Order Activity
public class ViewOrderActivity extends AppCompatActivity {
private ListView listView3;
private CustomAdapter2 listAdapter2;
ArrayList<Order> orderlist = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_order);
User user = SharedPrefManager.getInstance(this).getUser();
String str_oid=String.valueOf(user.getId());
String type="cancel";
BackgroundWorker backgroundWorker=new BackgroundWorker(this);
backgroundWorker.execute(type,str_oid);
listView3 = (ListView) findViewById(R.id.listView3);
getJSON("http://192.168.28.1/restaurant/getorder.php");
}
private void getJSON(final String urlWebService) {
class GetJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
loadIntoListView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON();
getJSON.execute();
}
private void loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
orderlist.add(new Order(obj.getInt("orderid"), obj.getInt("pickuptime"), obj.getInt("pickupdate")));
}
listAdapter2 = new CustomAdapter2(this, orderlist);
listView3.setAdapter(listAdapter2);
}
}
This is custom adapter where the listview is structured.
Custom Adapter
class CustomAdapter2 extends BaseAdapter {
public ArrayList<Order> ordlists;
private Context context;
CustomAdapter2(Context context, ArrayList<Order> ordlists) {
//super(context, R.layout.item_food, strilist);
this.context = context;
this.ordlists = ordlists;
}
#Override
public int getCount(){
return ordlists.size();
}
#Override
public Order getItem(int position){
return ordlists.get(position);
}
#Override
public long getItemId(int position){
return 0;
}
#NonNull
#Override
public View getView(final int position, View convertView, #NonNull ViewGroup parent) {
final ListViewHolder2 listViewHolder2;
View customView2;
if(convertView == null)
{
LayoutInflater menuInflater2 = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// LayoutInflater menuInflater = LayoutInflater.from(getContext());
customView2 = menuInflater2.inflate(R.layout.item_order, parent, false);
listViewHolder2 = new ListViewHolder2();
listViewHolder2.tvorderid = (TextView) customView2.findViewById(R.id.tvorderid );
listViewHolder2.tvtime = (TextView) customView2.findViewById(R.id.tvtime);
listViewHolder2.tvdate = (TextView) customView2.findViewById(R.id.tvdate);
listViewHolder2.btncancel = (Button) customView2.findViewById(R.id.btncancel);
customView2.setTag(listViewHolder2);
}
else
{
customView2=convertView;
listViewHolder2= (ListViewHolder2) customView2.getTag();
}
final Order order=getItem(position);
//Typeface customfont= Typeface.createFromAsset(parent.getContext().getAssets(),"fonts");
listViewHolder2.tvorderid.setText(String.valueOf(order.getOrderid()));
listViewHolder2.tvorderid.setTextColor(Color.YELLOW);
listViewHolder2.tvorderid.setTextSize(10);
listViewHolder2.tvtime.setText(String.valueOf(order.getPickuptime()));
listViewHolder2.tvtime.setTextColor(Color.YELLOW);
listViewHolder2.tvtime.setTextSize(10);
listViewHolder2.tvdate.setText(String.valueOf(order.getPickupdate()));
listViewHolder2.tvdate.setTextColor(Color.YELLOW);
listViewHolder2.tvdate.setTextSize(10);
listViewHolder2.btncancel.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
}
});
return customView2;
}
Background Worker for cancel type
else if (type.equals("cancel")){
try{
String id=params[1];
URL url=new URL(cancel_url);
HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream=httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String post_data= URLEncoder.encode("id","UTF-8")+"="+URLEncoder.encode(id,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream=httpURLConnection.getInputStream();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line=bufferedReader.readLine())!=null){
result+=line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
}catch(MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
This is my code for url getorder.php
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$database = "y77";
$conn = new mysqli($hostname, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$orders = array();
session_start();
$id=$_POST["id"];
$stmt =$conn->prepare("SELECT `orderid`, `pickuptime`, `pickupdate` FROM `order` WHERE `id`=$id");
$stmt->execute();
$stmt->bind_result($orderid, $pickuptime, $pickupdate);
while($stmt->fetch()){
$temp = [
'orderid'=>$orderid,
'pickuptime'=>$pickuptime,
'pickupdate'=>$pickupdate
];
array_push($orders, $temp);
}
echo json_encode($orders);
?>
I have to run json format which is shown in below
and have to parse this data into listview
and for this i tried following code
MainActivity
swipeRefreshLayout.setOnRefreshListener(this);
// swipeRefreshLayout.setRefreshing(true);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
SyncMethod("http://52.26.35.210/api/web/v1/api-beautician/country-state-city");
}
}
);
notification_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String postloadid = actorsList.get(position).gettitle();
String source_addoc=actorsList.get(position).gettitle();
Constants.vCountry=actorsList.get(position).gettitle();
Toast.makeText(getApplicationContext(),"Selecting "+ Constants.vCountry+" State ", Toast.LENGTH_LONG).show();
finish();
}
});
}
public void init()
{
norecord=(LinearLayout)findViewById(R.id.norecord);
notification_listview=(ListView)findViewById(R.id.listView_notification);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
}
#Override
public void onRefresh()
{
swipeRefreshLayout.setRefreshing(false);
SyncMethod("http://52.26.35.210/api/web/v1/api-beautician/country-state-city");
}
private static String pad(int c)
{
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
#Override
public void onResume()
{
super.onResume();
swipeRefreshLayout.setRefreshing(false);
SyncMethod("http://52.26.35.210/api/web/v1/api-beautician/country-state-city");
}
public void SyncMethod(final String GetUrl)
{
Log.i("Url.............", GetUrl);
final Thread background = new Thread(new Runnable() {
// After call for background.start this run method call
public void run() {
try {
String url = GetUrl;
String SetServerString = "";
// document all_stuff = null;
SetServerString = fetchResult(url);
threadMsg(SetServerString);
} catch (Throwable t) {
Log.e("Animation", "Thread exception " + t);
}
}
private void threadMsg(String msg) {
if (!msg.equals(null) && !msg.equals("")) {
Message msgObj = handler11.obtainMessage();
Bundle b = new Bundle();
b.putString("message", msg);
msgObj.setData(b);
handler11.sendMessage(msgObj);
}
}
// Define the Handler that receives messages from the thread and update the progress
private final Handler handler11 = new Handler() {
public void handleMessage(Message msg) {
try {
String aResponse = msg.getData().getString("message");
Log.e("Exam", "screen>>" + aResponse);
swipeRefreshLayout.setRefreshing(false);
JSONObject jobj = new JSONObject(aResponse);
Log.e("Home Get draft--", jobj.toString());
String status = jobj.getString("status");
Log.e("Myorder Homestatusdraft",status);
Log.e("--------------------", "----------------------------------");
if (status.equalsIgnoreCase("true"))
{
actorsList = new ArrayList<Doctortype_method>();
JSONArray array = new JSONArray();
array = jobj.getJSONArray("response");
if(actorsList.size()>0){
actorsList.clear();
}
for(int i=0;i<array.length();i++)
{
JSONObject jsonChildNode = array.getJSONObject(i);
actorsList.add(new Doctortype_method(jsonChildNode.optString("State id"),jsonChildNode.optString("State name")));
}
if (getApplicationContext() != null)
{
if (adapter == null)
{
adapter = new Doctortype_Adapter(getApplicationContext(),actorsList);
notification_listview.setAdapter(adapter);
} else {
adapter.notifyDataSetChanged();
}
}
if(actorsList.size()==0)
{
norecord.setVisibility(View.VISIBLE);
}
}
else
{
swipeRefreshLayout.setRefreshing(false);
norecord.setVisibility(View.VISIBLE);
// UF.msg(message + "");
}
} catch (Exception e) {
}
}
};
});
// Start Thread
background.start();
}
public String fetchResult(String urlString) throws JSONException {
StringBuilder builder;
BufferedReader reader;
URLConnection connection = null;
URL url = null;
String line;
builder = new StringBuilder();
reader = null;
try {
url = new URL(urlString);
connection = url.openConnection();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
//Log.d("DATA", builder.toString());
} catch (Exception e) {
}
//JSONArray arr=new JSONArray(builder.toString());
return builder.toString();
}
}
For this i also add adapter as well as arraylist.
but when i run this application api is not called perfectly..
hope anyone a]can help me..
here i add adapter and arraylist
Adapter
public Doctortype_Adapter(Context context, ArrayList<Doctortype_method> objects) {
super(context, R.layout.list_doctortype, objects);
this.context = context;
this.vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.actorList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
//View v = convertView;
View rowView;
ViewHolder vh;
if (convertView == null) {
rowView = vi.inflate(R.layout.list_doctortype, null);
setViewHolder(rowView);
} else {
rowView = convertView;
}
vh = (ViewHolder) rowView.getTag();
vh.title.setText(Html.fromHtml(actorList.get(position).gettitle()));
vh.subtitle.setText(Html.fromHtml(actorList.get(position).getsubtitle()));
/* String image=actorList.get(position).getid();
UrlImageViewHelper.setUrlDrawable(vh.dimage, image.toString(), R.drawable.no_img);*/
return rowView;
}
static class ViewHolder {
public TextView title, subtitle;
}
private void setViewHolder(View rowView) {
ViewHolder vh = new ViewHolder();
vh.title = (TextView) rowView.findViewById(R.id.tvProfileName);
vh.subtitle = (TextView) rowView.findViewById(R.id.tvDesc);
}
}
arraylist
public Doctortype_method( String title, String subtitle) {
super();
this.title = title;
this.subtitle = subtitle;
}
public String gettitle() {
return title;
}
public void settitle(String title) {
this.title = title;
}
public String getsubtitle()
{
return subtitle;
}
public void setsubtitle(String subtitle) {
this.subtitle = subtitle;
}
there is no error but when i run this code api is not called and i didnt get the output i want.
Thnx in advance..
if (status.equalsIgnoreCase("true")) is wrong because you getting status:1 so it is if (status.equalsIgnoreCase("1")) try this and then change this array = jobj.getJSONArray("response"); to array = jobj.getJSONArray("data"); your JSONArray key is "data"
And replace this also
actorsList.add(new Doctortype_method(jsonChildNode.optString("State id"),jsonChildNode.optString("State name")));
with
actorsList.add(new Doctortype_method(jsonChildNode.optString("countryID"),jsonChildNode.optString("vCountry")));
hope this helps. if this doesn't help feel free to ask
EDIT:
I cant understand what you want but have a look at this
-> you need to create baseAdapter for listview and set that adapter into the listview with your arraylist
FOR FETCHING YOUR ABOVE DATA YOU NEED TO DO BELOW CODE:
String data;//your entire JSON data as String
try {
JSONObject object = new JSONObject(data);
String status = object.getString("status");
JSONArray dataArray = object.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
JSONObject json1 = dataArray.getJSONObject(i);
String countryID = json1.getString("countryID");
String vCountry = json1.getString("vCountry");
}
} catch (JSONException e) {
e.printStackTrace();
}
Now if you want to show this vCountry in listview you have to add vCountry in ArrayList and then in listview.setAdapter you have to pass this ArrayList which is filled by vCountry. Hope you understand now. If you want adapter and listview code please check this link http://www.vogella.com/tutorials/AndroidListView/article.html
Finally i got the right answer.
May anyone get help from this in future.
ActivityClass.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city_list_item);
lv_city = (ListView)findViewById(R.id.listView_city);
Bundle b=getIntent().getExtras();
city_stateid = b.getString("stateid");
city_statename=b.getString("stateName");
city_countryid=b.getString("country");
lv_city.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
page_cityname = cityist.get(position).getCityName();
SharedPreferences sp=getSharedPreferences("abc",MODE_WORLD_WRITEABLE);
SharedPreferences.Editor edit=sp.edit();
edit.putString("city_name", page_cityname);
edit.commit();
Toast.makeText(getApplicationContext(),"Selected city & State"+page_cityname + "-" +city_statename, Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), NextActivity.class);
/*i.putExtra("cityname", page_cityname);*/
startActivity(i);
}
});
}
#Override
public void onResume() {
super.onResume();
params12 = new ArrayList<NameValuePair>();
params12.add(new BasicNameValuePair("type", city_type));
params12.add(new BasicNameValuePair("stateID", city_stateid));
params12.add(new BasicNameValuePair("countryID", city_countryid));
new Sync().execute();
}
class Sync extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(Void... params) {
String obj;//new JSONArray();
try {
// obj=getJSONFromUrl("Your posting path", params11);
obj = getJSONFromUrl("http://52.26.35.210/api/web/v1/api-beautician/country-state-city", params12);
return obj;
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
Log.e("Result of geting data", "" + result);
try {
Log.e("Exam", "screen>>" + result);
JSONObject get_res = new JSONObject(result);
String status = get_res.getString("status");
Log.e("Exam", "screen33333>>" + status);
if (status.equalsIgnoreCase("1")) {
cityist = new ArrayList<city_method>();
JSONArray array = new JSONArray();
array = get_res.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
cityist.add(new city_method(array.getJSONObject(i).getString("cityID"),array.getJSONObject(i).getString("cityName")));
}
if (getApplicationContext() != null)
{
if (adapter == null)
{
adapter = new city_Adapter(getApplicationContext(),cityist);
lv_city.setAdapter(adapter);
} else {
adapter.notifyDataSetChanged();
}
}
}
} catch (Exception e) {
}
}
}
public String fetchResult(String urlString) throws JSONException {
StringBuilder builder;
BufferedReader reader;
URLConnection connection = null;
URL url = null;
String line;
builder = new StringBuilder();
reader = null;
try {
url = new URL(urlString);
connection = url.openConnection();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
//Log.d("DATA", builder.toString());
} catch (Exception e) {
}
//JSONArray arr=new JSONArray(builder.toString());
return builder.toString();
}
public String getJSONFromUrl(String url, List<NameValuePair> params) {
InputStream is = null;
String json = "";
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
//sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
}
Adapterclass.java
public class city_Adapter extends ArrayAdapter<city_method> {
ArrayList<city_method> citylist;
LayoutInflater vi;
Context context;
public city_Adapter(Context context, ArrayList<city_method> items) {
super(context, R.layout.list_doctortype, items);
this.context = context;
this.vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.citylist = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
//View v = convertView;
View rowView;
city_Adapter.ViewHolder vh;
if (convertView == null) {
rowView = vi.inflate(R.layout.program_list, null);
setViewHolder(rowView);
} else {
rowView = convertView;
}
vh = (city_Adapter.ViewHolder) rowView.getTag();
vh.cityid.setText((citylist.get(position).getCityID()));
vh.cityname.setText((citylist.get(position).getCityName()));
return rowView;
}
static class ViewHolder {
private TextView cityid,cityname;
}
private void setViewHolder(View rowView) {
ViewHolder vh = new ViewHolder();
vh.cityid = (TextView) rowView.findViewById(R.id.cityid);
vh.cityname = (TextView) rowView.findViewById(R.id.cityname);
rowView.setTag(vh);
}
}
Methodclass.java
public class city_method {
private String cityID,cityName;
public String getCityID() {
return cityID;
}
public void setCityID(String cityID) {
this.cityID = cityID;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public city_method(String cityID, String cityName) {
this.cityID = cityID;
this.cityName = cityName;
}
}
JSONParser.class
package com.example.diptiagravat.myapplication;
public class JSONParser {
public String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
public String sendHTTPData(String urlpath, String id) {
HttpURLConnection connection = null;
try {
URL url=new URL(urlpath);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
streamWriter.write(id);
streamWriter.flush();
StringBuilder stringBuilder = new StringBuilder();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(streamReader);
String response = null;
while ((response = bufferedReader.readLine()) != null) {
stringBuilder.append(response + "\n");
}
bufferedReader.close();
Log.d("test", stringBuilder.toString());
return stringBuilder.toString();
} else {
Log.e("test", connection.getResponseMessage());
return null;
}
} catch (Exception exception){
Log.e("test", exception.toString());
return null;
} finally {
if (connection != null){
connection.disconnect();
}
}
}
}
MainActivity.java
package com.example.diptiagravat.myapplication;
public class MainActivity extends AppCompatActivity {
private TextView txtid, txtcname;
Spinner spcnt, spstate;
public ArrayList<String> clist;
ArrayAdapter<String> cad;
public ArrayList<String> slist;
ArrayAdapter<String> sad;
public String strcnt;
private static String url = "http://urmiinfotech.com/demo/ifirst/app_api/get_country_list.php";
private static String stateUrl = "http://urmiinfotech.com/demo/ifirst/app_api/get_state_list.php";
private static final String TAG_USER = "country";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "country_name";
private ArrayList<Country> clistModels;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
CountryAsyncTask countryAsyncTask= new CountryAsyncTask();
countryAsyncTask.execute();
}
private void initViews() {
txtid = (TextView) findViewById(R.id.tvid);
txtcname = (TextView) findViewById(R.id.tvcname);
spcnt = (Spinner) findViewById(R.id.spcnt);
spstate = (Spinner) findViewById(R.id.spstate);
clist = new ArrayList<String>();
slist = new ArrayList<String>();
}
public class CountryAsyncTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = null;
try {
json = new JSONObject(jParser.getJSON(url, 5000));
} catch (JSONException e) {
e.printStackTrace();
}
return json.toString();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.i("Result Ravi", result);
try {
JSONObject obj = new JSONObject(result);
JSONArray cntArray = obj.getJSONArray("country");
if (cntArray.length() > 0) {
for (int i = 0; i < cntArray.length(); i++) {
final JSONObject temp = cntArray.getJSONObject(i);
// txtid.setText(temp.getString("id"));
// txtcname.setText(temp.getString("country_name"));
Country country = new Gson().fromJson(temp.toString(), Country.class);
clist = new ArrayList<String>();
clistModels = new ArrayList<Country>();
clistModels.add(new Country(temp.optString("id"), temp.optString("country_name"), "", null));
clist.add(temp.getString("country_name"));
cad = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, clist);
spcnt.setAdapter(cad);
spcnt.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
strcnt = clistModels.get(position).getId();
//strcnt = parent.getItemAtPosition(position).toString();
Log.i("id", strcnt);
new StatesAsyncTask().execute();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// txtid.setText(temp.getString(country.getId()));
// txtcname.setText(temp.getString(country.getCountryName()));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class StatesAsyncTask extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = null;
try {
json = new JSONObject(jParser.sendHTTPData(stateUrl, strcnt));
} catch (JSONException e) {
e.printStackTrace();
}
return json.toString();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject obj = new JSONObject(s);
JSONArray stArray = obj.getJSONArray("statelist");
if (stArray.length() > 0) {
for (int i = 0; i < stArray.length(); i++) {
final JSONObject temp = stArray.getJSONObject(i);
// txtid.setText(temp.getString("id"));
// txtcname.setText(temp.getString("country_name"));
Statelist stlist = new Gson().fromJson(temp.toString(), Statelist.class);
slist = new ArrayList<String>();
// clistModels = new ArrayList<Country>();
//clistModels.add(new Country(temp.optString("id"), temp.optString("country_name"), "", null));
slist.add(temp.getString("state_name"));
sad = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, slist);
spstate.setAdapter(sad);
spstate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// strcnt = clistModels.get(position).getId();
//strcnt = parent.getItemAtPosition(position).toString();
// Log.i("id", strcnt);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// txtid.setText(temp.getString(country.getId()));
// txtcname.setText(temp.getString(country.getCountryName()));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
My response is null?
HttpURLConnection is deprecated in Android Lollipop, so please try to use DefaultHttpClient instead. Also, check your logs, this is at your onPostExecute():
Log.i("Result Ravi", result);
For DefaultHttpClient check this post.
Another way is to try Retrofit
I'm doing a app can update data every 1 minutes, data will from database mysql on server to show on listview of my app android. My problem is when show data the first is ok but when show data the second on listview, data of the first and the second is duplication.Can you help me!
Source code:
public class Hoadon extends Activity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<String> al = new ArrayList<String>();
ArrayList<String> al1 = new ArrayList<String>();
ArrayList<String> al2 = new ArrayList<String>();
ArrayList<String> al3 = new ArrayList<String>();
ArrayList<String> al1a = new ArrayList<String>();
String date;
String name;
String address;
String url;
String code;
int responseCode;
private String IDinvoice;
private TimerTask mTimerTask;
private Timer t=new Timer();
private final Handler handler=new Handler();
private ListView listview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hoadon);
int currentOrientation = getResources().getConfiguration().orientation;
if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
}
else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
}
try {
URL url = new URL("http://longvansolution.tk/monthlytarget.php");
URLConnection connection = url.openConnection();
connection.setConnectTimeout(2000);
HttpURLConnection httpConnection = (HttpURLConnection) connection;
responseCode = httpConnection.getResponseCode();
} catch (Exception e) {
}
try {
if (isNetworkAvailable() == true
//&& responseCode == HttpURLConnection.HTTP_OK
) {
//new LoadData().execute();
al.clear();
al1.clear();
al2.clear();
al3.clear();
al1a.clear();
doTimerTask();
} else {
AlertDialog.Builder ad = new AlertDialog.Builder(this);
ad.setMessage("No Internet Connection available!!!");
ad.show();
}
} catch (Exception e) {
}
Bundle extras = getIntent().getExtras();
if (extras != null) {
IDinvoice = extras.getString("IDinvoice");
}
}
public void doTimerTask(){
mTimerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
new LoadData().execute();
Log.d("TIMER", "TimerTask run");
}
});
}};
// public void schedule (TimerTask task, long delay, long period)
t.schedule(mTimerTask, 500, 10000); //
}
#Override
public void onBackPressed() {
//do something with bitmap
}
private class LoadData extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
// can use UI thread here
protected void onPreExecute() {
this.progressDialog = ProgressDialog.show(
Hoadon.this, "", " Loading...");
}
#Override
protected void onPostExecute(final Void unused) {
this.progressDialog.dismiss();
try {
listview = (ListView) findViewById(R.id.listView1);
this.progressDialog.dismiss();
listview.setAdapter(new DataAdapter(Hoadon.this,
al.toArray(new String[al.size()]), al1a
.toArray(new String[al1a.size()]), al1
.toArray(new String[al1.size()]), al2
.toArray(new String[al2.size()])));
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String t = al3.get(position);
Intent i = new Intent(Hoadon.this,
Signature.class);
i.putExtra("url", t);
startActivity(i);
}
});
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// HTTP post
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(
"http://longvansolution.tk/monthlytarget.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
// buffered reader
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 80);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
date = json_data.getString("date");
address = json_data.getString("address");
name = json_data.getString("name");
url = json_data.getString("url");
code = json_data.getString("code");
al.add(date);
al1a.add(code);
al1.add(name);
al2.add(address);
al3.add(url);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
} catch (ParseException e) {
// Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
// Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
return null;
}
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// if no network is available networkInfo will be null, otherwise check
// if we are connected
if (networkInfo != null && networkInfo.isConnected()) {
// Log.i("net status:", "Online...!!!");
return true;
}
// Log.i("net status:", "offline...!!!");
return false;
}
}
Source DataAdapter
public class DataAdapter extends BaseAdapter {
Context mContext;
private LayoutInflater mInflater;
String[] date;
String[] code;
String[] address;
String[] name;
public DataAdapter(Context c, String[] date,String[] code, String[] name, String[] address) {
this.date = date;
this.code=code;
this.name = name;
this.address = address;
mContext = c;
mInflater = LayoutInflater.from(c);
}
public void clearData() {
// clear the data
Arrays.fill(date, null);
Arrays.fill(code, null);
Arrays.fill(address, null);
Arrays.fill(name, null);
}
public int getCount() {
return date.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.customgrid, parent, false);
holder = new ViewHolder();
holder.date = (TextView) convertView.findViewById(R.id.date);
holder.code=(TextView)convertView.findViewById(R.id.mahd);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.address = (TextView) convertView.findViewById(R.id.address);
if (position == 0) {
convertView.setTag(holder);
}
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
holder.date.setText(date[position]);
holder.code.setText(code[position]);
holder.name.setText(name[position]);
holder.address.setText(address[position]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return convertView;
}
static class ViewHolder {
TextView date,code;
TextView name, address;
}
}
you should clear your arralist every LoadData task.
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
al.clear();
al1.clear();
al2.clear();
al3.clear();
al1a.clear();
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
date = json_data.getString("date");
address = json_data.getString("address");
name = json_data.getString("name");
url = json_data.getString("url");
code = json_data.getString("code");
al.add(date);
al1a.add(code);
al1.add(name);
al2.add(address);
al3.add(url);
}