RecyclerView: No adapter attached; skipping layout when Im running - java

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);
}
}
}

Related

Unable to fetch images in Grid view

Main Activity:
public class MainActivity extends AppCompatActivity {
// ImageView iv;
public static StringBuffer finalparsedData;
public static GridView myGrid;
private static final String TAG = MainActivity.class.getSimpleName();
ArrayList<String> values = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myGrid=(GridView)findViewById(R.id.grid_view);
Button btnHit = (Button) findViewById(R.id.btnHit);
btnHit.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
new JSONTask().execute("https://api.flickr.com/services/rest/?method=flickr.photos.getRecent&" +
"api_key=46e71c8d2b35ba8c9c333a462ec8aea7&per_page=3&format=json&nojsoncallback=10");
}
});
values = new ArrayList<>();
}
/*static boolean isAirplaneModeOn(Context context) {
ContentResolver contentResolver = context.getContentResolver();
return Settings.System.getInt(contentResolver, AIRPLANE_MODE_ON, 0) != 0;
}*/
public class JSONTask extends AsyncTask<String, Void, String> {
String photoid;
int farm;
String server;
String secret;
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
StringBuffer buffer = null;
JSONArray parentarray = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
//JSONObject initialObject = new JSONObject("photos");
JSONObject initialObject = parentObject.getJSONObject("photos");
parentarray = initialObject.getJSONArray("photo");
finalparsedData = new StringBuffer();
for (int i = 0; i < parentarray.length(); i++) {
JSONObject finalObject = parentarray.getJSONObject(i);
photoid = finalObject.optString("id");
farm = finalObject.optInt("farm");
server = finalObject.optString("server");
secret = finalObject.optString("secret");
finalparsedData.append("https://farm" + farm + ".staticflickr.com/" + server + "/" + photoid+ "_" + secret + ".jpg" +"\n\n");
values.add(String.valueOf((finalparsedData)));
}
return "done";
} catch (MalformedURLException e) {
e.printStackTrace();
return "error";
} catch (IOException e) {
e.printStackTrace();
return "error";
} catch (JSONException e) {
e.printStackTrace();
return "error";
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
return "done";
}
} catch (IOException e) {
e.printStackTrace();
return "error";
}
}
}
#Override
protected void onPostExecute(String result) {
switch (result){
case "done":
MyImageAdapter adapter = new MyImageAdapter(MainActivity.this, values);
myGrid.setAdapter((ListAdapter) adapter);
break;
}
}
}
}
MyAdapterClass:
public class MyImageAdapter extends BaseAdapter {
ArrayList<String> values;
Context mContext;
public MyImageAdapter(Context mContext, ArrayList<String> values) {
this.values = values;
this.mContext = mContext;
}
#Override
public int getCount() {
return values.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder;
;
if (row == null){
LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.grid,parent,false);
holder = new ViewHolder();
holder.imageView = (ImageView) row.findViewById(R.id.image_View);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
String image = values.get(position);
Picasso.with(mContext).load(image).into(holder.imageView);
return row;
}
public class ViewHolder {
ImageView imageView;
}
}
I got a problem during images loading in gridview, out of 10 images only 1 image is shown and rest of them showing "this images is no longer available"
Hahaha, silly mistake. Just replace your for loop inside JSONTask with this,
.
.
.
for (int i = 0; i < parentarray.length(); i++) {
JSONObject finalObject = parentarray.getJSONObject(i);
photoid = finalObject.optString("id");
farm = finalObject.optInt("farm");
server = finalObject.optString("server");
secret = finalObject.optString("secret");
String fullPath = "https://farm" + farm + ".staticflickr.com/" + server + "/" + photoid+ "_" + secret + ".jpg";
values.add(fullPath);
}
.
.
.
No need to use StringBuffer. You should use normal String variable. :)

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;
}
}
}

Some Issue on sending data to next activity using onClickListner

i am trying to send Data (ID value) from one activity to other
but it wouldn't send correct data , i want it to send only ID Value of Clicked Item to next activity , here is my code
public class Order extends AppCompatActivity {
private ListView lvUsers;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading, please wait.....");
lvUsers = (ListView) findViewById(R.id.lvUsers);
new JSONTask().execute("http://146.185.178.83/resttest/order");
}
public class JSONTask extends AsyncTask<String, String, List<OrderModel> > {
#Override
protected void onPreExecute(){
super.onPreExecute();
dialog.show();
}
#Override
protected List<OrderModel> 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<OrderModel> orderModelList = new ArrayList<>();
Gson gson = new Gson();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
OrderModel orderModel = gson.fromJson(finalObject.toString(), OrderModel.class);
orderModelList.add(orderModel);
}
return orderModelList;
}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<OrderModel> result) {
super.onPostExecute(result);
dialog.dismiss();
OrderAdapter adapter = new OrderAdapter(getApplicationContext(), R.layout.row_order, result);
lvUsers.setAdapter(adapter);
}
}
public class OrderAdapter extends ArrayAdapter {
public List<OrderModel> orderModelList;
private int resource;
private LayoutInflater inflater;
public OrderAdapter(Context context, int resource, List<OrderModel> objects) {
super(context, resource, objects);
orderModelList = 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){
holder = new ViewHolder();
convertView=inflater.inflate(resource, null);
holder.bOrderNo = (Button) convertView.findViewById(R.id.bOrderNo);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
final int orderId = orderModelList.get(position).getId();
holder.bOrderNo.setText("Order No: " + orderModelList.get(position).getOrderId());
holder.bOrderNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Order.this, OrderSelected.class);
intent.putExtra("parameter_name", orderId);
startActivity(intent);
}
});
return convertView;
}
class ViewHolder{
private Button bOrderNo;
}
}
}
The holder gets executed in loop i guess is why it wouldn't send right Id.
How do i get it to send only Id of the clicked orderId
you can check this link to see how json Response looks like http://146.185.178.83/resttest/order
You have a silly mistake in your code . I have edited single line in your code . I think you are getting same "orderId" every time instead of actual "orderId". Check this one . I hope your problem will resolve .
final int index = position;
holder.bOrderNo.setText("Order No: " + orderModelList.get(position).getOrderId());
holder.bOrderNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Order.this, OrderSelected.class);
intent.putExtra("parameter_name", orderModelList.get(index).getId());
startActivity(intent);
}
});
Please try
In place of
intent.putExtra("parameter_name", orderId);
Please put
intent.putExtra("parameter_name", orderModelList.get(position).getId());

Recyclerview+JSON+Fragment+Android

I'm trying to pass an Arraylist with Objects obtained from a JSON, and pass to another fragment in Android Studio.
Here is the class that i want to receive the array
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_car, container, false);
new AsyncTaskParseJson().execute();
mRecyclerView = (RecyclerView) view.findViewById(R.id.rv_list);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.addOnItemTouchListener(new RecyclerViewTouchListener( getActivity(), mRecyclerView, this ));
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(llm);
CarAdapter adapter = new CarAdapter(getActivity(), mList);
mRecyclerView.setAdapter( adapter );
return view;
}
That is my class that is creating the array:
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
String yourJsonStringUrl = "http://marciowelben.servidorturbo.net/getjson.php";
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
try {
JsonParser jParser = new JsonParser();
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
dataJsonArr = json.getJSONArray("emp_info");
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
String firstname = c.getString("employee name");
String lastname = c.getString("employee no");
Car d = new Car(firstname, lastname, R.mipmap.ic_launcher );
listAux.add(d);
}
} catch (JSONException e) {
e.printStackTrace();
}
mList = listAux;
return null;
}
}
So i just want to populate my Recyclerview with this array.
Since you are adding the adapter first before waiting for the data to return you will have to call notifyDataSetChanged() for the adapter to redraw the list after it is done parsing. Another way of accomplishing this is waiting for the result to come back and then set the adapter. See below
public class MainActivity extends AppCompatActivity {
private static final String TAG = "RecyclerViewExample";
private List<FeedItem> feedItemList = new ArrayList<FeedItem>();
private RecyclerView mRecyclerView;
private MyRecyclerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Initialize recyclerview */
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
/*Downloading data from below url*/
final String url = "http://javatechig.com/api/get_category_posts/?dev=1&slug=android";
new AsyncHttpTask().execute(url);
}
public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {
#Override
protected void onPreExecute() {
setProgressBarIndeterminateVisibility(true);
}
#Override
protected Integer doInBackground(String... params) {
InputStream inputStream = null;
Integer result = 0;
HttpURLConnection urlConnection = null;
try {
/* forming th java.net.URL object */
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
/* for Get request */
urlConnection.setRequestMethod("GET");
int statusCode = urlConnection.getResponseCode();
/* 200 represents HTTP OK */
if (statusCode == 200) {
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
parseResult(response.toString());
result = 1; // Successful
}else{
result = 0; //"Failed to fetch data!";
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(Integer result) {
setProgressBarIndeterminateVisibility(false);
/* Download complete. Lets update UI */
if (result == 1) {
adapter = new MyRecyclerAdapter(MainActivity.this, feedItemList);
mRecyclerView.setAdapter(adapter);
} else {
Log.e(TAG, "Failed to fetch data!");
}
}
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("posts");
/*Initialize array if null*/
if (null == feedItemList) {
feedItemList = new ArrayList<FeedItem>();
}
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
FeedItem item = new FeedItem();
item.setTitle(post.optString("title"));
item.setThumbnail(post.optString("thumbnail"));
feedItemList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
1.Design Recycleview in layout
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="10dp"
android:layout_weight="1"
/>
2.add dependency in gradle.build
compile 'com.android.support:recyclerview-v7:23.1.1'
3.Write the code in Activity
public class DoctorInformationActivity extends AppCompatActivity {
String URL="YOUR URL";
JSONArray Cities=null;
ArrayList<DocotorInformation> doctorList =new ArrayList<DocotorInformation>();
Sqlitedatabase sql;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.doctor_information_listview);
sql=new Sqlitedatabase(getApplicationContext());
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if(activeNetworkInfo != null && activeNetworkInfo.isConnected())
{
Toast.makeText(getApplicationContext()," connect",Toast.LENGTH_LONG).show();
new JSONAsyncTask().execute();
}
else
{
ArrayList<DocotorInformation> listdata=sql.getAllContacts();
doctorList=listdata;
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
DoctorAdapter mAdapter = new DoctorAdapter(getApplicationContext(), doctorList);
recyclerView.setAdapter(mAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
Toast.makeText(getApplicationContext(),"Not connect",Toast.LENGTH_LONG).show();
}
}
private class JSONAsyncTask extends AsyncTask<String, Void, JSONArray> {
private ProgressDialog dialog = new ProgressDialog(DoctorInformationActivity.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
#Override
protected JSONArray doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(URL);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
Cities = jsono.getJSONArray("SearchDoctorsData");
return Cities;
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return Cities;
}
protected void onPostExecute(JSONArray result) {
dialog.dismiss();
System.out.println(result);
for (int i = 0; i < result.length(); i++) {
JSONObject c = null;
try {
DocotorInformation doc=new DocotorInformation();
c = result.getJSONObject(i);
doc.setName(c.getString("DoctorName"));
doc.setNumber(c.getString("Mobile"));
doctorList.add(doc);
sql.insertData(doc);
} catch (JSONException e) {
e.printStackTrace();
}
}
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
DoctorAdapter mAdapter = new DoctorAdapter(getApplicationContext(), doctorList);
recyclerView.setAdapter(mAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
}
}
}
public class DoctorAdapter extends RecyclerView.Adapter<DoctorAdapter.ViewHolder> {
private ArrayList<DocotorInformation> countries;
Context con;
public DoctorAdapter(Context c ,ArrayList<DocotorInformation> countries) {
this.con=c;
this.countries = countries;
}
#Override
public DoctorAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.doctor_textviews, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(DoctorAdapter.ViewHolder viewHolder, int i) {
viewHolder.name.setText(countries.get(i).getName());
viewHolder.number.setText(countries.get(i).getNumber());
}
#Override
public int getItemCount() {
return countries.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView name,number;
public ViewHolder(View view) {
super(view);
name = (TextView)view.findViewById(R.id.name);
number = (TextView)view.findViewById(R.id.numebr);
}
}
}

Issues connecting to RecyclerView and CardAdapter to database

So my issue comes up with context in the library fragment. I get the following error.
CardAdapter(Android.content.Context, in ArrayList<Card> in
CardAdapter cannot be applied to Library ArrayList<Card>
I've got some of this code from a friend thankfully but we can't seem to figure out the difference/error in it.
In Library.java:
public class Library extends Fragment {
// Private variables
private RecyclerView recyclerView;
private CardAdapter cardAdapter;
private ArrayList<Card> cardArrayList;
private ArrayList<Card> tempList;
public Library() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate view
View view = inflater.inflate(R.layout.library, container, false);
// Find recyclerView
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
// Initialize cardArrayList
cardArrayList = new ArrayList<>();
// Initialize cardAdapter
cardAdapter = new CardAdapter(this.getContext(), cardArrayList);
// Initialize recyclerView
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this.getContext(), 1);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(cardAdapter);
// Populate cardArrayList with test Cards
testCards();
// Return inflated view
return view;
}
public URL createURL(String constraint) {
try {
StringBuilder urlString = new StringBuilder();
//System.out.print(constraint);
if (constraint.length() > 0) {
urlString.append("https://camerondewey.000webhostapp.com/android_podcast_connect.php");
urlString.append(constraint);
System.out.print(urlString.toString());
}
String muhURL = urlString.toString();
//System.out.print(muhURL);
URL myURL = new URL(muhURL);
System.out.print(myURL);
return myURL;
//return new URL(muhURL);
} catch (Exception e) {
System.out.print("Failed to return url");
}
return null;
}
public class GetCardTask extends AsyncTask<URL, Void, JSONArray> {
#Override
protected JSONArray doInBackground(URL... params) {
//System.out.print("Params: " + params[0]);
HttpURLConnection connection = null;
StringBuilder result = new StringBuilder();
try {
connection = (HttpURLConnection) params[0].openConnection();
//System.out.println(connection.getResponseCode());
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
try {
//System.out.print("SUCCESS");
return new JSONArray(result.toString());
} catch (JSONException je) {
//System.out.print("FAILURE2");
JSONArray jArray = new JSONArray();
jArray.put(new JSONObject(result.toString()));
return jArray;
}
} else {
throw new Exception();
}
} catch (Exception e) {
System.out.print("FAILURE1");
e.printStackTrace();
} finally {
connection.disconnect();
}
return null;
}
#Override
protected void onPostExecute(JSONArray article) {
if (article != null) {
convertJSONtoArrayList(article);
Library.this.updateDisplay();
} else {
System.out.print("failure to execute json conversion");
}
}
}
private void convertJSONtoArrayList(JSONArray articles) {
cardArrayList = new ArrayList<Card>(); // clear old player data
tempList = new ArrayList<Card>();
try {
for (int i = 0; i < articles.length(); i++) {
JSONObject currentArticle = articles.getJSONObject(i);
cardArrayList.add(new Card(
currentArticle.has("name") ? currentArticle.getString("name") : "No Headline",
currentArticle.has("description") ? currentArticle.getString("description") : "No Name"
));
tempList.add(new Card(
currentArticle.has("name") ? currentArticle.getString("name") : "No Headline",
currentArticle.has("description") ? currentArticle.getString("description") : "No Name"
));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void updateDisplay() {
if (cardArrayList == null) {
System.out.print("Display failed to update");
}
ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
for (Card item : cardArrayList) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", item.getCardName());
map.put("description", item.getDescription());
data.add(map);
}
int resource = R.layout.card;
String[] from = {"name", "description"};
int[] to = {R.id.card_name, R.id.podcast_desc};
//The error happens here.
CardAdapter cardAdapter = new CardAdapter(this, cardArrayList);
recyclerView.setAdapter(cardAdapter);
cardAdapter.notifyDataSetChanged();
}
In CardAdapter.java
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardViewHolder> implements Filterable {
// Private variables
private Context cardContext;
ArrayList<Card> cardList, filteredList;
public class CardViewHolder extends RecyclerView.ViewHolder{
public View view;
public TextView cardName;
public Card currentItem;
public CardViewHolder(View v) {
// Invoke super on view
super(v);
view = v;
this.cardName = (TextView) v.findViewById(R.id.card_name);
v.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent i = new Intent(v.getContext(),PodcastPage.class);
//item clicked
v.getContext().startActivity(i);
}
});
// Find cardText
cardName = (TextView) view.findViewById(R.id.card_name);
}
}
public CardAdapter(Context c, ArrayList<Card> l) {
this.cardContext = c;
this.cardList = l;
this.filteredList = l;
}
#Override
public CardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card, null);
return new CardViewHolder(view);
}
#Override
public void onBindViewHolder(final CardViewHolder holder, int position) {
Card card = cardList.get(position);
holder.currentItem = cardList.get(position);
holder.cardName.setText(card.getCardName());
}
#Override
public int getItemCount() {
return filteredList.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence query) {
FilterResults results = new FilterResults();
if (query != null && query.length() > 0) {
query = query.toString().toUpperCase();
ArrayList<Card> searchResults = new ArrayList<Card>();
for (int i = 0; i < filteredList.size(); i++) {
if (filteredList.get(i).getCardName().toUpperCase().contains(query)) {
searchResults.add(filteredList.get(i));
}
else if (filteredList.get(i).getDescription().toUpperCase().contains(query)) {
searchResults.add(filteredList.get(i));
}
}
results.count = searchResults.size();
results.values = searchResults;
}
else {
results.count = filteredList.size();
results.values = filteredList;
}
return results;
}
#Override
protected void publishResults(CharSequence query, FilterResults results) {
filteredList = (ArrayList<Card>) results.values;
notifyDataSetChanged();
System.out.println(filteredList);
}
};
}
}
In your code in the line CardAdapter cardAdapter = new CardAdapter(this, cardArrayList); this is not a Context but a Fragment. Change the line to this:
CardAdapter cardAdapter = new CardAdapter(getActivity(), cardArrayList);

Categories