I have divided my android screen into 2 fragements .In the first one I make a listview from server database to android mobile.The problem is that I can't call getview method in the base adapter class. Do help me out
public class MyListFragment1 extends ListFragment {
ImageView back;
String url = Main.url;
String Qrimage;
Bitmap bmp;
ListView list ;
AppetiserFragment adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.applistviewfragment, container, false);
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// back=(ImageView)findViewById(R.id.backfoodmenu);
/*
* back.setOnClickListener(new OnClickListener() {
*
* public void onClick(View v) { // TODO Auto-generated method stub
* Intent intent=new Intent(getApplicationContext(),FoodMenu.class);
* intent.putExtra("url", url); startActivity(intent); } });
*/
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
InputStream is = null;
String result = "";
JSONObject jArray = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url + "test.php3");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
// TODO: handle exception
Log.e("Log", "Error in Connection" + e.toString());
// Intent intent = new Intent(ViewQRCode.this, PimCarder.class);
// startActivity(intent);
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
jArray = new JSONObject(result);
JSONArray json = jArray.getJSONArray("appetiser");
Context context = null;
context = this.getActivity().getApplicationContext();
//(Here i want give lisid from xml)
list=(Listview)findViewById(R.id.list);//i type here it shows an error
adapter = new AppetiserFragment(context, json);
context = getActivity().getApplicationContext();
list.setAdapter(adapter);
} catch (Exception e) {
// TODO: handle exception
Log.e("log", "Error in Passing data" + e.toString());
}
}
}
AppetiserFragment.java
public class AppetiserFragment extends BaseAdapter {
String url = Main.url;
public Context Context;
String qrimage;
Bitmap bmp, resizedbitmap;
Bitmap[] bmps;
Activity activity = null;
private LayoutInflater inflater;
private ImageView[] mImages;
String[] itemimage;
TextView[] tv;
String itemname, price, desc, itemno;
String[] itemnames, checkeditems, itemnos;
String[] prices;
String[] descs;
HashMap<String, String> map = new HashMap<String, String>();
public AppetiserFragment(Context context, JSONArray imageArrayJson) {
Context = context;
// inflater =
System.out.println(imageArrayJson);
// (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader=new ImageLoader(activity);
inflater = LayoutInflater.from(context);
this.mImages = new ImageView[imageArrayJson.length()];
this.bmps = new Bitmap[imageArrayJson.length()];
this.itemnames = new String[imageArrayJson.length()];
this.prices = new String[imageArrayJson.length()];
this.descs = new String[imageArrayJson.length()];
this.itemnos = new String[imageArrayJson.length()];
try {
for (int i = 0; i < imageArrayJson.length(); i++) {
JSONObject image = imageArrayJson.getJSONObject(i);
qrimage = image.getString("itemimage");
itemname = image.getString("itemname");
itemno = new Integer(i + 1).toString();
price = image.getString("price");
desc = image.getString("itemdesc");
System.out.println(price);//here i can print price
itemnames[i] = itemname;
prices[i] = price;
descs[i] = desc;
itemnos[i] = itemno;
byte[] qrimageBytes = Base64.decode(qrimage.getBytes());
bmp = BitmapFactory.decodeByteArray(qrimageBytes, 0,
qrimageBytes.length);
int width = 100;
int height = 100;
resizedbitmap = Bitmap.createScaledBitmap(bmp, width, height,
true);
bmps[i] = bmp;
mImages[i] = new ImageView(context);
mImages[i].setImageBitmap(resizedbitmap);
mImages[i].setScaleType(ImageView.ScaleType.FIT_START);
// tv[i].setText(itemname);
}
System.out.println(map);
} catch (Exception e) {
// TODO: handle exception
}
}
public AppetiserFragment() {
// TODO Auto-generated constructor stub
}
public int getCount() {
return mImages.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder viewHolder;
if (view == null) {
view = inflater.inflate(R.layout.appetiserlistview, null);
System.out.println("prakash");
viewHolder = new ViewHolder();
viewHolder.image = (ImageView) view
.findViewById(R.id.appetiserimage);
viewHolder.text = (TextView) view.findViewById(R.id.appetisertext);
viewHolder.desc = (TextView) view.findViewById(R.id.appetiserdesc);
viewHolder.price = (TextView) view
.findViewById(R.id.appetiserprice);
viewHolder.appitemnum = (TextView) view
.findViewById(R.id.appitemno);
// viewHolder.checkbox = (CheckBox) view.findViewById(R.id.bcheck);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.image.setImageBitmap(bmps[position]);
viewHolder.appitemnum.setText(itemnos[position]);
viewHolder.price.setText(prices[position]);
viewHolder.desc.setText(descs[position]);
// viewHolder.checkbox.setTag(itemnames[position]);
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(itemnames[position]);
return view;
}
static class ViewHolder {
protected TextView text, price, desc, appitemnum;
protected ImageView image;
}
}
i can able to print json data in base adpater class . Now i want pass json data in to text,image. i thought getview method is not calling . please help me
You can also user ListActivity instead of ListFragment.
It will behave like normal activity and you can find all the list related methods easily.
like this..,
public class MainActivity extends ListActivity {
oncreate() {
** code
ListView list = getListView();
**code
}
}
I think as you are using the custom list with you id "R.id.list" so no need to extend your fragment with listFragment extend with Fragment only.
other wise if you want use the listFragment then use like in XML
<ListView android:id="#id/android:list" android:layout_height="fill_parent"
android:layout_width="fill_parent" android:layout_weight="1.0"
android:layout_marginTop="2dip" android:scrollingCache="false"
android:clickable="true" android:cacheColorHint="#00000000"
android:focusable="true"
android:background="#drawable/listfocused"
android:dividerHeight="1dip" xmlns:android="http://schemas.android.com/apk/res/android"/>
in java get list as
ListView list = this.getListView();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
...
list=(Listview)findViewById(R.id.list);//i type here it shows an error
...
}
This is because you are trying to find the views in the onCreate() method; at this point of time, the fragment's layout has not yet been inflated, hence all findViewById() calls will return null.
You can only find the view after the layout is inflated, which is in onCreateView(). So override the onCreateView() method and call findViewById() and set the list's adapter there!
Related
OnPost Execute method how can I pass image from one Fragment to other activity. Able to pass the image from drawable folder using Bundle. Loding product details from server and able to other information except Image to other Activity.
package sanjay.apackage.torcente.com.torcentemotors;
public class HomeFragment extends Fragment {
FragmentTransaction fragmentTransaction;
//private TextView tvData;
private ListView lvMovies;
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
//Image loader
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getContext()) //getApplicationContext()
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config); // Do it on Application start
lvMovies = (ListView)view.findViewById(R.id.lvMovies);
new JSONTask().execute("http://torcentemotors.com/app_001/productsInfoNew.php");
return view;
}
public class JSONTask extends AsyncTask<String, String, List<MovieModel> > {
#Override
protected List<MovieModel> 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);
}
//return buffer.toString();
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies");
List<MovieModel> movieModelList = new ArrayList<>();
for(int i = 0; i< parentArray.length() ;i++ ) {
JSONObject finalObject = parentArray.getJSONObject(i);
MovieModel movieModel = new MovieModel();
movieModel.setProduct_name(finalObject.getString("product_name"));
movieModel.setProduct_price(finalObject.getInt("product_price"));
movieModel.setProduct_image(finalObject.getString("product_image"));
movieModel.setProduct_color(finalObject.getString("product_color"));
movieModel.setCover_image(finalObject.getString("cover_image"));
movieModel.setOriginal_price(finalObject.getInt("original_price"));
movieModel.setApp_desc(finalObject.getString("app_desc"));
//adding the final object to the list
movieModelList.add(movieModel);
}
//return finalBufferedData.toString();
return movieModelList;
} 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(List<MovieModel> result) {
super.onPostExecute(result);
final MovieAdapter adapter = new MovieAdapter( getActivity().getApplicationContext(), R.layout.rownew, result );
//// getApplicationContext() // getActivity is added by me
lvMovies.setAdapter(adapter);
//set data to list
lvMovies.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Toast.makeText(getActivity().getBaseContext(),parent.getItemIdAtPosition(position)+" is selected",Toast.LENGTH_LONG).show();
MovieModel movieModel = (MovieModel) adapter.getItem(position);
Intent intent = new Intent("sanjay.apackage.torcente.com.torcentemotors.product_details");
//intent.putExtra("product_image", movieModel.getProduct_image());
//sanjay //
intent.putExtra("id",position);
intent.putExtra("product_name",movieModel.getProduct_name());
intent.putExtra("product_price", movieModel.getProduct_price());
intent.putExtra("product_color", movieModel.getProduct_color());
intent.putExtra("original_price", movieModel.getOriginal_price());
intent.putExtra("app_desc", movieModel.getApp_desc());
Bundle bundle=new Bundle();
bundle.putInt("image",R.drawable.ban);
bundle.putInt("image2",R.drawable.fz25);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
}
public class MovieAdapter extends ArrayAdapter{
private List<MovieModel> movieModelList;
private int resource;
private LayoutInflater inflater ;
public MovieAdapter(Context context, int resource, List objects) {
super(context, resource, objects);
movieModelList = objects;
this.resource = resource ;
inflater = (LayoutInflater)context.getSystemService(LAYOUT_INFLATER_SERVICE); // context is added by me.
}
#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.tvIcon = (ImageView)convertView.findViewById(R.id.tvIcon);
holder.tvcover = (ImageView)convertView.findViewById(R.id.tvcover);
holder.tvproduct_name = (TextView)convertView.findViewById((R.id.tvproduct_name));
holder.tvproduct_price = (TextView)convertView.findViewById((R.id.tvproduct_price));
holder.tvproduct_color = (TextView)convertView.findViewById((R.id.tvproduct_color));
holder.tvoriginal_price = (TextView)convertView.findViewById((R.id.tvoriginal_price));
holder.tvapp_desc = (TextView)convertView.findViewById((R.id.tvapp_desc));
convertView.setTag(holder);
} else{
holder = (viewHolder)convertView.getTag();
}
ImageLoader.getInstance().displayImage(movieModelList.get(position).getProduct_image(), holder.tvIcon);
ImageLoader.getInstance().displayImage(movieModelList.get(position).getCover_image(), holder.tvcover);
//holder.tvproduct_id.setText(" Product ID : " +movieModelList.get( position ).getProduct_id());
//holder.tvcategory_id.setText("Category ID : " +movieModelList.get(position).getCategory_id());
//holder.tvsub_category_id.setText("Sub Category ID : " +movieModelList.get(position).getSub_category_id());
holder.tvproduct_name.setText(movieModelList.get(position).getProduct_name());
//holder.tvproduct_code.setText(movieModelList.get(position).getProduct_code());
holder.tvproduct_price.setText("BookingPrice : "+movieModelList.get(position).getProduct_price());
holder.tvproduct_color.setText(movieModelList.get(position).getProduct_color());
holder.tvoriginal_price.setText("Price : "+movieModelList.get(position).getOriginal_price());
//holder.tvapp_desc.setText(movieModelList.get(position).getApp_desc());
return convertView;
}
class viewHolder{
private ImageView tvIcon ;
private ImageView tvcover ;
private TextView tvproduct_id;
private TextView tvcategory_id;
private TextView tvsub_category_id;
private TextView tvproduct_name;
private TextView tvproduct_code;
private TextView tvproduct_color;
private TextView tvproduct_price;
private TextView tvoriginal_price;
private TextView tvapp_desc;
}
}
}
Call BaseAdapter In Fragment Close Application
Comment in line spinner.setAdapter(new Category_Adapter(getActivity(), categorylist));
Work
Error Log
Class FragmentNews
public class FragmentNews extends Fragment {
ArrayList<Category> categorylist = new ArrayList<Category>();
#Override
public View onCreateView(final LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
final View rootView = inflater.inflate(R.layout.fragment_news,
container, false);
Spinner spinner = (Spinner) rootView.findViewById(R.id.category);
new fechPosts().execute("");
return rootView;
}
class fechPosts extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
ringProgressDialog = new ProgressDialog(getActivity());
ringProgressDialog.setMessage("در حال ارسال پیام");
ringProgressDialog.setCancelable(true);
ringProgressDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String result = fetch(params[0]);
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Activity myActivity = getActivity();
spinner.setAdapter(new Category_Adapter(getActivity(), categorylist));
ringProgressDialog.dismiss();
}
}
public String fetch(String titel) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = null;
httppost = new HttpGet(
"http://mynikan.ir/paliz/mobile/GetAllProduct.php");
String r = "ok";
String result = null;
InputStream inputStream = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
JSONArray array = null;
try {
array = new JSONArray(result);
} catch (JSONException e) {
e.printStackTrace();
}
if (array.length() != 0) {
for (int i = 0; i < array.length(); i++) {
JSONObject json_data;
try {
json_data = array.getJSONObject(i);
Category obj = new Category();
obj.Image = json_data.getString("Product_Image");
obj.Title = json_data.getString("Price");
categorylist.add(obj);
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return r;
}
Class Adapter
public class Category_Adapter extends BaseAdapter {
public String[] items;
public LayoutInflater myinflater;
Context context;
static class ViewHolder
{
TextView text;
TextView price;
ImageView im;
}
public int[] picmenu;
ArrayList<Category> categorylist = new ArrayList<Category>();
public Category_Adapter(Context c, ArrayList<Category> pthemop) {
myinflater = LayoutInflater.from(c);
context = c;
categorylist = pthemop;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return categorylist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
// /////
if (convertView == null) {
convertView = myinflater.inflate(R.layout.snipper_single, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.im = (ImageView) convertView.findViewById(R.id.image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(categorylist.get(position).Title);
Picasso.with(context).load(categorylist.get(position).Image)
.into(holder.im);
return convertView;
}}
Class Category
public class Category {
String Title;
String Image;
}
Here:
spinner.setAdapter(new Category_Adapter(getActivity(), categorylist));
line causing issue because spinner object of Spinner is null.
In onCreateView method creating new object instead of initializing object which is using in spinner.
Change onCreateView method as:
spinner = (Spinner) rootView.findViewById(R.id.category);
new fechPosts().execute("");
I'm new to making android apps. I'm trying to make a simple app that pulls movie data from themoviedb.org and displays the posters from the movie on the main page. I'm using GridView and ImageView with a custom adapter but the screen shows up blank. I'm not sure what I need to do to get the images to show up.
Custom adapter:
public class CustomImageAdapter extends BaseAdapter {
private Context mContext;
private String[] inputs;
private List<ImageView> imageList;
LayoutInflater inflater;
public CustomImageAdapter(Context c, String[] inputs) {
mContext = c;
this.inputs = inputs;
inflater = (LayoutInflater) this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return inputs.length;
}
public Object getItem(int position) {
return imageList.get(position);
}
public long getItemId(int position) {
return position;
}
public void add(String[] results) {
inputs = results;
imageList = new ArrayList<ImageView>();
for (int i = 0; i < inputs.length; i++){
ImageView imageView = new ImageView(mContext);
Picasso.with(mContext)
.load(inputs[i])
.into(imageView);
imageList.add(imageView);
}
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(mContext);
convertView = inflater.inflate(R.layout.grid_layout, null);
ImageView imageView = (ImageView) gridView.findViewById(R.id.grid_layout_image_view);
imageView = imageList.get(position);
} else {
gridView = (View) convertView;
}
return gridView;
}
}
Main Fragment:
public class GridFragment extends Fragment {
private static ImageView imageView;
private static String[] jsonStringHolder = new String[1];
private static CustomImageAdapter customImageAdapter;
private static GridView gridView;
public GridFragment() {
}
#Override
public void onStart() {
super.onStart();
FetchMovieTask fetchMovieTask = new FetchMovieTask();
fetchMovieTask.execute();
}
private void loadImageView(String[] result) {
try {
getMovieDataFromJson(result);
} catch (JSONException e) {
Log.e("LOG_TAG", e.getMessage(), e);
e.printStackTrace();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
//customImageAdapter = new CustomImageAdapter(getContext(), null);
gridView = (GridView) rootView.findViewById(R.id.grid_view);
//gridView.setAdapter(customImageAdapter);
return rootView;
}
private void getMovieDataFromJson(String[] jsonStringHolder)
throws JSONException {
final String OWM_POSTER_PATH = "poster_path";
final String OWM_RESULTS = "results";
String movieJsonStr = jsonStringHolder[0];
JSONObject movieJsonObject = new JSONObject(movieJsonStr);
JSONArray movieJsonArray = movieJsonObject.getJSONArray(OWM_RESULTS);
String[] resultStrs = new String[movieJsonArray.length()];
for (int i = 0; i < movieJsonArray.length(); i++) {
JSONObject movieDescriptionJsonObject = movieJsonArray.getJSONObject(i);
String posterPathPlaceholder =
movieDescriptionJsonObject.getString(OWM_POSTER_PATH);
final String FORECAST_BASE_URL =
"http://api.themoviedb.org/3/movie/";
final String SIZE = "w185";
resultStrs[i] = FORECAST_BASE_URL + SIZE + posterPathPlaceholder;
}
customImageAdapter = new CustomImageAdapter(getContext(), null);
customImageAdapter.add(resultStrs);
gridView.setAdapter(customImageAdapter);
}
public class FetchMovieTask extends AsyncTask<Void, Void, String[]> {
private final String LOG_TAG = FetchMovieTask.class.getSimpleName();
#Override
protected String[] doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String movieJsonStr = null;
// String format = "json";
//String units = "metric";
//int numDays = 7;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
final String FORECAST_BASE_URL =
"http://api.themoviedb.org/3/movie/";
final String PREFERENCE = "now_playing?";
final String API_KEY = "api_key=e0cbb327025cf835dfc53ca51d11db68";
//final String UNITS_PARAM = "units";
//final String DAYS_PARAM = "cnt";
String urlString = FORECAST_BASE_URL + PREFERENCE + API_KEY;
URL url = new URL(urlString);
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
movieJsonStr = buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error pits", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
String[] movieJsonStrArray = new String[1];
movieJsonStrArray[0] = movieJsonStr;
return movieJsonStrArray;
}
#Override
protected void onPostExecute(String[] result) {
if (result != null) {
jsonStringHolder[0] = result[0];
}
loadImageView(result);
}
}
XML:
<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" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivityFragment">
<GridView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/grid_view"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true">
</GridView>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/grid_layout_image_view" />
</RelativeLayout>
if you are trying to fill a list with rows, and you are new to android, perhaps, you should try extending from ListActivity or FragmentList, see the google guide at http://developer.android.com/guide/topics/ui/layout/listview.html , ListActivity and FragmentList are helper clases, they have a method "setListAdapter" that do the trick.
I seem to have a problem with my ImageAdapter. It should update a GridView but does not do it.
Code:
public class MainActivityFragment extends Fragment {
ImageAdapter imageAdapter;
GridView gridView;
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
gridView = (GridView) rootView.findViewById(R.id.gridView);
imageAdapter = new ImageAdapter(getActivity(),new ArrayList<Movie>());
gridView.setAdapter(imageAdapter);
return rootView;
}
#Override
public void onStart() {
super.onStart();
UpdateMovies();
}
private void UpdateMovies() {
FetchMoviesTask task = new FetchMoviesTask();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
String sort = preferences.getString(getString(R.string.pref_sort_key), getString(R.string.pref_sort_default));
task.execute(sort);
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<Movie> data;
public ImageAdapter(Context c, ArrayList<Movie> movies) {
mContext = c;
data = movies;
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
View gridView;
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
gridView = new GridView(mContext);
gridView = inflater.inflate(R.layout.grid_item_poster, null);
imageView = (ImageView)gridView.findViewById(R.id.poster);
} else {
imageView = (ImageView) convertView;
}
if (data.size() != 0) {
Log.v("IMAGE_ADAPTER","SetView= " + data.get(position).poster);
Picasso.with(mContext).load(data.get(position).poster).into(imageView);
}
return imageView;
}
public void updatePosters(ArrayList<Movie> newMovies) {
data.clear();
data.addAll(newMovies);
this.notifyDataSetChanged();
}
}
public class FetchMoviesTask extends AsyncTask<String, Void, ArrayList<Movie>> {
private final String LOG_TAG = FetchMoviesTask.class.getName();
private ArrayList<Movie> getMovieDataFromJson(String movieJsonStr, int numDays)
throws JSONException {
// These are the names of the JSON objects that need to be extracted.
final String MOV_LIST = "results";
final String MOV_ID = "id";
final String MOV_TITLE = "original_title";
final String MOV_OVERVIEW = "overview";
final String MOV_RATING = "vote_average";
final String MOV_DATE = "release_date";
final String MOV_POSTER = "poster_path";
JSONObject listJson = new JSONObject(movieJsonStr);
JSONArray movieArray = listJson.getJSONArray(MOV_LIST);
ArrayList<Movie> movies = new ArrayList<>();
for(int i = 0; i < movieArray.length(); i++) {
int id;
String title;
String overview;
String rating;
String date;
String poster;
// Get the JSON object representing the day
JSONObject movie = movieArray.getJSONObject(i);
id = movie.getInt(MOV_ID);
title = movie.getString(MOV_TITLE);
overview = movie.getString(MOV_OVERVIEW);
rating = movie.getString(MOV_RATING);
date = movie.getString(MOV_DATE);
poster = movie.getString(MOV_POSTER);
Movie newMovie = new Movie(id, title, overview, rating, date, poster);
movies.add(newMovie);
}
for (Movie s : movies) {
Log.v(LOG_TAG, "Movie entry: " + s.print());
}
return movies;
}
#Override
protected void onPostExecute(ArrayList<Movie> result) {
if(result != null){
Log.v(LOG_TAG,"DATA SET CHANGED! SIZE= " + result.size());
imageAdapter.updatePosters(result);
}
}
#Override
protected ArrayList<Movie> doInBackground(String... params) {
if(params.length == 0){
return null;
}
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String movieJsonStr = null;
String format = "JSON";
String units = "metric";
String apiKey = "********************";
int numDays = 7;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
final String MOVIE_BASE_URL = "http://api.themoviedb.org/3/discover/movie?";
final String SORT_PARAM = "sort_by";
final String DESC = ".desc";
final String API_PARAM = "api_key";
Uri builtUri = Uri.parse(MOVIE_BASE_URL).buildUpon()
.appendQueryParameter(SORT_PARAM,(params[0]+DESC))
.appendQueryParameter(API_PARAM,apiKey)
.build();
URL url = new URL(builtUri.toString());
Log.v(LOG_TAG, "Built URI " + builtUri.toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
movieJsonStr = buffer.toString();
Log.v(LOG_TAG,"Movie JSON String: " + movieJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return getMovieDataFromJson(movieJsonStr, numDays);
}catch (JSONException e){
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
}
}
fragment_main.xml
<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=".MainActivityFragment">
<GridView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/gridView"
android:columnWidth="180dp"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"/>
grid_item_poster.xml
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="120dp"
android:scaleType="centerCrop"
android:id="#+id/poster"
android:adjustViewBounds="true">
</ImageView>
The strange thing is that when I add a ArrayList with elements when I create my ImageAdapter in onCreateView, it does work but when I leave that list unpopulated it does not update.
Anyone got any clue what to do?
Been searching for the solution the whole day now. :D
Thanks in advance.
I have weird impression that something is wrong with your getView() method - I can be wrong but try this one:
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
ImageView imageView;
if (convertView == null) {
convertView = inflater.inflate(R.layout.grid_item_poster, null);
imageView = (ImageView) convertView.findViewById(R.id.poster);
convertView.setTag(imageView);
} else {
imageView = (ImageView) convertView.getTag();
}
if (data.size() != 0 && data.get(position) != null) {
Log.v("IMAGE_ADAPTER","SetView= " + data.get(position).poster);
Picasso.with(mContext).load(data.get(position).poster).into(imageView);
} else {
//I think that you should reset image when there is a issue with data set
imageView.setImageResource(-1);
}
return imageView;
}
Moreover this comment - create a new ImageView for each item referenced by the Adapter is invalid because adapter reuse views, which are outside of the screen, so sometimes instead of creating new instance of ImageView, list displays old one with new data
Edit
Try to create new data list instead of cleaning old one:
public void updatePosters(ArrayList<Movie> newMovies) {
data = new ArrayList<Movies>();
data.addAll(newMovies);
this.notifyDataSetChanged();
}
You getView is not correctly implemented. Firs of all it is very weird what you are trying to achieve there, you are inflating something just to get an ImageView from that layout. You could instead instantiate the ImageView inside the method:
public View getView(int position, View convertView, ViewGroup parent) {
View view=convertView;
if (view == null) {
view=new ImageView(mContext);
view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout
.LayoutParams.MATCH_PARENT,LinearLayout
.LayoutParams.WRAP_CONTENT));
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
final String url=data.get(position).poster;
if (!TextUtis.isEmpty(url) {
Log.v("IMAGE_ADAPTER","SetView= " + url);
Picasso.with(mContext).load(url).into(((ImageView)view));
} else {
Picasso.with(mContext).load(android.R.color.transparent).into(((ImageView)view);
}
return view;
}
I made one custom listview with image and text.When u click on image it ll lead you to new activity.Now i want to pass image and text to new activity.i know with putExtra method you can pass data but i don't know how can i use it here..
thanks in advance...
here is my code for adapter class..
Note..I am parsing data from json
Onclick method is used to go on another activity...
public class Adapter extends BaseAdapter {
private static final String TAG = "Adapter";
private Activity mActivity;
public ArrayList<Data> mObjects;
// /private final Context context;
Context context;
static class ViewHolder {
static ImageView icon;
TextView title;
TextView name;
TextView review;
DownloadImageTask mTask;
String ab[];
// DownloadImageTask1 mTask1;
// ImageView photo;
}
public Adapter(Activity activity, Context context, ArrayList<Data> mObjects) {
this.mActivity = (Activity) activity;
this.context = context;
this.mObjects = mObjects;
}
public void setObjects(ArrayList<Data> mObjects) {
this.mObjects = mObjects;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Data item = mObjects.get(position);
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = mActivity.getLayoutInflater();
rowView = inflater.inflate(R.layout.item, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.icon = (ImageView) rowView.findViewById(R.id.image);
// viewHolder.photo = (ImageView) rowView.findViewById(R.id.photo);
viewHolder.title = (TextView) rowView.findViewById(R.id.title);
viewHolder.name = (TextView) rowView.findViewById(R.id.name);
viewHolder.review = (TextView) rowView.findViewById(R.id.status);
rowView.setTag(viewHolder);
}
ViewHolder holder = (ViewHolder) rowView.getTag();
holder.title.setText(item.getmTitle());
holder.name.setText(item.getmConcatinate());
holder.review.setText(item.getmreview());
holder.icon.setBackgroundResource(R.drawable.ic_ab);
// holder.photo.setBackgroundResource(0);
holder.mTask = new DownloadImageTask(item.getmImageUrl(), holder.icon);
if (!holder.mTask.isCancelled()) {
holder.mTask.execute();
}
ViewHolder.icon.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Parsing JSON Data", "Before user try122222"); // perform
// action
Intent intent = new Intent(v.getContext(), LargeView.class);
v.getContext().startActivity(intent);
}
});
// holder.mTask1 = new DownloadImageTask1(item.getmImageUrl1(),
// holder.photo);
// if (!holder.mTask1.isCancelled()) {
// holder.mTask1.execute();
// }
return rowView;
}
#Override
public int getCount() {
return (this.mObjects.size());
}
#Override
public Object getItem(int position) {
return (this.mObjects.get(position));
}
#Override
public long getItemId(int position) {
return (position);
}
public AbsListView.RecyclerListener mRecyclerListener = new RecyclerListener() {
public void onMovedToScrapHeap(View view) {
ViewHolder viewHolder = (ViewHolder) view.getTag();
DownloadImageTask imagetask = viewHolder.mTask;
// DownloadImageTask1 imagetask1 = viewHolder.mTask1;
if (imagetask != null) {
imagetask.cancel(true);
}
// if (imagetask1 != null) {
// // imagetask1.cancel(true);
// }
}
};
code in main activity.class
#Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.detectAll().penaltyLog().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile3);
name = (TextView) findViewById(R.id.textView1);
bmImage2 = (ImageView) findViewById(R.id.imageView1);
address = (TextView) findViewById(R.id.textView2);
gender = (TextView) findViewById(R.id.textView3);
loyalitypoints = (TextView) findViewById(R.id.textView7);
followers = (TextView) findViewById(R.id.textView8);
following = (TextView) findViewById(R.id.textView9);
// list13 = new ArrayList<HashMap<String, Object>>();
mListView = (ListView) findViewById(android.R.id.list);
mListView.setClickable(true);
// mListView=(ListView)findViewById(R.id.list);
mAdapter = new Adapter(this,c,mSource );
mListView.setAdapter(mAdapter);
Log.w("Parsing JSON Data", "Before Item click");
mListView.setRecyclerListener(mAdapter.mRecyclerListener);
}
public String getJSONfromURL(String url) {
InputStream is = null;
String result = "";
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
use this way:
ViewHolder.icon.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Parsing JSON Data", "Before user try122222"); // perform
// action
Intent intent = new Intent(context, LargeView.class);
intent.putExtra("name", "dhaval");
context.startActivity(intent);
}
});
pass image in intent is BAD idea. just pass URL, Image Path, image name whatever you have..
like:
Intent intent = new Intent(context, LargeView.class);
intent.putExtra("name", "dhaval");
intent.putExtra("imangeUTL", "www.xyz.com/images/test.png");
context.startActivity(intent);