Gridview two columns per row without spacing - android

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

Related

Fetching image from database into Android GridView

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.)

Doesn't run oncreateview at Fragment after AsyncTask

I'm new in android and stuck at one step, so really need someones help.
I m code for small piece of program, that should parse Json local file, and post it to activity. Image decode with Base64 to Bitmap and given to CustomAdapter(extends Base Adapter). I check program's steps with Log.
AsyncTask make all correct, but in method "Oncreate view" it seems to run nothing.
Her is my code. I m really have no idea , what the problem, help!
My MainFragment+AsyncTask
public class MainFragment extends Fragment {
ArrayList<Bitmap> bitArray;
public MainFragment() {
}
#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("Pl","1");
listview.setAdapter(new CustomListAdapter(getContext(), bitArray));
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();
}
});
return rootView;
}
#Override
public void onStart() {
super.onStart();
}
private void updatePost() {
FetchPosterTask postTask = new FetchPosterTask(getActivity());
postTask.execute("uk_news.json");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
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 == null){
bitArray = new ArrayList<>(bitmapArrayList);
}
else{
for(Bitmap bit: bitmapArrayList){
bitArray.clear();
bitArray.add(bit);
}
}
}
}
}
CustomListAdapter
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 0;
}
#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");
holder.imageView.setImageBitmap((Bitmap)getItem(position));
Log.v(LOG_TAG,"4");
return convertView;
}
static class ViewHolder {
ImageView imageView;
}
}
Layouts
list_post_item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/list_item"/>
</LinearLayout>
fragment main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="273dp"
android:layout_height="wrap_content"
android:id="#+id/listViewPost" />
</LinearLayout>
Your Adapter Has Not Any Item So Please change That on Adapter
#Override
public int getCount() {
return bitmapArrayList.size();
}
And also call updatePost() methed in onActivityCreated() Mehhed

Listview doesn't appear at Fragment after second compile

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();
}
}
}

No searching results after onTextChanged in android Listview [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I can't resolve this problem. I want to add search functionality by EditText. Results should dynamically display after typing letters but now there is no results.
Thanks for Your quick response :)
ParkingActivity.java
public class ParkingActivity extends FragmentActivity {
private final String URL_TO_HIT = "http://www-users.mat.umk.pl/~discordia/dane.json";
private ListView lvParking;
private EditText inputSearch;
public ParkingAdapter adapter;
public ArrayList<ParkingModel> parkingModelList = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_activity);
lvParking = (ListView) findViewById(R.id.lvParking);
inputSearch = (EditText) findViewById(R.id.editText);
new JSONTask().execute(URL_TO_HIT);
}
public class JSONTask extends AsyncTask<String,String, List<ParkingModel> > {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<ParkingModel> 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));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("parkingInfo");
ArrayList<ParkingModel> parkingModelList = new ArrayList<>();
Gson gson = new Gson();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
/**
* below single line of code from Gson saves you from writing the json parsing yourself which is commented below
*/
ParkingModel parkingModel = gson.fromJson(finalObject.toString(), ParkingModel.class);
parkingModelList.add(parkingModel);
}
return parkingModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException 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(final List<ParkingModel> result) {
super.onPostExecute(result);
if(result != null) {
adapter = new ParkingAdapter(getApplicationContext(), R.layout.row, result);
lvParking.setAdapter(adapter);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
ParkingActivity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
lvParking.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ParkingModel parkingModel = result.get(position);
Intent intent = new Intent(ParkingActivity.this, DetailActivity.class);
intent.putExtra("parkingModel", new Gson().toJson(parkingModel));
startActivity(intent);
}
});
}
}
}
public class ParkingAdapter extends ArrayAdapter {
private List<ParkingModel> parkingModelList;
private int resource;
private LayoutInflater inflater;
public ParkingAdapter(Context context, int resource, List<ParkingModel> objects) {
super(context, resource, objects);
parkingModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
holder = new ViewHolder();
convertView = inflater.inflate(resource, null);
holder.tvLokalizacja = (TextView)convertView.findViewById(R.id.tvLokalizacja);
holder.tvIle_wolnych_zwyklych = (TextView)convertView.findViewById(R.id.tvIle_wolnych_zwyklych);
holder.tvIle_wszystkich_zwyklych = (TextView)convertView.findViewById(R.id.tvIle_wszystkich_zwyklych);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvLokalizacja.setText(parkingModelList.get(position).getLokalizacja());
holder.tvIle_wolnych_zwyklych.setText("Wolne: " + parkingModelList.get(position).getIle_wolnych_zwyklych());
holder.tvIle_wszystkich_zwyklych.setText("Wszystkie:" + parkingModelList.get(position).getIle_wszystkich_zwyklych());
return convertView;
}
class ViewHolder{
private TextView tvLokalizacja;
private TextView tvIle_wolnych_zwyklych;
private TextView tvIle_wszystkich_zwyklych;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_parking, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
}
This is my model which I use to create final array with data.
ParkingModel.java
public class ParkingModel {
private String lokalizacja;
private int ile_wolnych_zwyklych;
private int ile_wszystkich_zwyklych;
public String getLokalizacja() {
return lokalizacja;
}
public void setLokalizacja(String lokalizacja) {
this.lokalizacja = lokalizacja;
}
public int getIle_wolnych_zwyklych() {
return ile_wolnych_zwyklych;
}
public void setIle_wolnych_zwyklych(int ile_wolnych_zwyklych) {
this.ile_wolnych_zwyklych = ile_wolnych_zwyklych;
}
public int getIle_wszystkich_zwyklych() {
return ile_wszystkich_zwyklych;
}
public void setIle_wszystkich_zwyklych(int ile_wszystkich_zwyklych) {
this.ile_wszystkich_zwyklych = ile_wszystkich_zwyklych;
}
}
Here is my xml file.
list_activity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ParkingActivity">
<EditText
android:layout_width="319dp"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:inputType="text"
android:layout_gravity="center_horizontal" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lvParking" />
</LinearLayout>
Because in onPostExecute of JSONTask you have created new object of ParkingAdapter class and below that
ParkingActivity.this.adapter.getFilter().filter(cs); you are using this line.
this is always null;
To set adapter just use
adapter = new ParkingAdapter(getApplicationContext(), R.layout.row, result);
lvParking.setAdapter(adapter);
change this line
ParkingAdapter adapter = new ParkingAdapter(getApplicationContext(), R.layout.row, result);
To This
adapter = new ParkingAdapter(getApplicationContext(), R.layout.row, result);

Adapter not displaying correct data

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.

Categories

Resources