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
Related
Is there a way to choose a specific row of my RecyclerView (maybe by getting the index of the row) and then use it to create an intent.
I tried some things by getting the specific row information but that was not even close. My recycler is populated with data from a database.
To choose a specific row of my recycler, you can add setOnItemClickListener code like this one to your onCreate function:
listView_search.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id){
//Here I'm getting store_id and store_name
TextView store_search_id =(TextView) v.findViewById(R.id.store_search_id);
TextView store_search_name =(TextView) v.findViewById(R.id.store_search_name);
String store_name = store_search_name.getText().toString();
String store_id = store_search_id.getText().toString();
//Then I'm sending theses variables to a shared Intent
Intent myIntent = new Intent(getApplicationContext(), StoresShowActivity.class);
myIntent.putExtra("STORE_ID", store_id);
myIntent.putExtra("STORE_NAME", store_name);
startActivity(myIntent);
}
}
);
You may also want to follow these steps:
A. Add a layout for the Recycle view:
<?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:id="#+id/activity_stores_search"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="ksa.ikp.activities.StoresSearchActivity">
<SearchView
android:id="#+id/SearchView_store"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:iconifiedByDefault="false">
<requestFocus />
</SearchView>
<ListView
android:id="#+id/listView_search"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/SearchView_store" />
</RelativeLayout >
B. Add a layout for the recycleview item
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:padding="10dp">
<TextView
android:id="#+id/store_search_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible" />
<TextView
android:id="#+id/store_search_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/store_search_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
C. Use adapter like this one and you can modify it based on your need
public class StoresSearchAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<Store> myList = null;
private ArrayList<Store> myArrayList;
public StoresSearchAdapter(Context context, List<Store> myList) {
mContext = context;
this.myList = myList;
inflater = LayoutInflater.from(mContext);
this.myArrayList = new ArrayList<Store>();
this.myArrayList.addAll(myList);
}
public class ViewHolder {
TextView store_search_id;
TextView store_search_name;
TextView store_search_category;
}
#Override
public int getCount() {
return myList.size();
}
#Override
public Store getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.activity_stores_search_item, null);
// Locate the TextViews in activity_stores_search_item.xml
holder.store_search_id = (TextView) view.findViewById(R.id.store_search_id);
holder.store_search_name = (TextView) view.findViewById(R.id.store_search_name);
holder.store_search_category = (TextView) view.findViewById(R.id.store_search_category);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.store_search_id.setText(myList.get(position).getStr_id()+"");
holder.store_search_name.setText(myList.get(position).getStr_name());
String s = SplashActivity.db.getNameById(myList.get(position).getStr_cat_id()+"",SplashActivity.db.TABLE_CATEGORY,SplashActivity.db.COLUMN_CAT_NAME,SplashActivity.db.COLUMN_CAT_ID);
s = " in ("+ s + ")";
holder.store_search_category.setText(s);
return view;
}
// Filter Class
public void filter(String s) {
s = s.toLowerCase(Locale.getDefault());
myList.clear();
if (s.length() == 0) {
myList.addAll(myArrayList);
} else {
myList.addAll(SplashActivity.db.getAllStoresFiltered(s));
}
notifyDataSetChanged();
}
}
Finally your final output will be something like this one:
screenshot
This is my recyclerbackgroundtask
public class RecycleBackgroundTask extends AsyncTask{
Context ctx;
Activity activity;
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<Post> arrayList = new ArrayList<>();
public RecycleBackgroundTask(Context ctx){
this.ctx = ctx;
activity = (Activity)ctx;
}
String json_string = "http://192.168.2.110/app/post.php";
#Override
public void onPreExecute() {
recyclerView = (RecyclerView)activity.findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(ctx);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerAdapter(arrayList);
recyclerView.setAdapter(adapter);
}
#Override
public Void doInBackground(Void... params) {
try {
URL url = new URL(json_string);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line=bufferedReader.readLine())!=null) {
stringBuilder.append(line+"\n");
}
httpURLConnection.disconnect();
String json_string = stringBuilder.toString().trim();
JSONObject jsonObject = new JSONObject(json_string);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while(count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
count++;
Post post = new Post(JO.getString("headline"),JO.getString("source"),JO.getString("url"));
publishProgress(post);
}
Log.d("JSON STRING",json_string);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
public void onProgressUpdate(Post... values) {
arrayList.add(values[0]);
adapter.notifyDataSetChanged();
}
And my RecyclerAdapter
public class RecyclerAdapter extends RecyclerView.Adapter {
private static final int TYPE_HEAD = 0;
private static final int TYPE_LIST = 1;
ArrayList<Post> arrayList = new ArrayList<>();
public RecyclerAdapter (ArrayList<Post> arrayList){
this.arrayList = arrayList;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == TYPE_HEAD){
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_recycler,parent,false); // instead of row_recycler ,header_layout.
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view,viewType);
return recyclerViewHolder;
}
if(viewType == TYPE_LIST){
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_recycler,parent,false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view,viewType);
return recyclerViewHolder;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
if(holder.viewType == TYPE_LIST) {
Post post = arrayList.get(position-1);
holder.Headline.setText(post.getHeadline());
holder.Source.setText(post.getSource());
//holder.Url.setText(post.getUrl());
}
}
#Override
public int getItemCount() {
return arrayList.size()+1;
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView Headline,Source;//,Url;
int viewType;
public RecyclerViewHolder(View view,int viewType){
super(view);
if(viewType == TYPE_LIST) {
Headline = (TextView) view.findViewById(R.id.headline);
Source = (TextView) view.findViewById(R.id.source);
Headline.setOnClickListener(this);
Source.setOnClickListener(this);
// Url = (TextView) view.findViewById(R.id.url);
this.viewType = TYPE_LIST;
}else if (viewType == TYPE_HEAD){
this.viewType = TYPE_HEAD;
}
}
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "ITEM PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
}
}
#Override
public int getItemViewType(int position){
if(position==0)
return TYPE_HEAD;
return TYPE_LIST;
}
public void setFilter(ArrayList<Post> newList){
arrayList = new ArrayList<>();
arrayList.addAll(newList);
notifyDataSetChanged();
}
}
Maybe that helps. i already set up a simple onclicklistener with a toast btw
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.)
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'm getting a Null Pointer Exception when setting a custom adapter to listview.
Note. I am using a Fragment
I think this is the issue because there's no error if I removed this:
lvwVenues.setAdapter(adapter);
Here's my current code VenuesFragment.java:
public class VenuesFragment extends Fragment {
private static final String TAG = VenuesFragment.class.getName();
private static AsyncHttpClient client = new AsyncHttpClient();
private static ArrayList<String> name_array = new ArrayList<String>();
private static ArrayList<String> address_array = new ArrayList<String>();
static ListView lvwVenues;
static MyBaseAdapter adapter;
public VenuesFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_events, container, false);
lvwVenues = (ListView) rootView.findViewById(R.id.lvwVenues);
try
{
String storageG = Storage.readFile(Constants.storage, this.getActivity());
JSONObject userObj = new JSONObject(storageG);
getVenues(userObj.getString("authentication_token"), getActivity());
} catch (Exception e)
{
e.printStackTrace();
}
return rootView;
}
public void getVenues(String token, final Context context){
client = new AsyncHttpClient();
client.addHeader("Authorization", "Token token=" + token);
client.get(Constants.API_URL_STAGING_V1 + "/venues", new AsyncHttpResponseHandler() {
#Override
public void onStart() {
}
#Override
public void onSuccess(String response) {
try {
JSONArray new_array = new JSONArray(response);
Log.v(TAG, "VENUES " + new_array);
for (int i = 0, count = new_array.length(); i < count; i++) {
JSONObject jsonObject = new_array.getJSONObject(i);
name_array.add(jsonObject.getString("name").toString());
address_array.add(jsonObject.getString("address").toString());
}
adapter = new MyBaseAdapter(context, name_array, address_array);
Log.v(TAG, "ADAPTER " + adapter);
lvwVenues.setAdapter(adapter);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable error, String content)
{
error.printStackTrace();
}
});
}
}
fragment_venues.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/lvwVenues"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</ListView>
</LinearLayout>
MyBaseAdapter.java
public class MyBaseAdapter extends ArrayAdapter<String> {
private final Context context;
private final ArrayList<String> venue_names_array;
private final ArrayList<String> venue_address_array;
public MyBaseAdapter(Context context, ArrayList<String> name_array, ArrayList<String> address_array) {
super(context, R.layout.row_listitem, name_array);
this.context = context;
this.venue_names_array = name_array;
this.venue_address_array = address_array;
Log.v("VENUE NAMES", venue_names_array.toString());
Log.v("VENUE ADDRESS", venue_address_array.toString());
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.row_listitem, parent, false);
TextView txtName = (TextView) rowView.findViewById(R.id.name);
TextView txtDescription = (TextView) rowView.findViewById(R.id.address);
String venue_name = venue_names_array.get(position).toString();
String venue_address = venue_address_array.get(position).toString();
txtName.setText(venue_name);
txtDescription.setText(venue_address);
return rowView;
}
}
I fixed my own problem by adding a onViewCreated callback for my Fragment
Here's the code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState) {
return inflater.inflate(R.layout.fragment_venues, container, false);
}
#Override
public void onViewCreated (View view, Bundle savedInstanceState) {
lvwVenues = (ListView) view.findViewById(R.id.lvwVenues);
try
{
// put your codes here
} catch (Exception e)
{
e.printStackTrace();
}
}