First of all, PLEASE HELP ... I have done almost everything to figure out and now I am here !
1st confusion is: why on earth Async class works so slow, I am using the click event to fetch some data from api, while using SYSO to see the output of populated array in Android monitor, it nearly took 4,5 seconds every time to populate the arraylist with 20 elements. There must be something very wrong which i dont know right now ....
Activity code is :
Toolbar toolbar;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_news);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Get Request
String url = "MY URL HERE";
new JSONAsync(getApplicationContext()).execute(url);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(MainNews.this, JSONAsync.dataArray);
recyclerViewAdapter.notifyDataSetChanged();
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerViewAdapter);
recyclerViewAdapter.notifyDataSetChanged();
}
Async class is written as:
Context context;
public static List<Data> dataArray = new ArrayList<>();
public JSONAsync(Context context) {
this.context = context;
dataArray.clear();
}
#Override
protected Boolean doInBackground(String... params) {
try {
return downloadUrl(params[0]);
} catch (IOException e) {
return false;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public boolean downloadUrl(String myurl) throws IOException, JSONException {
InputStream is = null;
int response;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
response = conn.getResponseCode();
is = conn.getInputStream();
if (response == 200) {
String responseBody = convertToString(conn.getInputStream());
JSONArray jArray = new JSONArray(responseBody);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jobj = jArray.getJSONObject(i);
System.out.println("Output is: ....."+jobj);
Data data = new Data();
data.setId(jobj.getInt("id"));
data.setHeading(jobj.getString("heading"));
data.setBrief(jobj.getString("brief"));
data.setDate(jobj.getString("date"));
String imageURL = "http://paktribune.com/images/news/";
imageURL = imageURL.concat(jobj.getString("limage"));
data.setImage(getBitmapFromURL(imageURL));
dataArray.add(data);
}
return true;
} else return false;
} finally {
if (is != null) {
is.close();
}
}
}
public Bitmap getBitmapFromURL(String imageURL) {
Bitmap myBitmap = null;
try {
int responseCode;
URL url = new URL(imageURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
responseCode = connection.getResponseCode();
if (responseCode==200)
{
InputStream input = connection.getInputStream();
myBitmap = BitmapFactory.decodeStream(input);
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
return myBitmap;
}
public String convertToString(InputStream is) {
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) {
} finally {
try {
is.close();
} catch (IOException e) {
}
}
return sb.toString();
}
#Override
protected void onPostExecute(Boolean result) {
if (result == false) {
Toast.makeText(context, "Unable to fetch data from server", Toast.LENGTH_SHORT).show();
}
}
And the adapter is :
private LayoutInflater inflater;
Context context;
List<Data> dataArray;
private int lastPosition = -1;
public RecyclerViewAdapter(Context context, List<Data> dataArray) {
this.dataArray = dataArray;
this.context = context;
inflater = LayoutInflater.from(context);
}
#Override
public RecyclerViewAdapter.CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.cardview, parent, false);
CustomViewHolder holder = new CustomViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
Data current = dataArray.get(position);
holder.textView1.setText(current.heading);
holder.textView2.setText(current.date);
holder.textView3.setText(current.brief);
holder.image.setImageBitmap(current.image);
setAnimation(holder.relativeLayout, position);
}
#Override
public int getItemCount() {
return dataArray.size();
}
public static class CustomViewHolder extends admin.myproject.CustomViewHolder {
ImageView image;
RelativeLayout relativeLayout;
TextView textView1, textView2, textView3;
public CustomViewHolder(View itemView) {
super(itemView);
textView1 = (TextView) itemView.findViewById(R.id.heading);
textView2 = (TextView) itemView.findViewById(R.id.date);
textView3 = (TextView) itemView.findViewById(R.id.brief);
image = (ImageView) itemView.findViewById(R.id.imageView);
relativeLayout = (RelativeLayout) itemView.findViewById(R.id.Relative);
}
}
private void setAnimation(View viewToAnimate, int position) {
if (position > lastPosition) {
Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}
Can anyone tell me why the app moves to the next activity when i click some button before the loop in doInBackground completes.
I am clearing the dataArray and also updating the notifyDataSetChanged(). If i use the notifyDataSetChanged() in doInBackground() or in postExecute method, it just points the Null pointer exception so this is the reason I am using it in adapter but i think it's okay to use it there as well.
PLEASE HELP guys !
Your logic is flawed and the implementation is vulnerable to many problematic issues.
1) Async task, as its name suggets performs its task asynchronously. That is, the line new JSONAsync(getApplicationContext()).execute(url); returns immediately and execution continues in the activity. As you tell the adapter that data is ready, it most probably is not ready and async task is trying to do its job in the mean time.
2) Using the static member to communicate in a multi-threaded environment is prone to errors. Instead, implement a listener interface in your activity and let the async task call the listener's method in onPostExecute. Only then tell the adapter about the data change.
private List<Data> dataArray = new ArrayList<>();
private IAsyncTaskListener listener;
public JSONAsync(Context context, IAsyncTaskListener listener) {
this.context = context;
this.listener = listener;
}
public interface IAsyncTaskListener {
void onCompleted(List<Data> dataArray);
}
#Override
protected void onPostExecute(Boolean result) {
this.listener.onCompleted(dataArray);
}
Your activity can implement IAsyncTaskListener
public class YourActivity extends AppCompatActivity implements JSONAsync.IAsyncTaskListener {
#Override
public void onCompleted(List<Data> dataArray) {
recyclerViewAdapter.setData(dataArray);
recyclerViewAdapter.notifyDataSetChanged();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_news);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Get Request
String url = "http://paktribune.com/api/newsList";
new JSONAsync(getApplicationContext(), this).execute(url);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(MainNews.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerViewAdapter);
}
}
You would provide a method to change the adapter's data. In the listener callback, you set the data on the adapter and call notifyDataSetChanged on it, to inform the adapter about the changes.
Try using Picasso or Glide library for downloading images. Those libraries might provide faster downloads, their cache handling is better.
Related
I am trying to get strings(usernames) from Server wanna put it into Recycle.For that, I am using JSON to fetch data and Asynctask to generate a new thread.I successfully getting usernames from the server but failed to put them in recycleview.
This is my Mainactivity.java
public class MainActivity extends AppCompatActivity {
BufferedReader reader;
private String content;
RecyclerView recyclerView;
Adapter madapter;
List<String> data = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ApiAsyncTask().execute();
}
private class ApiAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
getData();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
recyclerView=(RecyclerView)findViewById(R.id.rv123);
recyclerView.setLayoutManager(new LinearLayoutManager());
data.add("name");
Dataadapter madapter = new Dataadapter(data);
recyclerView.setAdapter(madapter);
}
}
private void getData(){
try {
URL url = new URL("https://jsonplaceholder.typicode.com/comments");
URLConnection conn = url.openConnection();
conn.setDoOutput(false);
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + " ");
}
// Append Server Response To Content String
content = sb.toString();
Log.e("TAG", "Response is -> " + content);
JSONArray jsonArray = new JSONArray(content);
for(int i=0;i<=4;i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
Log.e("TAG", "Username is -> " + name);}
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is my Adapter
public class Dataadapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public TextView textView;
private List<String> data;
public Dataadapter(List<String> data) {
this.data = data;
}
public class MyViewHolder extends RecyclerView.ViewHolder{
public MyViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.tv);
}}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View dataView = layoutInflater.inflate(R.layout.container, parent, false);
MyViewHolder myViewHolder = new MyViewHolder(dataView);
return myViewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
textView.setText(data.get(position));
}
#Override
public int getItemCount() {
return data.size();
}
}
Using 2 XML files.One is Mainactivity.xml and other is Container.xml.Please help me on how to show usernames (which I fetched from the server)into recycleview.For now, when I run the app, it just showing the layout only.Not getting any username in that layout.But in my log, I can see the usernames.Thank u
Just add the objects to your list
for(int i=0;i<=4;i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
data.add(jsonObject.getString("name"));
}
And the LinearLayoutManager constructor takes one parameter, a Context.
In your onPostExecute, do this -
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
Try this code, I tested it and it's working.
Here's MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
BufferedReader reader;
RecyclerView recyclerView;
Dataadapter madapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.rv123);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
madapter = new Dataadapter();
recyclerView.setAdapter(madapter);
new ApiAsyncTask().execute();
}
private class ApiAsyncTask extends AsyncTask<Void, Void, List<String>> {
#Override
protected List<String> doInBackground(Void... voids) {
return getData();
}
#Override
protected void onPostExecute(List<String> names) {
madapter.updateData(names);
}
}
private List<String> getData() {
List<String> data = new ArrayList<>();
try {
URL url = new URL("https://jsonplaceholder.typicode.com/comments");
URLConnection conn = url.openConnection();
conn.setDoOutput(false);
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line);
}
// Append Server Response To Content String
String content = sb.toString();
Log.e("TAG", "Response is -> " + content);
JSONArray jsonArray = new JSONArray(content);
for (int i = 0; i < 50; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
Log.e("TAG", "Username is -> " + name);
data.add(name);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
Log.d(TAG, "getData: " + data.size());
return data;
}
}
and here's Dataadapter.java
public class Dataadapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public TextView textView;
private List<String> data;
public Dataadapter() {
data = new ArrayList<>();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public MyViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.tv);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View dataView = layoutInflater.inflate(R.layout.container, parent, false);
return new MyViewHolder(dataView);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
textView.setText(data.get(position));
}
#Override
public int getItemCount() {
return data.size();
}
public void updateData(List<String> data) {
this.data = data;
notifyDataSetChanged();
}
}
The data returned from the API endpoint contains 500 items, I used 50 instead to load faster.
You should not make holder's textView as adapter's local variable and assign value on holder's constructor. Since ViewHolder may be reused and parsed to Adapter.onBindViewHolder() and then the textView used in onBindViewHolder() method is not the textView in holder( the ViewHolder constructor not called). You can make textView as MyViewHolder's variable and use holder.getTextView().setText(item) to set text.
I hope someone out there can help me solve my problem. I have android app that have 3 tabs, i use fragment, first tab is recyclerView list, second tabs is map. the problem is in tabs 1, i need to fetch data with volley to recyclerView on tabs 1, if run fine but i cannot see the data on first app start, but when i change tab and back to tab 1 again it will refresh the data and show the data on recyclerView.
Adapter.java
public class CustomListAdapterWarkop extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private List<Warkop> mWarkop;
private LayoutInflater inflater;
public CustomListAdapterWarkop(Context context, List<Warkop> mWarkop) {
this.context=context;
inflater= LayoutInflater.from(context);
this.mWarkop = mWarkop;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.list_warkop_row, parent, false);
ItemViewHolder holder = new ItemViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ItemViewHolder viewHolder = (ItemViewHolder) holder;
Warkop current = mWarkop.get(position);
viewHolder.tvNamaWarkop.setText(current.getNamaWarkop());
ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(R.drawable.noimage)
.showImageOnFail(R.drawable.noimage)
.showImageOnLoading(R.drawable.noimage).build();
imageLoader.displayImage(current.getFotoWarkop(), viewHolder.ivFotoWarkop, options);
}
#Override
public int getItemCount() {
return mWarkop.size();
}
}
ItemHolder.java
package com.andylah.warkopedia;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by andylah on 11/3/2017.
*/
public class ItemViewHolder extends RecyclerView.ViewHolder {
public ImageView ivFotoWarkop;
public TextView tvNamaWarkop;
public ItemViewHolder(View itemView) {
super(itemView);
tvNamaWarkop = itemView.findViewById(R.id.nama_warkop);
ivFotoWarkop = itemView.findViewById(R.id.image_warkop);
}
}
Tab 1.java
public class tabSatu extends Fragment {
private static final String TAG = tabDua.class.getSimpleName();
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private boolean isFragmentLoaded = false;
View vTabSatu;
private RecyclerView recyclerView;
public static List<Warkop> warkopList = new ArrayList<Warkop>();
private CustomListAdapterWarkop warkopAdapter;
public tabSatu(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
new AsyncFetch().execute();
vTabSatu = inflater.inflate(R.layout.tabsatu_view, container, false);
recyclerView = vTabSatu.findViewById(R.id.warkop_container);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
Log.d("LOG : ", "onCreatedView Run");
// Inflate the layout for this fragment
return vTabSatu;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
warkopAdapter = new CustomListAdapterWarkop(getActivity(), warkopList);
warkopAdapter.notifyDataSetChanged();
recyclerView.setAdapter(warkopAdapter);
Log.d("LOG : ", "onViewCreated Run");
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && !isFragmentLoaded ) {
// Load your data here or do network operations here
isFragmentLoaded = true;
//new AsyncFetch().execute();
}else{
isFragmentLoaded = false;
Log.d("LOG : ", "isFragmentLoaded = false");
}
}
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pDialog = new ProgressDialog(getActivity());
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Loading list warkop ...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... strings) {
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
url = new URL(AppConfig.LOAD_WARKOP);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
try{
JSONObject object = new JSONObject(result);
String getObject = object.getString("warkop");
JSONArray jsonArray = new JSONArray(getObject);
boolean error = object.getBoolean("error");
if(!error){
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Warkop warkop = new Warkop();
warkop.setNamaWarkop(jsonObject.getString("nama_warkop"));
warkop.setAlamatWrkop(jsonObject.getString("alamat_warkop"));
warkop.setKotaWarkop(jsonObject.getString("kota_warkop"));
warkop.setLatWarkop(Double.parseDouble(jsonObject.getString("lat_warkop")));
warkop.setLangWarkop(Double.parseDouble(jsonObject.getString("long_warkop")));
warkop.setIsWifi(Integer.parseInt(jsonObject.getString("is_wifi")));
warkop.setIsToilet(Integer.parseInt(jsonObject.getString("is_toilet")));
warkop.setIsTv(Integer.parseInt(jsonObject.getString("is_tv")));
warkop.setIsColokan(Integer.parseInt(jsonObject.getString("is_colokan")));
warkop.setIsParkir(Integer.parseInt(jsonObject.getString("is_parkir")));
warkop.setFotoWarkop(jsonObject.getString("foto_warkop"));
warkopList.add(warkop);
}
}else{
String errorMsg = object.getString("error_msg");
Toast.makeText(getContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
}catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
Problem: Even you call notifyDataSetChanged() but there are no data in Adapter.
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
warkopAdapter = new CustomListAdapterWarkop(getActivity(), warkopList);
warkopAdapter.notifyDataSetChanged();
recyclerView.setAdapter(warkopAdapter);
}
So you need to set and notify warkopList to Adapter after API call. It will help you.
tabSatu:
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
try {
JSONObject object = new JSONObject(result);
String getObject = object.getString("warkop");
JSONArray jsonArray = new JSONArray(getObject);
boolean error = object.getBoolean("error");
if (!error) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Warkop warkop = new Warkop();
...
warkopList.add(warkop);
adapter.setItems(warkopList);
}
}
...
}
CustomListAdapterWarkop: add setItem() method to Adapter
public class CustomListAdapterWarkop extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
...
public void setItems(List<WarkopList> warkopList) {
mWarkop = warkopList;
notifyDataSetChanged();
}
...
}
I want to retrieve json recycler image gallery data and display in RecyclerView manner, anyone help me
like Instagram click image gallery open in RecyclerView with image name
Currently I am displaying in a grid manner I don't no how to pass from this recycler to another recycler :
ProfilActivity:
public class ProfilActivity extends AppCompatActivity {
private RecyclerView recyclerView;
ArtistAdapterGallary artistAdapterGallary;
ArrayList < DataArtist > data = new ArrayList < > (); //its in progress dialog arraylist to retrieve array data
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profil);
new AsyncFetch().execute();
}
private class AsyncFetch extends AsyncTask < String, String, String > {
ProgressDialog pdLoading = new ProgressDialog(ProfilActivity.this);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String...params) {
try {
url = new URL("http://exxxxxxxxxxxxxx");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
pdLoading.dismiss();
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataArtist artistPic = new DataArtist();
artistPic.artistName = json_data.getString("name");
artistPic.artistImage = json_data.getString("profile_image");
data.add(artistPic);
}
// Setup and Handover data to recyclerview
recyclerView = (RecyclerView) findViewById(R.id.profileGride);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 3);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
artistAdapterGallary = new ArtistAdapterGallary(ProfilActivity.this, data);
// recyclerView.setLayoutManager(new LinearLayoutManager(ProfileGrideActivity.this));
recyclerView.setAdapter(artistAdapterGallary);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Custom Adatpter
public class ArtistAdapterGallary extends RecyclerView.Adapter < ArtistAdapterGallary.MyViewHolder > {
private Context context;
private LayoutInflater inflater;
List < DataArtist > data = new ArrayList < > ();
public ArtistAdapterGallary(ProfilActivity context, List < DataArtist > data1) {
this.context = context;
this.data = data1;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.gallary_layout, parent, false);
return new ArtistAdapterGallary.MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final ArtistAdapterGallary.MyViewHolder holder, int position) {
final DataArtist current = data.get(position);
holder.artistname.setText(current.artistName);
Glide.with(context).load(data.get(position).getArtistImage()).into(holder.artistImage);
holder.artistImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, Main2Activity.class);
intent.putExtra("link", current.getArtistImage());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return data.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView artistImage;
TextView artistname;
private View view;
public MyViewHolder(View itemView) {
super(itemView);
artistImage = (ImageView) itemView.findViewById(R.id.imageGride);
artistname = (TextView) itemView.findViewById(R.id.artistName);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(context, Main2Activity.class);
DataArtist artistData = (DataArtist) view.getTag();
String strUrl = artistData.getArtistImage();
String product1 = artistData.getArtistName();
intent.putExtra("ARTIST_IMG", strUrl);
intent.putExtra("ARTIST_NAME", product1);
// intent.putExtra("Your string key",product1);
context.startActivity(intent);
}
}
}
DataArtist :
public class DataArtist {
public String artistImage;
public String artistName;
public String artistId;
private boolean isSelected = false;
public DataArtist() {
this.artistImage = artistImage;
this.artistName = artistName;
}
public String getArtistId() {
return artistId;
}
public void setArtistId(String artistId) {
this.artistId = artistId;
}
public String getArtistImage() {
return artistImage;
}
public void setArtistImage(String artistImage) {
this.artistImage = artistImage;
}
public void setArtistName(String artistName) {
this.artistName = artistName;
}
public String getArtistName() {
return artistName;
}
public void setSelected(boolean selected) {
boolean isSelected = selected;
}
public boolean isSelected() {
return isSelected;
}
}
and I want to know how I can call this data into another recycler
trying to make a searchview works, with php and mysql.
user enters search query into search view/search bar to search for particular information, the query is sent to php file and result from php file is displayed on RecyclerView.
dont know whats wrong
MainActivity
public class MainActivity extends AppCompatActivity {
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVProd;
private AdapterProd mAdapter;
SearchView searchView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.searchmain, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) MainActivity.this.getSystemService(Context.SEARCH_SERVICE);
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName()));
searchView.setIconified(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#Override
protected void onNewIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
if (searchView != null) {
searchView.clearFocus();
}
new AsyncFetch(query).execute();
}
}
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
HttpURLConnection conn;
URL url = null;
String searchQuery;
public AsyncFetch(String searchQuery){
this.searchQuery=searchQuery;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
url = new URL("http://192.168.0.2/prod-search.php");
} catch (MalformedURLException e) {
e.printStackTrace();
return e.toString();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
if (response_code == HttpURLConnection.HTTP_OK) {
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
return (result.toString());
} else {
return("Erro");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
pdLoading.dismiss();
List<DataProd> data=new ArrayList<>();
pdLoading.dismiss();
if(result.equals("no rows")) {
Toast.makeText(MainActivity.this, "Nenhum resultado encontrado", Toast.LENGTH_LONG).show();
}else{
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataProd prodData = new DataProd();
prodData.nomep = json_data.getString("nomeprod");
prodData.marcap = json_data.getString("marcaprod");
prodData.pesop = json_data.getInt("pesoprod");
prodData.valorp = json_data.getInt("valorprod");
prodData.pratp = json_data.getInt("pratprod");
data.add(prodData);
}
mRVProd = (RecyclerView) findViewById(R.id.listaprodpreco);
mAdapter = new AdapterProd(MainActivity.this, data);
mRVProd.setAdapter(mAdapter);
mRVProd.setLayoutManager(new LinearLayoutManager(MainActivity.this));
} catch (JSONException e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
}
Adapter
public class AdapterProd extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private LayoutInflater inflater;
List<DataProd> data= Collections.emptyList();
DataProd current;
int currentPos=0;
public AdapterProd(Context context, List<DataProd> data){
this.context=context;
inflater= LayoutInflater.from(context);
this.data=data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.containerprod, parent, false);
MyHolder holder=new MyHolder(view);
return holder;
}
// Bind data
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
MyHolder myHolder= (MyHolder) holder;
DataProd current=data.get(position);
myHolder.textnomep.setText(current.nomep);
myHolder.textmarcap.setText("Marca: " + current.marcap);
myHolder.textpesop.setText("Peso: " + current.pesop);
myHolder.textvalorp.setText("Rs " + current.valorp + "\\Und");
myHolder.textvalorp.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
myHolder.textpratp.setText("Prateleira: current.pratprod");
}
#Override
public int getItemCount() {
return data.size();
}
class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView textnomep;
TextView textmarcap;
TextView textpesop;
TextView textvalorp;
TextView textpratp;
public MyHolder(View itemView) {
super(itemView);
textnomep = (TextView) itemView.findViewById(R.id.textnomep);
textmarcap = (TextView) itemView.findViewById(R.id.textmarcap);
textpesop = (TextView) itemView.findViewById(R.id.textpesop);
textvalorp = (TextView) itemView.findViewById(R.id.textvalorp);
textpratp = (TextView) itemView.findViewById(R.id.textpratp);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(context, "VocĂȘ clicou em um item", Toast.LENGTH_SHORT).show();
}
}
}
dont know what im doing wrong, keep getting this E/RecyclerView: No adapter attached; skipping layout, anyone can help?
Is there any chance that you are getting an exception while decoding the JSON and go directly to catch block, which skips the adapter initialization?
If you'd like to avoid that I'd suggest you to create an empty adapter set it to the recycler view when the UI initializes(in onCreate() for example), after that just have a method setData(List data) and use it to set the data after the async task finishes. In this case don't forget to call notifyDataSetChanged() when the data changes so that the recycler view is updated with the new data. This way you don't have to recreate the adapter each time you call the service.
PS: For your current code you will get that message each time the UI initializes as it doesn't have adapter attached. You should stop seeing this message once the async task finishes with no exceptions decoding the json.
hi guys i want to sent location name and some other string values to the server...i am new in android so i dont know much about it....i pass the location and other values with url...url hits but the values are not receive by the server..help please me out...
public class SearchResult extends AppCompatActivity {
private ListView lvSearch;
private ProgressDialog dialog;
private final String URL_TO_HIT = "http://www.abcd.com/mobile_search.php";
private String location = "bathinda";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result);
setContentView(R.layout.activity_search_result);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Search Result");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading. Please wait...");
// 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(getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config); // Do it on Application start
lvSearch = (ListView)findViewById(R.id.lvSearch);
Bundle bundle = getIntent().getExtras();
String bar = bundle.getString("bar");
String nights = bundle.getString("nights");
String nearby = bundle.getString("nearby");
String deals = bundle.getString("deals");
// To start fetching the data when app start, uncomment below line to start the async task.
new JSONTask().execute(URL_TO_HIT, location, bar, nights, nearby, deals );
}
public class JSONTask extends AsyncTask<String,String, List<SearchData> >{
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.show();
}
#Override
protected List<SearchData> 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();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("search");
List<SearchData> searchDataList = new ArrayList<>();
Gson gson = new Gson();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
/**
* below single line of code from Gson saves you from writing the json parsing yourself which is commented below
*/
SearchData searchData = gson.fromJson(finalObject.toString(), SearchData.class);
searchDataList.add(searchData);
}
return searchDataList;
} 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(final List<SearchData> result) {
super.onPostExecute(result);
dialog.dismiss();
if(result != null) {
SearchAdapter adapter = new SearchAdapter(getApplicationContext(), R.layout.searchresultrow, result);
lvSearch.setAdapter(adapter);
} else {
Toast.makeText(getApplicationContext(), "Not able to fetch data from server, please check internet", Toast.LENGTH_SHORT).show();
}
}
}
public class SearchAdapter extends ArrayAdapter{
private List<SearchData> searchDataList;
private int resource;
private LayoutInflater inflater;
public SearchAdapter(Context context, int resource, List<SearchData> objects) {
super(context, resource, objects);
searchDataList = 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.searchimg11 = (ImageView)convertView.findViewById(R.id.searchimg1);
holder.barname1 = (TextView)convertView.findViewById(R.id.barname);
holder.address1 = (TextView)convertView.findViewById(R.id.address);
holder.offer1 = (TextView)convertView.findViewById(R.id.offer);
holder.hourtext1 = (TextView)convertView.findViewById(R.id.hourtext);
holder.coststext1 = (TextView)convertView.findViewById(R.id.coststext);
holder.textv11 = (TextView)convertView.findViewById(R.id.textv1);
holder.featuredtext1 = (TextView)convertView.findViewById(R.id.featuredtext);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//final ProgressBar progressBar = (ProgressBar)convertView.findViewById(R.id.progressBar);
// Then later, when you want to display image
ImageLoader.getInstance().displayImage(searchDataList.get(position).getBar_image(), holder.searchimg11, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
// progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
//progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
// progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
// progressBar.setVisibility(View.GONE);
}
});
holder.barname1.setText(searchDataList.get(position).getBarname());
holder.address1.setText(searchDataList.get(position).getLocation());
holder.offer1.setText( searchDataList.get(position).getOffers());
holder.hourtext1.setText( searchDataList.get(position).getOpen_hours());
holder.coststext1.setText(searchDataList.get(position).getCost_for_two());
holder.textv11.setText(searchDataList.get(position).getFreebe());
holder.featuredtext1.setText(searchDataList.get(position).getFeaured());
return convertView;
}
class ViewHolder{
private ImageView searchimg11;
private TextView address1;
private TextView offer1;
private TextView hourtext1;
private TextView coststext1;
private TextView textv11;
private TextView barname1;
private TextView featuredtext1;
}
}
}
You are not passing any parameters to the server there . You are calling URL without any parameters
Read this solution to know how to pass parameters to HttpURLConnection using POST
How to add parameters to HttpURLConnection using POST
I did not go through your code. I suggest you to use the library to do much of the work instead of you developing on top of HTTP stack.
Use Retrofit(http://square.github.io/retrofit/) or Volley(https://developer.android.com/training/volley/index.html).
Retrofit is easy to use and manage but volley give you lot of control. Since you are new to programming on the client side, I suggest you use the Retrofit. You can't go wrong with sending JSON data, and few post using this libraries.