The adapter doesn't show the current element? - java

The adapter shows only one item will JSON has more than that number how can the adapter shows all the JSON elements? i have loader and it is only shows one element and repeat it?
the JSON ger elements doesn't show in the adapter I tried things but it doesn't work !! how can I show and take every single element from the response.
the image shows the elements
the adapter:
public class shelfsAdapter extends ArrayAdapter < shelfs > {
public shelfsAdapter(MainActivity context, ArrayList < shelfs > objects) {
super(context, 0, objects);
}#
Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItem = convertView;
if (listItem == null) {
listItem = LayoutInflater.from(getContext())
.inflate(R.layout.item, parent, false);
}
shelfs current = getItem(position);
TextView title = (TextView) listItem.findViewById(R.id.title);
title.setText(current.getTitle());
TextView author = (TextView) listItem.findViewById(R.id.author);
author.setText(current.getAuthors());
return listItem;
}
}
the loader:
public class LoaderApp extends AsyncTaskLoader<List<shelfs>> {
private String url;
public LoaderApp( Context context,String mUrl) {
super(context);
url = mUrl;
}
#Override
protected void onStartLoading() {
Log.v("forceload","force close dossseeeeeee!!!");
forceLoad();
}
#Override
public List<shelfs> loadInBackground(){
if(url==null){return null;}
Log.v("get books","get books");
List<shelfs> books = QueryUtils.fetchData(url);
Log.v("get query","get query");
Log.v("equals query","equals"+books.get(0)+""+books.get(2));
// books.add(new shelfs("books","books inback "));
return books;
}
the main Activity:
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<shelfs>> {
private shelfsAdapter adapter;
private static final String url = "https://www.googleapis.com/books/v1/volumes?q={search%20terms}";
private static final int ID=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//final String url1=" https://www.googleapis.com/books/v1/volumes?q=android&maxResults=1\n";
adapter = new shelfsAdapter(this, new ArrayList<shelfs>());
ListView listView = (ListView) findViewById(R.id.list);
Log.v("geturl fine","fine get it");
listView.setAdapter(adapter);
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
// Get details on the currently active default data network
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
// If there is a network connection, fetch data
if (networkInfo != null && networkInfo.isConnected()) {
// Get a reference to the LoaderManager, in order to interact with loaders.
android.app.LoaderManager loaderManager = getLoaderManager();
Log.v("loading ","loader inflater");
// Initialize the loader. Pass in the int ID constant defined above and pass in null for
// the bundle. Pass in this activity for the LoaderCallbacks parameter (which is valid
// because this activity implements the LoaderCallbacks interface).
getSupportLoaderManager().initLoader(ID, null, this);
}}
#NonNull
#Override
public Loader<List<shelfs>> onCreateLoader(int id, #Nullable Bundle args) {
Log.v("get load","get load on create");
Toast.makeText(this,"creat it just!!!",Toast.LENGTH_SHORT).show();
adapter.add(new shelfs("oncreat","loadApp on create loader"));
return new LoaderApp(this,url);
}
#Override
public void onLoadFinished(#NonNull Loader<List<shelfs>> loader, List<shelfs> data) {
if(data != null && !data.isEmpty() )
Log.v("get load","get load on finished");
// adapter.add(new shelfs("onloadfinish","addall??"));
adapter.addAll(data);
adapter.notifyDataSetChanged();
// Log.v("data add","data"+data.get(0)+""+data.get(6));
// Toast.makeText(this,"data",Toast.LENGTH_SHORT).show();
}
#Override
public void onLoaderReset(#NonNull Loader<List<shelfs>> loader) {
Log.v("get load","get load on reset");
adapter.clear();
}
and the json class:
public class QueryUtils {
public QueryUtils(){}
public static List<shelfs> fetchData(String requestUrl) {
if (requestUrl ==null) {return null;}
Log.v("fetchData work!","fetchData work!");
URL uRl=getUrl(requestUrl);
Log.v("geturl work!","geturl work!");
String json=null;
try {
json=makeHttprequest(uRl);
Log.v("makehttp work!","makehttp work!");
}catch (IOException e){Log.v("error fetch","error fetch");}
List<shelfs> makeit=ExtractJsonData(json);
Log.v("extractdata work!","extractdata work!");
return makeit;
}
public static URL getUrl(String urlhttp) {
URL url=null;
try{ url=new URL(urlhttp);}
catch (MalformedURLException e){Log.v("url error","url error",e);}
return url;
}
public static String readStream(InputStream inputStream) throws IOException {
StringBuilder stringBuilder=new StringBuilder();
if(inputStream!=null)
{ InputStreamReader isr=new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader=new BufferedReader(isr);
String line=reader.readLine();
while(line!=null){stringBuilder.append(line);
line=reader.readLine();}}
return stringBuilder.toString();
}
public static String makeHttprequest(URL url)throws IOException{
String jsonResponse="";
InputStream inputStream=null;
HttpURLConnection urlConnection=null;
try {
urlConnection=(HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.connect();
if(urlConnection.getResponseCode()==200)
{inputStream=urlConnection.getInputStream();
jsonResponse=readStream(inputStream);
Log.e("connect error","connect");}}
catch(IOException e){Log.e("connect error","connect error");}
finally{
if(urlConnection!=null){urlConnection.disconnect();}
if(inputStream!=null){inputStream.close();}
}
return jsonResponse; }
public static List<shelfs> ExtractJsonData(String jsonResponse){
List<shelfs> putshelfs=new ArrayList<>();
try {
JSONObject base=new JSONObject(jsonResponse);
JSONArray items=base.getJSONArray("items");
shelfs firstShelfs=new shelfs("","");
for(int i=0;i<items.length();i++)
{
JSONObject index = items.getJSONObject(i);
JSONObject volume=index.getJSONObject("volumeInfo");
String title=volume.getString("title");
JSONArray authors=volume.getJSONArray("authors");
String auth=authors.getString(0);
firstShelfs= new shelfs(title,auth);
putshelfs.add(i,firstShelfs);
Log.v("gggg","net get"+i+auth+title+"dom");}
Log.v("dff","json take");
} catch (JSONException e) {
e.printStackTrace(); }
return putshelfs;}
}

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

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

Can't get custom list adapter to populate listview using asynctask

I'm trying to populate an ArrayList of objects and use those objects to populate a ListView. My Asynctask can get the json data and I can parse it and make the objects I need but my ListView doesn't populate. When I check to see if my ArrayList has any object in it before the adapter runs I can see that it doesn't. I want to know why my ListView isn't populating.
Here's my code: (Sorry if it's messy, some spots I haven't gotten to updating yet)
public class MovieDisplayFragment extends Fragment{
private ArrayList<Movie> movieList = new ArrayList<Movie>();
private MovieAdapter movieAdapter;
ListView listView;
public MovieDisplayFragment(){
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
movieAdapter = new MovieAdapter(getActivity(), movieList);
listView = (ListView) rootView.findViewById(R.id.listview_data);
listView.setAdapter(movieAdapter);
if(movieList.size() > 0) {
Log.e("Hello", "1");
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l){
Movie movie = movieAdapter.getItem(position);
Intent i = new Intent(getActivity(), DetailActivity.class)
.putExtra(Intent.EXTRA_TEXT, "Hello");
startActivity(i);
}
});
return rootView;
}
private void updateMovieData(){
getMovieData movieData = new getMovieData();
movieData.execute();
}
#Override
public void onStart(){
super.onStart();
updateMovieData();
}
public class getMovieData extends AsyncTask<Void, Void, List<Movie>> {
private final String LOG_CAT = getMovieData.class.getSimpleName();
private List<Movie> getMovieData(String movieJsonStr) throws JSONException {
final String MOV_ITEMS = "results";
final String MOV_TITLE = "original_title";
final String MOV_DATE = "release_date";
final String MOV_SYNOPSIS = "overview";
final String MOV_VOTE = "vote_average";
final String MOV_POSTER_URL = "poster_path";
JSONObject movieJson = new JSONObject(movieJsonStr);
JSONArray movieArray = movieJson.getJSONArray(MOV_ITEMS);
Log.e("Hello", "2");
for (int i = 0; i < movieArray.length(); i++) {
JSONObject movie = movieArray.getJSONObject(i);
movieList.add(new Movie(movie.getString(MOV_TITLE), movie.getString(MOV_DATE),
movie.getString(MOV_SYNOPSIS), movie.getString(MOV_VOTE), movie.getString(MOV_POSTER_URL)));
}
return movieList;
}
protected List<Movie> doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String movieJsonStr = null;
try {
final String BASE_URL = "http://api.themoviedb.org/3/genre/10751/movies?api_key=358f3b44734f7e6404f2d01a62d3c176&include_all_movies=true&include_adult=true";
Uri builtUri = Uri.parse(BASE_URL).buildUpon().build();
URL url = new URL(builtUri.toString());
Log.v(LOG_CAT, "Built URI " + builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null){
movieJsonStr = null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while((line = reader.readLine()) != null){
buffer.append(line + "\n");
}
if (buffer.length() == 0){
movieJsonStr = buffer.toString();
}
movieJsonStr = buffer.toString();
Log.v(LOG_CAT, "Movie String: " + movieJsonStr);
} catch (IOException e) {
Log.e("Fragment", "Error", e);
movieJsonStr = null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PlaceholderFragment", "Error closing stream", e);
}
}
}
try {
return getMovieData(movieJsonStr);
} catch (JSONException e) {
Log.e(LOG_CAT, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<Movie> movies){
if(movies != null){
movieAdapter.clear();
for(Movie movieData : movies){
movieAdapter.add(movieData);
}
}
}
}
}
Put these 2 lines inside your onPostExecute() in Async.
movieAdapter = new MovieAdapter(getActivity(), movieList);
listView.setAdapter(movieAdapter);
AsyncTask runs in Background Thread. It gets the data from json after few seconds. But your adapter is called few milli seconds after your fragment is created.
So the data from the Json will not be there when you are setting the adapter.
Calling it in onPostExecute solves this problem as the adatpter is set after Json data is retrieved from the server!
Hope it helps a bit.
You are printing size of movieList (movieList.size()) much before movieList() is getting populated. It will never print "Hello" "1" in debugger. The asynctask will fill data in movieList much later than your movieList.size() check code in OnCreateView()
Anyways, after the below code
for(Movie movieData : movies)
{
movieAdapter.add(movieData);
}
you need to insert this bit:
listView.setAdapter(movieAdapter);
You are populating the adapter but not setting it to your listView in your onPostExecute() in your getMovieData Asynctask.
It looks like on post execute you are clearing the List that your adapter is using to populate the listview, then adding in new items to the list. However, in order to update the view after that happens, you need to call notifyDataSetChanged(); after updating the list
#Override
protected void onPostExecute(List<Movie> movies){
if(movies != null){
movieAdapter.clear();
for(Movie movieData : movies){
movieAdapter.add(movieData);
}
movieAdapter.notifyDataSetChanged();
}
}

Android how can i get value of ArrayList Hashmap in my baseadapter

I have an Activity called Myprofile and a baseAdapter called Myprofile_CustomView on my activity I get Json data which then I convert into a ArrayList with a hashmap and my question is how can I retrieve the values of the hashmap in the baseadapter ?
This is my activity Myprofile
public class Myprofile extends Activity {
String URI_URL;
Integer page;
ProgressBar pb;
ListView mm;
Myprofile_CustomView BA;
ArrayList<HashMap<String,String>> userslist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myprofile);
URI_URL = getResources().getString(R.string.PathUrl) + "/api/myprofile";
page=0;
// Listview for adapter
mm= (ListView)findViewById(R.id.myprofiles);
new Myprofile_Async().execute();
}
public class Myprofile_Async extends AsyncTask<String,String,String> {
HttpURLConnection conn;
URL url;
String result="";
DataOutputStream wr;
int id;
#Override
protected void onPreExecute() {
super.onPreExecute();
pb=(ProgressBar)findViewById(R.id.progressBar);
pb.setVisibility(View.VISIBLE);
id= getIntent().getExtras().getInt("id");
// page Int is used to keep count of scroll events
if(page==0)
{page=1;}
else {page=page+1;}
Toast.makeText(Myprofile.this,""+page,Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(String... params) {
// Gets data from api
BufferedReader reader=null;
String cert="id="+id+"&page="+page;
try{
url = new URL(URI_URL);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.connect();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(cert);
wr.flush();
wr.close();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sBuilder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
sBuilder.append(line + "\n");
}
result = sBuilder.toString();
reader.close();
conn.disconnect();
return result;
}
catch (Exception e)
{
e.printStackTrace();
}
System.err.println("cassies" + result);
return result;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
HashMap<String,String> map= new HashMap<>();
JSONObject jsonn= new JSONObject(result);
JSONArray jArray = jsonn.getJSONArray("myprofile");
JSONObject jobject=null;
JSONArray sss= new JSONArray();
for(int i=0; i < jArray.length(); i++) {
jobject= jArray.getJSONObject(i);
map.put("fullname",jobject.getString("fullname"));
sss.put(jobject);
}
jsonn.put("myprofile", sss);
// Add values to arrayList
userslist.add(map);
// Send information to BaseAdapter
BA= new Myprofile_CustomView(userslist,Myprofile.this);
mm.setAdapter(BA);
} catch (Exception e) {
System.err.println("mpee: " + e.toString());
}
pb.setVisibility(View.INVISIBLE);
}
}
}
this part above I have no issues with my problem is in the BaseAdapter with the ArrayList userList I don't know how to get HashMap keys from it. I am naming the keys because I have other fields that I will eventually do
public class Myprofile_CustomView extends BaseAdapter {
JSONObject names;
Context ctx;
LayoutInflater myiflater;
ArrayList<HashMap<String,String>> usersList;
// Have data come in and do a toast to see changes
public Myprofile_CustomView(ArrayList<HashMap<String,String>> arr, Context c) {
notifyDataSetChanged();
ctx = c;
usersList= arr;
myiflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
try {
JSONArray jaLocalstreams = names.getJSONArray("myprofile");
return jaLocalstreams.length();
} catch (Exception e) {
Toast.makeText(ctx, "Error: Please try again", Toast.LENGTH_LONG).show();
return names.length();
}
}
#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;
MyViewHolder holder=null;
try {
if(row==null) {
LayoutInflater li = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = li.inflate(R.layout.zmyprofile,parent,false);
holder=new MyViewHolder(row);
row.setTag(holder);
}
else
{
holder=(MyViewHolder)row.getTag();
}
// How can I get HashMap value for fullname here so I can set it to to Text
String fullname= usersList
holder.fullname.setText(fullname);
return row;
} catch (Exception e) {
e.printStackTrace();
}
return row;
}
class MyViewHolder{
TextView fullname;
MyViewHolder(View v)
{
fullname= (TextView)v.findViewById(R.id.fullname);
}
}
}
getCount should return the size of your dataset. In your case usersList
public int getCount() {
return usersList == null ? 0 : userLists.size();
}
int getView you want to retrieve the item at position:
HashMap<String, String> item = usersList.get(i);
String fullname = item.get("fullname");
the value of position changes with the scrolling,

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

Categories