I am trying to fetch a text and image link from the database and add it to an ArrayList and then use it to display the text and image in a grid view. But it doesn't show up. It seems like the list items seem to be null when I try to add it.
What am I missing? I have gone through some answers and wasn't able to figure it out.
public final class GridAdapter extends BaseAdapter {
public static final String showUrl = "http://netbigs.com/apps/fetch.php";
String myJSON;
public String mvname;
String mvinfo;
public String rdate,imglink;
private Context mContext;
private final List<Item> mItems = new ArrayList<Item>();
private final LayoutInflater mInflater;
private static final String TAG_RESULTS = "result";
private static final String TAG_ID = "mvid";
private static final String TAG_NAME = "mvname";
private static final String TAG_IMG = "imglink";
private static final String TAG_DATE = "rdate";
private static final String TAG_MOVINF = "mvinfo";
JSONArray movies = null;
public GridAdapter(Context context) {
mItems.add(new Item(mvname,imglink));
mContext=context;
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return mItems.size();
}
#Override
public Item getItem(int i) {
return mItems.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
ImageView picture;
TextView name;
getData();
if (v == null) {
v = mInflater.inflate(R.layout.grid_item, viewGroup, false);
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.text, v.findViewById(R.id.text));
}
picture = (ImageView) v.getTag(R.id.picture);
name = (TextView) v.getTag(R.id.text);
Item item = getItem(i);
Picasso.with(this.mContext).load(item.drawableId).into(picture);
name.setText(item.name);
System.out.println(item.name);
return v;
}
private static class Item {
public final String name;
public final String drawableId;
Item(String name, String drawableId) {
this.name = name;
this.drawableId = drawableId;
}
}
protected void showList(){
try{
JSONObject jsonObj = new JSONObject(myJSON);
movies = jsonObj.getJSONArray(TAG_RESULTS);
for (int i=0;i<movies.length();i++){
JSONObject c = movies.getJSONObject(i);
String mvid = c.getString(TAG_ID);
mvname = c.getString(TAG_NAME);
System.out.println(mvname);
imglink = c.getString(TAG_IMG);
System.out.println(imglink);
rdate = c.getString(TAG_DATE);
mvinfo = c.getString(TAG_MOVINF);
try {
}
catch (Exception e){
e.printStackTrace();
}
}
}
catch (JSONException e){
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
String uri = showUrl;
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
InputStream inputStream = null;
String result = null;
inputStream = con.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
return sb.toString();
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
}
This is the fragment to which the GridAdapter is attached.
public class MovieFragment extends Fragment {
public MovieFragment() {
// Required empty public constructor
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_movie, container, false);
GridView gridView = (GridView)view.findViewById(R.id.gridview);
gridView.setAdapter(new GridAdapter(getActivity()));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i;
switch (position){
case 0:
i = new Intent(MovieFragment.this.getActivity(),MovieDetail.class);
startActivity(i);
break;
case 1:
i = new Intent(MovieFragment.this.getActivity(),MovieDetail.class);
startActivity(i);
break;
case 2:
i = new Intent(MovieFragment.this.getActivity(),MovieDetail.class);
startActivity(i);
break;
case 3:
i = new Intent(MovieFragment.this.getActivity(),MovieDetail.class);
startActivity(i);
break;
}
}
});
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}
You are calling getData() from your Adapter so it may possible that when you initialize it at that time your list is null.
Try calling that method form your activity or fragment and then pass the received data you received in your adapter class.
getView() is called multiple time when you scroll up or down so never call any api in that method
Provide the code where you are using this adapter.
the problem is you are not getting values from the DB.
you must get the values from the db first. by using Volley or some plugin like that(or Aysnc task. volley will be better i think.)
Related
I have problem while diplayin pictures , nothing is dsplayed in the sceen , seems empty only data are displayed no pictures. I think that the problem while parsing JSON Data in pictures.
here in the Fragment of the hotel where i want to display picture gallery.
public class ViewHotels extends AppCompatActivity {
private Bitmap bitmap;
private TextView nom1;
private TextView grade;
private TextView tele;
private ImageView image;
private TextView sit;
private TextView add1;
private TextView email1;
private FloatingActionButton fab;
LinearLayout layout;
private String id;
public static final String URL="http://gabes.comlu.com/Base_Controle/getEmpdetail.php";
private FeatureCoverFlow coverFlow;
private CoverFlowAdapter adapter;
private ArrayList<Game> games;
String image2;
String addresses;
String subject;
public static final String TAG_JSON_ARRAY="result";
ImageView im;
private int imageSource;
public String stringUrl;
public String stringUrl1;
public String stringUrl2;
public String stringUrl3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hotelsdetails);
final Intent intent = getIntent();
layout=(LinearLayout) findViewById(R.id.layout);
coverFlow = (FeatureCoverFlow) findViewById(R.id.coverflow);
settingDummyData();
adapter = new CoverFlowAdapter(this, games);
coverFlow.setAdapter(adapter);
coverFlow.setOnScrollPositionListener(onScrollListener());
id = intent.getStringExtra("Type");
nom1 = (TextView) findViewById(R.id. nom);
grade = (TextView) findViewById(R.id. grade);
tele = (TextView) findViewById(R.id. tele);
image= (ImageView)findViewById(R.id.imageView);
sit=(TextView) findViewById(R.id.site);
add1=(TextView) findViewById(R.id.adde);
email1=(TextView)findViewById(R.id.email);
nom1.setText(id);
im =new ImageView (this);
getEmployee();
}
private void getEmployee(){
final String login11 = nom1.getText().toString().trim();
class GetEmployee extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ViewHotels.this,"Fetching...","Wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
showEmployee(s);
}
#Override
protected String doInBackground(Void... v) {
HashMap<String,String> params = new HashMap<>();
params.put("id",login11)
RequestHandler rh = new RequestHandler();
String res= rh.sendPostRequest(URL, params);
return res;
}
}
GetEmployee ge = new GetEmployee();
ge.execute();
}
private void showEmployee(String json){
try {
JSONArray result = new JSONArray(json);
JSONObject c = result.getJSONObject(0);
String name = c.getString("nom");
String tel = c.getString("tele");
String grade1 = c.getString("grade");
String image1 = c.getString("image");
image2 = c.getString("img1");
String image3 = c.getString("img2");
String image4 = c.getString("img3");
String site= c.getString("site");
String add11= c.getString("add");
String email11= c.getString("email");
tele.setText("Tel : \t"+tel);
grade.setText("Grade : \t"+grade1);
sit.setText("site: \t"+site);
add1.setText("adresse :\t" + add11);
email1.setText("email :\t"+ email11);
final ImageView im1 =new ImageView (this);
final ImageView im2 =new ImageView (this);
final ImageView im3 =new ImageView (this);
stringUrl = ("http://gabes.comlu.com/Base_Controle/ImageBD/"+image1+".jpg");
stringUrl1 = ("http://gabes.comlu.com/Base_Controle/ImageBD/"+image2+".jpg");
stringUrl2 = ("http://gabes.comlu.com/Base_Controle/ImageBD/"+image3+".jpg");
stringUrl3 = ("http://gabes.comlu.com/Base_Controle/ImageBD/"+image4+".jpg");
} catch (JSONException e) {
e.printStackTrace();
}
}
private FeatureCoverFlow.OnScrollPositionListener onScrollListener() {
return new FeatureCoverFlow.OnScrollPositionListener() {
#Override
public void onScrolledToPosition(int position) {
Log.v("ViewHotels", "position: " + position);
}
#Override
public void onScrolling() {
Log.i("ViewHotels", "scrolling");
}
};
}
private void settingDummyData() {
games = new ArrayList<>();
Game game1 = new Game("stringUrl","");
Game game2 = new Game("stringUrl1","");
Game game3 = new Game("stringUrl2","");
games.add(game1);
games.add(game2);
games.add(game3);
}
}
Here is the coverFlow adapter :
public class CoverFlowAdapter extends BaseAdapter {
private ArrayList<Game> data;
private AppCompatActivity activity;
public CoverFlowAdapter(AppCompatActivity context, ArrayList<Game> objects) {
this.activity = context;
this.data = objects;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Game getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_flow_view, null, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
try {
URL myFileUrl = new URL(data.get(position).getImageSource());
Log.e("TAG stringUri",myFileUrl+"" );
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
viewHolder.gameImage.setImageBitmap(BitmapFactory.decodeStream(is));
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
//viewHolder.gameImage.setImageResource(data.get(position).getImageSource());
viewHolder.gameName.setText(data.get(position).getName());
return convertView;
}
private static class ViewHolder {
private TextView gameName;
private ImageView gameImage;
public ViewHolder(View v) {
gameImage = (ImageView) v.findViewById(R.id.image);
gameName = (TextView) v.findViewById(R.id.name);
}
}
}
And this the Game class :
public class Game {
private String name;
private String imageSource;
public Game (String imageSource, String name) {
this.name = name;
this.imageSource = imageSource;
}
public String getName() {
return name;
}
public String getImageSource() {
return imageSource;
}
}
I think (one of) your problem(s) is this part:
Game game1 = new Game("stringUrl","");
Game game2 = new Game("stringUrl1","");
Game game3 = new Game("stringUrl2","");
You are handing over the String "stringUrlx" to your Game-constructor.
In Java, quotation marks("") are used to explicitly define a string, which means that you are handing over "stringUrl" instead of the variable stringUrl, which would have the correct content ("http://gabes.comlu.com/Base_Controle/ImageBD/"+image1+".jpg").
so replace e.g.
Game game1 = new Game("stringUrl","");
by
Game game1 = new Game(stringUrl,"");
That should solve that one issue.
Other than that, you will also run into issues downloading your files and with memory management. I advise you to look into java specific tutorials, which use pre-built asynchronous image loading and caching libraries (such as Glide or Picasso !)
Listview doesn't appear at Fragment after second compile.
The button at fragment works, so the problem is with listview and adapter, but I can't understand where the problem is.
Even if I delete the program and reinstall, it doesn't help. Only if move some other place method updatepost it can work once.
Hope for advice! I'm just learning all this.
Main fragment:
public class MainFragment extends Fragment {
ArrayList<Bitmap> bitArray;
CustomListAdapter adapter;
public MainFragment() {
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onStart() {
super.onStart();}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ListView listview = (ListView)rootView.findViewById(R.id.listViewPost);
Log.v("Plaxehere","1");
adapter = new CustomListAdapter(getContext(), bitArray);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Toast.makeText(getActivity(), "YESS", Toast.LENGTH_SHORT).show();
}
});
Button but =(Button) rootView.findViewById(R.id.button_back_to_home);
but.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(getContext(), "Text", Toast.LENGTH_SHORT).show();
/*Intent intent = new Intent(getActivity(), MainActivity.class).putExtra(Intent.EXTRA_TEXT, "Hello");
startActivity(intent);*/
}
});
return rootView;
}
private void updatePost() {
FetchPosterTask postTask = new FetchPosterTask(getActivity());
postTask.execute("uk_news.json");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bitArray = new ArrayList<>();
updatePost();
}
class FetchPosterTask extends AsyncTask<String, Void, ArrayList<Bitmap>> {
private final String LOG_TAG = FetchPosterTask.class.getSimpleName();
private Context context;
public FetchPosterTask (Context myContext) {
this.context = myContext;
}
#Override
protected ArrayList<Bitmap> doInBackground(String... params) {
if(params.length ==0 ){
return null;
}
String json = null;
try {
json = getJson(params[0]);
} catch (IOException e)
{
e.printStackTrace();
}
try {
String[] masPst = getPosterfromJsonAsString(json);
ArrayList<Bitmap> result =decodeImageToBitmap(masPst);
return result;
}catch (JSONException e){
Log.e(LOG_TAG, "Place 5", e);
}
return null;
}
private String getJson(String filename) throws IOException{
InputStream is = this.context.getAssets().open(filename);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer);
}
private String[] getPosterfromJsonAsString(String posterJson) throws JSONException {
final String OWM_NFO = "nfo";
final String OWM_NWS = "nws";
final String OWM_PST = "pst";
JSONObject imageJson = new JSONObject(posterJson);
JSONObject nfoArray = imageJson.getJSONObject(OWM_NFO);
JSONArray nwsArray = nfoArray.getJSONArray(OWM_NWS);
String[] resultStr = new String[nwsArray.length()];
for(int i =0; i<nwsArray.length(); i++){
JSONObject pst = nwsArray.getJSONObject(i);
String im = pst.getString(OWM_PST);
resultStr[i] = im;
}
return resultStr;
}
public ArrayList<Bitmap> decodeImageToBitmap (String[] base64Image) {
ArrayList<Bitmap> bitmapArrayList = new ArrayList<Bitmap>();
for(int i =0; i<4; i++) {
byte[] decodedString = Base64.decode(base64Image[i], Base64.DEFAULT);
Bitmap base64Bitmap = BitmapFactory.decodeByteArray(decodedString, 0,
decodedString.length);
bitmapArrayList.add(i, base64Bitmap);
}
return bitmapArrayList;
}
#Override
protected void onPostExecute(ArrayList<Bitmap> bitmapArrayList) {
if(bitArray.size()!=0){
bitArray.clear();
bitArray.addAll(bitmapArrayList);
}
else{
bitArray.addAll(bitmapArrayList);
}
}
}
}
Adapter
public class CustomListAdapter extends BaseAdapter {
private final String LOG_TAG = CustomListAdapter.class.getSimpleName();
private ArrayList<Bitmap> bitmapArrayList;
private LayoutInflater layoutInflater;
public CustomListAdapter(Context context, ArrayList<Bitmap> bitmapArrayList) {
this.bitmapArrayList = bitmapArrayList;
this.layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return bitmapArrayList.size();
}
#Override
public Object getItem(int position) {
return bitmapArrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_post_item, null);
holder = new ViewHolder();
holder.imageView = (ImageView) convertView.findViewById(R.id.list_item);
convertView.setTag(holder);
Log.v(LOG_TAG,"1");
}
else {
holder = (ViewHolder) convertView.getTag();
Log.v(LOG_TAG,"2");
}
Log.v(LOG_TAG,"3");
if(getItem(position) == null) {
holder.imageView.setImageResource(R.drawable.pst_0);
Log.v(LOG_TAG,"5");
}
else{
holder.imageView.setImageBitmap((Bitmap) getItem(position));
Log.v(LOG_TAG,"6");
}
Log.v(LOG_TAG,"4");
return convertView;
}
static class ViewHolder {
ImageView imageView;
}
}
Main Activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new MainFragment())
.commit();
}
}
}
i am trying to display two images per row in GridView using custom adapter and using picasso library for display images but i am having spaces between the images and i want the app look like App mock
mine is image
i want to remove white spacings between the images
Here is the class File MovieFragment
package com.example.good.movieapp;
public class MovieFragment extends Fragment {
String[] movieTitle, moviePosterPath;
public MovieFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
ImageAdapter mImageAdater;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_movie, container, false);
mImageAdater = new ImageAdapter(getActivity());
GridView movieView = (GridView) rootView.findViewById(R.id.movieview);
movieView.setAdapter(mImageAdater);
updateMovie();
movieView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MovieFragment.this.getActivity(), "" + position,
Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
private void updateMovie(){
FetchMovie fetchMovie = new FetchMovie();
fetchMovie.execute();
}
public class FetchMovie extends AsyncTask<Void, Void, List<String>>{
private final String LOG_TAG = FetchMovie.class.getSimpleName();
private List<String> getMovies(String jsonString) throws JSONException{
JSONObject movieJson = new JSONObject(jsonString);
JSONArray movieArray = movieJson.getJSONArray("results");
List<String> urls = new ArrayList<>();
for(int i=0; i<movieArray.length(); i++){
JSONObject movie = movieArray.getJSONObject(i);
urls.add("http://image.tmdb.org/t/p/w342" + movie.getString("poster_path"));
}
return urls;
}
#Override
protected List<String> doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String jsonString = null;
String sort_by = "popularity.desc";
int page = 1;
try{
final String BASE_URL = "https://api.themoviedb.org/3/discover/movie?";
final String PAGE_PARAM = "page";
final String SORT_BY_PARAM = "popularity.desc";
final String APP_ID = "api_key";
Uri builtUri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(PAGE_PARAM, Integer.toString(page))
.appendQueryParameter(SORT_BY_PARAM, sort_by)
.appendQueryParameter(APP_ID, BuildConfig.MOVIE_API_KEY)
.build();
URL url = new URL(builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if(inputStream==null){
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while((line = reader.readLine()) != null){
buffer.append(line + "\n");
}
if(buffer.length()==0){
return null;
}
jsonString = buffer.toString();
}catch (final IOException e){
Log.e(LOG_TAG, "Error closing stream", e);
return null;
}finally{
if(urlConnection != null){
urlConnection.disconnect();
}
if(reader!=null){
try{
reader.close();
}catch(final IOException e){
Log.e(LOG_TAG, "error closing reader", e);
}
}
}
try {
return getMovies(jsonString);
}catch (JSONException j){
Log.e(LOG_TAG, j.getMessage(), j);
j.printStackTrace();
}
return null;
}
protected void onPostExecute(List<String> strings) {
mImageAdater.replace(strings);
}
}
public class ImageAdapter extends BaseAdapter{
private final String LOG_TAG = ImageAdapter.class.getSimpleName();
private final Context context;
private final List<String> urls = new ArrayList<String>();
public ImageAdapter(Context context){
this.context = context;
//Collections.addAll(urls, moviePosterPath);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
convertView = new ImageView(context);
}
ImageView movieView = (ImageView) convertView;
String url = getItem(position);
Log.e(LOG_TAG, "URL: " + url);
Picasso.with(context).load(url).into(movieView);
return convertView;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public String getItem(int position) {
return urls.get(position);
}
#Override
public int getCount() {
return urls.size();
}
public void replace(List<String> urls) {
this.urls.clear();
this.urls.addAll(urls);
notifyDataSetChanged();
}
}
}
Here is the xml file for MovieFragment
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.good.movieapp.MovieFragment">
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/movieview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
/>
MainActivityClass
package com.example.good.movieapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//populate the fragment
if(savedInstanceState == null){
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new MovieFragment())
.commit();
}
}
MainActivity xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.good.movieapp.MainActivity"
android:id="#+id/container">
</RelativeLayout>
used center_crop instead of center
I am developing an application in which i am getting a large json data from the server. i want to display it in the list view. But i am getting the same value repeated. The no of items shown by the list view is proper. only same data repeated in all the list items.
Here is my code.
public class HistoryActivity extends AppCompatActivity {
private Toolbar toolbar;
String strServerResponse = null;
ProgressDialog nDialog;
ArrayList<String>clicklat;
ArrayList<String>clicklong;
ArrayList<String>dttime;
ArrayList<Pojo> history;
HistoryAdapter myAdapter;
ListView list;
public String date, inTime, outTime, inLat, inLong;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
toolbar = (Toolbar) findViewById(R.id.app_bar);
toolbar.setTitle("History");
clicklat=new ArrayList<String>();
clicklong=new ArrayList<String>();
dttime=new ArrayList<String>();
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
list = (ListView) findViewById(R.id.historyList);
history = new ArrayList<Pojo>();
new NetCheck().execute();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ArrayList<String>clicklat= new ArrayList<String>(history.get(position).getLati());
ArrayList<String>clicklong= new ArrayList<String>(history.get(position).getLongi());
ArrayList<String>dttime= new ArrayList<String>(history.get(position).getDatetime());
Intent i = new Intent(HistoryActivity.this, DetailsActivity.class);
i.putStringArrayListExtra("clicklat", clicklat);
i.putStringArrayListExtra("clicklong", clicklong);
i.putStringArrayListExtra("clickdatetime", dttime);
startActivity(i);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class NetCheck extends AsyncTask<Void, Void, Void> {
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
nDialog.dismiss();
// TODO Auto-generated method stub
myAdapter = new HistoryAdapter(HistoryActivity.this, history);
list.setAdapter(myAdapter);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(
"http://myurl");
httpRequest.setHeader("Content-Type", "application/json");
SharedPreferences mmm = getSharedPreferences(
"MyPref", MODE_PRIVATE);
String logempid = mmm.getString("id", null);
JSONObject json = new JSONObject();
json.put("empid", logempid);
Log.e("JSON Object", json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding("UTF-8");
se.setContentType("application/json");
httpRequest.setEntity(se);
HttpResponse httpRes = httpClient.execute(httpRequest);
java.io.InputStream inputStream = httpRes.getEntity()
.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
strServerResponse = sb.toString();
Log.e("Server Response", "" + strServerResponse.toString());
if (strServerResponse != null) {
try {
JSONArray arr = new JSONArray(strServerResponse);
for (int k = 0; k < arr.length(); k++) {
JSONObject jsonObj1 = arr.getJSONObject(k);
Pojo pojo = new Pojo();
JSONArray subArrayLat = jsonObj1.getJSONArray("lati_long");
List<String> lati= new ArrayList<String>();
List<String> longi= new ArrayList<String>();
List<String> dateandtime= new ArrayList<String>();
for (int i = 0; i < subArrayLat.length(); i++) {
String lat = subArrayLat.getJSONObject(i).getString("Latitude").toString();
String loong = subArrayLat.getJSONObject(i).getString("Longitude").toString();
String datetimee = subArrayLat.getJSONObject(i).getString("date_time").toString();
lati.add(lat);
longi.add(loong);
dateandtime.add(datetimee);
}
pojo.setLati(lati);//adding latitude list
pojo.setLongi(longi); //adding longitude list
pojo.setDatetime(dateandtime);
String dateee = arr.getJSONObject(k).getString("login_date");
String timeeee = arr.getJSONObject(k).getString("login_time");
String timeeee2 = arr.getJSONObject(k).getString("logout_time");
pojo.setDate(dateee);
pojo.setLoginTime(timeeee);
pojo.setLogoutTime(timeeee2);
history.add(pojo);
}
} catch (JSONException e) {
e.printStackTrace();
}
And this is Adapter
public class HistoryAdapter extends BaseAdapter {
private Context activity;
TextView tv_date;
TextView tv_loginTime;
TextView tv_logoutTime;
ArrayList<Pojo> list;
private ArrayList<Pojo> arraylist = null;
public static LayoutInflater inflater;
private Context context;
public HistoryAdapter(Context a, ArrayList<Pojo> history) {
// TODO Auto-generated constructor stub
activity = a;
list = history;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arraylist = new ArrayList<Pojo>();
this.arraylist.addAll(list);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if(convertView == null) {
v = inflater.inflate(R.layout.history_item, parent, false);
}
final Pojo pojo = list.get(position);
tv_date = (TextView) v.findViewById(R.id.historyDate);
tv_loginTime = (TextView) v.findViewById(R.id.historyLoginTime);
tv_logoutTime = (TextView) v.findViewById(R.id.historyLogoutTime);
tv_date.setText(pojo.getDate());
tv_loginTime.setText(pojo.getLoginTime());
tv_logoutTime.setText(pojo.getLogoutTime());
return v;
}
}
and setters and getters
public class Pojo {
public static String empid11;
public static String loginTime;
public static String date;
public static String logoutTime;
public static List<String> lat;
public static List<String> datetime;
public static List<String> longi;
public static List<String> inlogin;
public static List<String> inDate;
public List<String> getInTime(){
return this.inlogin;
}
public List<String> getInDate(){
return this.inDate;
}
public void setInDate(List<String> inDate){
this.inDate = inDate;
}
public List<String> getLati(){
return this.lat;
}
public List<String> getLongi(){
return this.longi;
}
public void setLati(List<String> lat){
this.lat = lat;
}
public void setLongi(List<String> longi){
this.longi = longi;
}
public void setId(String empid) {
this.empid11 = empid;
}
public String getId() {
return empid11;
}
public void setLoginTime(String loginTime) {
this.loginTime = loginTime;
}
public String getLoginTime() {
return loginTime;
}
public void setLogoutTime(String logoutTime) {
this.logoutTime = logoutTime;
}
public String getLogoutTime() {
return logoutTime;
}
public void setDate(String date) {
this.date = date;
}
public String getDate() {
return date;
}
public List<String> getDatetime(){
return this.datetime;
}
public void setDatetime(List<String> datetime){
this.datetime = datetime;
}
}
Hello see the modifiy version of your adapter. Let me know if you have any problem with it.
public class HistoryAdapter extends BaseAdapter
{
private Context activity;
TextView tv_date;
TextView tv_loginTime;
TextView tv_logoutTime;
private ArrayList<Pojo> arraylist = null;
public static LayoutInflater inflater;
private Context context;
public HistoryAdapter(Context a) {
activity = a;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arraylist = new ArrayList<Pojo>();
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void addHistoryData(ArrayList<Pojo> newDataset){
if(arraylist != null){
arraylist.addAll(newDataset);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder mViewHolder = null;
if(convertView == null)
{
mViewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.history_item, parent, false);
mViewHolder.tv_date = (TextView) convertView.findViewById(R.id.historyDate);
mViewHolder.tv_loginTime = (TextView)convertView.findViewById(R.id.historyLoginTime);
mViewHolder.tv_logoutTime = (TextView)convertView.findViewById(R.id.historyLogoutTime);
convertView.setTag(mViewHolder);
}else{
mViewHolder = (ViewHolder) convertView.getTag();
}
final Pojo pojo = list.get(position);
mViewHolder.tv_date.setText(pojo.getDate());
mViewHolder.tv_loginTime.setText(pojo.getLoginTime());
mViewHolder.tv_logoutTime.setText(pojo.getLogoutTime());
return v;
}
public class ViewHolder{
TextView tv_date
TextView tv_loginTime;
TextView tv_logoutTime;
}
}
In next the activity NetCheck class when web service response come change like below :
history.add(pojo);
myAdapter.addHistoryData(history);
myAdapter.notifiyDatasetChanged();
There may be problem you are getting repeated value in array, please check your array first.
I'm stuck creating an Adapter for my Griview that accepts an ArrayList. I think the bad line in the Adapter class is: viewHldr.wcbc_image_iv.setImageResource(urlStrArrList.get(position)); and it appears that the call .setImageResource is the problem.
public class JGrid66 extends Activity {
JSONObject jsonOb;
JSONArray JSArrGallery = null;;
GridView grid65_gv;
JGrid66Adapter2 jGr7Adap;
ProgressDialog mProgressDialog;
ArrayList<String> idStrArrList = new ArrayList<String>();
ArrayList<String> urlStrArrList = new ArrayList<String>();
ArrayList<String> descrStrArrList = new ArrayList<String>();
// JSON Node names
private static final String TAG_GALLERY = "gallery";
private static final String TAG_GALLERYURL = "galleryurl";
private static final String TAG_ID = "id";
private static final String TAG_GALLERYDESCR = "gallerydescr";
static String FLAG = "flag";
private String jsonUrl = "http://www.mysite.com/apps/wcbc/galleryuil.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jgrid66);
grid65_gv = (GridView) findViewById(R.id.jgrid66_gv);
}//--- END onCreate
//--- DownloadJSON Class
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
JGrid4Adapter jParser = new JGrid4Adapter();
// getting JSON string from URL
JSONObject jsonOb = jParser.getJSONFromUrl(jsonUrl);
try {
JSArrGallery = jsonOb.getJSONArray(TAG_GALLERY);
// looping through All gallery images
for (int i = 0; i < JSArrGallery.length(); i++) {
JSONObject galleryJO = JSArrGallery.getJSONObject(i);
String idStr = galleryJO.getString(TAG_ID);
String urlStr = galleryJO.getString(TAG_GALLERYURL);
String descrStr = galleryJO.getString(TAG_GALLERYDESCR);
idStrArrList.add(idStr);
urlStrArrList.add(urlStr);
descrStrArrList.add(descrStr);
}// -- END for loop
} catch (JSONException e) {
e.printStackTrace();
}// --- END Try
return null;
}
#Override
protected void onPostExecute(Void args) {
jGr7Adap = new JGrid66Adapter2(JGrid66.this, urlStrArrList);
grid65_gv.setAdapter(jGr7Adap);
jGr7Adap.notifyDataSetChanged();
}
}
//--- END DownloadJSON Class
}
Here;s the Adapter:
public class JGrid66Adapter2 extends BaseAdapter {
private ArrayList<String> urlStrArrList;
Context context;
public JGrid66Adapter2(Context context,ArrayList<String> urlStrArrList) {
super();
this.urlStrArrList = urlStrArrList;
}
#Override
public int getCount() {
return urlStrArrList.size();
}
#Override
public String getItem(int position) {
return urlStrArrList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public static class ViewHolder
{
public ImageView wcbc_image_iv;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHldr;
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
if(convertView==null){
viewHldr = new ViewHolder();
convertView = inflater.inflate(R.layout.jgrid66_item, null);
viewHldr.wcbc_image_iv = (ImageView) convertView.findViewById (R.id.jgrid66_iv);
convertView.setTag(viewHldr);
}
else
{
viewHldr = (ViewHolder) convertView.getTag();
}
//--- I commented this out because this is where it breaks.
//viewHldr.wcbc_image_iv.setImageResource(urlStrArrList.get(position));
return convertView;
}
}
Any help would be great!
private ArrayList<String> urlStrArrList;
is arraylist of strings. If you have the url you need to download the images and then set it to imageview.
setImageResource takes a resource id as a param which is an int value.
public void setImageResource (int resId)
Added in API level 1
Sets a drawable as the content of this ImageView.
You may consider using Lazy Loading Universal Image Loader or using picasso
Caching images and displaying