Image Slider image not loading (ViewPager + Picasso) - android

I'm creating a Image Slider using Picasso + Viewpager.
I am able to swipe the slider base on the image size(counts).
But no images from array has been loaded even though i can swipe the screen with default images.
Please correct my mistakes if any founded. I am new to android.
Thanks in advance
My json array is like this
[
{
"guid": "C410B2AA-EC03-29E4-F5C0-CB48510ED9E5",
"id": "2",
"created_on": "2016-05-17 13:13:22",
"car_name": "Hundai",
"model": "C001",
"version": "i20",
"make_year": "2012",
"kms_driven": "2000",
"city": "Bangalore",
"pincode": "560072",
"expected_price": "200000",
"name": "Vishnu",
"email": "dreamvishnu#gmail.com",
"mobile": "9863265358",
"image": [
{
"newimage": "https://images.cardekho.com/car-images/carexteriorimages/large/Ford/Ford-Mustang/ford-mustang-exterior-047.jpg"
},
{
"newimage": "https://www.enterprise.com/content/dam/global-vehicle-images/cars/FORD_FOCU_2012-1.png"
},
{
"newimage": "https://imagecdn8.cartrade.com/img/800x600/car-data/big/bmw-i8-default-image.png"
}
]
}
]
In the postexecute of my activity i am setting the adapter as follow
protected void onPostExecute(Void v) {
try {
JSONArray object = new JSONArray(result);
ArrayList<String> items = new ArrayList<String>();
try {
for (int i = 0; i < object.length(); i++) {
JSONObject obj = object.getJSONObject(i);
vehicleSliderIamges = obj.getJSONArray("image");
guid = obj.getString("guid");
name = obj.getString("car_name");
model = obj.getString("version");
price = obj.getString("expected_price");
km = obj.getString("kms_driven");
fuel = obj.getString("model");
year = obj.getString("make_year");
location = obj.getString("city");
gear = obj.getString("name");
}
ArrayList<String> list = new ArrayList<String>();
if (vehicleSliderIamges != null) {
int len = vehicleSliderIamges.length();
for (int i=0;i<len;i++){
list.add(vehicleSliderIamges.get(i).toString());
}
}
viewPagerAdapter = new ViewPagerAdapter(SecondHandCarDetailsActivity.this,list);
viewPager.setAdapter(viewPagerAdapter);
vehicleName.setText(name);
vehicleModel.setText(model);
vehiclePrice.setText(price);
vehicleYear.setText(year);
vehicleFuel.setText(fuel);
vehicleKm.setText(km);
vehicleGear.setText(gear);
vehicleLocation.setText(location);
this.progressDialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
}
My ViewpagerAdapter is
import android.content.Context;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.support.v4.view.ViewPager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class ViewPagerAdapter extends PagerAdapter {
private Context context;
private ArrayList<String> IMAGES = new ArrayList<>();
public ViewPagerAdapter(Context context, ArrayList<String> IMAGES) {
this.IMAGES = IMAGES;
this.context = context;
}
#Override
public int getCount() {
return IMAGES.size();
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return true;
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.imagepager_layout,null);
((ViewPager) collection).addView(view);
final ImageView img = (ImageView) view.findViewById(R.id.img);
Picasso.with(context)
.load(IMAGES.get(position))
.placeholder(R.drawable.loading)
.into(img);
return view;
}
}
My secondcar_detail.xml is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#color/white"
>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="150dp"
android:orientation="vertical"
>
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="150dp"></android.support.v4.view.ViewPager>
</LinearLayout>
</LinearLayout>

Replace get method call
vehicleSliderIamges.get(i).toString()
to getJSONObject method call:
vehicleSliderIamges.getJSONObject(i).get("newimage").toString()
get method call returns below strings:
{"newimage":"https:\/\/images.cardekho.com\/car-images\/carexteriorimages\/large\/Ford\/Ford-Mustang\/ford-mustang-exterior-047.jpg"}

You forgot to notify changes in your adapter using notifyDataSetChanged():
viewPagerAdapter = new ViewPagerAdapter(SecondHandCarDetailsActivity.this,list);
viewPager.setAdapter(viewPagerAdapter);
viewPagerAdapter.notifyDataSetChanged();

Apparently Picasso does not support https out of the box. See the Issue here.
1) Either you get a http url to the image or
2) You use a HTTP Client like OkHttpClient
OkHttpClient client = new OkHttpClient();
client.setProtocols(Arrays.asList(Protocol.HTTP_11));
Picasso picasso = new Picasso.Builder(context)
.downloader(new OkDownloader(client))
.build();
Use the following code:
ArrayList<String> list = new ArrayList<String>();
if (vehicleSliderIamges != null) {
for (JSONObject o: vehicleSliderIamges){
list.add(o.getString("newimage");
}
}

Related

Android Studio: I can't download a list of pictures from Firebase server

I'm using Firebase to download pictures from the server and display them in a listview in Android Studio. Specifically, it's a list of pictures that I store in an array which I later use for the listview.
If I need to download just one image the code works just fine, the problem is that when I receive more than one the listview displays only blank images with the exception of the last one, which is the right one for that spot. I've already used that listview for other stuff and I know it works.
Here is my method:
public void fetchImages(Map<String,Object> bitmaps) {
for (Map.Entry<String, Object> entry : bitmaps.entrySet()) {
storageRef = storage.getReference().child(entry.getKey());
try {
localFile = File.createTempFile("FileTemp", "jpg");
storageRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
returnedBitmaps[i++] = BitmapFactory.decodeFile(localFile.getAbsolutePath());
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
} catch(Exception e) {
}
}
}
I know that I always get a number of pictures equal to the array dimension so I don't get errors in that part. If I try taskSnapshot.getBytesTransferred() I get the exact number of bytes the pictures from the server have so I think the pictures are there and i'm just doing something wrong when I'm trying to display them. Any help would be appreciated, thanks.
Edit: this is the method I'm using on my listview:
public void fixImages () {
listItemsName = new String[returnedContacts.length];
imageNameBitmap = new Bitmap[returnedContacts.length];
int count = 0;
while (count < returnedContacts.length) {
listItemsName[count] = returnedContacts[count].name + " " + returnedContacts[count].lastName;
imageNameBitmap[count] = returnedBitmaps[count];
count++;
}
listView = (ListView)findViewById(R.id.listView1);
try {
listAdapterBitmap = new ListAdapterBitmap(CheckFollows.this, listItemsName, imageNameBitmap);
}
catch (Exception e) {
e.printStackTrace();
}
listView.setAdapter(listAdapterBitmap);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(returnedContacts[position] != null) {
Intent intent = new Intent(CheckFollows.this, PersonBrowsed.class);
startActivity(intent);
}
}
});
}
The listview displays on the right side a name and a last name using the listItemName array while showing a picture on the left side, using the imageNameBitmap array.
Class ListAdapterBitmap:
import android.app.Activity;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
class ListAdapterBitmap extends ArrayAdapter<String> {
private final Activity Context;
private final String [] ListItemsName;
private final Bitmap [] ImageName;
ListAdapterBitmap(Activity context, String [] content, Bitmap [] ImageName) {
super(context, R.layout.list_items, content);
this.Context = context;
this.ListItemsName = content;
this.ImageName = ImageName;
}
#NonNull
public View getView(int position, View view,#NonNull ViewGroup parent) {
LayoutInflater inflater = Context.getLayoutInflater();
View ListViewSingle = inflater.inflate(R.layout.list_items, null, true);
TextView ListViewItems = (TextView)ListViewSingle.findViewById(R.id.tvSportName);
ImageView ListViewImage = (ImageView)ListViewSingle.findViewById(R.id.imgSportPicture);
ListViewItems.setText(ListItemsName[position]);
ListViewImage.setImageBitmap(ImageName[position]);
return ListViewSingle;
}
}

Custom Listview from JSON

I want to show 2 pieces of data in 1 row of ListView, but I got stuck.
My problem is in showList() method. I can't use my custom ListView XML to show 2 data, I can only show 1 data. I want to show item and itemsemail array in my custom ListView not only item.
Here is my custom ListView adapter code...
private void getDosen() {
//Ketika Aplikasi mengambil data kita akan melihat progress dialog
final ProgressDialog loading = ProgressDialog.show(this,"Mengambil Data","Mohon tunggu..",false,false);
//Logging Interceptor
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
//set Level Log
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(logging);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ROOT_URL)
.addConverterFactory(GsonConverterFactory.create())//GsonConverter untuk parsing json
.client(httpClient.build())
.build();
RestAPI service = retrofit.create(RestAPI.class);
Call<Model> call = service.loadListDosen();
call.enqueue(new Callback<Model>() { //Asyncronous Request
#Override
public void onResponse(Call<Model> call, Response<Model> response) {
loading.dismiss();
List<Listdosen> dosen = response.body().getListdosen();
//memasukkan data dari varibel dosen ke dosens
dosens = dosen;
//memanggil method untuk menampilkan list
showList();
}
#Override
public void onFailure(Call<Model> call, Throwable t) {
}
});
}
private void showList() {
//String array untuk menyimpan nama semua nama dosen
String[] items = new String[dosens.size()];
String[] itemsemail = new String[dosens.size()];
for (int i = 0; i < dosens.size(); i++) {
items[i] = dosens.get(i).getNama();
itemsemail[i] = dosens.get(i).getEmail();
}
//Membuat Array Adapter for listview
ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.activity_dosen_listview, items);
//setting adapter untuk listview
listview.setAdapter(adapter);
}
First of all you need a adapter class that inflates a layout with two TextView that you will bind your data source to.
I have created a layout file and the adapter you can plug into your existing code and I hope it works for you.
This is the layout file.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/items"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="#string/app_name"
android:layout_margin="16dp"/>
<TextView
android:id="#+id/itemsEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/items"
android:text="#string/app_name"
android:layout_alignBaseline="#+id/items"/>
</RelativeLayout>
For the Adapter class, the code is below
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
public class MyBaseAdapter extends BaseAdapter {
private LayoutInflater layoutinflater;
private List<Listdosen> listStorage;
private Context context;
public MyBaseAdapter(Context context, List<Listdosen> customizedListView) {
this.context = context;
layoutinflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
listStorage = customizedListView;
}
#Override
public int getCount() {
return listStorage.size();
}
#Override
public Listdosen getItem(int position) {
return listStorage.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder listViewHolder;
if(convertView == null){
listViewHolder = new ViewHolder();
convertView = layoutinflater.inflate(R.layout.two_items, parent, false);
listViewHolder.items = (TextView)convertView.findViewById(R.id.items);
listViewHolder.itemEmail = (TextView)convertView.findViewById(R.id.itemsEmail);
convertView.setTag(listViewHolder);
}else{
listViewHolder = (ViewHolder)convertView.getTag();
}
listViewHolder.items.setText(listStorage.get(position).getName());
listViewHolder.itemEmail.setText(listStorage.get(position).getEmail());
return convertView;
}
static class ViewHolder{
TextView items;
TextView itemEmail;
}
}
Adjust your code a bit to fit with the changes.
showList() to showList(List<Listdosen> dosen)
Instead of
ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.activity_dosen_listview, items);
use this
ArrayAdapter adapter = new ArrayAdapter<Listdosen>(this, dosen);

Android ScrollView does not scroll

Unfortunately after listView is full it does not scroll. why?
Everything else just works fine.
I feel I'm gonna break down and cry.
listview is not scrolling individually.
I have following class:
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import co.uk.aq.application.R;
import co.uk.aq.application.core.ApplicationGlobalState;
import co.uk.aq.application.core.WifiDataSets;
import co.uk.aq.application.ui.qActivity;
import com.google.inject.Inject;
import roboguice.inject.InjectView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class WifiFeedbackActivity extends qActivity {
#Inject private ApplicationGlobalState applicationGlobalState;
private RealtimeUpdateScreenCS realtimeUpdateCurrentState;
#InjectView(R.id.list_of_strings) private ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wifi_feedback);
setTitle(getString(R.string.wifi_current_connection));
}
#Override
public void onResume() {
super.onResume();
realtimeUpdateCurrentState = new RealtimeUpdateScreenCS();
realtimeUpdateCurrentState.execute();
}
#Override
public void onPause() {
super.onPause();
if (realtimeUpdateCurrentState != null){
realtimeUpdateCurrentState.cancel(true);
realtimeUpdateCurrentState = null;
}
}
private class RealtimeUpdateScreenCS extends AsyncTask{
String [] from = new String[]{"Details"};
int [] to = new int []{R.id.wan_details_text};
List<HashMap<String, String>> fillMaps;
#Override
protected Object doInBackground(Object... arg0) {
while(!isCancelled()){
fillMaps = new ArrayList<HashMap<String, String>>();
try {
for(String line: WifiDataSets.currentStateStrings){
if(!line.equals("\n")&& !line.equals(" ") && !line.equals("")){
HashMap<String, String> map = new HashMap<String, String>();
map.put("Details", line);
fillMaps.add(map);
}
}
publishProgress(fillMaps);
} catch (Exception e) {
Log.e("","",e);
}
try{Thread.sleep(50L);}catch(Exception e){}
}
return null;
}
protected void onProgressUpdate (Object...objects ){
SpecialAdapter adapter = new SpecialAdapter(getApplicationContext(), (List)objects[0], R.layout.grid_item, from, to);
lv.setClickable(false);
lv.setAdapter(adapter);
}
}
private class SpecialAdapter extends SimpleAdapter {
private int[] colors = new int[] {/*DARK_BLUE*/ new Color().rgb(14,41,179), /*RED*/ new Color().rgb(224,0,0), /*LIGHT_BLUE*/ new Color().rgb(0,153,255), /*GREEN*/ new Color().rgb(81,191,17)};
private List<HashMap<String, String>> the_list;
public SpecialAdapter(Context context, List<HashMap<String, String>> items, int resource, String[] from, int[] to) {
super(context, items, resource, from, to);
this.the_list = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
int colorPos = 2 ;
if(the_list.get(position).get("Details").contains("successfully")
|| the_list.get(position).get("Details").contains("succeeded")
|| the_list.get(position).get("Details").contains("local IP address")
|| the_list.get(position).get("Details").contains("remote IP address")
|| the_list.get(position).get("Details").trim().contains("primary DNS address")
|| the_list.get(position).get("Details").trim().contains("secondary DNS address")
|| the_list.get(position).get("Details").trim().contains(applicationGlobalState.getString(R.string.wan_authentication_not_needed)))
colorPos = 3;
if(the_list.get(position).get("Details").contains("sent"))
colorPos = 2;
if(the_list.get(position).get("Details").contains("rcvd"))
colorPos = 0;
view.setBackgroundColor(colors[colorPos]);
return view;
}
}
}
And Layout is:
<?xml version="1.0" encoding="utf-8"?>
<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list_of_strings"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#000000"
android:dividerHeight="1px"/>
You are in a loop inside the AsyncTask by while(!isCancelled()) where call publishProgress every 50ms, then onProgressUpdate sets the adapter every single 50ml to the listview and so the listview is reseted. This is why you cannot scroll. For me, this code is all wrong, for example you should query the item inside the getView once the_list.get(position), not for every single check.

how do i get my JSON into android listview? [duplicate]

This question already has answers here:
JSON Android And Listview
(3 answers)
Closed 9 years ago.
I'm a new programmer and I'm making an app which can get data from MYSQL to php and then display on android. I've been trying to find a solution but none of the tutorials I've seen so far seems to work for me, I've only managed to get one object from json into a single textview. But what I really need is to get data to be displayed on individual rows on listview.
here's my JSON output,
[{"id":"1","name":"darrel","password":"pass1234"},{"id":"2","name":"garrett","password":"important"},{"id":"3","name":"neoys","password":"yseniopass"},{"id":"4","name":"john","password":"mikel123"},{"id":"5","name":"owen","password":"mike4l"}]
and my java code which gets only one of the users displayed onto a textview.
package com.darre.jsonreader;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ListActivity;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class Users extends ListActivity {
/** Called when the activity is first created. */
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//listView.setOnItemClickListener(new OnItemClickListener() {
// public void onItemClick(AdapterView<?> parent, View view,
// int position, long id) {
// When clicked, show a toast with the TextView text
// Toast.makeText(getApplicationContext(),
// ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://172.30.54.153/databases/");
TextView textView = (TextView)findViewById(R.id.textView1);
ListView listview = (ListView)findViewById(R.id.listView1);
try {
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
JSONArray mArray = new JSONArray(jsonResult);
for (int i = 0; i < mArray.length(); i++) {
JSONObject object = mArray.getJSONObject(i);
String name = object.getString("name");
String password = object.getString("password");
textView.setText(name + " - " + password);
}
}
catch (JSONException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
Thanks in advance!!!
You can read this tutorial, it explains to ways of implement it, the first, a "direct" List adapter, the second, the way to customize your List.
http://www.mkyong.com/android/android-listview-example/
Also, you shouldn't work with JSON data, first, you have to create an Object for each Item, and then group it with some kind of List (ArrayList, for example).
You have to create ListView adapter:
Put this in your Code :
private String[] listArr;
public ArrayList<String> ary_name = new ArrayList<String>();
try {
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
JSONArray mArray = new JSONArray(jsonResult);
for (int i = 0; i < mArray.length(); i++) {
JSONObject object = mArray.getJSONObject(i);
String name = object.getString("name");
String password = object.getString("password");
textView.setText(name + " - " + password);
ary_name.add(name);
}
listArr = new String[ary_name.size()];
listArr = ary_name.toArray(listArr);
MyArrayAdapter adapter = new MyArrayAdapter(this, listArr);
listView.setAdapter(adapter);
public class MyArrayAdapter extends ArrayAdapter<String> {
Activity context;
String[] listArr;
private TextView btnchkout;
// private final integer[] image;
public MyArrayAdapter(Activity context, String[] objects) {
super(context, R.layout.custmlayout, objects);
// TODO Auto-generated constructor stub
this.context = context;
listArr = objects;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custmlayout, null, true);
TextView textView = (TextView) view.findViewById(R.id.txtTicketNo);
textView.setText(listArr[position]);
return view;
}
}
If you want to use a ListView... then you should parse you JSON file into some kind of data structure like a List or an ArrayList and the n use an adapter to populate the ListView data.
Here is an example for ListView adapter:
private class MySecondAdapter extends ArrayAdapter<MiniTask>
{
private ArrayList<MiniTask> list;
public MySecondAdapter(Context context, int textViewResourceId, ArrayList<MiniTask> miniTaskList)
{
super(context, textViewResourceId, miniTaskList);
this.list = new ArrayList<MiniTask>();
this.list.addAll(miniTaskList);
}
public View getView(final int position, View convertView, ViewGroup parent)
{
miniTask = miniTaskList.get(position);
ViewHolder holder = new ViewHolder();
{
LayoutInflater inflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.check_list_item_new, null);
holder.title = (TextView) convertView.findViewById(R.id.tvItemTitle);
holder.commentsPicturesButton = (ImageView) convertView.findViewById(R.id.iAddCommetOrPicture);
holder.commentsPicturesButton.setTag(position);
holder.commentsPicturesButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(getApplicationContext(), PicturesAndCommentsActivity.class);
intent.putExtra(TasksListActivity.KEY_ID, task.getId());
intent.putExtra("mini_task_text", miniTask.getTitle());
startActivity(intent);
}
});
holder.selected = (CheckBox) convertView.findViewById(R.id.cbCheckListItem);
holder.selected.setTag(position);
holder.selected.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
{
Log.d(TAG, "pressed the checkbox: " + v.getId() + " in position: " + position + " tag: " +v.getTag() +" and item from array: " + miniTaskList.get(position) );
CheckBox checkbox = (CheckBox) v;
miniTaskList.get(position).setSelected(checkbox.isChecked());
numOfCheckedMiniTasks = 0;
for(int i=0;i<miniTaskList.size();i++)
{
miniTask = miniTaskList.get(i);
if(miniTask.isSelected())
{
numOfCheckedMiniTasks ++;
}
}
int percent = (int)(numOfCheckedMiniTasks * 100.0f) / miniTaskList.size();
Log.d(TAG, "the percentage is: " +percent);
tasksRepository.get(tasksRepository.indexOf(task)).setMiniTasksPercentageComplete(percent);
}
}
});
}
holder.title.setText(miniTask.getTitle());
holder.selected.setChecked(miniTask.isSelected());
return convertView;
}
}
Check this tutorials for getting more information:
http://cyrilmottier.com/2012/02/16/listview-tips-tricks-5-enlarged-touchable-areas/

How to create a listview with custom adapter

I have the following code:
package com.example.myfirstapp;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.UnknownHostException;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
public class FetchData extends Activity {
private TextView textView;
private JSONObject jObject;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fetch_data);
textView = (TextView) findViewById(R.id.TextView1);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
readWebpage(message);
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
mParseResponse(response);
}
#Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}
public void readWebpage(String message) {
//Intent intent = getIntent();
//String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] {message});
}
ArrayList<String> year, title, details, director, rating, cover;
// For Parse Login Response From Server
public void mParseResponse(String response) throws UnknownHostException {
year=new ArrayList<String>();
title=new ArrayList<String>();
details=new ArrayList<String>();
director=new ArrayList<String>();
rating=new ArrayList<String>();
cover=new ArrayList<String>();
try {
JSONObject jObject = new JSONObject(response);
JSONObject jsonobjresults = jObject.getJSONObject("results");
JSONArray jsonarrayresult = jsonobjresults.getJSONArray("result");
for(int i=0;i<jsonarrayresult.length(); i++){
JSONObject mJsonObj = jsonarrayresult.getJSONObject(i);
year.add(mJsonObj.getString("year"));
title.add(mJsonObj.getString("title"));
details.add(mJsonObj.getString("details"));
director.add(mJsonObj.getString("director"));
rating.add(mJsonObj.getString("rating"));
cover.add(mJsonObj.getString("cover"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am getting confused as to how to create a custom adapter. Yes, i have gone thoeugh tutorials but confusion still exits. Plus, I am having an error when i make a call to mParseResponse. Any ideas where I am going wrong and how should i implement list view?
Perhaps this simple sample custom adapter listview will get on your feet with this stuff.
The main activity
public class MainActivity extends Activity {
String [] children = {
"Award 1",
"Award 2",
"Award 3",
"Award 4",
"Award 5",
"Award 6",
"Award 7",
"Award 8",
"Award 9",
"Award 10",
"Award 11",
"Award 12",
"Award 13",
"Award 14",
"Award 15"};
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView list = (ListView) findViewById(R.id.listview);
CustomAdapter adapter = new CustomAdapter(this, children);
list.setAdapter(adapter);
}
The custom adapter
public class CustomAdapter extends BaseAdapter {
// you could have instead extend ArrayAdapter if you wished, i find it less fickle but less flexible
// extends CursorAdapter is available too for listviews backed by cursors
private LayoutInflater inflator;
private String[] children;
public CustomAdapter(Context context, String[] children) {
super();
// pass what you need into the constructor. in this case the string array and context.
// do as much as you can here and not in getView because getView acts for each row
// --> it will greatly help performance
this.children = children;
inflator = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// v---- your listview won't show anything if this is left default (at 0).
return children.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// getView is where all the action takes place
// first inflate the xml that holds the row and somehow connect it to convertView, the parameter
// checking if null allows these views to be recycled when they go off-screen not just made one per row
// ---> it will greatly help performance
if (convertView == null) {
convertView = inflator.inflate(R.layout.row, parent, false);
}
// then find the individual views with this xml (everything just like onCreate)
ImageView img = (ImageView) convertView.findViewById(R.id.imageView1);
TextView tv = (TextView) convertView.findViewById(R.id.textView1);
// then perform your actions to the your views
// each textView is set to an element in the array based on position. this is my listview limiter here.
// each imageview is set to the same picture but you should now have an idea how to set different images (based on position)
// using listview position in correspondence with array/arraylist positions is a very useful technique.
img.setImageResource(R.drawable.ic_launcher);
tv.setText(children[position]);
// v---- return your view, it's important.
return convertView;
}
}
row.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="TextView" />
</RelativeLayout>
The result
To get super acquainted with listview check out this video:
http://www.youtube.com/watch?v=wDBM6wVEO70
As for your other issue, you're gonna have to post a logcat for better responses.

Categories

Resources