Recyclerview+JSON+Fragment+Android - java

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

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

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

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

Gridview is refreshed from start when scrollbar reaches end

This happens while loading data in gridview. This is my fragment containing scroll listener over gridview. But whenever i reload the data then whole gridview reload and scroll starts from top not from where the data is loaded. I am using single gridview.
public class Women_Ethnic_Fragment extends Fragment {
private static String url = "http://------/-------";
private int mVisibleThreshold = 5;
private int mCurrentPage = 0;
private int mPreviousTotal = 0;
private boolean mLoading = true;
private boolean mLastPage = false;
public Women_Ethnic_Fragment() {
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.gridview_fragment, container,
false);
setRetainInstance(true);
arrayList = new ArrayList<Items>();
gridView = (GridView) rootView.findViewById(R.id.gridView1);
new LoadData().execute(url);
//scrolling portion
gridView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view,
int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (mLoading) {
if (totalItemCount > mPreviousTotal) {
mLoading = false;
mPreviousTotal = totalItemCount;
mCurrentPage++;
if (mCurrentPage + 1 > 50) {
mLastPage = true;
}
}
}
if (!mLastPage
&& !mLoading
&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + mVisibleThreshold)) {
//new asynctask called
new LoadData()
.execute("http://-------/---------");
mLoading = true;
}
}
#Override
public void onScrollStateChanged(AbsListView view,
int scrollState) {
}
});
return rootView;
}
//my asynctask
private class LoadData extends AsyncTask<String,
Void, Void> {
#Override
protected void onPostExecute(Void result) {
tp.dismiss();
adap = new Grid_View_Adatper(getActivity().getApplicationContext(),
arrayList);
gridView.setAdapter(adap);
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
tp = new TransparentProgressDialog(getActivity(),
R.drawable.spinner);
tp.setCancelable(false);
tp.setCanceledOnTouchOutside(false);
tp.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... urls) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(urls[0]);
HttpResponse response = client.execute(httpget);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray json = new JSONArray(data);
for (int i = 0; i < json.length(); i++) {
JSONObject e = json.getJSONObject(i);
String name = e.getString("name");
String price = e.getString("price");
String image = e.getString("image");
String code = e.getString("sku");
tems = new Items(name, price, image, code);
arrayList.add(tems);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
} catch (IOException e) {
} catch (RuntimeException e) {
}
return null;
}
}
Please help someone.
Thanks in advane.
The problem is you instantiate adapter over and over again. Instead check your adapter first, if it is not null, then set your data, then notify dataset changes.
if (adapter == null) {
adapter = new GridViewAdapter...
gridView.setAdapter(adapter)
}
// list refers the list inside in your adapter
list.addAll(newList); // or do your implementation
adapter.notifyDataSetChanged();

I am not able to get the gridview populated with textview in Android Fragment

i am not able to populate the imageview textview inside gridview using fragments.
It is showing blank intead of gridview populating in my project can please anyone see the code below and let me know what i have to change
And the populating the image and text is from the mysql database dynamically
public class StoreHomeFragment extends Fragment {
final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.store_home, container, false);
final GridView gridView1 = (GridView)rootView.findViewById(R.id.store_home_gridview);
gridView1.setAdapter(new ImageAdapter(rootView.getContext(), MyArrList));
return rootView;
}
//Activity is created
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String url = "http://192.168.1.132/Android/App/good.php"; //url where i am using select query and retrieving it from database
try {
JSONArray data = new JSONArray(getJSONUrl(url));
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);//retrieving from db
map = new HashMap<String, String>();
map.put("name", c.getString("name"));
map.put("artist", c.getString("artist"));
map.put("price", c.getString("price"));
map.put("image", c.getString("image"));
MyArrList.add(map);
}
//gridView1.setAdapter(new ImageAdapter(this,MyArrList));
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//I have used imageAdapter
class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageView imageView;
private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();
public ImageAdapter(Context c,ArrayList<HashMap<String, String>> list)
{
context = c;
MyArr = list;
}
public int getCount() {
return MyArr.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.store_home_gridview_row, null);
}
TextView tv_title = (TextView) convertView.findViewById(R.id.textview_name);
tv_title.setText("Title:"+MyArr.get(position).get("name"));
TextView tv_artist = (TextView) convertView.findViewById(R.id.textview_artist);
tv_artist.setText("Artist:"+MyArr.get(position).get("artist"));
TextView tv_duration = (TextView) convertView.findViewById(R.id.textview_price);
tv_duration.setText("Price:"+MyArr.get(position).get("price"));
String abc = (MyArr.get(position).get("image"));
String abcd = "http://192.168.1.132/images/products/"+abc;
imageView = (ImageView) convertView.findViewById(R.id.imageView1);
try
{
URL url3 = null;
try {
url3 = new URL(abcd);
} catch (Exception e) {
e.printStackTrace();
}
Bitmap bmp = BitmapFactory.decodeStream(url3.openConnection().getInputStream()); //image is populated
imageView.setImageBitmap(bmp);
}
catch(Exception par)
{
imageView.setImageResource(android.R.drawable.ic_menu_report_image);
}
return convertView;
}
}
/*** Get JSON Code from URL ***/
public String getJSONUrl(String url) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try
{
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
System.out.println ( "status Code : " + statusCode );
if (statusCode == 200)
{
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null)
{
str.append(line);
}
}
else
{
Log.e("Log", "Failed to download file..");
}
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println ( "str : " + str.toString() );
return str.toString();
}
}
Follow the steps Hope this helps you
1) Remove these lines from onCreateView() method
final GridView gridView1 = (GridView)rootView.findViewById(R.id.store_home_gridview);
gridView1.setAdapter(new ImageAdapter(rootView.getContext(), MyArrList));
2)Modify onActivityCreated() as follow
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
String url = "http://192.168.1.132/Android/App/good.php";
try {
JSONArray data = new JSONArray(getJSONUrl(url));
HashMap<String, String> map;
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("name", c.getString("name"));
map.put("artist", c.getString("artist"));
map.put("price", c.getString("price"));
map.put("image", c.getString("image"));
MyArrList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
final GridView gridView1 = (GridView) rootView.findViewById(R.id.store_home_gridview);
gridView1.setAdapter(new ImageAdapter(getActivity(), MyArrList));
}
}.execute();
}

Categories