edit item in listview with custom adapter depending on value - android

When I click on a button within my listview, I call a function where I send a value clearly depending on which button is clicked. When I get a positive response function of the item field changes value, in the first instance is to validado = 0 and if you click on the button changes to validado = 1. If validated this to 1, the button should have a background image as warning that this item is already validated. All this works well for me at first, but if I click on any button, regardless of how many items are on my list, always changes the item to which it is clicked and also the first item on my list. Pretty funny when my data base both locally and in my server, the validated value of the first item remains 0
getView in my adapter
#Override
public View getView(int position, View convertView, final ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.lista_validacion_multiple, null);
holder = new ViewHolder();
holder.txtNombre = (TextView)convertView.findViewById(R.id.txtNombre);
holder.txtAsiento = (TextView)convertView.findViewById(R.id.txtAsiento);
holder.txtTicket = (TextView)convertView.findViewById(R.id.txtTicket);
holder.txtNumero = (TextView)convertView.findViewById(R.id.txtNumero);
holder.btn = (Button)convertView.findViewById(R.id.button1);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtNombre.setText("Nombre :"+rowItem.getNombre());
holder.txtTicket.setText("Ticket :"+rowItem.getTicket());
if (!rowItem.getAsiento().equals("") && !rowItem.getAsiento().equals("null") && rowItem.getAsiento() != null) {
holder.txtAsiento.setText("Asiento :"+rowItem.getAsiento());
}
if (!rowItem.getNumero().equals("") && !rowItem.getNumero().equals("null") && rowItem.getNumero() != null) {
holder.txtNumero.setText("Número :"+rowItem.getNumero());
}
System.out.println("item "+rowItem.getId_inscripcion()+" validado = "+rowItem.getValidado());
if(rowItem.getValidado()==1){
System.out.println("ENTRO");
holder.btn.setBackgroundResource(R.drawable.icon_big_alert);
holder.btn.setText("");
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams((int)LayoutParams.WRAP_CONTENT, (int)LayoutParams.WRAP_CONTENT);
params.width = 50;
params.height = 50;
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
holder.btn.setLayoutParams(params);
}else{
holder.btn.setTag(position);
holder.btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position=(Integer)v.getTag();
RowItem item_click = getItem(position);
Connection cn = new Connection();
SessionManager manager = new SessionManager();
BaseDeDatos nueva = new BaseDeDatos();
JSONObject json = new JSONObject();
if(cn.isNetworkAvailable(parent.getContext())){
String nombreCliente = manager.getValue(parent.getContext(), "nombreCliente");
String user = manager.getValue(parent.getContext(), "nombreUser");
String folioEvento = manager.getValue(parent.getContext(), "folioEvento");
String codigoEvento = manager.getValue(parent.getContext(), "codigoEvento");
String seleccionValidadora = manager.getValue(parent.getContext(), "opcionVerificadora");
String nombreUser = manager.getValue(parent.getContext(), "nombreUser");
String hashUser = manager.getValue(parent.getContext(), "hashUsuario");
String URL_TICKET = Config.URL_BASE + nombreCliente
+ "/" + Config.URL_VALIDACION_TICKET
+ nombreUser + "/" + hashUser + "/"
+ folioEvento + "/" + item_click.getHash()
+ "/0/";
System.out.println(URL_TICKET);
if (manager.getValue(parent.getContext(),
"checkin") != null) {
int id_checkin = nueva.idCheckin(parent.getContext(), manager.getValue(parent.getContext(),"checkin"));
String url = URL_TICKET + id_checkin;
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setHeader("content-type",
"application/json");
try {
// Construimos el objeto cliente en formato
// JSON
JSONObject dato = new JSONObject();
StringEntity entity = new StringEntity(
dato.toString());
post.setEntity(entity);
HttpResponse resp = httpClient
.execute(post);
String respStr = EntityUtils.toString(resp
.getEntity());
JSONObject respJSON = new JSONObject(
respStr);
json = respJSON;
} catch (Exception ex) {
Log.e("ServicioRest", "Error!", ex);
}
} else {
String url = URL_TICKET;
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setHeader("content-type",
"application/json");
try {
// Construimos el objeto cliente en formato
// JSON
JSONObject dato = new JSONObject();
StringEntity entity = new StringEntity(
dato.toString());
post.setEntity(entity);
HttpResponse resp = httpClient
.execute(post);
String respStr = EntityUtils.toString(resp
.getEntity());
JSONObject respJSON = new JSONObject(
respStr);
json = respJSON;
} catch (Exception ex) {
Log.e("ServicioRest", "Error!", ex);
}
}
System.out.println(json);
}else{
}
}
});
}
return convertView;
}
I show logs to show that the value is still 0
08-07 13:39:21.890: I/System.out(14317): item 936 validado = 0
08-07 13:39:21.890: I/System.out(14317): item 937 validado = 0
08-07 13:39:21.890: I/System.out(14317): item 938 validado = 0
This log out when you first enter the view of the listview, then I will validate an inscription, whatever, and this is what I get
08-07 13:44:08.300: I/System.out(14317): item 936 validado = 0
08-07 13:44:08.300: I/System.out(14317): item 937 validado = 1
08-07 13:44:08.305: I/System.out(14317): item 938 validado = 0
That's all right, except the first item plus the charge to the button that validates an image which I just want to be charged to the element that is in rowItem.getValidado()==1
EDIT
I answered my question.

So you click on 1 item on the ListView it changes it look (which is intended), because your value changes to 1. But no matter what, the first Visible item in the ListView also changes (unintended)?
I am no expert but I gather you have an issue with your ViewHolder. Try removing the ViewHolder logic and see if you still get the issue (for testing). ListView is tricky with the recycling of Views and repopulating them with new data. Might even have an issue with your getItem(). But I suspect it's the ViewHolder logic.
Also do you need to declare that Inflater every time getView() is called? prob ought to move that up to Constructor and just instantiate it in the getView().

The error was where the code to and not how.
#Override
public View getView(int position, View convertView, final ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.lista_validacion_multiple, null);
holder = new ViewHolder();
holder.txtNombre = (TextView)convertView.findViewById(R.id.txtNombre);
holder.txtAsiento = (TextView)convertView.findViewById(R.id.txtAsiento);
holder.txtTicket = (TextView)convertView.findViewById(R.id.txtTicket);
holder.txtNumero = (TextView)convertView.findViewById(R.id.txtNumero);
holder.btn = (Button)convertView.findViewById(R.id.button1);
holder.txtNombre.setText("Nombre :"+rowItem.getNombre());
holder.txtTicket.setText("Ticket :"+rowItem.getTicket());
if (!rowItem.getAsiento().equals("") && !rowItem.getAsiento().equals("null") && rowItem.getAsiento() != null) {
holder.txtAsiento.setText("Asiento :"+rowItem.getAsiento());
}
if (!rowItem.getNumero().equals("") && !rowItem.getNumero().equals("null") && rowItem.getNumero() != null) {
holder.txtNumero.setText("Número :"+rowItem.getNumero());
}
System.out.println("item "+rowItem.getId_inscripcion()+" validado = "+rowItem.getValidado());
if(rowItem.getValidado()==1){
holder.btn.setBackgroundResource(R.drawable.icon_big_alert);
holder.btn.setText("");
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams((int)LayoutParams.WRAP_CONTENT, (int)LayoutParams.WRAP_CONTENT);
params.width = 50;
params.height = 50;
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
holder.btn.setLayoutParams(params);
}else{
holder.btn.setTag(position);
holder.btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position=(Integer)v.getTag();
RowItem item_click = getItem(position);
Connection cn = new Connection();
SessionManager manager = new SessionManager();
BaseDeDatos nueva = new BaseDeDatos();
JSONObject json = new JSONObject();
if(cn.isNetworkAvailable(parent.getContext())){
String nombreCliente = manager.getValue(parent.getContext(), "nombreCliente");
String user = manager.getValue(parent.getContext(), "nombreUser");
String folioEvento = manager.getValue(parent.getContext(), "folioEvento");
String codigoEvento = manager.getValue(parent.getContext(), "codigoEvento");
String seleccionValidadora = manager.getValue(parent.getContext(), "opcionVerificadora");
String nombreUser = manager.getValue(parent.getContext(), "nombreUser");
String hashUser = manager.getValue(parent.getContext(), "hashUsuario");
String URL_TICKET = Config.URL_BASE + nombreCliente
+ "/" + Config.URL_VALIDACION_TICKET
+ nombreUser + "/" + hashUser + "/"
+ folioEvento + "/" + item_click.getHash()
+ "/0/";
System.out.println(URL_TICKET);
if (manager.getValue(parent.getContext(),
"checkin") != null) {
int id_checkin = nueva.idCheckin(parent.getContext(), manager.getValue(parent.getContext(),"checkin"));
String url = URL_TICKET + id_checkin;
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setHeader("content-type",
"application/json");
try {
// Construimos el objeto cliente en formato
// JSON
JSONObject dato = new JSONObject();
StringEntity entity = new StringEntity(
dato.toString());
post.setEntity(entity);
HttpResponse resp = httpClient
.execute(post);
String respStr = EntityUtils.toString(resp
.getEntity());
JSONObject respJSON = new JSONObject(
respStr);
json = respJSON;
} catch (Exception ex) {
Log.e("ServicioRest", "Error!", ex);
}
} else {
String url = URL_TICKET;
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setHeader("content-type",
"application/json");
try {
// Construimos el objeto cliente en formato
// JSON
JSONObject dato = new JSONObject();
StringEntity entity = new StringEntity(
dato.toString());
post.setEntity(entity);
HttpResponse resp = httpClient
.execute(post);
String respStr = EntityUtils.toString(resp
.getEntity());
JSONObject respJSON = new JSONObject(
respStr);
json = respJSON;
} catch (Exception ex) {
Log.e("ServicioRest", "Error!", ex);
}
}
System.out.println(json);
}else{
}
}
});
}
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
return convertView;
}

Related

Images inside a customadapter not updating like strings are to fill a listview

I'll try my best explaining whats happening, so my code has a forloop which fills a listview, this listview is showing all the correct data from a json file, excpet for the images, the images are always from the last position in the listview and then copied to the one above, for example here
This is one single activity which i just and to snippet to make it fit. I'm guessing its something to do with the strings which i create to make the images, they are somehow being used twice, and then used again to fill the listview, even though all of the other strings are being reset and filled when its gets the new information from the JSON. Heres my code if anyone would could tell me why this is only happening to the images and not the strings which create the names of items
String ChampionName;
String item2;
String item3;
String item4;
private String ItemName;
private String ItemName2;
private String ItemName3;
private String ItemName4;
private String ItemName5;
private String ItemName6;
private String ItemNameHW;
private String ItemName2HW;
private String ItemName3HW;
private String ItemName4HW;
private String ItemName5HW;
private String ItemName6HW;
private ListView Champ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// http://api.champion.gg/champion/Ekko/
new JSONTask().execute("http://api.champion.gg/champion/aatrox/");
Champ = (ListView) findViewById(R.id.listView);
}
public class JSONTask extends AsyncTask<String, String, List<Layoutmodel>> {
#Override
protected List<Layoutmodel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder buffer = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray jsonarray = new JSONArray(finalJson);
List<Layoutmodel> LayoutModelList = new ArrayList<>();
//Number changes to what ever role you want it to be
//JSONObject finalObject = jsonarray.getJSONObject(jsonarray.length()-1);
for (int k = 0; k < jsonarray.length(); k++) {
JSONObject finalObject = jsonarray.getJSONObject(k);
Layoutmodel layoutmodel = new Layoutmodel();
layoutmodel.setChampionName2(finalObject.getString("key"));
layoutmodel.setRole(finalObject.getString("role"));
ChampionName = finalObject.getString("key");
String role = finalObject.getString("role");
String overallPosition = finalObject.getString("overallPosition");
JSONObject ItemArray4 = new JSONObject(overallPosition);
String champpos = ItemArray4.getString("position");
String items = finalObject.getString("items");
JSONObject ItemArray = new JSONObject(items);
item2 = ItemArray.getString("mostGames");
item3 = ItemArray.getString("highestWinPercent");
JSONObject ItemArray2 = new JSONObject(item2);
JSONObject ItemArray3 = new JSONObject(item3);
item3 = ItemArray2.getString("items");
item4 = ItemArray3.getString("items");
JSONArray jsonarray2 = new JSONArray(item3);
JSONArray jsonarray3 = new JSONArray(item4);
JSONObject finalObject2 = jsonarray2.getJSONObject(jsonarray2.length() - 6);
ItemName = finalObject2.getString("name");
JSONObject finalObject3 = jsonarray2.getJSONObject(jsonarray2.length() - 5);
ItemName2 = finalObject3.getString("name");
JSONObject finalObject4 = jsonarray2.getJSONObject(jsonarray2.length() - 4);
ItemName3 = finalObject4.getString("name");
JSONObject finalObject5 = jsonarray2.getJSONObject(jsonarray2.length() - 3);
ItemName4 = finalObject5.getString("name");
JSONObject finalObject6 = jsonarray2.getJSONObject(jsonarray2.length() - 2);
ItemName5 = finalObject6.getString("name");
JSONObject finalObject7 = jsonarray2.getJSONObject(jsonarray2.length() - 1);
ItemName6 = finalObject7.getString("name");
//Highest win names
JSONObject finalObject8 = jsonarray3.getJSONObject(jsonarray3.length() - 6);
ItemNameHW = finalObject8.getString("name");
JSONObject finalObject9 = jsonarray3.getJSONObject(jsonarray3.length() - 5);
ItemName2HW = finalObject9.getString("name");
JSONObject finalObject10 = jsonarray3.getJSONObject(jsonarray3.length() - 4);
ItemName3HW = finalObject10.getString("name");
JSONObject finalObject11 = jsonarray3.getJSONObject(jsonarray3.length() - 3);
ItemName4HW = finalObject11.getString("name");
JSONObject finalObject12 = jsonarray3.getJSONObject(jsonarray3.length() - 2);
ItemName5HW = finalObject12.getString("name");
JSONObject finalObject13 = jsonarray3.getJSONObject(jsonarray3.length() - 1);
ItemName6HW = finalObject13.getString("name");
layoutmodel.setItem1(ItemName);
layoutmodel.setItem2(ItemName2);
layoutmodel.setItem3(ItemName3);
layoutmodel.setItem4(ItemName4);
layoutmodel.setItem5(ItemName5);
layoutmodel.setItem6(ItemName6);
layoutmodel.setItem1HW(ItemNameHW);
layoutmodel.setItem2HW(ItemName2HW);
layoutmodel.setItem3HW(ItemName3HW);
layoutmodel.setItem4HW(ItemName4HW);
layoutmodel.setItem5HW(ItemName5HW);
layoutmodel.setItem6HW(ItemName6HW);
layoutmodel.setRole(role);
layoutmodel.setChampionName2(ChampionName);
layoutmodel.setChamppos(champpos);
LayoutModelList.add(layoutmodel);
}
return LayoutModelList;
} catch (JSONException | IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<Layoutmodel> result) {
super.onPostExecute(result);
LayoutAdapter adapter2 = new LayoutAdapter(getApplicationContext(), R.layout.rows, result);
Champ.setAdapter(adapter2);
}
}
public class LayoutAdapter extends ArrayAdapter {
private List<Layoutmodel> LayoutModelList2;
private int resource;
private LayoutInflater inflater;
public LayoutAdapter(Context context2, int resource, List<Layoutmodel> objects) {
super(context2, resource, objects);
LayoutModelList2 = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position2, View convertView2, ViewGroup parent2) {
ViewHolder holder = null;
if (convertView2 == null) {
holder = new ViewHolder();
convertView2 = inflater.inflate(resource, null);
holder.nameofchamp = (TextView) convertView2.findViewById(R.id.textView);
holder.position = (TextView) convertView2.findViewById(R.id.smalltxt);
holder.Champposition = (TextView) convertView2.findViewById(R.id.textView17);
String ItemNameInLowerCase;
String ItemName2InLowerCase;
String ItemName3InLowerCase;
String ItemName4InLowerCase;
String ItemName5InLowerCase;
String ItemName6InLowerCase;
String ItemName2InLowerCaseHW;
String ItemName3InLowerCaseHW;
String ItemName4InLowerCaseHW;
String ItemName5InLowerCaseHW;
String ItemName6InLowerCaseHW;
holder.Champitemimg1 = (ImageView) convertView2.findViewById(R.id.imageView7);
holder.Champitemimg2 = (ImageView) convertView2.findViewById(R.id.imageView6);
holder.Champitemimg3 = (ImageView) convertView2.findViewById(R.id.imageView5);
holder.Champitemimg4 = (ImageView) convertView2.findViewById(R.id.imageView4);
holder.Champitemimg5 = (ImageView) convertView2.findViewById(R.id.imageView3);
holder.Champitemimg6 = (ImageView) convertView2.findViewById(R.id.imageView2);
holder.Champitemimg1HW = (ImageView) convertView2.findViewById(R.id.imageView8);
holder.Champitemimg2HW = (ImageView) convertView2.findViewById(R.id.imageView9);
holder.Champitemimg3HW = (ImageView) convertView2.findViewById(R.id.imageView10);
holder.Champitemimg4HW = (ImageView) convertView2.findViewById(R.id.imageView11);
holder.Champitemimg5HW = (ImageView) convertView2.findViewById(R.id.imageView12);
holder.Champitemimg6HW = (ImageView) convertView2.findViewById(R.id.imageView13);
ImageView imgtesta;
String ChampionNameinlower;
imgtesta = (ImageView) convertView2.findViewById(R.id.imageView);
ChampionNameinlower = ChampionName.toLowerCase().replaceAll("'", "").replaceAll(" ", "");
int id10 = getResources().getIdentifier("com.example.kripzy.url:drawable/" + ChampionNameinlower + "_square_0", null, null);
imgtesta.setImageResource(id10);
holder.champitem1 = (TextView) convertView2.findViewById(R.id.textView9);
holder.champitem2 = (TextView) convertView2.findViewById(R.id.textView8);
holder.champitem3 = (TextView) convertView2.findViewById(R.id.textView7);
holder.champitem4 = (TextView) convertView2.findViewById(R.id.textView6);
holder.champitem5 = (TextView) convertView2.findViewById(R.id.textView5);
holder.champitem6 = (TextView) convertView2.findViewById(R.id.textView4);
holder.champitem1HW = (TextView) convertView2.findViewById(R.id.textView10);
holder.champitem2HW = (TextView) convertView2.findViewById(R.id.textView11);
holder.champitem3HW = (TextView) convertView2.findViewById(R.id.textView12);
holder.champitem4HW = (TextView) convertView2.findViewById(R.id.textView13);
holder.champitem5HW = (TextView) convertView2.findViewById(R.id.textView14);
holder.champitem6HW = (TextView) convertView2.findViewById(R.id.textView15);
holder.nameofchamp.setText(LayoutModelList2.get(position2).getChampionName2());
holder.position.setText(LayoutModelList2.get(position2).getRole());
holder.Champposition.setText(LayoutModelList2.get(position2).getChamppos());
holder.champitem1.setText(LayoutModelList2.get(position2).getItem1());
holder.champitem2.setText(LayoutModelList2.get(position2).getItem2());
holder.champitem3.setText(LayoutModelList2.get(position2).getItem3());
holder.champitem4.setText(LayoutModelList2.get(position2).getItem4());
holder.champitem5.setText(LayoutModelList2.get(position2).getItem5());
holder.champitem6.setText(LayoutModelList2.get(position2).getItem6());
holder.champitem1HW.setText(LayoutModelList2.get(position2).getItem1HW());
holder.champitem2HW.setText(LayoutModelList2.get(position2).getItem2HW());
holder.champitem3HW.setText(LayoutModelList2.get(position2).getItem3HW());
holder.champitem4HW.setText(LayoutModelList2.get(position2).getItem4HW());
holder.champitem5HW.setText(LayoutModelList2.get(position2).getItem5HW());
holder.champitem6HW.setText(LayoutModelList2.get(position2).getItem6HW());
ItemNameInLowerCase = ItemName.toLowerCase().replaceAll("'", "").replaceAll(" ", "");
ItemName2InLowerCase = ItemName2.toLowerCase().replaceAll("'", "").replaceAll(" ", "");
ItemName3InLowerCase = ItemName3.toLowerCase().replaceAll("'", "").replaceAll(" ", "");
ItemName4InLowerCase = ItemName4.toLowerCase().replaceAll("'", "").replaceAll(" ", "");
ItemName5InLowerCase = ItemName5.toLowerCase().replaceAll("'", "").replaceAll(" ", "");
ItemName6InLowerCase = ItemName6.toLowerCase().replaceAll("'", "").replaceAll(" ", "");
String itemNameInLowerCaseHW = ItemNameHW.toLowerCase().replaceAll("'", "").replaceAll(" ", "");
ItemName2InLowerCaseHW = ItemName2HW.toLowerCase().replaceAll("'", "").replaceAll(" ", "");
ItemName3InLowerCaseHW = ItemName3HW.toLowerCase().replaceAll("'", "").replaceAll(" ", "");
ItemName4InLowerCaseHW = ItemName4HW.toLowerCase().replaceAll("'", "").replaceAll(" ", "");
ItemName5InLowerCaseHW = ItemName5HW.toLowerCase().replaceAll("'", "").replaceAll(" ", "");
ItemName6InLowerCaseHW = ItemName6HW.toLowerCase().replaceAll("'", "").replaceAll(" ", "");
int id = getResources().getIdentifier("com.example.kripzy.url:drawable/" + ItemNameInLowerCase, null, null);
holder.Champitemimg1.setImageResource(id);
int id2 = getResources().getIdentifier("com.example.kripzy.url:drawable/" + ItemName2InLowerCase, null, null);
holder.Champitemimg2.setImageResource(id2);
int id3 = getResources().getIdentifier("com.example.kripzy.url:drawable/" + ItemName3InLowerCase, null, null);
holder.Champitemimg3.setImageResource(id3);
int id4 = getResources().getIdentifier("com.example.kripzy.url:drawable/" + ItemName4InLowerCase, null, null);
holder.Champitemimg4.setImageResource(id4);
int id5 = getResources().getIdentifier("com.example.kripzy.url:drawable/" + ItemName5InLowerCase, null, null);
holder.Champitemimg5.setImageResource(id5);
int id6 = getResources().getIdentifier("com.example.kripzy.url:drawable/" + ItemName6InLowerCase, null, null);
holder.Champitemimg6.setImageResource(id6);
int idHW = getResources().getIdentifier("com.example.kripzy.url:drawable/" + itemNameInLowerCaseHW, null, null);
holder.Champitemimg1HW.setImageResource(idHW);
int id2HW = getResources().getIdentifier("com.example.kripzy.url:drawable/" + ItemName2InLowerCaseHW, null, null);
holder.Champitemimg2HW.setImageResource(id2HW);
int id3HW = getResources().getIdentifier("com.example.kripzy.url:drawable/" + ItemName3InLowerCaseHW, null, null);
holder.Champitemimg3HW.setImageResource(id3HW);
int id4HW = getResources().getIdentifier("com.example.kripzy.url:drawable/" + ItemName4InLowerCaseHW, null, null);
holder.Champitemimg4HW.setImageResource(id4HW);
int id5HW = getResources().getIdentifier("com.example.kripzy.url:drawable/" + ItemName5InLowerCaseHW, null, null);
holder.Champitemimg5HW.setImageResource(id5HW);
int id6HW = getResources().getIdentifier("com.example.kripzy.url:drawable/" + ItemName6InLowerCaseHW, null, null);
holder.Champitemimg6HW.setImageResource(id6HW);
convertView2.setTag(holder);
}
else{
holder = (ViewHolder) convertView2.getTag();
}
return convertView2;
}
Newly added holder;
TextView nameofchamp;
TextView position;
TextView Champposition;
TextView champitem1;
TextView champitem2;
TextView champitem3;
TextView champitem4;
TextView champitem5;
TextView champitem6;
TextView champitem1HW;
TextView champitem2HW;
TextView champitem3HW;
TextView champitem4HW;
TextView champitem5HW;
TextView champitem6HW;
ImageView Champitemimg1;
ImageView Champitemimg2;
ImageView Champitemimg3;
ImageView Champitemimg4;
ImageView Champitemimg5;
ImageView Champitemimg6;
ImageView Champitemimg1HW;
ImageView Champitemimg2HW;
ImageView Champitemimg3HW;
ImageView Champitemimg4HW;
ImageView Champitemimg5HW;
ImageView Champitemimg6HW;
}
}
When i put a log.v at the bottom of the code, it always replies this
05-21 14:41:40.646 4536-4536/com.example.kripzy.url V/Where is my error: enchantment:bloodrazor
05-21 14:41:40.659 4536-4536/com.example.kripzy.url V/Where is my error: enchantment:bloodrazor
So what i was doing wrong was i was just using a string which just contained the information from the last entry on the listview, hence why it was only showing the images from it, so to fix this i had to change it to the following;
ItemNameInLowerCase = holder.champitem1.getText().toString().toLowerCase().replaceAll("'", "").replaceAll(" ", "");
ItemName2InLowerCase = holder.champitem2.getText().toString().toLowerCase().replaceAll("'", "").replaceAll(" ", "");
ItemName3InLowerCase = holder.champitem3.getText().toString().toLowerCase().replaceAll("'", "").replaceAll(" ", "");
ItemName4InLowerCase = holder.champitem4.getText().toString().toLowerCase().replaceAll("'", "").replaceAll(" ", "");
ItemName5InLowerCase = holder.champitem5.getText().toString().toLowerCase().replaceAll("'", "").replaceAll(" ", "");
ItemName6InLowerCase = holder.champitem6.getText().toString().toLowerCase().replaceAll("'", "").replaceAll(" ", "");
ItemNameInLowerCaseHW = holder.champitem1HW.getText().toString().toLowerCase().replaceAll("'", "").replaceAll(" ", "");
ItemName2InLowerCaseHW = holder.champitem2HW.getText().toString().toLowerCase().replaceAll("'", "").replaceAll(" ", "");
ItemName3InLowerCaseHW = holder.champitem3HW.getText().toString().toLowerCase().replaceAll("'", "").replaceAll(" ", "");
ItemName4InLowerCaseHW = holder.champitem4HW.getText().toString().toLowerCase().replaceAll("'", "").replaceAll(" ", "");
ItemName5InLowerCaseHW = holder.champitem5HW.getText().toString().toLowerCase().replaceAll("'", "").replaceAll(" ", "");
ItemName6InLowerCaseHW = holder.champitem6HW.getText().toString().toLowerCase().replaceAll("'", "").replaceAll(" ", "");

ListView CustomAdapter getView is not calling

Below is my code, here i am getting response..
Fetching Data from server in josn
getRequest();
list = (ListView) findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
//
private void getRequest(){
Thread trd = new Thread(new Runnable() {
#Override
public void run() {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
//
try{
Log.d("Get top called","try block");
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
if(response!=null){
try{
HashMap<String, String> defaultSongsDetails;
songs = new JSONArray(response);
JSONObject jsonObject;
for(int i=0;i<songs.length();i++){
defaultSongsDetails = new HashMap<String, String>();
String title,artist,language,imageUrl,songUrl,vocalUrl,duration=null;
String sdCardPathOfImage,sdCardPathOfOriginalSong,sdCardPathOfVocalSong=null;
jsonObject = songs.getJSONObject(i);
title = jsonObject.getString(SONG_TITLE);
defaultSongsDetails.put("song_title",title);
artist = jsonObject.getString(SONG_ARTIST);
defaultSongsDetails.put("song_artist",artist);
language = jsonObject.getString(SONG_LANGUAGE);
defaultSongsDetails.put("song_language",language);
duration = jsonObject.getString(SONG_DURATION);
defaultSongsDetails.put("song_duration",duration);
imageUrl = jsonObject.getString(SONG_THUMBNAL);
songUrl = jsonObject.getString(SONG_DOWNLOAD_URL);
vocalUrl = jsonObject.getString(SONG_VOCAL_URL);
String thumbnail=null;
int cutImg = imageUrl.lastIndexOf('/');
if (cutImg != -1) {
thumbnail = imageUrl.substring(cutImg + 1);
}
sdCardPathOfImage = basepath + "/songs/" + thumbnail;
defaultSongsDetails.put("song_thumbnail", sdCardPathOfImage);
String fileName=null; int cut = songUrl.lastIndexOf('/'); if (cut != -1) { fileName = songUrl.substring(cut + 1); }
sdCardPathOfOriginalSong = basepath+"/songs/" + fileName;
defaultSongsDetails.put("song_original_path",
sdCardPathOfOriginalSong);
String vocalFileName=null; int cutVocal = songUrl.lastIndexOf('/'); if (cut != -1) { vocalFileName =
songUrl.substring(cutVocal + 1); } sdCardPathOfVocalSong =
basepath+"/songs/" + vocalFileName;
defaultSongsDetails.put("song_vocal_path", sdCardPathOfVocalSong);
//Adding Hashmap to ArrayList
defaultSongsDetailList.add(defaultSongsDetails);
adapter = new CustomList(JsonActivity.this,defaultSongsDetailList);
}catch (Exception e){ e.printStackTrace(); } } }catch (Exception e) { e.printStackTrace(); } }
}); trd.start();
}
//CustomList Adapter class
public class CustomList extends ArrayAdapter<HashMap<String, String>>{
private final Activity context;
private ArrayList<HashMap<String, String>> songList;
public CustomList(Activity context,
ArrayList<HashMap<String, String>> songList) {
super(context, R.layout.list_item_view, songList);
this.context = context;
this.songList = songList;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_item_view, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.title);
ImageView imageView = (ImageView) rowView.findViewById(R.id.list_image);
TextView txtArtist = (TextView) rowView.findViewById(R.id.artist);
TextView txtDuration = (TextView) rowView.findViewById(R.id.duration);
System.out.println(" title ** "+songList.get(position).get("song_title")+" duration **
"+songList.get(position).get("song_duration")
+" thumb ** "+songList.get(position).get("song_thumbnail")+" language **
"+songList.get(position).get("song_language"));
txtArtist.setText(songList.get(position).get("song_title"));
txtDuration.setText(songList.get(position).get("song_duration"));
File file = new File(songList.get(position).get("song_thumbnail"));
Uri uri = Uri.fromFile(file);
imageView.setImageBitmap(BitmapFactory.decodeFile(defaultFilePath));
imageView.setImageURI(uri);
txtTitle.setText(songList.get(position).get("song_language"));
return rowView;
}
}
Any help would be appreciated...
//Fetching Data from server in josn
getRequest();
gAdapter = new BaseAdapter(HomeJsonActivity.this, defaultSongsDetailList);;
list = (ListView) findViewById(R.id.list);
gAdapter.notifyDataSetChanged();
list.setAdapter(gAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
private void getRequest() {
Thread trd = new Thread(new Runnable() {
#Override
public void run() {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
try {
Log.d("Get top called", "try block");
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
if (response != null) {
try {
HashMap<String, String> defaultSongsDetails;
songs = new JSONArray(response);
JSONObject jsonObject;
defaultSongsDetails = new HashMap<String, String>();
String title, artist, language, imageUrl, songUrl, vocalUrl, duration = null;
String sdCardPathOfImage, sdCardPathOfOriginalSong, sdCardPathOfVocalSong = null;
jsonObject = songs.getJSONObject(i);
title = jsonObject.getString(SONG_TITLE);
defaultSongsDetails.put("song_title", title);
artist = jsonObject.getString(SONG_ARTIST);
defaultSongsDetails.put("song_artist", artist);
language = jsonObject.getString(SONG_LANGUAGE);
defaultSongsDetails.put("song_language", language);
duration = jsonObject.getString(SONG_DURATION);
defaultSongsDetails.put("song_duration", duration);
imageUrl = jsonObject.getString(SONG_THUMBNAL);
songUrl = jsonObject.getString(SONG_DOWNLOAD_URL);
vocalUrl = jsonObject.getString(SONG_VOCAL_URL);
String thumbnail = null;
int cutImg = imageUrl.lastIndexOf('/');
if (cutImg != -1) {
thumbnail = imageUrl.substring(cutImg + 1);
}
sdCardPathOfImage = basepath + "/songs/" + thumbnail;
defaultSongsDetails.put("song_thumbnail", sdCardPathOfImage);
String fileName = null;
int cut = songUrl.lastIndexOf('/');
if (cut != -1) {
fileName = songUrl.substring(cut + 1);
}
sdCardPathOfOriginalSong = basepath + "/songs/" + fileName;
defaultSongsDetails.put("song_original_path", sdCardPathOfOriginalSong);
String vocalFileName = null;
int cutVocal = songUrl.lastIndexOf('/');
if (cut != -1) {
vocalFileName = songUrl.substring(cutVocal + 1);
}
sdCardPathOfVocalSong = basepath + "/songs/" + vocalFileName;
defaultSongsDetails.put("song_vocal_path", sdCardPathOfVocalSong);
defaultSongsDetailList.add(defaultSongsDetails);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
trd.start();
}
//Custom Base Adapter Class
public class BaseAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<HashMap<String, String>> songList;
public BaseAdapter(Context context, ArrayList<HashMap<String, String>> list) {
this.mInflater = LayoutInflater.from(context);
this.songList = list;
for (HashMap hh : songList) {
System.out.println("**** hh ***" + hh);
}
}
#Override
public int getCount() {
return songList.size();
}
#Override
public Object getItem(int position) {
return songList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView;
ViewHolder holder;
if (convertView == null) {
rowView = mInflater.inflate(R.layout.list_item_view, parent, false);
holder = new ViewHolder();
holder.title = (TextView) rowView.findViewById(R.id.title);
holder.thumb = (ImageView) rowView.findViewById(R.id.list_image);
holder.artist = (TextView) rowView.findViewById(R.id.artist);
holder.duration = (TextView) rowView.findViewById(R.id.duration);
rowView.setTag(holder);
} else {
rowView = convertView;
holder = (ViewHolder) rowView.getTag();
}
holder.title.setText(songList.get(position).get("song_title"));
File file = new File(songList.get(position).get("song_thumbnail"));
Uri uri = Uri.fromFile(file);
holder.thumb.setImageURI(uri);
holder.artist.setText(songList.get(position).get("song_artist"));
holder.duration.setText(songList.get(position).get("song_duration"));
System.out.println(" title ** " + songList.get(position).get("song_title") + " duration ** " + songList.get(position).get("song_duration")
+ " thumb ** " + songList.get(position).get("song_thumbnail") + " language ** " + songList.get(position).get("song_language"));
return rowView;
}
private class ViewHolder {
public ImageView thumb;
public TextView title, duration, artist;
}
}

i have one error passing of constructor as this in listfragments

I am newer to the fragments. In oncreate method i pass this value to Appetizerlist. but it shows an error. How to clear the error? Please help me.
public class MyListFragment1 extends ListFragment {
ImageView back;
String url = Main.url;
String Qrimage;
Bitmap bmp;
ListView list;
AppetiserFragment adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.applistviewfragment, null);
list = (ListView) view.findViewById(R.id.list);
return view;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
InputStream is = null;
String result = "";
JSONObject jArray = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url + "test.php3");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
// TODO: handle exception
Log.e("Log", "Error in Connection" + e.toString());
// Intent intent = new Intent(ViewQRCode.this, PimCarder.class);
// startActivity(intent);
}
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 + "\n");
}
is.close();
result = sb.toString();
jArray = new JSONObject(result);
JSONArray json = jArray.getJSONArray("appetiser");
adapter = new AppetiserFragment(this, json);
list.setAdapter(adapter);
} catch (Exception e) {
// TODO: handle exception
Log.e("log", "Error in Passing data" + e.toString());
}
}
}
AppetiserFragment.java
public class AppetiserFragment extends BaseAdapter {
String url = Main.url;
public Context Context;
String qrimage;
Bitmap bmp, resizedbitmap;
Bitmap[] bmps;
Activity activity = null;
private LayoutInflater inflater;
private ImageView[] mImages;
String[] itemimage;
TextView[] tv;
String itemname, price, desc, itemno;
String[] itemnames, checkeditems, itemnos;
String[] prices;
String[] descs;
HashMap<String, String> map = new HashMap<String, String>();
public AppetiserFragment(Context context, JSONArray imageArrayJson) {
Context = context;
// inflater =
System.out.println(imageArrayJson);
// (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader=new ImageLoader(activity);
inflater = LayoutInflater.from(context);
this.mImages = new ImageView[imageArrayJson.length()];
this.bmps = new Bitmap[imageArrayJson.length()];
this.itemnames = new String[imageArrayJson.length()];
this.prices = new String[imageArrayJson.length()];
this.descs = new String[imageArrayJson.length()];
this.itemnos = new String[imageArrayJson.length()];
try {
for (int i = 0; i < imageArrayJson.length(); i++) {
JSONObject image = imageArrayJson.getJSONObject(i);
qrimage = image.getString("itemimage");
itemname = image.getString("itemname");
itemno = new Integer(i + 1).toString();
price = image.getString("price");
desc = image.getString("itemdesc");
System.out.println(price);
itemnames[i] = itemname;
prices[i] = price;
descs[i] = desc;
itemnos[i] = itemno;
byte[] qrimageBytes = Base64.decode(qrimage.getBytes());
bmp = BitmapFactory.decodeByteArray(qrimageBytes, 0,
qrimageBytes.length);
int width = 100;
int height = 100;
resizedbitmap = Bitmap.createScaledBitmap(bmp, width, height,
true);
bmps[i] = bmp;
mImages[i] = new ImageView(context);
mImages[i].setImageBitmap(resizedbitmap);
mImages[i].setScaleType(ImageView.ScaleType.FIT_START);
// tv[i].setText(itemname);
}
System.out.println(map);
} catch (Exception e) {
// TODO: handle exception
}
}
public AppetiserFragment() {
// TODO Auto-generated constructor stub
}
public int getCount() {
return mImages.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder viewHolder;
if (view == null) {
view = inflater.inflate(R.layout.appetiserlistview, null);
System.out.println("prakash");
viewHolder = new ViewHolder();
viewHolder.image = (ImageView) view
.findViewById(R.id.appetiserimage);
viewHolder.text = (TextView) view.findViewById(R.id.appetisertext);
viewHolder.desc = (TextView) view.findViewById(R.id.appetiserdesc);
viewHolder.price = (TextView) view
.findViewById(R.id.appetiserprice);
viewHolder.appitemnum = (TextView) view
.findViewById(R.id.appitemno);
// viewHolder.checkbox = (CheckBox) view.findViewById(R.id.bcheck);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.image.setImageBitmap(bmps[position]);
viewHolder.appitemnum.setText(itemnos[position]);
viewHolder.price.setText(prices[position]);
viewHolder.desc.setText(descs[position]);
// viewHolder.checkbox.setTag(itemnames[position]);
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(itemnames[position]);
return view;
}
static class ViewHolder {
protected TextView text, price, desc, appitemnum;
protected ImageView image;
public static CheckBox checkbox = null;
}
}
i Given whole code i want custom listview using listfragments
In the above code in this line, I'm getting an error at adapter = new Appetizerlist(this, json); Please tell me how to solve the problem. Help me.
as onCreate called before onCreateView so list will null there in onCreate ...........
http://developer.android.com/guide/topics/fundamentals/fragments.html
in oncreate
list.setAdapter(adapter);
in onCreateView you initlized that
list = (ListView) view.findViewById(R.id.list);
......
so move this line list.setAdapter(adapter); in onCreateView
You have error in following line.
adapter = new Appetizerlist(this, json);
Change it to
adapter = new Appetizerlist(getActivity().getApplicationContext(), json);

How to View JSON array to edit View

I'm begginer develop android.
I'm confuse. Because I didn't know to convert JSON to be view at Edit View (for example).
many totorial just view at Log.
this, my JSON file
EditText txt1 = (EditText) findViewById(R.id.Text1);
RestClient client = new RestClient("http://192.168.2.79/restserver/index.php/api/example/users");
//client.AddParam("id", "1"); //parameter
client.AddParam("format", "json"); //parameter format
client.AddHeader("GData-Version", "2"); //header
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
String response = client.getResponse();
Log.i("respon",response);
//Toast.makeText(this, "json : "+ response, 1).show();
//create json creation
try {
JSONObject json = new JSONObject(response);
Log.i("respon","<jsonobject>\n"+json.toString()+"\n</json>");
//Log.i("respon","<jsonobject>\n"+json.t
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
//try 1
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
String[] id = new String[valArray.length()];
String[] name = new String[valArray.length()];
String Id,Name;
for(int i=0;i<valArray.length();i++) {
Log.i("respon","<jsonname"+i+">\n"+nameArray.getString(i)+"\n</jsonname"+i+">\n"
+"<jsonvalue"+i+"\n"+valArray.getString(i)+"\n</jsonvalue"+i+">");
//coba
JSONObject obj = valArray.getJSONObject(i);
id[i] = obj.getString("id");
name[i] = obj.getString("name");
//wanna show at EditView, ect (but I can't)
Toast.makeText(this, "id : " + " ,name : ", 1).show();
txt1.setText("id : " + id + " ,name : "+name);
}
how can to solve json to view not only at log. but also at object (widget android).
thanx alot guys....
I think your not able to get data from JSON go through with the following code.
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("LINK");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
int statuscode = statusLine.getStatusCode();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(is, "UTF8"), 16);
stringBuilder = new StringBuilder();
stringBuilder.append(bufferedReader.readLine() + "\n");
String line = "0";
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
is.close();
Strign result = stringBuilder.toString();
JSONArray jArrayTemp = new JSONArray(result);
JSONObject json_data = null;
userID[i] = json_data.getString("UserID");
userName[i] = json_data.getString("UserName");
userLoginID[i] = json_data.getString("UserLoginID");
userPassword[i] = json_data.getString("UserPassword");
Try the above code.
If can take the help of below link also::
http://www.vogella.de/articles/AndroidJSON/article.html

Android get image from web with JSON

I am getting the news information from web. So i can easily get the header and subject of news but the problem is how to get the image from json?
Here is my code:
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.haber_yapisi, null); // gets all of the views from adaptor_content and implements their id
holder = new ViewHolder();
holder.baslik = (TextView) convertView.findViewById(R.id.baslik);
holder.haber = (TextView) convertView.findViewById(R.id.haber);
holder.resim = (ImageView) convertView.findViewById(R.id.resim);
holder.aaa = (TextView) convertView.findViewById(R.id.aaa);
holder.bas=(TextView) findViewById(R.id.head_ana);
holder.bas.setText("Ana Sayfa");
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://www.dha.com.tr/mobil/anasayfa.asp");
HttpResponse response;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
try {
InputStream instream = entity.getContent();
String line = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder json = new StringBuilder();
while ((line = reader.readLine()) != null) {
json.append(line + "\n");
}
StringBuilder stringBuilder = new StringBuilder();
JSONArray siteler = new JSONArray(json.toString());
JSONObject ss = siteler.getJSONObject(position);
holder.baslik.setText(ss.getString("strsubject"));
holder.haber.setText( ss.getString("strbody") );
holder.resim.setImageBitmap("WHAT SHOULD I DO FOR GETTİNG IMAGE")
holder.aaa.setText(stringBuilder.toString());
instream.close();
} catch (Exception e) {
holder.aaa.setText("Error is: " + e);
}
}
} catch (Exception e) {
holder.aaa.setText("Error is : " + e);
}
return convertView;
}
}
PLESE HELP!
If your json contains image url you can use
String imageBaseDirectory = "http://www.dha.com.tr/newpics/news/";
String imageName = "230620111119295717933.jpg";//get image name from json parsing;
imageview.setImageURI(Uri.parse(imageBaseDirectory+imageName));
But I can see that the url that you are referring donot contain image url only it contains name of image
do you have image url in json ?? if so , then create another http connection for this url , get inputstream , then create bitmap from this stream .
else clarify here what kind of info you have for image in your json ??
Your JSON contains the filename. Assuming you know the path of the images, form the url and do as Shailendra suggested, example:
URL url = new URL(imgBaseUrl + ss.getString("foto"));
URLConnection connection = url.openConnection();
FlushedInputStream fis = new FlushedInputStream(connection.getInputStream());
ByteArrayBuffer baf = new ByteArrayBuffer(100);
int current = 0;
while((current = fis.read()) != -1){
baf.append((byte)current);
}
fis.close();
holder.resim.setImageBitmap(BitmapFactory.decodeByteArray(baf, 0, baf.length()));
Be sure to use FlushedInputStream as seen at http://code.google.com/p/android/issues/detail?id=6066
static class FlushedInputStream extends FilterInputStream {
public FlushedInputStream(InputStream inputStream) {
super(inputStream);
}
#Override
public long skip(long n) throws IOException {
long totalBytesSkipped = 0L;
while (totalBytesSkipped < n) {
long bytesSkipped = in.skip(n - totalBytesSkipped);
if (bytesSkipped == 0L) {
int bite = read();
if (bite < 0) {
break; // we reached EOF
} else {
bytesSkipped = 1; // we read one byte
}
}
totalBytesSkipped += bytesSkipped;
}
return totalBytesSkipped;
}
}
Most of the answer is in this other post here:
How to load an imageView by URL in Android
1) create the url and pass it to the method in the link I provided
String myPhoto = "foto2";
String url = "http://mysite.com/images/" + myPhoto + ".png";
How to load an image from a json? Use of picasso, it is easy:
String imageUrl = imgBaseUrl + ss.getString("foto"); // this is the image url
Picasso.with(this.getActivity()).load(imageUrl).into(holder.resim); // holder.resim is the imageview

Categories

Resources