Cannot fetch data from api to Gridview in fragment - java

if i using extends Activity it works normally. But when i move the code to fragment extends Fragment the progress bar is never stop and the data is never show up and there is no error to.
Frag_Country_List.java
public class Frag_Country_List extends Fragment implements DB_FetchDataListener {
private String CountryFlag;
private String CountryName;
private ProgressDialog dialog;
private GridView myGridview;
public Frag_Country_List() {
// 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.frag_country_list, container, false);
}
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
// do your variables initialisations here except Views!!!
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
return true;
}
public void onViewCreated(#NonNull View view, Bundle savedInstanceState){ super.onViewCreated(view, savedInstanceState);
myGridview = (GridView)view.findViewById(R.id.countryGridView);
initView();
/*myGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
OpenDialog();
}
});*/
}
private void initView() {
dialog = ProgressDialog.show(this.getContext(), "", "Loading...");
String url = "http://example.com/get_country.php";
DB_FetchDataTask task = new DB_FetchDataTask(this);
task.execute(url);
}
#Override
public void onFetchComplete(List<DB_Application> data) {
if(dialog != null) dialog.dismiss();
DB_ApplicationAdapter adapter = new DB_ApplicationAdapter(this.getContext(), data);
myGridview.setAdapter(adapter);
}
#Override
public void onFetchFailure(String msg) {
if(dialog != null) dialog.dismiss();
Toast.makeText(this.getContext(), msg, Toast.LENGTH_LONG).show();
}
}
DB_FetchDataTask.java
public class DB_FetchDataTask extends AsyncTask<String, Void, String>{
private final DB_FetchDataListener listener;
private String msg;
public DB_FetchDataTask(DB_FetchDataListener listener) {
this.listener = listener;
}
#Override
protected String doInBackground(String... params) {
if(params == null) return null;
// get url from params
String url = params[0];
try {
// create http connection
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
// connect
HttpResponse response = client.execute(httpget);
// get response
HttpEntity entity = response.getEntity();
if(entity == null) {
msg = "No response from server";
return null;
}
// get response content and convert it to json string
InputStream is = entity.getContent();
return streamToString(is);
}
catch(IOException e){
msg = "No Network Connection";
}
return null;
}
#Override
protected void onPostExecute(String sJson) {
if(sJson == null) {
if(listener != null) listener.onFetchFailure(msg);
return;
}
try {
// convert json string to json array
JSONArray aJson = new JSONArray(sJson);
// create apps list
List<DB_Application> apps = new ArrayList<DB_Application>();
for(int i=0; i<aJson.length(); i++) {
JSONObject json = aJson.getJSONObject(i);
DB_Application app = new DB_Application();
app.setCountry(json.getString("_country"));
app.setFlag(json.getString("_flag"));
// add the app to apps list
apps.add(app);
}
//notify the activity that fetch data has been complete
if(listener != null) listener.onFetchComplete(apps);
} catch (JSONException e) {
msg = "Invalid response";
if(listener != null) listener.onFetchFailure(msg);
return;
}
}
/**
* This function will convert response stream into json string
* #param is respons string
* #return json string
* #throws IOException
*/
public String streamToString(final InputStream is) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
}
catch (IOException e) {
throw e;
}
finally {
try {
is.close();
}
catch (IOException e) {
throw e;
}
}
return sb.toString();
}
}
tell me if you need more information.
Logcat
11-27 13:54:06.007 1934-1994/com.mysql.sample E/Surface: getSlotFromBufferLocked: unknown buffer: 0xaaa89aa0
11-27 13:54:06.177 1934-1934/com.mysql.sample E/SysUtils: ApplicationContext is null in ApplicationStatus
11-27 13:54:06.185 1934-1934/com.mysql.sample E/libEGL: validate_display:255 error 3008 (EGL_BAD_DISPLAY)
11-27 13:54:06.185 1934-1934/com.mysql.sample E/libEGL: validate_display:255 error 3008 (EGL_BAD_DISPLAY)
11-27 13:54:06.215 1934-1934/com.mysql.sample E/DataReductionProxySettingListener: No DRP key due to exception:java.lang.ClassNotFoundException: com.android.webview.chromium.Drp

Try moving your onViewCreated code to onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.frag_country_list, container, false);
myGridview = (GridView)view.findViewById(R.id.countryGridView);
initView();
return view;
}

Related

AsyncTask Test Connection

I trying to use AsyncTask it's work when the device has a internet connection, but when i open that without internet appear this message "Unfortunately, has stopped", follow the code, what i doing wrong? can someone explain me?
PS: I have one Activity and i working with AsyncTask inside a Fragment.
Fragment that use AsyncTask.
public class MasonFragment extends Fragment {
private ListView lstMason;
private ProgressDialog dialog;
//private Fragment fragmentMain = new MainFragment();
public MasonFragment() {
// 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_mason, container, false);
lstMason = (ListView)view.findViewById(R.id.lstMason);
// Create default options which will be used for every
// displayImage(...) call if no options will be passed to this method
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getActivity())
.defaultDisplayImageOptions(defaultOptions).build();
ImageLoader.getInstance().init(config); // Do it on Application start
//To that class work need this: compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5' in gradle module
new JSONTask().execute("https://deliveryteste.000webhostapp.com/production_version_1/json_services_v1.txt");
return view;
}
/*private View.OnClickListener requestJSON = new View.OnClickListener() {
#Override
public void onClick(View v) {
new JSONTask().execute("My_URL");
}
};*/
public class JSONTask extends AsyncTask<String, String, List<Services>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<Services> doInBackground(String... params) {
if(new CheckNetwork(getActivity()).isNetworkAvailable()) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject jsonObject = new JSONObject(finalJson);
JSONArray jsonArray = jsonObject.getJSONArray("mason");
List<Services> servicesList = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject finalObject = jsonArray.getJSONObject(i);
Services services = new Services();
services.setName(finalObject.getString("name"));
services.setTelephone(finalObject.getString("telephone"));
services.setCity(finalObject.getString("city"));
services.setDescription(finalObject.getString("description"));
services.setRating((float) finalObject.getDouble("rate"));
services.setImage(finalObject.getString("image"));
services.setFacebook(finalObject.getString("facebook"));
servicesList.add(services);
}
return servicesList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
//backToMain();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
Toast.makeText(getActivity(), "Por favor esteja conectado com a rede!", Toast.LENGTH_LONG).show();
}
return null;
}
#Override
protected void onPostExecute(List<Services> result) {
super.onPostExecute(result);
ServicesAdapter servicesAdapter = new ServicesAdapter(getActivity(), R.layout.custom_listview, result);
lstMason.setAdapter(servicesAdapter);
}
}
//Class to CustomArrayAdapter
public class ServicesAdapter extends ArrayAdapter {
private List<Services> servicesList;
private int resource;
private LayoutInflater inflater;
public ServicesAdapter(Context context, int resource, List<Services> objects) {
super(context, resource, objects);
servicesList = objects;
this.resource = resource;
inflater = (LayoutInflater) getActivity().getSystemService(LAYOUT_INFLATER_SERVICE);
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = inflater.inflate(resource, null);
}
ImageView imgPerson;
TextView lblName;
TextView lblTelephone;
TextView lblDescription;
TextView lblFacebookResult;
TextView lblCity;
RatingBar rtgServiceRating;
imgPerson = (ImageView)convertView.findViewById(R.id.imgPerson);
lblName = (TextView)convertView.findViewById(R.id.lblName);
lblTelephone = (TextView)convertView.findViewById(R.id.lblTelephone);
lblCity = (TextView)convertView.findViewById(R.id.lblCity);
lblDescription = (TextView)convertView.findViewById(R.id.lblDescription);
lblFacebookResult = (TextView)convertView.findViewById(R.id.lblFacebookResult);
rtgServiceRating = (RatingBar)convertView.findViewById(R.id.rtgSerciveRating);
// Then later, when you want to display image
ImageLoader.getInstance().displayImage(servicesList.get(position).getImage(), imgPerson); // Default options will be used
lblName.setText(servicesList.get(position).getName());
lblTelephone.setText(String.valueOf(servicesList.get(position).getTelephone()));
lblDescription.setText(servicesList.get(position).getDescription());
lblFacebookResult.setText(servicesList.get(position).getFacebook());
lblCity.setText(servicesList.get(position).getCity());
//Rating Bar
rtgServiceRating.setRating(servicesList.get(position).getRating());
StringBuffer stringBuffer = new StringBuffer();
return convertView;
}
}
/*private void backToMain(){
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.lnlContentMain, fragmentMain).commit();
}*/
Class to check network connection:
public class CheckNetwork {
private Context context;
public CheckNetwork(Context context) {
this.context = context;
}
public boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Error log:
01-30 17:30:13.886 6868-7284/com.archtech.gabrielgomes.hirehere E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.archtech.gabrielgomes.hirehere, PID: 6868
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.SecurityException: ConnectivityService: Neither user 10204 nor current process has android.permission.ACCESS_NETWORK_STATE.
at android.os.Parcel.readException(Parcel.java:1472)
at android.os.Parcel.readException(Parcel.java:1426)
at android.net.IConnectivityManager$Stub$Proxy.getActiveNetworkInfo(IConnectivityManager.java:1139)
at android.net.ConnectivityManager.getActiveNetworkInfo(ConnectivityManager.java:690)
at com.archtech.gabrielgomes.hirehere.CheckNetwork.isNetworkAvailable(CheckNetwork.java:21)
at com.archtech.gabrielgomes.hirehere.fragments.MasonFragment$JSONTask.doInBackground(MasonFragment.java:100)
at com.archtech.gabrielgomes.hirehere.fragments.MasonFragment$JSONTask.doInBackground(MasonFragment.java:90)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
at java.lang.Thread.run(Thread.java:841) 
Thank you guys.
As the error states, java.lang.SecurityException: ConnectivityService: Neither user 10204 nor current process has android.permission.ACCESS_NETWORK_STATE
To fix this just add <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> to your AndroidManifest.xml file

Adapter Can't Load Image from JSON on Android

i have some problem with my JSON code.
I want to display a list that contain text and image. The text and image stored on my online database, i using JSON for taking them down to my android app.
The JSON doesn't display any error, the text are displayed but the image are not appear.
I check the logcat and there's no error for this process. I using viewAdapter for displaying the image on the list.
Please master help me, can you gimme some simple explanation how to solve this??
Thanks...
NB. This is my code for HomeFragment.java (where i doing the JSON).
public class HomeFragment extends Fragment implements InternetConnectionListener, ApiHandler.ApiHandlerListener {
private static final String ARG_SECTION_NUMBER = "section_number";
private final int CATEGORY_ACTION = 1;
private CategorySelectionCallbacks mCallbacks;
private ArrayList<Category> categoryList;
private ListView categoryListView;
private String Error = null;
private InternetConnectionListener internetConnectionListener;
public HomeFragment() {
}
public static HomeFragment newInstance(int sectionNumber) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((HomeActivity) activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
try {
mCallbacks = (CategorySelectionCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement CategorySelectionCallbacks.");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
categoryListView = (ListView) rootView.findViewById(R.id.categoryListView);
return rootView;
}
#Override
public void onResume() {
super.onResume();
if (UtilMethods.isConnectedToInternet(getActivity())) {
initCategoryList();
} else {
internetConnectionListener = (InternetConnectionListener) HomeFragment.this;
showNoInternetDialog(getActivity(), internetConnectionListener,
getResources().getString(R.string.no_internet),
getResources().getString(R.string.no_internet_text),
getResources().getString(R.string.retry_string),
getResources().getString(R.string.exit_string), CATEGORY_ACTION);
}
}
public class getCategList extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
/**
* json is populating from text file. To make api call use ApiHandler class
*
* <CODE>ApiHandler apiHandler = new ApiHandler(this, URL_GET_CATEGORY);</CODE> <BR>
* <CODE>apiHandler.doApiRequest(ApiHandler.REQUEST_GET);</CODE> <BR>
*
* You will get the response in onSuccessResponse(String tag, String jsonString) method
* if successful api call has done. Do the parsing as the following.
*/
URL hp = null;
try {
hp = new URL(
getString(R.string.liveurl) + "foodcategory.php");
Log.d("URL", "" + hp);
URLConnection hpCon = hp.openConnection();
hpCon.connect();
InputStream input = hpCon.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(input));
String x = "";
x = r.readLine();
String total = "";
while (x != null) {
total += x;
x = r.readLine();
}
Log.d("UR1L", "" + total);
JSONArray j = new JSONArray(total);
Log.d("URL1", "" + j.length());
categoryList = new ArrayList<Category>();
for (int i = 0; i < j.length(); i++) {
Category category = new Category();// buat variabel category
JSONObject Obj;
Obj = j.getJSONObject(i); //sama sperti yang lama, cman ini lebih mempersingkat karena getJSONObject cm d tulis sekali aja disini
category.setId(Obj.getString(JF_ID));
category.setTitle(Obj.getString(JF_TITLE));
category.setIconUrl(Obj.getString(JF_ICON));
if (!TextUtils.isEmpty(Obj.getString(JF_BACKGROUND_IMAGE))) {
category.setImageUrl(Obj.getString(JF_BACKGROUND_IMAGE));
}
Log.d("URL1",""+Obj.getString(JF_TITLE));
categoryList.add(category);
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
categoryListView.setAdapter(new CategoryAdapter(getActivity(), mCallbacks, categoryList));
}
});
}catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Error = e.getMessage();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Error = e.getMessage();
} catch (JSONException e) {
// TODO Auto-generated catch block
Error = e.getMessage();
e.printStackTrace();
} catch (NullPointerException e) {
// TODO: handle exception
Error = e.getMessage();
}
return null;
}
}
//! function for populate category list
private void initCategoryList() {
new getCategList().execute();
}
#Override
public void onConnectionEstablished(int code) {
if (code == CATEGORY_ACTION) {
initCategoryList();
}
}
#Override
public void onUserCanceled(int code) {
if (code == CATEGORY_ACTION) {
getActivity().finish();
}
}
//! catch json response from here
#Override
public void onSuccessResponse(String tag, String jsonString) {
//! do same parsing as done in initCategoryList()
}
//! detect response error here
#Override
public void onFailureResponse(String tag) {
}
//! callback interface listen by HomeActivity to detect user click on category
public static interface CategorySelectionCallbacks {
void onCategorySelected(String catID, String title);
}
}
This code for categoryAdapter.java (where i put the result of JSON to the list)
public class CategoryAdapter extends ArrayAdapter<Category> implements View.OnClickListener {
private final LayoutInflater inflater;
private final ArrayList<Category> categoryList;
private Activity activity;
private HomeFragment.CategorySelectionCallbacks mCallbacks;
private String dummyUrl = "http://www.howiwork.org";
AbsListView.LayoutParams params;
public CategoryAdapter(Activity activity, HomeFragment.CategorySelectionCallbacks mCallbacks, ArrayList<Category> categoryList) {
super(activity, R.layout.layout_category_list);
this.activity = activity;
this.inflater = LayoutInflater.from(activity.getApplicationContext());
this.categoryList = categoryList;
this.mCallbacks = mCallbacks;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder row;
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_category_list, null);
row = new ViewHolder();
row.bannerImage = (ImageView) convertView.findViewById(R.id.catBannerImageView);
row.categoryImage = (ImageView) convertView.findViewById(R.id.catImageView);
row.categoryName = (TextView) convertView.findViewById(R.id.catNameTV);
} else {
row = (ViewHolder) convertView.getTag();
}
Category category = categoryList.get(position);
Picasso.with(activity).load(UtilMethods
.getDrawableFromFileName(activity,category.getIconUrl()))
.tag(category.getIconUrl())
.into(row.categoryImage);
row.categoryName.setText(category.getTitle());
Picasso.with(activity)
.load(UtilMethods.getDrawableFromFileName(activity,category.getImageUrl()))
.placeholder(R.drawable.img_banner_placeholder)
.tag(category.getIconUrl())
.fit()
.into(row.bannerImage);
row.bannerImage.setOnClickListener(this);
row.categoryImage.setTag(position);
row.categoryName.setTag(position);
row.bannerImage.setTag(position);
return convertView;
}
#Override
public int getCount() {
return categoryList.size();
}
#Override
public void onClick(View v) {
int position = Integer.parseInt(v.getTag().toString());
mCallbacks.onCategorySelected(categoryList.get(position).getId(),
categoryList.get(position).getTitle());
}
private static class ViewHolder {
public ImageView bannerImage;
public TextView categoryName;
public ImageView categoryImage;
}
}
Try this.
Picasso.with(activity).load(category.getIconUrl())
.into(row.categoryImage);
If it worked !. You Check the UtilMethods.getDrawableFromFileName() !!!

blank viewpager activity while scrolling down

I am using viewpager with gridview and downloading json data into it and implemented gridview scroll listener but whenever i start activity again the current viewpager fragment in which sroll listener implemented shows blank.
Here is my code, please see and tell me my mistake.
//My Activity Fragment
private static String url = "http://--------/------";
private int mVisibleThreshold = 5;
private int mCurrentPage = 0;
private int mPreviousTotal = 0;
private boolean mLoading = true;
private boolean mLastPage = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.gridview_fragment, container,
false);
setRetainInstance(true);
arrayList = new ArrayList<Items>();
gridView = (GridView) rootView.findViewById(R.id.gridView1);
//My Json Execution
new LoadData().execute(url);
//Scroll listener when gridview reaches at end
gridView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (mLoading) {
if (totalItemCount > mPreviousTotal) {
mLoading = false;
mPreviousTotal = totalItemCount;
mCurrentPage++;
if (mCurrentPage + 1 > 10) {
mLastPage = true;
}
}
}
if (!mLastPage
&& !mLoading
&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + mVisibleThreshold)) {
//Loading new datas in gridview
new LoadData()
.execute("http://-----/-----");
mLoading = true;
}
}
});
return rootView;
}
private class LoadData extends AsyncTask<String, Void, Void> {
#Override
protected void onPostExecute(Void result) {
//checking whether adapter is null or not
if (adap == null) {
adap = new Grid_View_Adatper(getActivity()
.getApplicationContext(), arrayList);
gridView.setAdapter(adap);
}
adap.notifyDataSetChanged();
super.onPostExecute(result);
}
#Override
protected Void doInBackground(String... urls) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(urls[0]);
HttpResponse response = client.execute(httpget);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray json = new JSONArray(data);
for (int i = 0; i < json.length(); i++) {
JSONObject e = json.getJSONObject(i);
String name = e.getString("name");
String price = e.getString("price");
String image = e.getString("image");
String code = e.getString("sku");
tems = new Items(name, price, image, code);
arrayList.add(tems);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
} catch (IOException e) {
} catch (RuntimeException e) {
}
return null;
}
}
}
Thanks in advance...

Reading multiple links using bufferedreader and delimiter

I am trying to load multiple url rss links from a text file. so far it works loading just one link from the file. i tried using a delimiter but it doesn't seem to work. any help is appreciated.
Code
StringBuilder rsslink = new StringBuilder();
InputStream is = getResources().openRawResource(R.raw.xmlsource);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
try {
while ((line = br.readLine()) != null)
{
rsslink.append(line) ;
}
String [] arr = rsslink.toString().split(";");
for (int i = 0; i < arr.length; i++)
{
}
}
catch (IOException e)
{
e.printStackTrace();
}
String RSS_LINK = rsslink.toString();
Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try
{
XMLRssParser parser = new XMLRssParser();
rssItems = parser.parse(getInputStream(RSS_LINK));
}
catch (XmlPullParserException e)
{
Log.w(e.getMessage(), e);
}
catch (IOException e)
{
Log.w(e.getMessage(), e);
}
Bundle bundle = new Bundle();
bundle.putSerializable(ITEMS, (Serializable) rssItems);
ResultReceiver receiver = intent.getParcelableExtra(RECEIVER);
receiver.send(0, bundle);
}
public InputStream getInputStream(String link)
{
try
{
URL url = new URL(link);
return url.openConnection().getInputStream();
} catch (IOException e)
{
Log.w(Constants.TAG, "Exception while retrieving the input stream", e);
return null;
}
}
}
And this what the text file looks like with ";" as the delimiter
http://www.engadget.com/rss.xml; http://www.pcworld.com/index.rss; http://feeds.feedburner.com/SpoonForkBacon?format=xml;
RssFragment
public class RssFragment extends Fragment implements OnItemClickListener
{
private ProgressBar progressBar;
private ListView listView;
private View view;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
if (view == null)
{
view = inflater.inflate(R.layout.fragment_layout, container, false);
progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
listView = (ListView) view.findViewById(R.id.listView);
listView.setOnItemClickListener(this);
startService();
}
else
{
ViewGroup parent = (ViewGroup) view.getParent();
parent.removeView(view);
}
return view;
}
private void startService()
{
Intent intent = new Intent(getActivity(), RssService.class);
intent.putExtra(RssService.RECEIVER, resultReceiver);
getActivity().startService(intent);
}
private final ResultReceiver resultReceiver = new ResultReceiver(new Handler())
{
#SuppressWarnings("unchecked")
#Override
protected void onReceiveResult(int resultCode, Bundle resultData)
{
progressBar.setVisibility(View.GONE);
List<RssItem> items = (List<RssItem>) resultData.getSerializable(RssService.ITEMS);
if (items != null)
{
RssAdapter adapter = new RssAdapter(getActivity(), items);
listView.setAdapter(adapter);
}
else
{
Toast.makeText(getActivity(), "An error occured while downloading the rss feed.",
Toast.LENGTH_LONG).show();
}
};
};
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
RssAdapter adapter = (RssAdapter) parent.getAdapter();
RssItem item = (RssItem) adapter.getItem(position);
Uri uri = Uri.parse(item.getLink());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
}

Android strange error

I have made an listview application, then i created a new one with fragments and want to implement listview to fragments. But when i do i got an strange error.
public class Fragment1 extends Fragment {
private ArrayList<FeedItem> feedList = null;
private ProgressBar progressbar = null;
private ListView feedListView = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.list_row_layout, container, false);
progressbar = (ProgressBar)rootView.findViewById(R.id.progressBar);
String url = "";
new DownloadFilesTask().execute(url);
return rootView;
}
public void updateList() {
feedListView= (ListView)getActivity().findViewById(R.id.custom_list);
feedListView.setVisibility(View.VISIBLE);
progressbar.setVisibility(View.GONE);
**feedListView.setAdapter(new CustomListAdapter(this, feedList));**
feedListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = feedListView.getItemAtPosition(position);
FeedItem newsData = (FeedItem) o;
**Intent intent = new Intent(FeedListActivity.this, FeedDetailsActivity.class);**
intent.putExtra("feed", newsData);
startActivity(intent);
}
});
}
public class DownloadFilesTask extends AsyncTask<String, Integer, Void> {
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected void onPostExecute(Void result) {
if (null != feedList) {
updateList();
}
}
#Override
protected Void doInBackground(String... params) {
String url = params[0];
// getting JSON string from URL
JSONObject json = getJSONFromUrl(url);
//parsing json data
parseJson(json);
return null;
}
}
public JSONObject getJSONFromUrl(String url) {
InputStream is = null;
JSONObject jObj = null;
String json = null;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
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();
json = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
public void parseJson(JSONObject json) {
try {
// parsing json object
if (json.getString("status").equalsIgnoreCase("ok")) {
JSONArray posts = json.getJSONArray("posts");
feedList = new ArrayList<FeedItem>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = (JSONObject) posts.getJSONObject(i);
FeedItem item = new FeedItem();
item.setTitle(post.getString("title"));
item.setDate(post.getString("description"));
item.setId(post.getString("id"));
item.setUrl(post.getString("url"));
item.setContent(post.getString("description"));
JSONArray attachments = post.getJSONArray("attachments");
if (null != attachments && attachments.length() > 0) {
JSONObject attachment = attachments.getJSONObject(0);
if (attachment != null)
item.setAttachmentUrl(attachment.getString("url"));
}
feedList.add(item);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Problems are on this lines
feedListView.setAdapter(new CustomListAdapter(this, feedList));
Intent intent = new Intent(FeedListActivity.this, FeedDetailsActivity.class);
Multiple markers at this line
- Line breakpoint:Fragment1 [line: 57] - updateList()
- The constructor CustomListAdapter(Fragment1, ArrayList<FeedItem>) is
undefined
No enclosing instance of the type FeedListActivity is accessible in scope
CustomListAdapter:
public class CustomListAdapter extends BaseAdapter {
private ArrayList<FeedItem> listData;
private LayoutInflater layoutInflater;
private Context mContext;
public CustomListAdapter(Context context, ArrayList<FeedItem> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
mContext = context;
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_row_layout, null);
holder = new ViewHolder();
holder.headlineView = (TextView) convertView.findViewById(R.id.title);
holder.reportedDateView = (TextView) convertView.findViewById(R.id.date);
holder.imageView = (ImageView) convertView.findViewById(R.id.thumbImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
FeedItem newsItem = (FeedItem) listData.get(position);
holder.headlineView.setText(newsItem.getTitle());
holder.reportedDateView.setText(newsItem.getDate());
if (holder.imageView != null) {
new ImageDownloaderTask(holder.imageView).execute(newsItem.getAttachmentUrl());
}
return convertView;
}
static class ViewHolder {
TextView headlineView;
TextView reportedDateView;
ImageView imageView;
}
}
in this line feedListView.setAdapter(new CustomListAdapter(this, feedList)); just replace this with getActivity();

Categories

Resources