AsyncTaskLoader issue in android - java

Hi I am using AsyncTaskLoader in my app and I have implemented that in MovieTaskLoader class but when I am implementing Loader callbacks in my fragment I am getting type conversion error in onCreateLoader() method.
MovieTaskLoader class:
class MovieTaskLoader extends AsyncTaskLoader<ArrayList<Movies>> {
MovieTaskLoader(Context context) {
super(context);
}
#Override
protected void onStartLoading() {
forceLoad();
}
#Override
public ArrayList<Movies> loadInBackground() {
//Building URL
URL url = null;
String jsonData = null;
Uri uri = Uri.parse(Utility.BASE_URL).buildUpon()
.appendPath("popular")
.appendQueryParameter("api_key", BuildConfig.api_key)
.build();
try {
url = new URL(uri.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
//Downloading json data
HttpURLConnection urlConnection;
try {
assert url != null;
urlConnection = (HttpURLConnection) url.openConnection();
if(urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
jsonData = readStream(urlConnection.getInputStream());
}
} catch (IOException e) {
e.printStackTrace();
}
return getMovieData(jsonData);
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuilder response = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
private ArrayList<Movies> getMovieData(String jsonData){
ArrayList<Movies> movies = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(jsonData);
JSONArray results = jsonObject.getJSONArray("results");
for(int i=0; i<20; i++){
Movies movie = new Movies();
JSONObject object = results.getJSONObject(i);
movie.setTitle(object.getString("title"));
movie.setSynopsis("overview");
movie.setVote_avg("vote_average");
movie.setDate("release_date");
movies.add(movie);
}
} catch (JSONException e) {
e.printStackTrace();
}
return movies;
}
}
Fragment class:
public class PopularFragment extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<Movies>> {
public PopularFragment() {
// 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_popular, container, false);
RecyclerView popularView = (RecyclerView) view.findViewById(R.id.popular_view);
GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
popularView.setLayoutManager(layoutManager);
popularView.setAdapter(new RecyclerViewAdapter());
return view;
}
#Override
public Loader<ArrayList<Movies>> onCreateLoader(int id, Bundle args) {
return new MovieTaskLoader(getContext());
}
#Override
public void onLoadFinished(Loader<ArrayList<Movies>> loader, ArrayList<Movies> data) {
}
#Override
public void onLoaderReset(Loader<ArrayList<Movies>> loader) {
}
}
I am getting error in onCreateLoader() method and type conversion error is:
Required: "Loader"
Found: MovieTaskLoader

Check your imports. Make sure both are same versions like this
android.support.v4.content.AsyncTaskLoader<D>
android.support.v4.app.LoaderManager.LoaderCallbacks<D>

Related

Android Studio ArrayAdapter GetFilter() is not working

I am trying to code a recipe app, I am pulling the recipes from an online JSON file.
Therefore I needed a custom ArrayAdapter and now I want to filter the List.
But as it turns out the adapter can't get the Filter function. I looked up other articles but none of them were helpful. Hope somebody can help out in this case.
This is the tutorial I watched to code online JSON to ListView: https://www.youtube.com/watch?v=v4X0y6-VOtM
Here is my Code:
public class Food_choosing_menu extends Fragment {
private ListView lv;
SearchView searchView;
ListAdapter adapter;
String name,time;
private static String JSON_URL = "https://---.github.io/---.json";
ArrayList<HashMap<String, String>> recepieList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_food_choosing_menu, container, false);
recepieList = new ArrayList<>();
lv = v.findViewById(R.id.Food_List_View);
searchView = v.findViewById(R.id.Searh_bar_food);
GetData getData = new GetData();
getData.execute();
return v;
}
public class GetData extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... strings) {
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(JSON_URL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while (data != -1) {
current += (char) data;
data = inputStreamReader.read();
}
return current;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}catch (Exception e){
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("Recepies");
for (int i = 0; i< jsonArray.length(); i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
name = jsonObject1.getString("name");
time = jsonObject1.getString("time");
HashMap<String, String> recepies = new HashMap<>();
recepies.put("name", name);
recepies.put("time", time);
recepieList.add(recepies);
}
}catch (JSONException e){
e.printStackTrace();
}
adapter = new SimpleAdapter(
getContext(),
recepieList,
R.layout.row_layout,
new String[] {"name", "time"},
new int[]{R.id.textView1});
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getContext(), "You Click -"+adapter.getItem(position).toString(), Toast.LENGTH_SHORT).show();
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}
}

BitmapFactory.decodeStream leads to : D/skia: --- Failed to create image decoder with message 'unimplemented'

I'm trying to download an image from a URL by creating a Bitmap using
bitmapFactory.decodeStream(InputStream) and then imageView.setImageBitmap(bitmap) but I am always getting this error:
D/skia: --- Failed to create image decoder with message
'unimplemented'. package com.example.flickrapp;
Here is my code:
import statements will go here ...
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
Button b = (Button)findViewById(R.id.getanimage);
b.setOnClickListener(new GetImageOnClickListener() {
#Override
public void onClick(View v) {
super.onClick(v);
}
});
}
public class GetImageOnClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
AsyncFlickrJSONData imagesData = new AsyncFlickrJSONData();
imagesData.execute("https://www.flickr.com/services/feeds/photos_public.gne?tags=trees&format=json");
}
}
public class AsyncFlickrJSONData extends AsyncTask<String, Void, JSONObject> {
#Override
protected JSONObject doInBackground(String... strings) {
String flickrUrl = strings[0];
JSONObject jsonFlickr = null;
URL url = null;
try {
url = new URL(flickrUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
String s1 = readStream(in);
int lengthS = s1.length();
String s = (String) s1.subSequence(15, lengthS-1);
jsonFlickr = new JSONObject(s);
} finally {
urlConnection.disconnect();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return jsonFlickr;
}
#Override
protected void onPostExecute(JSONObject jsonFlickr) {
super.onPostExecute(jsonFlickr);
try {
String firstUrl = jsonFlickr.getJSONArray("items").getJSONObject(0).getString("link");
AsyncBitmapDownloader firstAsyncImage = new AsyncBitmapDownloader();
firstAsyncImage.execute(firstUrl);
Log.i("JFL", firstUrl);
} catch (JSONException e) {
e.printStackTrace();
}
}
private String readStream(InputStream in) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
Log.e(TAG, "IOException", e);
} finally {
try {
in.close();
} catch (IOException e) {
Log.e(TAG, "IOException", e);
}
}
return sb.toString();
}
}
public class AsyncBitmapDownloader extends AsyncTask<String, Void, Bitmap> {
ImageView firstImage = (ImageView) findViewById(R.id.image);
#Override
protected Bitmap doInBackground(String... strings) {
String imageUrl = strings[0];
Bitmap bm = null;
URL url = null;
try {
url = new URL(imageUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
bm = BitmapFactory.decodeStream(in);
} finally {
urlConnection.disconnect();
}
} catch(IOException e){
e.printStackTrace();
}
return bm;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
firstImage.setImageBitmap(bitmap);
}
}
}
Any Suggestions or Ideas are welcomed :)

RecyclerView: No adapter attached; skipping layout when Im running

I'm new coder of android and trying to get list of images in my server and database(mysql) but I got error and I don't know what is causing it...
the error is 'E/RecyclerView: No adapter attached; skipping layout' and it happen when I'm running, anyone can help me??
public class LoadListFromServer extends AsyncTask<String, Void, String> {
private RecyclerView recyclerView;
private Context context;
private ArrayList<ImageGalleryItem> imageGalleryItems;
private boolean pattern;
public LoadListFromServer(RecyclerView recyclerView, Context context, boolean pattern) {
this.recyclerView = recyclerView;
this.context = context;
this.pattern = pattern;
}
public ArrayList<ImageGalleryItem> getImageGalleryItems() {
return imageGalleryItems;
}
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-type", "application/json");
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
return readStream(urlConnection.getInputStream());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(context,2);
recyclerView.setLayoutManager(layoutManager);
imageGalleryItems = prepareData(response);
MyAdapter adapter = new MyAdapter(context, imageGalleryItems);
recyclerView.setAdapter(adapter);
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in, "UTF-8"), 8);
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
private ArrayList<ImageGalleryItem> prepareData(String response) {
ArrayList<ImageGalleryItem> result = null;
try {
JSONArray jsonArray = new JSONArray(response);
result = new ArrayList<>(jsonArray.length());
for (int i=0; i < jsonArray.length(); i++) {
try {
JSONObject oneObject = jsonArray.getJSONObject(i);
String id = oneObject.getString("id");
String name = oneObject.getString("name");
result.add(new ImageGalleryItem(name, Long.parseLong(id), pattern));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
if(result == null) {
return new ArrayList<>();
} else {
return result;
}
}
}
I wrote my adapter as MyAdapter.java:
class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<ImageGalleryItem> galleryList;
public MyAdapter(Context context, ArrayList<ImageGalleryItem> galleryList) {
this.galleryList = galleryList;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cell_layout, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int i) {
final ImageGalleryItem imageGalleryItem = galleryList.get(i);
viewHolder.title.setText(imageGalleryItem.getName());
viewHolder.img.setScaleType(ImageView.ScaleType.FIT_XY);
String imageFolderName;
final boolean isPattern = imageGalleryItem.isPattern();
if(isPattern) {
imageFolderName = viewHolder.img.getContext().getString(R.string.patterns_directory);
} else {
imageFolderName = viewHolder.img.getContext().getString(R.string.collections_directory);
}
LoadSVGFromServer loadSVGFromServer = new LoadSVGFromServer(viewHolder.img);
loadSVGFromServer.execute(viewHolder.img.getContext().getString(R.string.server_base_address)
+ imageFolderName
+ imageGalleryItem.getID() + ".svg");
viewHolder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Activity activity = (Activity) v.getContext();
if(isPattern) {
Intent intent = new Intent(activity, ColoringActivity.class);
Bundle b = new Bundle();
b.putSerializable(activity.getString(R.string.CURRENT_COLLECTION_BUNDLE_KEY), imageGalleryItem);
intent.putExtras(b);
activity.startActivity(intent);
} else {
Intent intent = new Intent(activity, ShowPatternsActivity.class);
Bundle b = new Bundle();
b.putSerializable(activity.getString(R.string.CURRENT_COLLECTION_BUNDLE_KEY), imageGalleryItem);
intent.putExtras(b);
activity.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return galleryList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView title;
private ImageView img;
public ViewHolder(View view) {
super(view);
title = (TextView)view.findViewById(R.id.title);
img = (ImageView) view.findViewById(R.id.img);
}
}
}
You can setup your recyclerView and set items when data received.
activity code for setup recycler view:
public class MainActivity extends AppCompatActivity {
private MyAdapter mAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupRecyclerView();
}
private void setupRecyclerView(){
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(context,2);
recyclerView.setLayoutManager(layoutManager);
mAdapter = new MyAdapter(context);
recyclerView.setAdapter(mAdapter);
}
}
Pass adapter to async task:
public class LoadListFromServer extends AsyncTask<String, Void, String> {
private MyAdapter mAdapter;
private Context context;
private ArrayList<ImageGalleryItem> imageGalleryItems;
private boolean pattern;
public LoadListFromServer(MyAdapter adapter, Context context, boolean pattern) {
this.mAdapter = adapter;
this.context = context;
this.pattern = pattern;
}
public ArrayList<ImageGalleryItem> getImageGalleryItems() {
return imageGalleryItems;
}
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-type", "application/json");
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
return readStream(urlConnection.getInputStream());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
imageGalleryItems = prepareData(response);
mAdapter.setItems(imageGalleryItems);
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in, "UTF-8"), 8);
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
private ArrayList<ImageGalleryItem> prepareData(String response) {
ArrayList<ImageGalleryItem> result = null;
try {
JSONArray jsonArray = new JSONArray(response);
result = new ArrayList<>(jsonArray.length());
for (int i=0; i < jsonArray.length(); i++) {
try {
JSONObject oneObject = jsonArray.getJSONObject(i);
String id = oneObject.getString("id");
String name = oneObject.getString("name");
result.add(new ImageGalleryItem(name, Long.parseLong(id), pattern));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
if(result == null) {
return new ArrayList<>();
} else {
return result;
}
}
}
Adapter with setItems method:
class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<ImageGalleryItem> galleryList;
public MyAdapter(Context context) {
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cell_layout, viewGroup, false);
return new ViewHolder(view);
}
public void setItems(ArrayList<ImageGalleryItem> galleryList){
this.galleryList = galleryList;
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int i) {
final ImageGalleryItem imageGalleryItem = galleryList.get(i);
viewHolder.title.setText(imageGalleryItem.getName());
viewHolder.img.setScaleType(ImageView.ScaleType.FIT_XY);
String imageFolderName;
final boolean isPattern = imageGalleryItem.isPattern();
if(isPattern) {
imageFolderName = viewHolder.img.getContext().getString(R.string.patterns_directory);
} else {
imageFolderName = viewHolder.img.getContext().getString(R.string.collections_directory);
}
LoadSVGFromServer loadSVGFromServer = new LoadSVGFromServer(viewHolder.img);
loadSVGFromServer.execute(viewHolder.img.getContext().getString(R.string.server_base_address)
+ imageFolderName
+ imageGalleryItem.getID() + ".svg");
viewHolder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Activity activity = (Activity) v.getContext();
if(isPattern) {
Intent intent = new Intent(activity, ColoringActivity.class);
Bundle b = new Bundle();
b.putSerializable(activity.getString(R.string.CURRENT_COLLECTION_BUNDLE_KEY), imageGalleryItem);
intent.putExtras(b);
activity.startActivity(intent);
} else {
Intent intent = new Intent(activity, ShowPatternsActivity.class);
Bundle b = new Bundle();
b.putSerializable(activity.getString(R.string.CURRENT_COLLECTION_BUNDLE_KEY), imageGalleryItem);
intent.putExtras(b);
activity.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return galleryList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView title;
private ImageView img;
public ViewHolder(View view) {
super(view);
title = (TextView)view.findViewById(R.id.title);
img = (ImageView) view.findViewById(R.id.img);
}
}
}

Android AutocompleteTextview display no suggestions

Errors: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
Application run but display no output in autocompletetextview
englishSentence is jsonObject. and i have getter and setter methods in TranslatorModel class for json Objects.
public class MainActivity extends AppCompatActivity {
private AutoCompleteTextView autoCompleteTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
new HttpGetTask().execute("http://192.168.0.107/abc/translator.php");
}
public class HttpGetTask extends AsyncTask<String, String, List<TranslatorModel>> {
#Override
protected List<TranslatorModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
List<TranslatorModel> translatorModelList = new ArrayList<>();
for(int i= 0; i<parentArray.length();i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
TranslatorModel translatorModel = new TranslatorModel();
translatorModel.setEnglish(finalObject.getString("englishSentence"));
translatorModelList.add(translatorModel);
}
return translatorModelList;
} 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<TranslatorModel> data) {
AutoCompleteAdapter adapter = new AutoCompleteAdapter(getApplicationContext(),android.R.layout.simple_list_item_1,data);
autoCompleteTextView.setAdapter(adapter);
autoCompleteTextView.setThreshold(1);
super.onPostExecute(data);
}
}
public class AutoCompleteAdapter extends ArrayAdapter {
private List<TranslatorModel> translatorModelList;
private int resource;
private LayoutInflater inflater;
public AutoCompleteAdapter(Context context, int resource, List<TranslatorModel> objects) {
super(context, resource, objects);
translatorModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = inflater.inflate(resource, null);
holder = new ViewHolder();
holder.autoCompleteTextView = (AutoCompleteTextView) convertView.findViewById(R.id.autoCompleteTextView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.autoCompleteTextView.setText(translatorModelList.get(position).getEnglish());
return convertView;
}
class ViewHolder {
private AutoCompleteTextView autoCompleteTextView;
}
}
}

Pass two String array from doinbackground to fragment

I am trying to pass 2 String[] from doinbackground to fragment where i have RecyclerView. I also tried setter getter method but still no luck
Here is my Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.activity_friend_list,container,false);
recyclerView= (RecyclerView) view.findViewById(R.id.RecyclerViewForFriendList);
//WANTS TO REPLACE THESE TWO ARRAY WITH WHICH I AM GETTING IN DOINBACKGROUND
Name=getResources().getStringArray(R.array.left_Drawer_Menu);
Image=getResources().obtainTypedArray(R.array.user_image);
recyclerView.setHasFixedSize(true);
adapter=new RecyclerFriendListAdapter(getActivity(),Distance,Image,LastSeen,Name);
recyclerView.setAdapter(adapter);
layoutManager=new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
return view;
}
Here is my AsyncTask Class
protected String[] doInBackground(String... params) {
try {
URL url=new URL(URL_Path);
connection= (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream=connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuffer stringBuffer=new StringBuffer();
while ((line=reader.readLine())!=null){
stringBuffer.append(line);
}
String completeJSON=stringBuffer.toString();
JSONArray parentArray=new JSONArray(completeJSON);
String[] Name=new String[parentArray.length()];
String[] ImagePath=new String[parentArray.length()];
for (int i = 0; i <parentArray.length() ; i++) {
JSONObject childObject=parentArray.getJSONObject(i);
String Fname=childObject.getString("First_Name") ;
String Lname=childObject.getString("Last_Name") ;
Name[i]=Fname+" "+Lname;
ImagePath[i]=childObject.getString("Image");
Log.d(TAG,"String Arrays "+Name[i]+" "+ ImagePath[i]);
//GETTING ALL VALUES IN LOG SUCCESSFULLY
}
return Name;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
try {
connection.disconnect();
if (reader!=null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String[] strings) {
super.onPostExecute(strings);
}
I am calling AsyncTask Execute Method in Toolbar of Parent Activity Of Fragment
UPDATE:
1) As #BryanDunlap Asked for onPostExecute (its just implemented,No code inside it) And How to return both arrays to get in Fragment
2) #IrisLouis suggested to implement interface that's how i did with setter and getter but i wasn't work
ublic class WrapperClass {
private String[] Name;
private String[] ImagePath;
public String[] getImagePath() {
return ImagePath;
}
public void setImagePath(String[] imagePath) {
ImagePath = imagePath;
}
public String[] getName() {
return Name;
}
public void setName(String[] name) {
Name = name;
}
How i set this in AsyncTask
Name[i]=Fname+" "+Lname;
ImagePath[i]=childObject.getString("Image");
Log.d(TAG,"String Arrays "+Name[i]+" "+ ImagePath[i]);
//LOG RETURNS VALUE OF BOTH ARRAYS
WrapperClass w=new WrapperClass();
w.setImagePath(ImagePath);
w.setImagePath(Name);
Getting in Fragment in onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
....
....
....
WrapperClass wrapperClass=new WrapperClass();
String[] Name=wrapperClass.getName();
String[] ImagePath=wrapperClass.getImagePath();
Log.d(TAG,Name.toString()+" "+ ImagePath.toString())
//IT RETURNS NULLS
Solution for you, can test it.
In class Asynctask make a interface callback results :
public class PageLoader extends AsyncTask<String, Void, String[] results> {
private Context context;
private LoaderListener mLoaderListener;
public PageLoader(Context context, LoaderListener mLoaderListener) {
this.context = context;
this.mLoaderListener = mLoaderListener;
}
public interface LoaderListener {
void onLoadCompleted(String[] results);
void onLoadFailed();
void onPreparing();
}
#Override
protected void onPreExecute() {
mLoaderListener.onPreparing();
}
#Override
protected String[] doInBackground(String... params) {
try {
URL url=new URL(URL_Path);
connection= (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream=connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuffer stringBuffer=new StringBuffer();
while ((line=reader.readLine())!=null){
stringBuffer.append(line);
}
String completeJSON=stringBuffer.toString();
JSONArray parentArray=new JSONArray(completeJSON);
String[] Name=new String[parentArray.length()];
String[] ImagePath=new String[parentArray.length()];
for (int i = 0; i <parentArray.length() ; i++) {
JSONObject childObject=parentArray.getJSONObject(i);
String Fname=childObject.getString("First_Name") ;
String Lname=childObject.getString("Last_Name") ;
Name[i]=Fname+" "+Lname;
ImagePath[i]=childObject.getString("Image");
Log.d(TAG,"String Arrays "+Name[i]+" "+ ImagePath[i]);
//GETTING ALL VALUES IN LOG SUCCESSFULLY
}
return Name;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
try {
connection.disconnect();
if (reader!=null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String[] results) {
if (results!= null) {
mLoaderListener.onLoadCompleted(results);
} else {
mLoaderListener.onLoadFailed();
}
}
}
In Activity you execute Asynctask.
In Fragment you must implements LoaderListener and Override three function.
Ex : YourFragment extends Fragment implements LoaderListener
You can handle results callback in onLoadCompleted
Ex :
#Override
public void onLoadCompleted(String[] results){
//Do something with results
}

Categories