Why My Recyclerview Isn't Working In An Acticvity - java

I need to parse json and show them on RecyclerView.. But my RecyclerView isn't working..
I need to fix this..
This is Json
Simple Json File for My app
[
{
"name": "Saif Maroof",
"roll": 978617,
"gender":"Male",
"phonenumber": 01931078639,
"StudentImage": "R.drawble.books"
},
{
"name": "Minhaj",
"roll": 978617,
"gender":"Male",
"phonenumber": 01931078639,
"studentimage": "R.drawble.books"
}
]
This is StudentInfo Activity
I think in this activity nothing gets wrong
package com.college.npc17_18.activity;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import com.college.npc17_18.MainActivity;
import com.college.npc17_18.R;
import com.college.npc17_18.adapter.StudentInfoAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class StudentInfo extends AppCompatActivity {
RecyclerView recyclerView;
StudentInfoAdapter studentInfoAdapter;
RecyclerView.Adapter adapter;
// ProgressBar progressBar;
RecyclerView.LayoutManager layoutManager;
List <Object> studentInfo = new ArrayList<>();
DividerItemDecoration dividerItemDecoration;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_info);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// progressBar = findViewById(R.id.progress_circular_country);
recyclerView = findViewById(R.id.studentsInfoRecycleView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
adapter = new StudentInfoAdapter(this,studentInfo);
// String jsonFileString = Utils.getJsonFromAssets(getApplicationContext(), "studentinfo.json");
// progressBar.setVisibility(View.GONE);
// studentInfoAdapter = new StudentInfoAdapter(this,studentInfo);
recyclerView.setAdapter(adapter);
addItemsFromJSON();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
private void addItemsFromJSON() {
try {
String jsonDataString = readJSONDataFromFile();
JSONArray jsonArray = new JSONArray(jsonDataString);
for (int i=0; i<jsonArray.length(); ++i) {
JSONObject itemObj = jsonArray.getJSONObject(i);
String name = itemObj.getString("name");
String roll = itemObj.getString ("roll");
String phonenumber = itemObj.getString("phonenumber");
String gender = itemObj.getString("gender");
int studentimage = itemObj.getInt("studentimage");
com.college.npc17_18.model.StudentInfo studentInfos = new com.college.npc17_18.model.StudentInfo(name,roll,phonenumber,gender,studentimage);
studentInfo.add(studentInfos);
}
} catch (JSONException | IOException e) {
Log.d(TAG, "addItemsFromJSON: ", e);
}
}
private String readJSONDataFromFile() throws IOException{
InputStream inputStream = null;
StringBuilder builder = new StringBuilder();
try {
String jsonString = null;
inputStream = getResources().openRawResource(R.raw.studentinfo);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"));
while ((jsonString = bufferedReader.readLine()) != null) {
builder.append(jsonString);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
return new String(builder);
}
}
This is StudentInfo Adapter
package com.college.npc17_18.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.college.npc17_18.R;
import com.college.npc17_18.model.StudentInfo;
import java.util.ArrayList;
import java.util.List;
public class StudentInfoAdapter extends RecyclerView.Adapter <StudentInfoAdapter.Viewholder> {
private List <Object> studentInfos;
Context context;
public StudentInfoAdapter(Context context, List<Object> studentInfo) {
this.studentInfos = studentInfo;
this.context = context;
}
#NonNull
#Override
public StudentInfoAdapter.Viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.studentitem,parent,false);
return new Viewholder(view);
}
#Override
public void onBindViewHolder(#NonNull StudentInfoAdapter.Viewholder holder, int position) {
StudentInfo studentInfo = (StudentInfo) studentInfos.get(position);
holder.StudentImageId.setImageResource (studentInfo.getStudentImage());
holder.NameId.setText("Name:"+studentInfo.getNamme());
holder.RollId.setText("Roll"+studentInfo.getRoll());
holder.GenderId.setText("Gender:"+studentInfo.getGender());
holder.PhoneNumberId.setText("Phone Number:"+studentInfo.getPhoneNumber());
}
#Override
public int getItemCount() {
return studentInfos.size();
}
public class Viewholder extends RecyclerView.ViewHolder{
TextView NameId,RollId,PhoneNumberId,GenderId;
ImageView StudentImageId;
public Viewholder(#NonNull View itemView) {
super(itemView);
StudentImageId = itemView.findViewById(R.id.StudentImageId);
NameId = itemView.findViewById(R.id.NameId);
RollId = itemView.findViewById(R.id.RollId);
// CGPAId = itemView.findViewById(R.id.CGPAId);
GenderId = itemView.findViewById(R.id.GenderId);
PhoneNumberId = itemView.findViewById(R.id.PhoneNumberId);
}
}
}
This is StudentItem.xml
Layout for RecyclerView...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:clickable="true"
android:elevation="40dp"
app:cardCornerRadius="5dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/StudentImageId"
android:layout_width="71dp"
android:layout_height="match_parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:orientation="vertical">
<TextView
android:id="#+id/NameId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="18sp" />
<TextView
android:id="#+id/RollId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Roll" />
<TextView
android:id="#+id/GenderId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Gender" />
<TextView
android:id="#+id/PhoneNumberId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Phone Number" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
Now what do I need to do?

At the time when you instantiate an object of your adapter class
adapter = new StudentInfoAdapter(this,studentInfo);
Your adapter object is initialized with an empty studentInfo list
So, you should call adapter.notifyDataSetChanged(); in your addItemsFromJSON() method when the JSON parsing is completed.

update your adapter after you set your data
yourAdapter.notifyDataSerChanged();

Related

ViewPager second fragment is blank

I know that this question has been asked before but none of the solutions worked for me. I have a ViewPager in a TabLayout with fragments for each of the tabs. Now, each of those fragments has a RecyclerView that gets data from the internet and only the first RecyclerView is populated. I can't figure out how I'm messing up. I know it's just because I'm not using it right but I can't really figure out how. I'd really appreciate some help.
It looks like this where the second tab is just empty:
Here's my code:
Code
MainActivity.java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.Style;
public class MainActivity extends AppCompatActivity {
private MapView mapView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Mapbox Access token
Mapbox.getInstance(getApplicationContext(), getString(R.string.mapbox_api_key));
setContentView(R.layout.activity_main);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(mapboxMap -> mapboxMap.setStyle(Style.DARK, style -> {
}));
ViewPager2 pager = findViewById(R.id.view_pager);
ViewPageAdapter pageAdapter = new ViewPageAdapter(getSupportFragmentManager(), getLifecycle());
pager.setAdapter(pageAdapter);
pager.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
TabLayout tabLayout = findViewById(R.id.tabLayout2);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
new StatsLoader("https://api.covid19api.com/summary", pageAdapter, pager, tabLayout).execute();
new NewsLoader("https://newsapi.org/v2/top-headlines?q=coronavirus&sortBy=popularity", pageAdapter, pager, tabLayout).execute();
}
}
SortJSONArray.java
import android.util.Log;
import org.json.JSONObject;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class SortJsonArray {
void sortArray(List list, final String keyName, final boolean ascending) {
Collections.sort(list, new Comparator<JSONObject>() {
private final String KEY_NAME = keyName;
#Override
public int compare(JSONObject o1, JSONObject o2) {
String val1 = "";
String val2 = "";
try {
val1 = String.valueOf(o1.get(KEY_NAME));
val2 = String.valueOf(o2.get(KEY_NAME));
} catch (Exception e) {
Log.e("Sort Exception", "Issue when sorting JSONArray", e);
e.printStackTrace();
}
if (IntCheckHelper.isInteger(val1)) {
if (ascending) {
return Integer.valueOf(val1).compareTo(Integer.valueOf(val2));
}
else {
return Integer.valueOf(val2).compareTo(Integer.valueOf(val1));
}
}
else {
if (ascending) {
return val1.compareToIgnoreCase(val2);
}
else {
return val2.compareToIgnoreCase(val1);
}
}
}
});
}
}
StatsFragment.java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import org.json.JSONArray;
public class StatsFragment extends Fragment {
View view;
RecyclerView recyclerView;
JSONArray covidData;
String dataUrl;
public StatsFragment(JSONArray data, String url) {
covidData = data;
dataUrl = url;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.view_page, container, false);
recyclerView = view.findViewById(R.id.recyclerView2);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(false);
RecyclerView.Adapter<CustomListAdapter.ListViewHolder> mAdapter = new CustomListAdapter(covidData, dataUrl);
recyclerView.setAdapter(mAdapter);
return view;
}
}
CustomListAdapter.java
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import org.json.JSONArray;
import org.json.JSONException;
import java.text.NumberFormat;
public class CustomListAdapter extends RecyclerView.Adapter<CustomListAdapter.ListViewHolder> {
private JSONArray mDataset;
private String murl;
static class ListViewHolder extends RecyclerView.ViewHolder {
TextView textView;
TextView textView2;
ImageView imageView;
ListViewHolder(LinearLayout v) {
super(v);
textView = v.findViewById(R.id.name);
textView2 = v.findViewById(R.id.cases);
imageView = v.findViewById(R.id.image);
}
}
CustomListAdapter(JSONArray myDataset, String url) {
mDataset = myDataset;
murl = url;
}
#NonNull
#Override
public CustomListAdapter.ListViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
LinearLayout linearLayout = (LinearLayout) LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_view, parent, false);
// TextView v = (TextView) linearLayout.findViewById(R.id.info_text);
return new ListViewHolder(linearLayout);
}
#Override
public void onBindViewHolder(ListViewHolder holder, int position) {
String textViewString = "";
String textView2String = "";
try {
if (murl.contains("api.covid19api.com")) {
textViewString = mDataset.getJSONObject(position).getString("Country");
textView2String = NumberFormat.getInstance().format(mDataset.getJSONObject(position).getInt("TotalConfirmed"));
}
else if (murl.contains("newsapi.org")) {
textViewString = mDataset.getJSONObject(position).getString("title");
textView2String = mDataset.getJSONObject(position).getString("description");
}
holder.textView.setText(textViewString);
holder.textView2.setText(textView2String);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return mDataset.length();
}
}
StatsLoader.java
import android.os.AsyncTask;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.viewpager2.widget.ViewPager2;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import javax.net.ssl.HttpsURLConnection;
public class StatsLoader extends AsyncTask<String, Void, JSONArray> {
Exception exception;
String urlString = "";
static JSONArray covidData = new JSONArray();
ViewPageAdapter pageAdapter;
ViewPager2 viewPager2;
TabLayout tabLayout;
public StatsLoader(String url, ViewPageAdapter adapter, ViewPager2 pager, TabLayout tabs) {
super();
urlString = url;
pageAdapter = adapter;
viewPager2 = pager;
tabLayout = tabs;
}
#Nullable
#Override
public JSONArray doInBackground(String ... urls) {
HttpsURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(urlString);
connection = (HttpsURLConnection) url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder buffer = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
JSONObject json = new JSONObject(buffer.toString());
covidData = json.getJSONArray("Countries");
ArrayList<Object> list = new ArrayList<>();
for (int i = 0; i < covidData.length(); i++) {
list.add(covidData.get(i));
}
SortJsonArray sortJsonArray = new SortJsonArray();
sortJsonArray.sortArray(list, "TotalConfirmed", false);
covidData = new JSONArray();
for (Object object : list) {
covidData.put(object);
}
return covidData;
} 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;
}
protected void onPostExecute(JSONArray coviddata) {
if (this.exception == null) {
Log.d("Check", "Works!");
pageAdapter.addFragment(new StatsFragment(coviddata, urlString), "Stats");
viewPager2.setAdapter(pageAdapter);
new TabLayoutMediator(tabLayout, viewPager2,
(tab, position) -> {
switch (position) {
case 0:
tab.setText("Stats");
break;
case 1:
tab.setText("News");
break;
case 2:
tab.setText("Symptoms");
break;
case 3:
tab.setText("Safety");
break;
default:
break;
}
}).attach();
}
}
}
ViewPageAdapter.java
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import java.util.ArrayList;
public class ViewPageAdapter extends FragmentStateAdapter {
private final ArrayList<Fragment> fragments = new ArrayList<>();
private final ArrayList<String> titles = new ArrayList<>();
public ViewPageAdapter(#NonNull FragmentManager fragmentManager, #NonNull Lifecycle lifecycle) {
super(fragmentManager, lifecycle);
}
public void addFragment(Fragment fragment, String title) {
fragments.add(fragment);
titles.add(title);
}
#NonNull
#Override
public Fragment createFragment(int position) {
return fragments.get(position);
}
#Override
public int getItemCount() {
return fragments.size();
}
}
NewsFragment.java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import org.json.JSONArray;
public class NewsFragment extends Fragment {
View view;
RecyclerView recyclerView;
JSONArray news;
String newsUrl;
public NewsFragment(JSONArray data, String url) {
news = data;
newsUrl = url;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.view_page, container, false);
recyclerView = view.findViewById(R.id.recyclerView2);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(false);
RecyclerView.Adapter<CustomListAdapter.ListViewHolder> mAdapter = new CustomListAdapter(news, newsUrl);
recyclerView.setAdapter(mAdapter);
return view;
}
}
NewsLoader.java
import android.os.AsyncTask;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.viewpager2.widget.ViewPager2;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class NewsLoader extends AsyncTask<String, Void, JSONArray> {
Exception exception;
String urlString = "";
static JSONArray news = new JSONArray();
ViewPageAdapter pageAdapter;
ViewPager2 viewPager2;
TabLayout tabLayout;
public NewsLoader(String url, ViewPageAdapter adapter, ViewPager2 pager, TabLayout tabs) {
super();
urlString = url;
pageAdapter = adapter;
viewPager2 = pager;
tabLayout = tabs;
}
#Nullable
#Override
public JSONArray doInBackground(String ... urls) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(urlString);
connection = (HttpsURLConnection) url.openConnection();
connection.addRequestProperty("Authorization", "Bearer baef544b7dbe4ff8b15bb502d1fd5e1a");
connection.connect();
InputStream inputStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder buffer = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
JSONObject json = new JSONObject(buffer.toString());
news = json.getJSONArray("articles");
return news;
} 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;
}
protected void onPostExecute(JSONArray newsData) {
if (this.exception == null) {
Log.d("Check", "Works!");
pageAdapter.addFragment(new NewsFragment(newsData, urlString), "News");
viewPager2.setAdapter(pageAdapter);
new TabLayoutMediator(tabLayout, viewPager2,
(tab, position) -> {
switch (position) {
case 0:
tab.setText("Stats");
break;
case 1:
tab.setText("News");
break;
case 2:
tab.setText("Symptoms");
break;
case 3:
tab.setText("Safety");
break;
default:
break;
}
}).attach();
}
}
}
Layouts
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:statusBarScrim="#null"
app:titleEnabled="false"
android:minHeight="?attr/actionBarSize" >
<fragment
android:id="#+id/mapView"
android:name="com.mapbox.mapboxsdk.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="350sp"
android:apiKey="#string/mapbox_api_key"
android:clickable="true"
android:enabled="true"
android:focusable="true"
app:layout_collapseMode="parallax" />
<androidx.appcompat.widget.Toolbar
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginBottom="48dp"
android:gravity="top"
app:layout_collapseMode="pin"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:popupTheme="#style/ThemeOverlay.AppCompat.Dark"
app:title="" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="parent">
</com.google.android.material.tabs.TabLayout>
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="parent"
tools:listitem="#layout/view_page" >
</androidx.viewpager2.widget.ViewPager2>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
list_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.cardview.widget.CardView
android:id="#+id/card_view"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="14sp"
android:layout_margin="15sp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="40sp">
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/name"
android:layout_toStartOf="#+id/name"
android:contentDescription="Image of country flag" />
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10sp" />
<TextView
android:id="#+id/cases"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/name" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
view_page.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView2"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="parent"
tools:listitem="#layout/list_view">
</androidx.recyclerview.widget.RecyclerView>
</androidx.constraintlayout.widget.ConstraintLayout>
API Key
pk.eyJ1IjoiZGF5ZW1zYWVlZCIsImEiOiJja2E2d3FyZTYwZHh5MnptdzFjcXMycTRxIn0.hpzQHB9-_OTMC1iGkkvYpw
The issue is with the NewsFragment and NewsLoader section of the code since that's the one not showing up. I added the rest for context in case anyone needs it. Thank you!
Edit: Added the SortJSONArray code and API key as per the comment suggestion.
just fix your layout...data is there only
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView2"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:listitem="#layout/list_view">
</androidx.recyclerview.widget.RecyclerView>
remove:
app:layout_constraintTop_toBottomOf="parent"

How do I retrieve the ID number of this text view

How do I retrieve the text of a specific textView? BEcause when I click an ID number it displays '1' in the textview of the next class in every text view I click. I used JSON array so it's kind of tricky for me. And yes I'm completely a beginner.
DisplayListView
package rjj.tutorial_jsonandlistview;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class DisplayListView extends AppCompatActivity {
String json_string;
JSONObject jsonObject;
JSONArray jsonArray;
ContactAdapter contactAdapter;
ListView listView;
SearchView sv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_listview_layout);
listView = (ListView)findViewById(R.id.listview);
contactAdapter = new ContactAdapter(this,R.layout.row_layout);
listView.setAdapter(contactAdapter);
json_string = getIntent().getExtras().getString("json_data");
//Searchview
sv = (SearchView)findViewById(R.id.search);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
contactAdapter.getFilter().filter(newText);
return true;
}
});
//End of Searchview
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String id ,firstname , surname, age , username, password;
while(count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
id = JO.getString("id");
firstname = JO.getString("firstname");
surname = JO.getString("surname");
age = JO.getString("age");
username = JO.getString("username");
password = JO.getString("password");
Contacts contact = new Contacts(id, firstname, surname, age,username,password);
contactAdapter.add(contact);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void hello(View view) {
Intent intent = new Intent(this, Update.class);
TextView textView = (TextView)findViewById(R.id.tx_id);
String id = textView.getText().toString();
intent.putExtra("id", id);
startActivity(intent);
}
}
My ContactAdapter Class:
package rjj.tutorial_jsonandlistview;
import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Julian on 7/20/2017.
*/
public class ContactAdapter extends ArrayAdapter {
List list = new ArrayList();
public ContactAdapter(#NonNull Context context, #LayoutRes int resource) {
super(context, resource);
}
public void add(Contacts object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Nullable
#Override
public Object getItem(int position) {
return list.get(position);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View row;
row = convertView;
ContactHolder contactHolder;
if(row == null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
contactHolder = new ContactHolder();
contactHolder.tx_id = (TextView)row.findViewById(R.id.tx_id);
contactHolder.tx_firstname = (TextView)row.findViewById(R.id.tx_firstname);
contactHolder.tx_surname = (TextView)row.findViewById(R.id.tx_surname);
contactHolder.tx_age = (TextView)row.findViewById(R.id.tx_age);
contactHolder.tx_username = (TextView)row.findViewById(R.id.tx_username);
contactHolder.tx_password = (TextView)row.findViewById(R.id.tx_password);
row.setTag(contactHolder);
} else{
contactHolder = (ContactHolder)row.getTag();
}
Contacts contacts = (Contacts)this.getItem(position);
contactHolder.tx_id.setText(contacts.getId());
contactHolder.tx_firstname.setText(contacts.getFirstname());
contactHolder.tx_surname.setText(contacts.getSurname());
contactHolder.tx_age.setText(contacts.getAge());
contactHolder.tx_username.setText(contacts.getUsername());
contactHolder.tx_password.setText(contacts.getPassword());
return row;
}
static class ContactHolder{
TextView tx_id, tx_firstname, tx_surname, tx_age, tx_username, tx_password;
}
}
My Update Class:
package rjj.tutorial_jsonandlistview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class Update extends AppCompatActivity {
String id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
id = getIntent().getExtras().getString("id");
TextView textView = (TextView)findViewById(R.id.textView);
textView.setText(id);
}
}
My display_listview_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<android.widget.RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="rjj.tutorial_jsonandlistview.DisplayListView">
<SearchView
android:layout_width="match_parent"
android:layout_height="30dp"
android:id="#+id/search"
android:queryHint="Search..."/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/search"
android:id="#+id/listview">
</ListView>
</android.widget.RelativeLayout>
The row_layout.xml (which I use to display the JSON array)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="75dp">
<TextView
android:layout_width="60dp"
android:layout_height="match_parent"
android:id="#+id/tx_id"
android:layout_alignParentLeft="true"
android:text="ID"
android:gravity="center"
android:textAppearance="?android:textAppearanceLarge"
android:onClick="hello"
/>
<TextView
android:layout_width="60dp"
android:layout_height="match_parent"
android:id="#+id/tx_firstname"
android:layout_toRightOf="#+id/tx_id"
android:text="Firstname"
android:gravity="center"
android:textAppearance="?android:textAppearanceLarge"
/>
<TextView
android:layout_width="60dp"
android:layout_height="match_parent"
android:id="#+id/tx_surname"
android:layout_toRightOf="#+id/tx_firstname"
android:text="Lastname"
android:gravity="center"
android:textAppearance="?android:textAppearanceLarge"
/>
<TextView
android:layout_width="60dp"
android:layout_height="match_parent"
android:id="#+id/tx_age"
android:layout_toRightOf="#+id/tx_surname"
android:text="Age"
android:gravity="center"
android:textAppearance="?android:textAppearanceLarge"
/>
<TextView
android:layout_width="60dp"
android:layout_height="match_parent"
android:id="#+id/tx_username"
android:layout_toRightOf="#+id/tx_age"
android:text="Username"
android:gravity="center"
android:textAppearance="?android:textAppearanceLarge"
/>
<TextView
android:layout_width="60dp"
android:layout_height="match_parent"
android:id="#+id/tx_password"
android:layout_toRightOf="#+id/tx_username"
android:text="Password"
android:gravity="center"
android:textAppearance="?android:textAppearanceLarge"
/>
</RelativeLayout>
In method hello(View view) you don't need this string:
TextView textView = (TextView)findViewById(R.id.tx_id);
becouse the view in hello(View view) this is our TextView. Just cast it to TextView and get text from it:
String id = ((TextView)view).getText().toString();
Another and most universal approach: to change
TextView textView = (TextView)findViewById(R.id.tx_id);
to
TextView textView = (TextView)((ViewGroup)(view.getParent())).findViewById(R.id.tx_id);
In this way you can use any R.id for current list item.

Custom GridView doesn't display data

I am trying to feed my custom GridView with data fetched from Facebook Graph API. This data is a list of Album objects containing the picture for the album of the current user and the name of the album.
Fetching data doesn't represent a problem since I can see it in the LOGCAT.
What seems to be a problem is my GridView Adapter I suppose, the program doesn't give any particular error and this makes me confused.
Note that the MainActivity which will not be displayed here serves only to connect a user via Facebook account (there is no problem in this Activity)
Here is my different classes :
----LoggedInActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class LoggedInActivity extends Activity {
String name, surname, ID;
TextView nameOfUser;
Button logout;
GridView gridView;
GridViewAdapter gridViewAdapter;
List<Album> albumList = new ArrayList<Album>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle inBundle = getIntent().getExtras();
name = inBundle.getString("name");
surname = inBundle.getString("surname");
ID = inBundle.getString("ID");
setContentView(R.layout.activity_logged_in);
nameOfUser = (TextView) findViewById(R.id.name);
nameOfUser.setText(name + " " + surname);
logout = (Button) findViewById(R.id.logout);
gridView = (GridView) findViewById(R.id.myGridView);
albumList = getAlbums();
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginManager.getInstance().logOut();
Intent login = new Intent(LoggedInActivity.this, MainActivity.class);
startActivity(login);
finish();
}
});
gridViewAdapter = new GridViewAdapter(getBaseContext(), albumList);
gridView.setAdapter(gridViewAdapter);
}
public List<Album> getAlbums() {
albumList = new ArrayList<Album>();
GraphRequest request = GraphRequest.newGraphPathRequest(
AccessToken.getCurrentAccessToken(),
"/me/albums",
new GraphRequest.Callback() {
Album album = null;
#Override
public void onCompleted(GraphResponse response) {
JSONObject jsonDATA = response.getJSONObject();
JSONArray data = jsonDATA.optJSONArray("data");
for(int i = 0 ; i< data.length(); i++){
try {
JSONObject e = data.getJSONObject(i);
String name = e.optString("name");
JSONObject picture = e.getJSONObject("picture");
JSONObject dataOfPicture = picture.getJSONObject("data");
String url = dataOfPicture.optString("url");
album = new Album(name, url);
albumList.add(album);
Log.d("Mine",name + url);
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "Problem with JSON parsing", Toast.LENGTH_SHORT).show();
}
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "picture,name");
request.setParameters(parameters);
request.executeAsync();
return albumList;
}
}
------Album.java
public class Album {
public String album_name;
public String album_image;
public Album(String album_name, String album_image) {
this.album_name = album_name;
this.album_image = album_image;
}
public String getAlbum_name() {
return album_name;
}
public String getAlbum_image() {
return album_image;
}
public void setAlbum_name(String album_name) {
this.album_name = album_name;
}
public void setAlbum_image(String album_image) {
this.album_image = album_image;
}
}
-----GridViewAdapter.java
import android.content.Context;
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.net.URL;
import java.util.List;
public class GridViewAdapter extends BaseAdapter {
private List<Album> albumList;
private Context context;
public GridViewAdapter(#NonNull Context context, #NonNull List<Album> objects) {
this.albumList = objects;
this.context = context;
}
#Override
public int getCount() {
return albumList.size();
}
#Nullable
#Override
public Album getItem(int position) {
return albumList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View v = convertView;
if(v==null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.item,null);
}
Album album = getItem(position);
ImageView imageView = (ImageView)v.findViewById(R.id.imageHolder);
TextView description = (TextView)v.findViewById(R.id.albumDesc);
try {
imageView.setImageBitmap(BitmapFactory.decodeStream((new URL(album.getAlbum_image())).openConnection().getInputStream()));
} catch (IOException e) {
Toast.makeText(context, "Problem with input output streams", Toast.LENGTH_SHORT).show();
}
description.setText(album.getAlbum_name());
return v;
}
}
------item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageHolder"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentTop="true"
android:layout_gravity="center"
android:layout_weight="1"
app:srcCompat="#drawable/com_facebook_profile_picture_blank_square" />
<TextView
android:layout_width="wrap_content"
android:text="photo"
android:textSize="15sp"
android:id="#+id/albumDesc"
android:layout_below="#+id/imageHolder"
android:layout_marginLeft="20dp"
android:layout_height="wrap_content" />
</RelativeLayout>
------Activity_logged_in.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="ichou.facebooktest.LoggedInActivity">
<LinearLayout
android:id="#+id/intro"
android:layout_width="368dp"
android:layout_height="40dp"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:paddingTop="2dp"
android:paddingBottom="2dp"
android:orientation="horizontal">
<TextView
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_marginTop="0dp"
android:paddingTop="10dp"
android:text="username"
android:id="#+id/name"/>
<Button
android:layout_width="70dp"
android:layout_height="35dp"
android:text="logout"
android:id="#+id/logout"/>
</LinearLayout>
<GridView
android:layout_below="#+id/intro"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/myGridView"
android:layout_marginTop="10dp"
android:paddingTop="2dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:numColumns="2"
android:columnWidth="150dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
/>
</RelativeLayout>
write your code like in adapter below...
you do wrong line in inflate layout in getView() method
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View v = convertView;
if(v==null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.item,convertView, false);
}
Album album = getItem(position);
ImageView imageView = (ImageView)v.findViewById(R.id.imageHolder);
TextView description = (TextView)v.findViewById(R.id.albumDesc);
try {
imageView.setImageBitmap(BitmapFactory.decodeStream((new URL(album.getAlbum_image())).openConnection().getInputStream()));
} catch (IOException e) {
Toast.makeText(context, "Problem with input output streams", Toast.LENGTH_SHORT).show();
}
description.setText(album.getAlbum_name());
return v;
}

RecyclerView onCreateViewHolder not being called

i want to add data inside RecyclerView.After done compiled, RecyclerView not showed inside virtual mobile.When i check again,onCreateViewHolder is not being called.Hope you guys can help me solve this problem.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.user.mycustomvolley.MainActivity">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="#+id/recyclerview"
>
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
row_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:background="#BBDEFB"
>
<com.android.volley.toolbox.NetworkImageView
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignParentLeft="true"
android:layout_margin="8dp"
android:id="#+id/networkImage"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textName"
android:text="#string/title"
android:layout_toRightOf="#+id/networkImage"
android:padding="8dp"
android:textColor="#color/colorText"
android:textSize="18dp"
android:textStyle="bold"/>
</RelativeLayout>
MainActivity.java
package com.example.user.mycustomvolley;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<ArtInformation> arrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
BackgroundTask backgroundTask = new BackgroundTask(MainActivity.this);
arrayList = backgroundTask.getArrayList();
adapter = new RecyclerAdapter(arrayList,this);
recyclerView.setAdapter(adapter);
}
}
BackgroundTask.java
package com.example.user.mycustomvolley;
import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by User on 9/17/2016.
*/
public class BackgroundTask {
Context context;
ArrayList<ArtInformation> arrayList = new ArrayList<>();
private static final String json_url = "http://192.168.1.7/volley/imagetext/getData.php";
public BackgroundTask(Context context){
this.context = context;
}
public ArrayList<ArtInformation> getArrayList(){
//make json request.
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST,json_url,(String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
int count = 0;
while (count < response.length()) {
try{
JSONObject jsonObject = response.getJSONObject(count);
String artTemp = jsonObject.getString("art");
String imageTemp = jsonObject.getString("image");
ArtInformation artInformation = new ArtInformation(artTemp,imageTemp);
arrayList.add(artInformation);
count++;
}catch (JSONException ex){
ex.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,"Error:[JSON Process",Toast.LENGTH_LONG).show();
//progressDialog.hide();
error.printStackTrace();
}
});
MySingleton.getmInstances(context).addToRequestQueue(jsonArrayRequest);
return arrayList;
}
}
RecyclerAdapter.java
package com.example.user.mycustomvolley;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by User on 9/17/2016.
*/
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
ArrayList<ArtInformation> arrayList = new ArrayList<>();
Context context;
private ImageLoader imageLoader;
public RecyclerAdapter(ArrayList<ArtInformation> list, Context context){
super();
this.arrayList = list;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.d("","call onCreateViewHolder");
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_list,parent,false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
ArtInformation artInformation = arrayList.get(position);
// Log.d("Check:","art:"+artInformation.getArt_name()+" / path:"+artInformation.getImage_path());
imageLoader = MySingleton.getmInstances(context).getImageLoader();
imageLoader.get(artInformation.getImage_path(), ImageLoader.getImageListener(holder.image, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert));
holder.image.setImageUrl(artInformation.getImage_path(),imageLoader);
holder.artName.setText(artInformation.getArt_name());
}
#Override
public int getItemCount() {
return arrayList.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView artName;
NetworkImageView image;
public MyViewHolder(View itemView){
super(itemView);
artName = (TextView) itemView.findViewById(R.id.textName);
image = (NetworkImageView) itemView.findViewById(R.id.networkImage);
}
}
}
If getItemCount method returns 0 i.e arrayList.size() == 0 then RecyclerView never tries to instantiate a view.

Android ListView TextView

I've been struggling to get a listview to display correctly.
To clarify, I need a scrollview above the listview which is why I haven't extended a listfragment.
I need title and description to be separate elements. I can see how I have put them into a class so I think I'm half way there. If someone could help me out that would be great.
PhotosFragment.java
package info.androidhive.slidingmenu;
import android.app.Fragment;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PhotosFragment extends Fragment {
ListView list;
TextView pm;
TextView sp;
ArrayList<HashMap<String, String>> mlist = new ArrayList<HashMap<String,String>>();
private static final String TAG_APPLE = "Apple";
private static final String TAG_PHONEMODEL = "PhoneModel";
private static final String TAG_SPECS = "specs";
JSONArray model = null;
public PhotosFragment(){}
ListView mListView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_photos, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
mListView = (ListView) getView().findViewById(R.id.mListView);
new RequestTask().execute("http://www.horwichadvertiser.co.uk/app/index.php?Type=8&catid=7&userid=4");
}
private static final String TAG = MainActivity.class.getSimpleName();
JSONObject obj;
JSONArray stories;
public class RequestTask extends AsyncTask<String, String, String> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pm = (TextView)getView().findViewById(R.id.phonemodel);
sp = (TextView)getView().findViewById(R.id.specification);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
//Log.d(TAG, responseString);
} else {
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
// Log.d(TAG, String.valueOf(e));
} catch (IOException e) {
//TODO Handle problems..
// Log.d(TAG, String.valueOf(e));
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
super.onPostExecute(result);
//Log.e(TAG, result);
try {
obj = new JSONObject(result);
stories = obj.getJSONArray("stories");
// initialize the items list
List<ListViewItem> mItems = new ArrayList<ListViewItem>();
for (int i = 0; i < stories.length(); i++) {
JSONObject storyObj = stories.getJSONObject(i);
if (!storyObj.has("Advert")) {
newsStories newsStories = new newsStories();
newsStories.setTitle(storyObj.getString("subject"));
newsStories.setBody(storyObj.getString("body"));
mItems.add(new ListViewItem(newsStories.getTitle(), newsStories.getBody(), ""));
}
else {
newsStories newsStories = new newsStories();
newsStories.setThumbnailUrl(storyObj.getString("Advert"));
mItems.add(new ListViewItem("", "", newsStories.getThumbnailUrl()));
}
}
ArrayAdapter<ListViewItem> adapter = new ArrayAdapter<ListViewItem>(getActivity(), android.R.layout.simple_list_item_1, mItems);
mListView.setTextFilterEnabled(true);
// ArrayAdapter<ListViewItem> adapter = new ArrayAdapter<ListViewItem>(getActivity(), android.R.layout.two_line_list_item, mItems);
//mListView.setAdapter(adapter);
mListView.setAdapter(adapter);
}
catch (JSONException e) {
e.printStackTrace();
}
}
public class newsStories {
private String name, thumbnailUrl, body;
public String getTitle() {
return name;
}
public void setTitle(String name) {
this.name = name;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body.substring(0, 150);
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
//Check if thumbnail exists, if so take out spaces and replace with -
this.thumbnailUrl = thumbnailUrl;
}
}
}
public class ListViewItem{
public final String title; // the text for the ListView item title
public final String description; // the text for the ListView item description
public final String adUrl;
//public final Drawable image;
public ListViewItem(String title, String description, String Advert_Url) {
if (Advert_Url != null && !Advert_Url.isEmpty()) {
String Advert = "http://www.horwichadvertiser.co.uk/images/horwichadvertiserlogo.png?width=700&height=200";
this.title = "";
this.description = "";
this.adUrl = Advert;
} else {
this.title = title;
this.description = description;
this.adUrl = "";
}
}
#Override
public String toString() {
return this.title + ".\r\n" + Html.fromHtml(this.description);
}
}
}
Fragment_Photos.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="150dp" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button3" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button4" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button5" />
</LinearLayout>
</HorizontalScrollView>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="50dp"
android:id="#+id/relativeLayout">
<TextView
android:id="#+id/body"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="22px" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="13px" />
</RelativeLayout>
<ListView
android:id="#id/mListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_below="#+id/relativeLayout">
</ListView>
</RelativeLayout>
Your resource xml is incorrect.
1.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
android:orientation is used with LinearLayout, not RelativeLayout
2.
<ListView
android:id="#id/mListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_below="#+id/relativeLayout">
</ListView>
Incorrect use of android:layout_below - value should be an existing id: "#id/relativeLayout" (without + after #).
android:id="#id/mListView" incorrectly assigned id. If it is a new ID, then should be android:id="#+id/mListView"
Probably you'd like to use LinearLayouts instead of relative
fill_parent is obsolete until you develop for some API 7. Should be match_parent instead

Categories

Resources