Noob android developer trying to create a gallery with thumbnails saved on my server:
I am trying to use my ArrayList in my ImageAdapter so that I can reference my array values when creating my thumbnail list loop. My eclipse package is available for download here since I may not explain this correctly. When I do trying and reference my "thumb" values in my array I am getting an undefined error along with a syntax error when trying to create my "mThumbIds"
I am not sure why I am having such a hard time understanding this.
showThumb.java:
package com.flash_tattoo;
import android.os.Bundle;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
public class showThumb extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridlayout);
Bundle bundle = getIntent().getExtras();
String jsonData = bundle.getString("jsonData");
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(jsonData);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<image_data> myJSONArray = new ArrayList<image_data>();
for(int i=0;i<jsonArray.length();i++)
{
JSONObject json_data = null;
try {
json_data = jsonArray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
try {
image_data.id = json_data.getInt("id");
} catch (JSONException e) {
e.printStackTrace();
}
try {
image_data.name = json_data.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
try {
image_data.thumb = json_data.getString("thumb");
} catch (JSONException e) {
e.printStackTrace();
}
try {
image_data.path = json_data.getString("path");
} catch (JSONException e) {
e.printStackTrace();
}
myJSONArray.add(new image_data());
}
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this,myJSONArray));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(showThumb.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
}
}
ImageAdapter:
package com.flash_tattoo;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
public class ImageAdapter extends ArrayAdapter<image_data>
{
//This code below was put in when I change from BaseAdapter to ArrayAdapter
public ImageAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
}
private Context mContext;
public int getCount() {
return mThumbIds.length;
}
public image_data 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) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to our images
private Integer[] mThumbIds = {
for(int i=0;i<myJSONArray.lenght();i++){
Object[] myJSONArray;
setImageDrawable(Drawable.createFromPath(myJSONArray[i].thumb)
};
};
}
You have there a private field mThumbIds of type Integer[] and you're trying to initialize it inline, but you fail to do so because you have an static block {} with statements.
I would say you need to just declare:
private Integer[] mThumbIds;
then, in the constructor you can populate the array.
Related
I ran into a problem that I can not have any way to solve. I hope you will understand me better.
My code
GuideFragment.java
package ru.yktdevelopers.childrensofasia;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import ru.yktdevelopers.childrensofasia.Download_data.download_complete;
public class GuideFragment extends Fragment implements download_complete {
public ListView list;
public ArrayList<Countries> countries = new ArrayList<Countries>();
public ListAdapter adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.guide_fragment, null);
list = (ListView) v.findViewById(R.id.list_guide);
adapter = new ListAdapter(this);
list.setAdapter(adapter);
Download_data download_data = new Download_data((download_complete) this);
download_data.download_data_from_link("http://9142218380.myjino.ru/testfile.json");
return v;
}
public void get_data(String data)
{
try {
JSONArray data_array=new JSONArray(data);
for (int i = 0 ; i < data_array.length() ; i++)
{
JSONObject obj=new JSONObject(data_array.get(i).toString());
Countries add=new Countries();
add.name = obj.getString("country");
add.code = obj.getString("code");
countries.add(add);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
public class Countries {
String name;
String code;
}
}
The problem is:
How to make so that she was able to open the object with the name "Test".
JSON File located with http://9142218380.myjino.ru/testfile.json
replace it with your functions first line after try
JSONArray data_array=new JSONArray(new JsonObject(data).getJsonArray("Test"));
and pass your whole data from server as string
How to swipe my full screen images from gridview...and that images should Loading from JSON response...?
i'm new to android...please help me friends...
But i want to use only One url in my program(JSON URL)...from that i need
Gridview--->FullScreenImage(zooming and swiping)
This is my gridView Activity...
package com.example.admin.loadingimagefromwebgridandswipe;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.widget.GridView;
import android.widget.ListView;
import com.example.admin.adapter.GridViewImageAdapter;
import com.example.admin.helper.AppConstant;
import com.example.admin.helper.JSONfunctions;
import com.example.admin.helper.Utils;
import com.example.admin.ndimageslider.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class GridViewActivity extends Activity {
private Utils utils;
private ArrayList<String> imagePaths = new ArrayList<String>();
private GridViewImageAdapter adapter;
private GridView gridView;
private int columnWidth;
JSONObject jsonobject;
JSONArray jsonarray;
ProgressDialog mProgressDialog;
// ArrayList<HashMap<String, String>> imagePaths;
static String RANK = "rank";
static String COUNTRY = "country";
static String POPULATION = "population";
static String FLAG = "flag";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid_view);
gridView = (GridView) findViewById(R.id.grid_view);
utils = new Utils(this);
// Initilizing Grid View
InitilizeGridLayout();
new DownloadJSON().execute();
}
private void InitilizeGridLayout() {
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
AppConstant.GRID_PADDING, r.getDisplayMetrics());
columnWidth = (int) ((utils.getScreenWidth() -
((AppConstant.NUM_OF_COLUMNS + 1) * padding)) / AppConstant.NUM_OF_COLUMNS);
gridView.setNumColumns(AppConstant.NUM_OF_COLUMNS);
gridView.setColumnWidth(columnWidth);
gridView.setStretchMode(GridView.NO_STRETCH);
gridView.setPadding((int) padding, (int) padding, (int) padding,
(int) padding);
gridView.setHorizontalSpacing((int) padding);
gridView.setVerticalSpacing((int) padding);
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(GridViewActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
imagePaths = new ArrayList<>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("actors");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
imagePaths.add( jsonobject.getString("name"));
imagePaths.add(jsonobject.getString("country"));
imagePaths.add( jsonobject.getString("spouse"));
imagePaths.add(jsonobject.getString("image"));
// Set the JSON Objects into the array
// imagePaths.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
gridView = (GridView) findViewById(R.id.grid_view);
// Pass the results into ListViewAdapter.java
adapter = new GridViewImageAdapter(GridViewActivity.this, imagePaths,columnWidth);
// Set the adapter to the ListView
gridView.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
this is my Gridview Adapter...
package com.example.admin.adapter;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.admin.loadingimagefromwebgridandswipe.FullScreenViewActivity;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
public class GridViewImageAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<String> filePaths = new ArrayList<String>();
private int imageWidth;
public GridViewImageAdapter(Activity activity, ArrayList<String> filePaths,
int imageWidth) {
this.activity = activity;
this.filePaths = filePaths;
this.imageWidth = imageWidth;
}
#Override
public int getCount() {
return this.filePaths.size();
}
#Override
public Object getItem(int position) {
return this.filePaths.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(activity);
} else {
imageView = (ImageView) convertView;
}
String designationUrl = filePaths.get(position);
// Log.d("designationUrl",""+designationUrl);
// URL url = null;
// try {
// url = new URL(designationUrl);
// } catch (MalformedURLException e) {
// e.printStackTrace();
// }
// Bitmap bmp = null;
// try {
// bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
// } catch (IOException e) {
// e.printStackTrace();
// }
Picasso.with(activity)
.load(designationUrl)
.resize(imageWidth, imageWidth).into(imageView);
// image view click listener
imageView.setOnClickListener(new OnImageClickListener(position));
//Toast.makeText(GridViewImageAdapter.this,"url: "+designationUrl,Toast.LENGTH_LONG).show();
return imageView;
}
class OnImageClickListener implements OnClickListener {
int _postion;
// constructor
public OnImageClickListener(int position) {
this._postion = position;
}
#Override
public void onClick(View v) {
// on selecting grid view image
// launch full screen activity
// Toast.makeText(GridViewImageAdapter.this,"url: "+,Toast.LENGTH_LONG).show();
Intent i = new Intent(activity, FullScreenViewActivity.class);
i.putExtra("position", _postion);
activity.startActivity(i);
}
}
/*
* Resizing image size
*/
public static Bitmap decodeFile(String filePath, int WIDTH, int HIGHT) {
try {
File f = new File(filePath);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
final int REQUIRED_WIDTH = WIDTH;
final int REQUIRED_HIGHT = HIGHT;
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
&& o.outHeight / scale / 2 >= REQUIRED_HIGHT)
scale *= 2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
Fullscreen imageViewActivity....
package com.example.admin.loadingimagefromwebgridandswipe;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.widget.ImageView;
import com.example.admin.Application;
import com.example.admin.adapter.FullScreenImageAdapter;
import com.example.admin.helper.JSONfunctions;
import com.example.admin.helper.Utils;
import com.example.admin.ndimageslider.R;
public class FullScreenViewActivity extends Activity{
private Utils utils;
private FullScreenImageAdapter adapter;
private ViewPager viewPager;
private ImageView flag;
private ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_view);
viewPager = (ViewPager) findViewById(R.id.pager);
utils = new Utils(getApplicationContext());
//flag=(ImageView)findViewById(R.id.flag);
image=(ImageView)findViewById(R.id.image);
Intent i = getIntent();
int position = i.getIntExtra("position", 0);
adapter = new FullScreenImageAdapter(FullScreenViewActivity.this,
Application.url());
viewPager.setAdapter(adapter);
// displaying selected image first
viewPager.setCurrentItem(position);
}
}
FullScreenImageAdapter:
package com.example.admin.adapter;
import android.app.Activity;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import com.example.admin.helper.TouchImageView;
import com.example.admin.ndimageslider.R;
import com.squareup.picasso.Picasso;
import org.json.JSONObject;
import java.util.ArrayList;
public class FullScreenImageAdapter extends PagerAdapter {
private Activity activity;
private ArrayList<String> imagePaths;
private LayoutInflater inflater;
// constructor
public FullScreenImageAdapter(Activity activity,
ArrayList<String> imagePaths) {
this.activity = activity;
this.imagePaths = imagePaths;
}
#Override
public int getCount() {
return this.imagePaths.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
TouchImageView imgDisplay;
Button btnClose;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewLayout = inflater.inflate(R.layout.layout_fullscreen_image, container,
false);
imgDisplay = (TouchImageView) viewLayout.findViewById(R.id.imgDisplay);
btnClose = (Button) viewLayout.findViewById(R.id.btnClose);
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inPreferredConfig = Bitmap.Config.ARGB_8888;
// Bitmap bitmap = BitmapFactory.decodeFile(_imagePaths.get(position), options);
// imgDisplay.setImageBitmap(bitmap);
Picasso.with(activity)
.load(imagePaths.get(position)).into(imgDisplay);
// close button click event
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activity.finish();
}
});
((ViewPager) container).addView(viewLayout,0);
return viewLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((RelativeLayout) object);
}
}
Application:
package com.example.admin;
import android.widget.Toast;
import com.example.admin.helper.FileCache;
import java.util.ArrayList;
public class Application extends android.app.Application {
public static ArrayList<String> url(){
ArrayList<String> filePaths = new ArrayList<String>();
filePaths.add("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
return filePaths;
}
}
JSONfunctions:
package com.example.admin.helper;
/**
* Created by Admin on 14-03-2016.
*/
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
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());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
you'll have to implement Viewpage in your application. Take a look at this tutorial for the application you are trying to make.
http://www.androidhive.info/2013/09/android-fullscreen-image-slider-with-swipe-and-pinch-zoom-gestures/
Follow this link. Cheers.
I have some dummy problem, I need to get Spinner Item Position from the Fragment to this class:
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Spinner;
import com.example.nortti.politrange.R;
import com.example.nortti.politrange.intefaces.ICatalog;
import com.example.nortti.politrange.objects.Person;
import com.example.nortti.politrange.objects.Site;
import com.example.nortti.politrange.utils.WebApiAdapter;
import com.example.nortti.politrange.views.GeneralFragment;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
public class PersonCatalog implements ICatalog{
private final String COMMAND_PREFIX = "/api/stats/1";
private final WebApiAdapter apiAdapter = new WebApiAdapter(COMMAND_PREFIX);
private ArrayList<Person> catalogList = new ArrayList<Person>();
private Site site;
public PersonCatalog(Site site) {
this.site = site;
}
#Override
public ArrayList<Person> getCatalogList() {
return catalogList;
}
public void populateData() {
JSONArray jsonObject = null;
try {
jsonObject = (JSONArray)(new JSONParser()).parse(apiAdapter.select(null));
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
catalogList.clear();
Iterator<JSONObject> iterator = jsonObject.iterator();
while(iterator.hasNext()) {
JSONObject o = iterator.next();
catalogList.add(new Person((String)o.get("personName"),(int)(long)o.get("rank")));
}
}
}
I broke my head, I don't know how to do it. Please help! Should I use some Intents or create some getters?
UPD: Fragment Code
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import com.example.nortti.politrange.R;
import com.example.nortti.politrange.adapters.GenAdapter;
import com.example.nortti.politrange.adapters.SiteAdapter;
import com.example.nortti.politrange.intefaces.ICatalog;
import com.example.nortti.politrange.intefaces.impls.PersonCatalog;
import com.example.nortti.politrange.intefaces.impls.SitesCatalog;
import com.example.nortti.politrange.objects.Site;
public class GeneralFragment extends Fragment implements OnClickListener, OnItemSelectedListener {
private Button genApply;
private Spinner spinner;
private ListView genList;
private View header;
private ICatalog siteCatalogImpl;
private ICatalog personCatalogImpl;
public int Num;
public void setSpinnerSource(ICatalog siteCatalogImpl) {
this.siteCatalogImpl = siteCatalogImpl;
spinData();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.general_fragment, container,false);
header = inflater.inflate(R.layout.gen_head, null);
spinner = (Spinner) v.findViewById(R.id.wSpin);
spinner.setOnItemSelectedListener(this);
genApply = (Button) v.findViewById(R.id.genApply);
genApply.setOnClickListener(this);
genList = (ListView) v.findViewById(R.id.genList);
genList.addHeaderView(header);
this.setSpinnerSource(new SitesCatalog());
Intent i = new Intent();
i.putExtra("spin", spinner.getSelectedItemPosition()+1);
return v;
}
private void spinData() {
siteCatalogImpl.populateData();
spinner.setAdapter(new SiteAdapter(getActivity(), siteCatalogImpl.getCatalogList()));
}
private void listData(Site site) {
personCatalogImpl = new PersonCatalog(site);
personCatalogImpl.populateData();
genList.setAdapter(new GenAdapter(getActivity(), personCatalogImpl.getCatalogList()));
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onClick(View v) {
int siteIndex = spinner.getSelectedItemPosition();
switch (v.getId()) {
case R.id.genApply:
listData((Site)siteCatalogImpl.getCatalogList().get(siteIndex));
break;
}
}
}
I calling PersonCatalog at the listdata method.
Try this.
final ArrayList<String> providerlist= new ArrayList<String>();
Spinner spinner1 = (Spinner) findViewById(R.id.prospin);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, providerlist);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = providerlist.get(position);
// Showing selected spinner item
Toast.makeText(this,
"Selected Country : " + item, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
sorry for my question, I guess it's pretty simple. I have a Fragment that needs to implements an interface listener.
package com.tumta.henrique.teste;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.tumta.henrique.teste.ConsultaEntidades.*;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class EntidadeFragment extends Fragment implements ConsultaConcluidaListener {
private static final String ARG_SECTION_NUMBER = "section_number";
public EntidadeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_entidade, container, false);
new ConsultaEntidades((ConsultaEntidades)getActivity()).execute();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
public static EntidadeFragment newInstance(int sectionNumber){
EntidadeFragment frag = new EntidadeFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
frag.setArguments(args);
return frag;
}
#Override
public void onConsultaConcluida(List<String> result) {
ListView listaEntidades = (ListView) getView().findViewById(R.id.listaentidades);
ArrayAdapter arrayAdapter = new ArrayAdapter<>(getView().getContext(),android.R.layout.simple_list_item_1, result);
listaEntidades.setAdapter(arrayAdapter);
}
}
I need used to use this when it was an Activity: new ConsultaEntidades(this).execute(); But now I need to use the same line in the Frag, but I can't use this and when I use new ConsultaEntidades((ConsultaEntidades)getActivity()).execute(); It shows ~cannot cast FragmentActivity to ConsultaEntidades<br><br>ConsultaEntidades` is my class:
package com.tumta.henrique.teste;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
public class ConsultaEntidades extends AsyncTask<Void, Void, List<String>> {
private ConsultaConcluidaListener listener;
private static final String URL_STRING = "http://192.168.0.14:7001/com.henrique.rest/api/v1/status/entidade/";
public ConsultaEntidades(ConsultaConcluidaListener listener){
this.listener = listener;
}
#Override
protected List<String> doInBackground(Void... arg0) {
try {
String resultado = ConsultaServidor();
return InterpretaResultado(resultado);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private List<String> InterpretaResultado(String resultado) throws JSONException {
JSONObject object = new JSONObject(resultado);
JSONArray jsonArray = object.getJSONArray("entidade");
List<String> listaNomes = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonWaether = jsonArray.getJSONObject(i);
//int id = jsonWaether.getInt("ent_id");
String nome = jsonWaether.getString("ent_nome");
listaNomes.add(i, nome);
}
return listaNomes;
}
private String ConsultaServidor() throws IOException {
InputStream is = null;
try {
URL url = new URL(URL_STRING);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
conn.getResponseCode();
is = conn.getInputStream();
Reader reader = null;
reader = new InputStreamReader(is);
char[] buffer = new char[2048];
reader.read(buffer);
return new String(buffer);
} finally {
if (is != null) {
is.close();
}
}
}
#Override
protected void onPostExecute(List<String> result) {
listener.onConsultaConcluida(result);
super.onPostExecute(result);
}
public interface ConsultaConcluidaListener {
void onConsultaConcluida(List<String> result);
}
}
So you note that I need to implement that interface in the frag. How can I do that?
you have two mistakes in your onCreateView
you are trying to instantiate the AsyncTask after you are returning
you are casting the getActivity() to the interface, without having the Activity implementing it.
it should look like :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
new ConsultaEntidades(this).execute();
return inflater.inflate(R.layout.fragment_entidade, container, false);
}
I'm pretty new new Android development. I have a class that extends Activity and I'd like to change to to a Fragment. I know as a fragment it would use onCreateView(LayoutInflater, ViewGroup, Bundle) but I'm not sure how to change my working activity to a fragment.
EDIT: I have gotten it kind of working. The problem now is that my list from the RSS feed isn't showing. I get my loading indicator and it stops once it's finished but the list doesn't show.
EDIT: Actually the list is showing, but the text is the same color as the background so I couldn't see it.
Here is my existing Activity:
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
public class ActionAlerts extends Activity {
ListView listFeed;
ProgressBar prgLoading;
TextView txtAlert;
ActionAlertsAdapter la;
static String[] title;
static String[] pubDate;
static String[] link;
String URLFeed;
URL Feed;
DocumentBuilder db;
Document doc;
NodeList nodeList;
Bundle rssBundle = new Bundle();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actionalerts);
Bundle b = getIntent().getExtras();
URLFeed = b.getString("url");
la = new ActionAlertsAdapter(this);
listFeed = (ListView) findViewById(R.id.listFeed);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
// ColorDrawable whiteColor = new ColorDrawable(Color.WHITE);
ColorDrawable blackColor = new ColorDrawable(Color.BLACK);
listFeed.setDivider(blackColor);
listFeed.setDividerHeight(3);
new getDataTask().execute();
listFeed.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
Intent web = new Intent(ActionAlerts.this, WebBrowser.class);
rssBundle.putString("myURL", link[position]);
web.putExtras(rssBundle);
startActivity(web);
}
});
}
/** this class is used to handle thread */
public class getDataTask extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
getDataFromFeed();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
//dialog.dismiss();
prgLoading.setVisibility(8);
if(title != null){
listFeed.setVisibility(0);
listFeed.setAdapter(la);
}else{
txtAlert.setVisibility(0);
}
}
}
/*
* This code is used to get data from feed and store them
* to array attributes
*/
public void getDataFromFeed(){
try {
Feed = new URL(URLFeed);
DocumentBuilderFactory dbf= DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
doc = db.parse(new InputSource(Feed.openStream()));
doc.getDocumentElement().normalize();
nodeList = doc.getElementsByTagName("item");
title = new String[nodeList.getLength()];
pubDate = new String[nodeList.getLength()];
link = new String[nodeList.getLength()];
for(int i=0;i<nodeList.getLength();i++){
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList titleList = fstElmnt.getElementsByTagName("title");
Element titleElement = (Element) titleList.item(0);
titleList = titleElement.getChildNodes();
title[i] = ((Node) titleList.item(0)).getNodeValue();
NodeList pubDateList = fstElmnt.getElementsByTagName("pubDate");
Element pubDateElement = (Element) pubDateList.item(0);
pubDateList = pubDateElement.getChildNodes();
pubDate[i] = ((Node) pubDateList.item(0)).getNodeValue();
// chops off the " +0000" on date
pubDate[i] = pubDate[i].substring(0, pubDate[i].length()-14);
NodeList linkList = fstElmnt.getElementsByTagName("link");
Element linkElement = (Element) linkList.item(0);
linkList = linkElement.getChildNodes();
link[i] = ((Node) linkList.item(0)).getNodeValue();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
}
Here is my adapter class:
package kyfb.android.kyfb.com.kyfb;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;
class ActionAlertsAdapter extends BaseAdapter {
private LayoutInflater inflater;
public ActionAlertsAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
public int getCount() {
// TODO Auto-generated method stub
return ActionAlertsFragment.title.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if(convertView == null){
convertView = inflater.inflate(R.layout.item_feed, null);
holder = new ViewHolder();
holder.lytItemFeed = (RelativeLayout) convertView.findViewById(R.id.lytItemFeed);
holder.txtTitle= (TextView) convertView.findViewById(R.id.txtTitle);
holder.txtPubDate = (TextView) convertView.findViewById(R.id.txtPubDate);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
if((position%2)!=0){
// holder.lytItemFeed.setBackgroundResource(R.drawable.row_1);
holder.lytItemFeed.setBackgroundColor(Color.TRANSPARENT);
}else{
// holder.lytItemFeed.setBackgroundResource(R.drawable.row_2);
holder.lytItemFeed.setBackgroundColor(Color.TRANSPARENT);
}
holder.txtTitle.setText(ActionAlertsFragment.title[position]);
holder.txtPubDate.setText(ActionAlertsFragment.pubDate[position]);
holder.txtTitle.setTextColor(Color.BLACK);
holder.txtPubDate.setTextColor(Color.BLACK);
return convertView;
}
static class ViewHolder {
TextView txtTitle, txtPubDate;
RelativeLayout lytItemFeed;
}
}
Here is my Fragment class that I'm trying to make from the activity class above:
package kyfb.android.kyfb.com.kyfb;
import android.app.Fragment;
import android.app.ListFragment;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
public class ActionAlertsFragment extends Fragment {
ListView listFeed;
ProgressBar prgLoading;
TextView txtAlert;
ActionAlertsAdapter la;
static String[] title;
static String[] pubDate;
static String[] link;
String URLFeed;
URL Feed;
DocumentBuilder db;
Document doc;
NodeList nodeList;
Bundle rssBundle = new Bundle();
public ActionAlertsFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
// View rootView = inflater.inflate(R.layout.fragment_actionalerts, container, false);
View rootView = inflater.inflate(R.layout.fragment_actionalerts, null);
URLFeed = "http://kyfbnewsroom.com/category/notifications/feed";
Context ctx = rootView.getContext();
la = new ActionAlertsAdapter(ctx);
listFeed = (ListView) rootView.findViewById(R.id.listFeed);
prgLoading = (ProgressBar) rootView.findViewById(R.id.prgLoading);
txtAlert = (TextView) rootView.findViewById(R.id.txtAlert);
// ColorDrawable whiteColor = new ColorDrawable(Color.WHITE);
ColorDrawable blackColor = new ColorDrawable(Color.BLACK);
listFeed.setDivider(blackColor);
listFeed.setDividerHeight(3);
new getDataTask().execute();
listFeed.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
// Intent web = new Intent(ActionAlertsFragment.this, WebBrowser.class);
// rssBundle.putString("myURL", link[position]);
// web.putExtras(rssBundle);
// startActivity(web);
}
});
return rootView;
}
/** this class is used to handle thread */
public class getDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
getDataFromFeed();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
//dialog.dismiss();
prgLoading.setVisibility(8);
if(title != null){
listFeed.setVisibility(0);
listFeed.setAdapter(la);
}else{
txtAlert.setVisibility(0);
}
}
}
/*
* This code is used to get data from feed and store them
* to array attributes
*/
public void getDataFromFeed(){
try {
Feed = new URL(URLFeed);
DocumentBuilderFactory dbf= DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
doc = db.parse(new InputSource(Feed.openStream()));
doc.getDocumentElement().normalize();
nodeList = doc.getElementsByTagName("item");
title = new String[nodeList.getLength()];
pubDate = new String[nodeList.getLength()];
link = new String[nodeList.getLength()];
for(int i=0;i<nodeList.getLength();i++){
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList titleList = fstElmnt.getElementsByTagName("title");
Element titleElement = (Element) titleList.item(0);
titleList = titleElement.getChildNodes();
title[i] = ((Node) titleList.item(0)).getNodeValue();
NodeList pubDateList = fstElmnt.getElementsByTagName("pubDate");
Element pubDateElement = (Element) pubDateList.item(0);
pubDateList = pubDateElement.getChildNodes();
pubDate[i] = ((Node) pubDateList.item(0)).getNodeValue();
// chops off the " +0000" on date
pubDate[i] = pubDate[i].substring(0, pubDate[i].length()-14);
NodeList linkList = fstElmnt.getElementsByTagName("link");
Element linkElement = (Element) linkList.item(0);
linkList = linkElement.getChildNodes();
link[i] = ((Node) linkList.item(0)).getNodeValue();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
}
First change this.
View rootView = inflater.inflate(R.layout.fragment_actionalerts, null);
to
View rootView = inflater.inflate(R.layout.fragment_actionalerts, container, false);
And use Fragment Context as a getActivity().
Try this:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_submenus_list, null);
....
return view;
}
And change every findViewById(...) to view.findViewById(...)