How to fix an empty fragment? - java

I am new to Android development, trying to create my own app. It should display a particular YouTube Channel by using the YouTube Data API. I have started with the standard bottom navigation template in Android Studio and used the following project on Github for some start-up help. https://github.com/stressGC/Remake-YouTube-Android
I had to change a few things like the deprecated http call inside the code to keep it running with the new Android APKs. Everything seems fine from my point of view: I can see that the API content looks good and that each title / description / publishdate is placed in the according variables. There is also no error message in the log. When I start the emulator, the app is running fine. But as soon as I switch to the "Dashboard" fragment (where the code is placed), it is empty.
DashboardFragment.java
public class DashboardFragment extends Fragment {
private static String API_KEY = "hidden"; //normaler API key ohne limits, kein oauth
private static String CHANNEL_ID = "hidden";
private static String CHANNEL_GET_URL = "https://www.googleapis.com/youtube/v3/search?part=snippet&order=date&channelId="+CHANNEL_ID+"&maxResults=20&key="+API_KEY+"";
private RecyclerView mList_videos = null;
private VideoPostAdapter adapter = null;
private ArrayList<YouTubeDataModel> mListData = new ArrayList<>();
public DashboardFragment () {
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_dashboard, container, false);
mList_videos = (RecyclerView) view.findViewById(R.id.mList_videos);
initList(mListData);
new RequestYouTubeAPI().execute();
return view;
}
private void initList(ArrayList<YouTubeDataModel> mListData) {
mList_videos.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new VideoPostAdapter(getActivity(), mListData);
mList_videos.setAdapter(adapter);
}
// create asynctask to get data from youtube
private class RequestYouTubeAPI extends AsyncTask<Void, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
URL url = null;
String json = null;
StringBuffer sb = new StringBuffer();
try {
url = new URL(CHANNEL_GET_URL);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
//HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
HttpURLConnection urlConnection = NetCipher.getHttpsURLConnection(url);
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String inputLine = "";
while ((inputLine = br.readLine()) != null) {
sb.append(inputLine);
}
json = sb.toString();
return json;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if(response != null){
try {
JSONObject jsonObject = new JSONObject(response);
Log.e("response", jsonObject.toString());
mListData = parseVideoListFromResponse(jsonObject);
initList(mListData);
//adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
public ArrayList<YouTubeDataModel> parseVideoListFromResponse(JSONObject jsonObject) {
ArrayList<YouTubeDataModel> mList = new ArrayList<>();
if (jsonObject.has("items")) {
try {
JSONArray jsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
if (json.has("id")) {
JSONObject jsonID = json.getJSONObject("id");
String video_id = "";
if (jsonID.has("videoId")) {
video_id = jsonID.getString("videoId");
}
if (jsonID.has("kind")) {
if (jsonID.getString("kind").equals("youtube#video")) {
YouTubeDataModel youtubeObject = new YouTubeDataModel();
JSONObject jsonSnippet = json.getJSONObject("snippet");
String title = jsonSnippet.getString("title");
String description = jsonSnippet.getString("description");
String publishedAt = jsonSnippet.getString("publishedAt");
String thumbnail = jsonSnippet.getJSONObject("thumbnails").getJSONObject("high").getString("url");
youtubeObject.setTitle(title);
youtubeObject.setDescription(description);
youtubeObject.setPublishedAt(publishedAt);
youtubeObject.setThumbnail(thumbnail);
youtubeObject.setVideo_id(video_id);
mList.add(youtubeObject);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return mList;
}
}
VideoPostAdapter.java
public class VideoPostAdapter extends RecyclerView.Adapter<VideoPostAdapter.YouTubePostHolder> {
private ArrayList<YouTubeDataModel> dataSet;
private Context mContext = null;
public VideoPostAdapter(Context mContext, ArrayList<YouTubeDataModel> dataSet) {
this.dataSet = dataSet;
this.mContext = mContext;
}
#NonNull
#Override
public YouTubePostHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.youtube_post_layout,parent,false);
YouTubePostHolder postHolder = new YouTubePostHolder(view);
return postHolder;
}
#Override
public void onBindViewHolder(#NonNull YouTubePostHolder holder, int position) {
// set the views here
TextView textViewTitle = holder.textViewTitle;
TextView textViewDes = holder.textViewDes;
TextView textViewDate = holder.textViewDate;
ImageView ImageThumb = holder.ImageThumb;
YouTubeDataModel object = dataSet.get(position);
textViewTitle.setText(object.getTitle());
textViewDes.setText(object.getDescription());
textViewDate.setText(object.getPublishedAt());
// image will be downloaded from url
}
#Override
public int getItemCount() {
return dataSet.size();
}
public static class YouTubePostHolder extends RecyclerView.ViewHolder{
TextView textViewTitle;
TextView textViewDes;
TextView textViewDate;
ImageView ImageThumb;
public YouTubePostHolder(#NonNull View itemView) {
super(itemView);
this.textViewTitle = (TextView) itemView.findViewById(R.id.textViewTitle);
this.textViewDes = (TextView) itemView.findViewById(R.id.textViewDes);
this.textViewDate = (TextView) itemView.findViewById(R.id.textViewDate);
this.ImageThumb = (ImageView) itemView.findViewById(R.id.ImageThumb);
}
}
}
YouTubeDataModel.java
public class YouTubeDataModel {
private String title = "";
private String description = "";
private String publishedAt = "";
private String thumbnail = "";
public String getVideo_id() {
return video_id;
}
public void setVideo_id(String video_id) {
this.video_id = video_id;
}
private String video_id = "";
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPublishedAt() {
return publishedAt;
}
public void setPublishedAt(String publishedAt) {
this.publishedAt = publishedAt;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
}
youtube_post_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="200dp">
<ImageView
android:id="#+id/ImageThumb"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary"/>
<TextView
android:id="#+id/textViewDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="published at"
android:singleLine="true"
android:layout_alignParentRight="true"
android:layout_margin="5dp"
android:textColor="#android:color/white"
android:textSize="12dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_margin="10dp"
android:orientation="vertical">
<TextView
android:id="#+id/textViewTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="video Title"
android:singleLine="true"
android:textColor="#android:color/white"
android:textSize="22dp"/>
<TextView
android:id="#+id/textViewDes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="video description"
android:singleLine="true"
android:textColor="#android:color/white"
android:textSize="12dp"/>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
fragment_dashboard.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/mList_videos"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Unfortunately I have no idea why the fragment is still empty. And without any error in Android Studio log I really hope you can help me :/

Inside your RequestYouTubeAPI ASyncTask you have this error code:
} catch (IOException e) {
e.printStackTrace();
return null;
}
Then in onPostExecute you have the following:
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if(response != null){
try {
JSONObject jsonObject = new JSONObject(response);
Log.e("response", jsonObject.toString());
mListData = parseVideoListFromResponse(jsonObject);
initList(mListData);
//adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Therefore if you get an error, you return null and if onPostExecute is given a null response it does nothing.
So this one place you could have an error and therefore a blank fragment.
Before you fix this, you can prove this is happening like so:
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if(response == null){
Log.e("TUT", "We did not get a response, not updating the UI.");
} else {
try {
JSONObject jsonObject = new JSONObject(response);
Log.e("response", jsonObject.toString());
mListData = parseVideoListFromResponse(jsonObject);
initList(mListData);
//adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
You can fix this two ways:
in doInBackground change the catch to this:
} catch (IOException e) {
Log.e("TUT", "error", e);
// Change this JSON to match what the parse expects, so you can show an error on the UI
return "{\"yourJson\":\"error!\"}";
}
or onPostExecute:
if(response == null){
List errorList = new ArrayList();
// Change this data model to show an error case to the UI
errorList.add(new YouTubeDataModel("Error");
mListData = errorList;
initList(mListData);
} else {
try {
JSONObject jsonObject = new JSONObject(response);
Log.e("response", jsonObject.toString());
mListData = parseVideoListFromResponse(jsonObject);
initList(mListData);
//adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
Hope that helps, there may be other errors in the code but this is one case that can happen if there is a problem with the API, the Json, the authorization, the internet etc.

Related

RecyclerCardview did not show anything

I am trying to pass the data from a weather api and make it into a recyclerView and cardView, but I have no idea why my activity doesn't show anything and i don't know why is not working.
Here is my code***
DailyWeatherInfo.java
private Daily mDaily;
private RecyclerView recyclerView;
private LinearLayoutManager layoutManager;
private CustomAdapter adapter;
private List<Daily> data_list;
private double latitude;
private double longitude;
public DailyWeatherInfo() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily_weather_info);
recyclerView = findViewById(R.id.recyclerView);
data_list = new ArrayList<>();
load_weather_info(37.8267,-122.4233);
layoutManager = new LinearLayoutManager(this);
adapter = new CustomAdapter(this,data_list);
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
//getForcus(37.8267,-122.4233);
}
private void load_weather_info(final double latitude, final double longitude) {
//this.latitude = latitude;
//this.longitude = longitude;
AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
#Override
protected Void doInBackground(Integer... integers) {
String apiKey = "--------------------------------";
String forecastUrl = "https://api.darksky.net/forecast/" + apiKey +
"/" + latitude + "," + longitude;
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(forecastUrl)
.build();
try {
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i = 0; i<array.length(); i++){
JSONObject jsonObject = array.getJSONObject(i);
JSONObject daily = jsonObject.getJSONObject("daily");
JSONObject mDaily = daily.getJSONObject("data");
Daily daily1 = new Daily(mDaily.getString("summary"), mDaily.getString("icon"),
mDaily.getDouble("precipProbability"), mDaily.getLong("time"));
data_list.add(daily1);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
};
task.execute((int) latitude, (int) longitude);
}
Daily.java
public class Daily {
private String nIcon;
private String nSummary;
private String nTimeZone;
private Long nTimeStamp;
private Double nPrecipPro;
public Daily(String nSummary, String nIcon, double nPrecipPro, long nTimeStamp ){
this.nSummary = nSummary;
this.nIcon = nIcon;
this.nPrecipPro = nPrecipPro;
this.nTimeStamp = nTimeStamp;
}
public String getnTimeZone() {
return nTimeZone;
}
public void setnTimeZone(String nTimeZone) {
this.nTimeZone = nTimeZone;
}
public String getnIcon() {
return nIcon;
}
public int getIconId(){
//clear-day, clear-night, rain, snow, sleet, wind, fog, cloudy, partly-cloudy-day, or partly-cloudy-night
int iconId = R.drawable.clear_day;
if (nIcon.equals("clear-day")){
iconId = R.drawable.clear_day;
}else if (nIcon.equals("clear-night")) {
iconId = R.drawable.clear_night;
}
else if (nIcon.equals("rain")) {
iconId = R.drawable.rain;
}
else if (nIcon.equals("snow")) {
iconId = R.drawable.snow;
}
else if (nIcon.equals("sleet")) {
iconId = R.drawable.sleet;
}
else if (nIcon.equals("wind")) {
iconId = R.drawable.wind;
}
else if (nIcon.equals("fog")) {
iconId = R.drawable.fog;
}
else if (nIcon.equals("cloudy")) {
iconId = R.drawable.cloudy;
}
else if (nIcon.equals("partly-cloudy-day")) {
iconId = R.drawable.partly_cloudy;
}
else if (nIcon.equals("partly-cloudy-night")) {
iconId = R.drawable.cloudy_night;
}
return iconId;
}
public void setnIcon(String nIcon) {
this.nIcon = nIcon;
}
public String getnSummary() {
return nSummary;
}
public void setnSummary(String nSummary) {
this.nSummary = nSummary;
}
public Long getnTimeStamp() {
return nTimeStamp;
}
public String getFormattedTime(){
SimpleDateFormat formatter = new SimpleDateFormat("h:mm a");
formatter.setTimeZone(TimeZone.getTimeZone(getnTimeZone()));
Date dateTime = new Date(getnTimeStamp()*1000);
String timeString = formatter.format(dateTime);
return timeString;
}
public void setnTimeStamp(Long nTimeStamp) {
this.nTimeStamp = nTimeStamp;
}
public Double getnPrecipPro() {
return nPrecipPro;
}
public void setnPrecipPro(Double nPrecipPro) {
this.nPrecipPro = nPrecipPro;
}
}
CustomAdapter.java
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private Context context;
private List<Daily> myDaily;
public CustomAdapter(Context context, List<Daily> myDaily){
this.context = context;
this.myDaily = myDaily;
notifyDataSetChanged();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view,parent,false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.cSummary.setText(myDaily.get(position).getnSummary());
holder.cPrecipProability.setText(myDaily.get(position).getnPrecipPro() + "");
holder.cDate.setText(myDaily.get(position).getFormattedTime());
holder.cImage.setImageResource(myDaily.get(position).getIconId());
}
#Override
public int getItemCount() {
return myDaily.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView cDate;
public ImageView cImage;
public TextView cSummary;
public TextView cPrecipProability;
public ViewHolder(View itemView) {
super(itemView);
cDate = itemView.findViewById(R.id.txtDate);
cSummary = itemView.findViewById(R.id.txtSummary);
cPrecipProability = itemView.findViewById(R.id.txtRainChance);
cImage = itemView.findViewById(R.id.weather_icon);
}
}
}
card_view xml
Is there anything wrong in my xml file?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="100dp">
<ImageView
android:id="#+id/weather_icon"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_marginLeft="12dp"
android:layout_marginTop="15dp" />
<TextView
android:id="#+id/txtDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/weather_icon"
android:layout_marginLeft="18dp"
android:layout_marginStart="18dp"
android:layout_toEndOf="#+id/weather_icon"
android:layout_toRightOf="#+id/weather_icon"
android:text="2018/04/06, Friday"
android:textSize="15dp" />
<TextView
android:id="#+id/txtSummary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtDate"
android:layout_alignStart="#+id/txtDate"
android:layout_centerVertical="true"
android:text="Mostly cloudy throughout the day."
android:textSize="20dp" />
<TextView
android:id="#+id/txtRainChance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/weather_icon"
android:layout_alignLeft="#+id/txtSummary"
android:layout_alignStart="#+id/txtSummary"
android:text="Rain of Chance : 65%" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
You just forgot to setLayoutManager(); to your recyclerView check it
recyclerView.setLayoutManager(layoutManager);
EDIT
Network operation need some time to perform action so better to set your set your adapter after you get data from API
Try this
data_list = new ArrayList<>();
recyclerView = findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
adapter = new CustomAdapter(this,data_list);
recyclerView.setAdapter(adapter);
load_weather_info(37.8267,-122.4233);
Change your load_weather_info method like below code
private void load_weather_info(final double latitude, final double longitude) {
//this.latitude = latitude;
//this.longitude = longitude;
AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
#Override
protected Void doInBackground(Integer... integers) {
String apiKey = "--------------------------------";
String forecastUrl = "https://api.darksky.net/forecast/" + apiKey +
"/" + latitude + "," + longitude;
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(forecastUrl)
.build();
try {
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i = 0; i<array.length(); i++){
JSONObject jsonObject = array.getJSONObject(i);
JSONObject daily = jsonObject.getJSONObject("daily");
JSONObject mDaily = daily.getJSONObject("data");
Daily daily1 = new Daily(mDaily.getString("summary"), mDaily.getString("icon"),
mDaily.getDouble("precipProbability"), mDaily.getLong("time"));
data_list.add(daily1);
}
adapter.notifyDataSetChanged();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
};
task.execute((int) latitude, (int) longitude);
}
Most of the error are already pointed out. just rectify them.
data_list = new ArrayList<>();
recyclerView = findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
adapter = new CustomAdapter(this,data_list);
recyclerView.setAdapter(adapter);
load_weather_info(37.8267,-122.4233);
Notify adapter as follows.
private void load_weather_info(final double latitude, final double longitude) {
AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
#Override
protected Void doInBackground(Integer... integers) {
String apiKey = "--------------------------------";
String forecastUrl = "https://api.darksky.net/forecast/" + apiKey +
"/" + latitude + "," + longitude;
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(forecastUrl)
.build();
try {
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i = 0; i<array.length(); i++){
JSONObject jsonObject = array.getJSONObject(i);
JSONObject daily = jsonObject.getJSONObject("daily");
JSONObject mDaily = daily.getJSONObject("data");
Daily daily1 = new Daily(mDaily.getString("summary"), mDaily.getString("icon"),
mDaily.getDouble("precipProbability"), mDaily.getLong("time"));
data_list.add(daily1);
}
recyclerView.post(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
}
});
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
};
task.execute((int) latitude, (int) longitude);
}
PS: Here you should make use of onPostExecute() to get the returned data set and handle the Exception.
You have not notified the adapter on the change of data.
for (int i = 0; i<array.length(); i++){
JSONObject jsonObject = array.getJSONObject(i);
JSONObject daily = jsonObject.getJSONObject("daily");
JSONObject mDaily = daily.getJSONObject("data");
Daily daily1 = new Daily(mDaily.getString("summary"), mDaily.getString("icon"),
mDaily.getDouble("precipProbability"), mDaily.getLong("time"));
data_list.add(daily1);
}
adapter.notifyDataSetChanged(); //notify here

How to populate a RecyclerView with data from a Service on Button click

I have this setup in my fragment. The user makes selections from the spinners and when they click the go button a service is initiated that is meant to get data and populate a recycler view with the data.The recycler view is located right below the spinners.The code is below.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/weekSpinner"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_margin="5dp">
</Spinner>
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/sessionSpinner"
android:layout_toRightOf="#+id/weekSpinner"
android:layout_toEndOf="#+id/weekSpinner"
android:layout_margin="5dp">
</Spinner>
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/termSpinner"
android:layout_toRightOf="#+id/sessionSpinner"
android:layout_toEndOf="#+id/sessionSpinner"
android:layout_margin="5dp">
</Spinner>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go"
android:id="#+id/resultsSearch"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_margin="10dp"
android:layout_below="#+id/sessionSpinner"
android:textColor="#android:color/white"
android:background="#color/toolBar"/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/caRecycler">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
</LinearLayout>
I am getting this error.
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
I understand that it has to do with the context being used but i have no idea how to solve it as this is the first time i'm using this sort of setup. Below is my fragment code.
public class caFragment extends Fragment
{
ArrayList<String> weeks,terms,sessions;
String selectedWeek,selectedTerm,selectedSession;
String activeChild;
Button go;
private static final String selectedChildTracker = "selectedChild";
SharedPreferences sharedpreferences;
static RecyclerView caDisplay = null;
static caCardAdapter cardAdapter = null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.results_ca,null);
sharedpreferences = this.getActivity().getSharedPreferences(selectedChildTracker, Context.MODE_PRIVATE);
activeChild = sharedpreferences.getString("selectedChild",null);
final Spinner week,term,session;
setup();
week = (Spinner) view.findViewById(R.id.weekSpinner);
ArrayAdapter<String> weekAdapter = new ArrayAdapter<>(getContext(),android.R.layout.simple_spinner_item,weeks);
weekAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
week.setAdapter(weekAdapter);
term = (Spinner) view.findViewById(R.id.termSpinner);
ArrayAdapter<String> termAdapter = new ArrayAdapter<>(getContext(),android.R.layout.simple_spinner_item,terms);
termAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
term.setAdapter(termAdapter);
session = (Spinner) view.findViewById(R.id.sessionSpinner);
ArrayAdapter<String> sessionAdapter = new ArrayAdapter<>(getContext(),android.R.layout.simple_spinner_item,sessions);
sessionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
session.setAdapter(sessionAdapter);
caDisplay = (RecyclerView) view.findViewById(R.id.caRecycler);
go = (Button) view.findViewById(R.id.resultsSearch);
go.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
selectedWeek = week.getSelectedItem().toString();
selectedTerm = term.getSelectedItem().toString();
selectedSession = session.getSelectedItem().toString();
Bundle extra = new Bundle();
extra.putString("selectedWeek",selectedWeek);
extra.putString("selectedTerm",selectedTerm);
extra.putString("selectedSession",selectedSession);
extra.putString("selectedChild",activeChild);
try
{
getActivity().startService(new Intent(getContext(), results.class).putExtras(extra));
}
catch (Exception ex)
{
System.out.print(ex);
}
}
});
return view;
}
public void setup()
{
weeks = new ArrayList<>();
terms = new ArrayList<>();
sessions = new ArrayList<>();
try
{
weeks.add("4");
weeks.add("8");
}
catch (Exception ex)
{
Log.e("Error adding weeks",ex.toString());
}
try
{
terms.add("First Term");
terms.add("Second Term");
terms.add("Third Term");
}
catch (Exception ex)
{
Log.e("Error adding terms",ex.toString());
}
try
{
sessions.add("2015/2016");
}
catch (Exception ex)
{
Log.e("Error adding sessions",ex.toString());
}
}
public void showResults()
{
cardAdapter = new caCardAdapter(getActivity(),cardResults.getResultSet());
caDisplay.setAdapter(cardAdapter);
caDisplay.setLayoutManager(new LinearLayoutManager(getActivity()));
}
}
and below is my service code
public class results extends Service
{
int mStartMode;
String tag_results_req = "tag_results_req";
static ArrayList<cardResults> cardResult;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Bundle params = intent.getExtras();
Log.d("bundle param",params.toString());
String week = params.getString("selectedWeek");
String term = params.getString("selectedTerm");
String session = params.getString("selectedSession");
String child = params.getString("selectedChild");
makeRequest(week,term,session,child);
return mStartMode;
}
#Override
public void onDestroy()
{
super.onDestroy();
}
public void makeRequest(String week,String term,String session,String child)
{
String dataSet = week.trim()+","+term+","+session.trim()+","+child.trim();
byte[] data = new byte[0];
try
{
data = dataSet.getBytes("UTF-8");
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
String query = Base64.encodeToString(data, Base64.DEFAULT);
Log.d("Query param",query);
//the url we are posting the request to
String url = " http://mobile.map.education/api/result/ca/"+query;
// prepare the Request
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
// display response
Log.d("results",response.toString());
cardResults(response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Log.e("Error.Response", error.toString());
Toast.makeText(getApplicationContext(),"Sorry there was an error getting results data",Toast.LENGTH_LONG).show();
}
}
);
queuer.getInstance().addToRequestQueue(request, tag_results_req);
}
public void cardResults(JSONObject result)
{
cardResult = new ArrayList<>();
JSONArray res = null;
try
{
res = (JSONArray) result.get("result_details");
Log.d("results",res.toString());
}
catch (Exception ex)
{
Log.e("error getting results",ex.toString());
}
for (int i = 0; i < res.length(); i++)
{
try
{
JSONObject subject = res.getJSONObject(i);
cardResults cardModel = new cardResults();
cardModel.setAverage("50");
cardModel.setScore(subject.getString("total"));
cardModel.setSubject(subject.getString("subject"));
cardModel.setAssignment(subject.getString("ASSIGNMENT"));
cardModel.setTest(subject.getString("CLASS TEST"));
cardModel.setWork(subject.getString("CLASS WORK"));
cardModel.setTeacher(subject.getString("teacher"));
cardResult.add(cardModel);
}
catch (Exception ex)
{
Log.e("card list",ex.toString());
}
}
try {
cardResults.setResultSet(cardResult);
caFragment m = new caFragment();
m.showResults();
}
catch (Exception ex)
{
Log.e("show result",ex.toString());
}
}
}
Looks like problem with your adapter which you are setting outside the onCreate of Fragment
cardAdapter = new caCardAdapter(getActivity());
caDisplay.setAdapter(cardAdapter);
caDisplay.setLayoutManager(new LinearLayoutManager(getActivity()));
move above lines inside the onCreate and just create one data Setter method in your Adapter class and then call this method to set data.
public void showResults()
{
//create setter method inside your adapter and notify
cardAdapter.setData(cardResults.getResultSet());
cardAdapter.notifyDataSetChanged();
}
before set Data just check that your data is not null!

Android Calling API and parsing JSON

Trying to make an API call to the url below and parse the returning JSON, when the "refresh" button is called.
I can link to a button and get text (Hello world) to the screen, but can't seem to link the button click to the API request. Error message says I cannot reference non-static method "execute" from a static context
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void retrieveInformation(View view){
RetrieveFeedTask.execute();
TextView textview = (TextView) findViewById(R.id.responseView);
textview.setText("Hello world");
}
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
String jsonString = "";
private Exception exception;
protected void onPreExecute() {
}
protected String doInBackground(Void... urls) {
// Do some validation here
try {
URL url = new URL("www.liftin.co.uk/api/v1/journeys");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
} finally {
urlConnection.disconnect();
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if (response == null) {
response = "THERE WAS AN ERROR";
}
Log.i("INFO", response);
jsonString = response;
try {
getInformationFromJson(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
}
private String getInformationFromJson(String jsonString)
throws JSONException {
final String DRIVER = "driver";
final String START = "start";
final String DESTINATION = "destination";
final String TIME = "pick_up_time";
final String PASSENGERS = "passengers";
final String SEATS = "seats_available";
JSONObject journeyJson = new JSONObject(jsonString);
String time = journeyJson.getString(TIME);
String seats = journeyJson.getString(SEATS);
String results = seats + "-----" + time;
return results;
}
}
}
Main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.android.liftin.MainActivity">
<Button
android:id="#+id/queryButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="end"
style="#style/Base.Widget.AppCompat.Button.Borderless"
android:text="Refresh"
android:onClick="retrieveInformation"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/responseView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</ScrollView>
</RelativeLayout>
</LinearLayout>
You should create asynchronous call for your AsyncTask like this :
public void retrieveInformation(View view){
new RetrieveFeedTask().execute(); //asynchronous call
TextView textview = (TextView) findViewById(R.id.responseView);
textview.setText("Hello world");
}
UPDATE
If you want to set data to textview after parsing data. You have to make little bit changes in your activity as follows.
You should initialize your textview in onCreate() and make it global variable for your activity, so that you can access it in full activity.
then in your onPostExecute() do this :
textview.setText(getInformationFromJson(response));
Hope it will Help :)
You must create a object of AsyncTask (RetrieveFeedTask) before calling it. For example
public void retrieveInformation(View view){
TextView textview = (TextView) findViewById(R.id.responseView);
textview.setText("Hello world");
new RetrieveFeedTask().execute();
}
You still need to pass something for Void.
public void retrieveInformation(View view){
new RetrieveFeedTask().execute(null);
TextView textview = (TextView) findViewById(R.id.responseView);
textview.setText("Hello world");
}

Use JSON file to populate a listview

I have the following code which retrieves the JSON file:
public class GetJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) { //Running in background
try {
httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://pagesbyz.com/test.json");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("TEST", e.toString());
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return null;
}
#Override
protected void onPreExecute() { //Activity is on progress
}
#Override
protected void onPostExecute(Void v) { //Activity is done...
Toast.makeText(getActivity(), result, 2000).show();
int k = 0;
try {
JSONArray jsonall = new JSONArray();
jsonArray = new JSONArray(result);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = (JSONObject)jsonArray.get(i); // get the json object
if(jsonObj.getString("type").equals("image") || jsonObj.getString("type").equals("text")) { // compare for the key-value
k++;
jsonall.put(jsonObj);
sId = new String[jsonall.length()];
sType = new String[jsonall.length()];
sData = new String[jsonall.length()];
for (int m = 0 ; m < jsonall.length(); m++){ //4 entries made
JSONObject c = jsonall.getJSONObject(m);
String id = c.getString("id");
String type = c.getString("type");
String data = c.getString("data");
sId[m] = id;
sType[m] = type;
sData[m] = data;
}
}
}
Toast.makeText(getActivity(), String.valueOf(k), 2000).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
On the onPostExecute() function I am able to de-serialize the data, in this case by TYPE.
I have the following code for the CustomAdapter
public class SetRowsCustomAdapter extends ArrayAdapter<SetRows> {
Context context;
int layoutResourceId;
ArrayList<SetRows> data=new ArrayList<SetRows>();
public SetRowsCustomAdapter(Context context, int layoutResourceId, ArrayList<SetRows> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ImageHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ImageHolder();
holder.tID = (TextView)row.findViewById(R.id.tvID);
holder.tType = (TextView)row.findViewById(R.id.tvType);
holder.tData = (TextView)row.findViewById(R.id.tvData);
row.setTag(holder);
}
else
{
holder = (ImageHolder)row.getTag();
}
SetRows myImage = data.get(position);
holder.tID.setText(myImage.id);
holder.tType.setText(myImage.type);
holder.tData.setText(myImage.data);
return row;
}
static class ImageHolder
{
TextView tID;
TextView tType;
TextView tData;
}
}
My SetRows code is:
public class SetRows {
String id;
String type;
String data;
public String getData () {
return data;
}
public void setData (String data) {
this.data = data;
}
public String getID () {
return id;
}
public void setID (String id) {
this.id = id;
}
public String getType () {
return type;
}
public void setType (String type) {
this.type = type;
}
public SetRows(String id, String type, String data) {
super();
this.id = "ID: \t" + id;
this.type = "TYPE: \t" + type;
this.data = "DATA: \t" + data;
}
}
My XML file for the Layout file is:
<?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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView android:id="#+id/lvAll"
android:layout_height="match_parent"
android:layout_width="match_parent" />
</RelativeLayout>
The custom layout for the ListView is:
<?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:orientation="horizontal"
android:padding="#dimen/list_row_pad"
android:background="#drawable/list_row_bg" >
<TextView
android:id="#+id/tvID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="#dimen/margin_left_tv"
android:text="ID: "
android:textStyle="bold"
android:textColor="#FFFFFF" />
<TextView
android:id="#+id/tvType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvID"
android:layout_alignLeft="#+id/tvID"
android:text="TYPE: "
android:textStyle="bold"
android:textColor="#FFFFFF" />
<TextView
android:id="#+id/tvData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvType"
android:layout_alignLeft="#+id/tvType"
android:text="DATA: "
android:textStyle="bold"
android:textColor="#FFFFFF" />
</RelativeLayout>
I want to display the data like this in a ListView from the JSON file from my server:
I think I have all the information needed. I just need to know, now, how to display the information. All help is greatly appreciated. Thanks!
UPDATE: The following code is working, but it's entering multiple entries for each:
public class GetJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) { //Running in background
try {
httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://pagesbyz.com/test.json");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("TEST", e.toString());
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return null;
}
#Override
protected void onPreExecute() { //Activity is on progress
}
#Override
protected void onPostExecute(Void v) { //Activity is done...
//Toast.makeText(getActivity(), result, 2000).show();
int k = 0;
try {
JSONArray jsonall = new JSONArray();
jsonArray = new JSONArray(result);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = (JSONObject)jsonArray.get(i); // get the json object
if(jsonObj.getString("type").equals("image") || jsonObj.getString("type").equals("text")) { // compare for the key-value
k++;
jsonall.put(jsonObj);
sId = new String[jsonall.length()];
sType = new String[jsonall.length()];
sData = new String[jsonall.length()];
for (int m = 0 ; m < jsonall.length(); m++){
JSONObject c = jsonall.getJSONObject(m);
String id = c.getString("id");
String type = c.getString("type");
String data = c.getString("data");
//sId[m] = id;
//sType[m] = type;
//sData[m] = data;
contents.add(new SetRows(id, type, data));
}
}
adapter = new SetRowsCustomAdapter(getActivity(), R.layout.listrow, contents);
lAll.setAdapter(adapter);
lAll.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent myIntent = new Intent(getActivity(), DisplayWeb.class);
startActivityForResult(myIntent, 0);
}
});
}
//Toast.makeText(getActivity(), String.valueOf(k), 2000).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
The duplicate shows up as like this:
Sublacss ListActivy and create a layout that contains a ListView with id #android:id/list
put inside this subclass you AsyncTask and execute it in the on create.
when onPostExecute is called, after you parse the JSON, create an instance of SetRowsCustomAdapter
call getListView().setAdapter(adapterInstance).
#Override
protected void onPostExecute(Void v) {
ArrayList<SetRows> contents = new ArrayList<SetRows>();
// other code
//instead of those
//sId[m] = id;
//sType[m] = type;
//sData[m] = data;
//add
contents.add(new SetRows(id, type, data));
}
Edit 2: You have two duplicates entry because you have an unuseful for loop (the innere one). Imo your code should look like:
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = (JSONObject)jsonArray.get(i);
if(jsonObj.getString("type").equals("image") || jsonObj.getString("type").equals("text")) {
String id = jsonObj.getString("id");
String type = jsonObj.getString("type");
String data = jsonObj.getString("data");
contents.add(new SetRows(id, type, data));
}
}
// the other stuff
ps. check for typo

json array shows in logacat with no errors but does not show in android view

A large part of my app is grabbing data from a website. The data shows in my logcat, green with no errors but will not display in my android view. Ive tried and searched for a week or and have had no luck.
here is my class.
public class Json extends ListActivity {
ArrayList<HashMap<String, String>> jsonParser = new ArrayList<HashMap<String, String>>();
ListView lv ;
private static final String jsonFilePath = "http://xda.olinksoftware.com/leaderboard/all";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.json);
new ProgressTask(Json.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
public ProgressTask(Json json) {
Log.i("1", "Called");
context = json;
dialog = new ProgressDialog(context);
}
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(context, jsonParser,
R.layout.listitem, new String[] { TAG_NAME, TAG_SCORE,
}, new int[] {
R.id.score, R.id.name,
});
setListAdapter(adapter);
// selecting single ListView item
lv = getListView();
}
#Override
protected Boolean doInBackground(final String... args) {
new JSONParser();
try {
BufferedReader reader = null;
String jsonString = "";
StringBuffer buffer = new StringBuffer();
try{
URL url = new URL(jsonFilePath);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
}finally {
if (reader != null)
reader.close();
}
jsonString = buffer.toString();
try{
JSONParser jsonParser = new JSONParser();
JSONArray leaderboard = (JSONArray)jsonParser.parse(jsonString);
for(int i = 0;i<leaderboard.size();i++){
JSONObject user = (JSONObject)leaderboard.get(i);
System.out.println((i+1) + ". " + user.get("forumName") + " (" + user.get("score") + ")");
}
}catch(ParseException pe){
System.out.println("position: " + pe.getPosition());
System.out.println(pe);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}}
}
and here are my xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- Main ListView
Always give id value as list(#android:id/list)
-->
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<!-- Name Label -->
<TextView
android:id="#+id/score"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dp"
android:paddingLeft="6dp"
android:textSize="17sp"
android:textStyle="bold"/>
</LinearLayout>
any help is greatly appreciated. I know I am doing something wrong with my listview as it also works as a straight java application run in eclipse.
here is the data i am grabbing, i am only taking two values at this time. "forumUser" and "score"
[{"userId":"3579348","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=3579348","forumName":"newtoroot","totalPosts":"5074","postsPerDay":"5.14","totalThanks":"18302","joinDate":"2011-01-29","yearsJoined":"2","referrals":"4","friendCount":"38","recognizedDeveloper":"1","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"48","kernelCount":"0","tutorialCount":"0","modCount":"1","themeCount":"0","score":"302","userName":"","password":""},{"userId":"1596076","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=1596076","forumName":"il Duce","totalPosts":"16335","postsPerDay":"9.75","totalThanks":"15799","joinDate":"2009-02-25","yearsJoined":"4","referrals":"2","friendCount":"83","recognizedDeveloper":"1","recognizedContributor":"0","recognizedThemer":"0","moderator":"1","recognizedEliteDeveloper":"0","romCount":"1","kernelCount":"1","tutorialCount":"0","modCount":"0","themeCount":"0","score":"132","userName":"","password":""},{"userId":"2930301","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=2930301","forumName":"fernando sor","totalPosts":"8967","postsPerDay":"7.93","totalThanks":"4549","joinDate":"2010-09-07","yearsJoined":"3","referrals":"2","friendCount":"29","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"1","moderator":"0","recognizedEliteDeveloper":"0","romCount":"1","kernelCount":"0","tutorialCount":"5","modCount":"2","themeCount":"15","score":"120","userName":"fernando sor","password":""},{"userId":"3220669","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=3220669","forumName":"1975jamie","totalPosts":"582","postsPerDay":"0.56","totalThanks":"127","joinDate":"2010-11-23","yearsJoined":"2","referrals":"0","friendCount":"0","recognizedDeveloper":"1","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"4","kernelCount":"0","tutorialCount":"0","modCount":"0","themeCount":"0","score":"46","userName":"1975jamie","password":""},{"userId":"2552854","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=2552854","forumName":"jeffsanace","totalPosts":"2797","postsPerDay":"2.25","totalThanks":"2836","joinDate":"2010-05-05","yearsJoined":"3","referrals":"0","friendCount":"12","recognizedDeveloper":"0","recognizedContributor":"1","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"0","kernelCount":"0","tutorialCount":"0","modCount":"0","themeCount":"0","score":"37","userName":"","password":""},{"userId":"2067958","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=2067958","forumName":"eg1122","totalPosts":"1200","postsPerDay":"0.82","totalThanks":"1695","joinDate":"2009-10-05","yearsJoined":"3","referrals":"0","friendCount":"6","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"0","kernelCount":"0","tutorialCount":"0","modCount":"2","themeCount":"0","score":"20","userName":"","password":""},{"userId":"3042344","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=3042344","forumName":"dfuse06","totalPosts":"3331","postsPerDay":"3.08","totalThanks":"2270","joinDate":"2010-10-11","yearsJoined":"2","referrals":"1","friendCount":"29","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"0","kernelCount":"0","tutorialCount":"0","modCount":"1","themeCount":"0","score":"17","userName":"","password":""},{"userId":"1070340","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=1070340","forumName":"chrisloveskaos","totalPosts":"215","postsPerDay":"0.11","totalThanks":"8","joinDate":"2008-07-08","yearsJoined":"5","referrals":"0","friendCount":"7","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"1","kernelCount":"0","tutorialCount":"0","modCount":"0","themeCount":"0","score":"14","userName":"","password":""},{"userId":"2688514","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=2688514","forumName":"GooTz66","totalPosts":"999","postsPerDay":"0.84","totalThanks":"70","joinDate":"2010-06-25","yearsJoined":"3","referrals":"0","friendCount":"7","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"0","kernelCount":"0","tutorialCount":"0","modCount":"0","themeCount":"0","score":"7","userName":"","password":""},{"userId":"2141845","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=2141845","forumName":"Kush.Kush\u00c2\u0099","totalPosts":"86","postsPerDay":"0.06","totalThanks":"0","joinDate":"2009-11-09","yearsJoined":"3","referrals":"0","friendCount":"16","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"0","kernelCount":"0","tutorialCount":"0","modCount":"0","themeCount":"0","score":"6","userName":"","password":""}]
Why is this line
setListAdapter(adapter);
Before this
// selecting single ListView item
lv = getListView();
Also, the LogCat you posted is showing the results using the "info" filter only. Try looking at the verbose view to make sure no exceptions that you're missing.
what i did to solve this was pretty much start over. i added a JSONParser class
public class JSONParser {
static InputStream is = null;
static JSONArray jarray = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jarray = new JSONArray( builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jarray;
and a JsonActivity
public class MainActivity extends ListActivity {
private static String url = "website";
private static final String TAG_VTYPE = "forumName";
private static final String TAG_VCOLOR = "score";
private static final String TAG_THANKS = "totalThanks";
private static final String TAG_POSTS = "totalPosts";
private static final String TAG_JOIN_DATE = "joinDate";
private static final String TAG_ROM_COUNT = "romCount";
private static final String TAG_THEME_COUNT = "themeCount";
private static final String TAG_MOD_COUNT = "modCount";
private static final String TAG_KERNEL_COUNT = "kernelCount";
private static final String TAG_TUTORIAL_COUNT = "tutorialCount";
private static final String TAG_DEV = "recognizedDeveloper";
private static final String TAG_THEMER = "recognizedThemer";
private static final String TAG_MODERATOR = "moderator";
private static final String TAG_RDEV = "recognizedEliteDeveloper";
private static final String TAG_RCOD = "recognizedContributor";
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
private View header;
ListView lv ;
LayoutInflater Inflater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_view);
Inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
new ProgressTask(MainActivity.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
private ListActivity activity;
// private List<Message> messages;
public ProgressTask(ListActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
View header = Inflater.inflate(R.layout.header_view_name, null);
ListAdapter adapter = new SimpleAdapter(context, jsonlist,
R.layout.list_item, new String[] { TAG_VTYPE, TAG_VCOLOR, TAG_THANKS, TAG_POSTS, TAG_JOIN_DATE, TAG_ROM_COUNT,
TAG_THEME_COUNT, TAG_MOD_COUNT, TAG_KERNEL_COUNT, TAG_DEV, TAG_TUTORIAL_COUNT, TAG_THEMER, TAG_MODERATOR, TAG_RDEV, TAG_RCOD,
}, new int[] {
R.id.vehicleType, R.id.vehicleColor, R.id.totalThanks, R.id.totalPosts, R.id.joinDate, R.id.romCount,
R.id.themeCount, R.id.kernelCount, R.id.modCount, R.id.tutorialCount, R.id.moderator, R.id.rThemer, R.id.rDev,
R.id.rCon, R.id.rEliteDev,
});
lv = getListView();
lv.addHeaderView(header);
setListAdapter(adapter);
// selecting single ListView item
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// getting values from selected ListItem
String forumName = ((TextView) view.findViewById(R.id.vehicleType)).getText().toString();
String score = ((TextView) view.findViewById(R.id.vehicleColor)).getText().toString();
String totalThanks = ((TextView) view.findViewById(R.id.totalThanks)).getText().toString();
String totalPosts = ((TextView) view.findViewById(R.id.totalPosts)).getText().toString();
String joinDate = ((TextView) view.findViewById(R.id.joinDate)).getText().toString();
String romCount = ((TextView) view.findViewById(R.id.romCount)).getText().toString();
String themeCount = ((TextView) view.findViewById(R.id.themeCount)).getText().toString();
String kernelCount = ((TextView) view.findViewById(R.id.kernelCount)).getText().toString();
String modCount = ((TextView) view.findViewById(R.id.modCount)).getText().toString();
String tutorialCount = ((TextView) view.findViewById(R.id.tutorialCount)).getText().toString();
String moderator = ((TextView) view.findViewById(R.id.moderator)).getText().toString();
String recognizedThemer = ((TextView) view.findViewById(R.id.rThemer)).getText().toString();
String recognizedDeveloper = ((TextView) view.findViewById(R.id.rDev)).getText().toString();
String recognizedContributor = ((TextView) view.findViewById(R.id.rCon)).getText().toString();
String recognizedEliteDeveloper = ((TextView) view.findViewById(R.id.rEliteDev)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_VTYPE, forumName);
in.putExtra(TAG_VCOLOR, score);
in.putExtra(TAG_THANKS, totalThanks);
in.putExtra(TAG_POSTS, totalPosts);
in.putExtra(TAG_JOIN_DATE, joinDate);
in.putExtra(TAG_ROM_COUNT, romCount);
in.putExtra(TAG_THEME_COUNT, themeCount);
in.putExtra(TAG_MOD_COUNT, modCount);
in.putExtra(TAG_KERNEL_COUNT, kernelCount);
in.putExtra(TAG_TUTORIAL_COUNT, tutorialCount);
in.putExtra(TAG_DEV, recognizedDeveloper);
in.putExtra(TAG_THEMER, recognizedThemer);
in.putExtra(TAG_MODERATOR, moderator);
in.putExtra(TAG_RDEV, recognizedEliteDeveloper);
in.putExtra(TAG_RCOD, recognizedContributor);
startActivity(in);
}});}
protected Boolean doInBackground(final String... args) {
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String forumName = c.getString(TAG_VTYPE);
String score = c.getString(TAG_VCOLOR);
String totalThanks = c.getString(TAG_THANKS);
String totalPosts = c.getString(TAG_POSTS);
String joinDate = c.getString(TAG_JOIN_DATE);
String romCount = c.getString(TAG_ROM_COUNT);
String themeCount = c.getString(TAG_THEME_COUNT);
String modCount = c.getString(TAG_MOD_COUNT);
String kernelCount = c.getString(TAG_KERNEL_COUNT);
String tutorialCount = c.getString(TAG_TUTORIAL_COUNT);
String recognizedDeveloper = c.getString(TAG_DEV);
String recognizedThemer = c.getString(TAG_THEMER);
String moderator = c.getString(TAG_MODERATOR);
String recognizedEliteDeveloper = c.getString(TAG_RDEV);
String recognizedContributor = c.getString(TAG_RCOD);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_VTYPE, forumName);
map.put(TAG_VCOLOR, score);
map.put(TAG_THANKS, totalThanks);
map.put(TAG_POSTS, totalPosts);
map.put(TAG_JOIN_DATE, joinDate);
map.put(TAG_ROM_COUNT, romCount);
map.put(TAG_THEME_COUNT, themeCount);
map.put(TAG_MOD_COUNT, modCount);
map.put(TAG_KERNEL_COUNT, kernelCount);
map.put(TAG_TUTORIAL_COUNT, tutorialCount);
map.put(TAG_DEV, recognizedDeveloper);
map.put(TAG_THEMER, recognizedThemer);
map.put(TAG_MODERATOR, moderator);
map.put(TAG_RDEV, recognizedEliteDeveloper);
map.put(TAG_RCOD, recognizedContributor);
jsonlist.add(map);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}}}
and tied it together with a list view and xml for all my values. turned out really cool. i added an onclick on each value to show more individual data

Categories