I just follow this tutorial: HERE to retrieve products from DB, but when I run my app I get blank page, I try to fix the problem but with any result.
NOTE: I have create add product form and it work, the product inserted to DB but in the interface that I have apply the tutorial to display my products stay always blank.
this is my code:
AjouterProduit.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class AjouterProduit extends AppCompatActivity implements Download_data.download_complete {
public ListView list;
public ArrayList<Countries> countries = new ArrayList<Countries>();
public ListAdapter adapter;
EditText gamme,produit,desc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ajouterproduit);
list = (ListView) findViewById(R.id.list);
adapter = new ListAdapter(this);
list.setAdapter(adapter);
Download_data download_data = new Download_data((Download_data.download_complete) this);
download_data.download_data_from_link("http://192.168.148.1/Ajout.php");
// download_data.download_data_from_link("http://www.kaleidosblog.com/tutorial/tutorial.json");
gamme =(EditText)findViewById(R.id.editText);
produit=(EditText)findViewById(R.id.editText2);
desc=(EditText)findViewById(R.id.editText3);
}
public void Ajout(View view){
String ga,pro,des;
ga=gamme.getText().toString();
pro=produit.getText().toString();
des=desc.getText().toString();
String type = "ajout";
work3 backgroundWorker = new work3(this);
backgroundWorker.execute(type,ga, pro ,des);
}
#Override
public void get_data(String data) {
}
public class Countries {
private String DescriptionProduit;
//public String NomProduit;
private String NomProduit;
{
String data = null;
JSONArray data_array= null;
try {
data_array = new JSONArray(data);
} catch (JSONException e1) {
e1.printStackTrace();
}
for (int i = 0 ; i < data_array.length() ; i++)
{
JSONObject obj= null;
try {
obj = new JSONObject(data_array.get(i).toString());
} catch (JSONException e1) {
e1.printStackTrace();
}
Countries add=new Countries(getNomProduit(), getDescriptionProduit());
try {
add.setNomProduit(obj.getString("NomProduit"));
} catch (JSONException e1) {
e1.printStackTrace();
}
try {
add.setDescriptionProduit(obj.getString("DescriptionProduit"));
} catch (JSONException e1) {
e1.printStackTrace();
}
countries.add(add);
}
adapter.notifyDataSetChanged();
}
private Countries(String nomProduit, String descriptionProduit) {
setNomProduit(nomProduit);
setDescriptionProduit(descriptionProduit);
}
public String getNomProduit() {
return NomProduit;
}
public void setNomProduit(String nomProduit) {
NomProduit = nomProduit;
}
public String getDescriptionProduit() {
return DescriptionProduit;
}
public void setDescriptionProduit(String descriptionProduit) {
DescriptionProduit = descriptionProduit;
}
}
}
Download_data.java
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Download_data implements Runnable {
public download_complete caller;
public interface download_complete
{
public void get_data(String data);
}
Download_data(download_complete caller) {
this.caller = caller;
}
public String link;
public void download_data_from_link(String link)
{
this.link = link;
Thread t = new Thread(this);
t.start();
}
public void run() {
threadMsg(download(this.link));
}
private void threadMsg(String msg) {
if (!msg.equals(null) && !msg.equals("")) {
Message msgObj = handler.obtainMessage();
Bundle b = new Bundle();
b.putString("message", msg);
msgObj.setData(b);
handler.sendMessage(msgObj);
}
}
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
String Response = msg.getData().getString("message");
caller.get_data(Response);
}
};
public static String download(String url) {
URL website;
StringBuilder response = null;
try {
website = new URL(url);
HttpURLConnection connection = (HttpURLConnection) website.openConnection();
connection.setRequestProperty("charset", "utf-8");
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
} catch (Exception e) {
return "";
}
return response.toString();
}
}
ListAdapter.java
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import static android.content.Context.LAYOUT_INFLATER_SERVICE;
public class ListAdapter extends BaseAdapter {
AjouterProduit main;
ListAdapter(AjouterProduit main)
{
this.main = main;
}
#Override
public int getCount() {
return main.countries.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
static class ViewHolderItem {
TextView NomProduit;
TextView DescriptionProduit;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
ViewHolderItem holder = new ViewHolderItem();
if (convertView == null) {
LayoutInflater inflater;
inflater = (LayoutInflater) main.getSystemService(LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cell, null);
holder.NomProduit = (TextView) convertView.findViewById(R.id.NomProduit);
holder.DescriptionProduit = (TextView) convertView.findViewById(R.id.DescriptionProduit);
convertView.setTag(holder);
}
else
{
holder = (ViewHolderItem) convertView.getTag();
}
holder.NomProduit.setText(this.main.countries.get(position).getNomProduit());
holder.DescriptionProduit.setText(this.main.countries.get(position).getDescriptionProduit());
return convertView;
}
}
cell.xml
<?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="match_parent"
android:orientation="vertical" >
<!--nom-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/NomProduit" />
<!--description-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/DescriptionProduit" />
</RelativeLayout>
list.xml
<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" >
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/list"
/>
</RelativeLayout>
ajouterproduit.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Nom gamme"
android:id="#+id/textView9"
android:textStyle="bold" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Nom produit"
android:id="#+id/textView10" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Description produit"
android:id="#+id/textViewD" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText3" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ajouter produit"
android:id="#+id/Ajout"
android:layout_gravity="center_horizontal"
android:onClick="Ajout"/>
</LinearLayout>
Ajout.php
<?php
$NomGamme=$_POST["NomGamme"];
$NomProduit=$_POST["NomProduit"];
$DescriptionProduit=$_POST["DescriptionProduit"];
//echo "Produit bien ajouter";
if($id=mysql_connect("localhost","root","") ) {
if(mysql_select_db("applicationcolorado"))
$query= "INSERT INTO `applicationcolorado`.`produitgamme` (`NomGamme`, `NomProduit`, `DescriptionProduit`)
VALUES ('$NomGamme', '$NomProduit', '$DescriptionProduit')";
if (mysql_query($query))
{echo "Produit bien ajouter";}
else {
echo "false";
}
mysql_close($id);}
?>
There is no ListView with the id list in your ajouterproduit.xml layout.
In your AjouterProduit activity, you have these lines:
setContentView(R.layout.ajouterproduit);
list = (ListView) findViewById(R.id.list);
The first line set's this activity's layout to ajouterproduit.xml and the second one tries to find a ListView with the id list in this layout which doesn't exist so list is set to null.
Related
I am developing an app where I have a Json api and I need to populate it in recyclerview. Its a news api(not from newsapi.org). I am beginner to parsing json. However, I have tried to do but nothing came except an empty screen.
The Json api is
https://earnezy.in/android_shop/newsapi2.php
I have attached the code.
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.JsonObject;
import com.news.newsapp.R;
import com.news.newsapp.adapters.Adapter;
import com.news.newsapp.model.News;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private final String JSON_URL = "https://earnezy.in/android_shop/newsapi2.php";
private JsonArrayRequest jsonArrayRequest;
private RequestQueue requestQueue;
private List<News> newsList;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.news);
jsonRequest();
}
private void jsonRequest() {
jsonArrayRequest = new JsonArrayRequest(JSON_URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i=0;i<response.length();i++){
try {
jsonObject = response.getJSONObject(i);
News news = new News();
news.setAuthor(jsonObject.getString("author"));
news.setDescription(jsonObject.getString("description"));
news.setTitle(jsonObject.getString("title"));
news.setPublishedAt(jsonObject.getString("publishedAt"));
newsList.add(news);
} catch (JSONException e) {
e.printStackTrace();
}
}
setUpRecyclerView(newsList);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(jsonArrayRequest);
}
private void setUpRecyclerView(List<News> newsList) {
Adapter adapter = new Adapter(MainActivity.this, newsList);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
}
activity_main.xml
<androidx.constraintlayout.widget.ConstraintLayout 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:background="#000"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activities.MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_marginLeft="15dp"
android:text="Top Headlines"
android:textColor="#fff"
android:textSize="22dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/news"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView"
app:layout_constraintVertical_bias="0.034" />
</androidx.constraintlayout.widget.ConstraintLayout>
Adapter.java
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.news.newsapp.R;
import com.news.newsapp.activities.Utils;
import com.news.newsapp.model.News;
import java.util.List;
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder>{
private Context context;
private List<News> news;
public Adapter(Context context, List<News> news) {
this.context = context;
this.news = news;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
LayoutInflater inflater = LayoutInflater.from(context);
view = inflater.inflate(R.layout.news_item, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, int position) {
final MyViewHolder holders = holder;
News model = news.get(position);
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(Utils.getRandomDrawbleColor());
requestOptions.error(Utils.getRandomDrawbleColor());
requestOptions.diskCacheStrategy(DiskCacheStrategy.ALL);
requestOptions.centerCrop();
Glide.with(context)
.load(model.getUrlToImage())
.apply(requestOptions)
.listener(new RequestListener<Drawable>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
holder.progressBar.setVisibility(View.GONE);
return false;
}
#Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
holder.progressBar.setVisibility(View.GONE);
return false;
}
})
.transition(DrawableTransitionOptions.withCrossFade())
.into(holder.imageView);
holder.author.setText(news.get(position).getAuthor());
holder.description.setText(news.get(position).getDescription());
holder.title.setText(news.get(position).getTitle());
holder.time.setText("\u2022" + Utils.DateToTimeFormat(model.getPublishedAt()));
holder.publishedAd.setText(Utils.DateFormat(model.getPublishedAt()));
}
#Override
public int getItemCount() {
return news.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView author, title, description, time, publishedAd;
ImageView imageView;
ProgressBar progressBar;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
}
}
}
Utils.java
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import org.ocpsoft.prettytime.PrettyTime;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
public class Utils {
public static ColorDrawable[] vibrantLightColorList =
{
new ColorDrawable(Color.parseColor("#ffeead")),
new ColorDrawable(Color.parseColor("#93cfb3")),
new ColorDrawable(Color.parseColor("#fd7a7a")),
new ColorDrawable(Color.parseColor("#faca5f")),
new ColorDrawable(Color.parseColor("#1ba798")),
new ColorDrawable(Color.parseColor("#6aa9ae")),
new ColorDrawable(Color.parseColor("#ffbf27")),
new ColorDrawable(Color.parseColor("#d93947"))
};
public static ColorDrawable getRandomDrawbleColor() {
int idx = new Random().nextInt(vibrantLightColorList.length);
return vibrantLightColorList[idx];
}
public static String DateToTimeFormat(String oldstringDate){
PrettyTime p = new PrettyTime(new Locale(getCountry()));
String isTime = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'",
Locale.ENGLISH);
Date date = sdf.parse(oldstringDate);
isTime = p.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return isTime;
}
public static String DateFormat(String oldstringDate){
String newDate;
SimpleDateFormat dateFormat = new SimpleDateFormat("E, d MMM yyyy", new Locale(getCountry()));
try {
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").parse(oldstringDate);
newDate = dateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
newDate = oldstringDate;
}
return newDate;
}
public static String getCountry(){
Locale locale = Locale.getDefault();
String country = String.valueOf(locale.getCountry());
return country.toLowerCase();
}
}
News.java
public class News {
private String author;
private String title;
private String description;
private String url;
private String publishedAt;
private String urlToImage;
public News() {
}
public News(String author, String title, String description, String url, String publishedAt, String urlToImage) {
this.author = author;
this.title = title;
this.description = description;
this.url = url;
this.publishedAt = publishedAt;
this.urlToImage = urlToImage;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
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 getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPublishedAt() {
return publishedAt;
}
public void setPublishedAt(String publishedAt) {
this.publishedAt = publishedAt;
}
public String getUrlToImage() {
return urlToImage;
}
public void setUrlToImage(String urlToImage) {
this.urlToImage = urlToImage;
}
}
news_item.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<androidx.cardview.widget.CardView
android:id="#+id/cardView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="11dp"
android:layout_marginRight="11dp"
android:layout_marginTop="7dp"
android:layout_marginBottom="7dp"
app:cardBackgroundColor="#000"
app:cardElevation="#dimen/cardview_default_elevation"
app:cardCornerRadius="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/img"
android:layout_width="match_parent"
android:layout_height="200dp"
android:scaleType="centerCrop"
android:transitionName="img"
tools:ignore="UnusedAttribute"/>
<ImageView
android:id="#+id/shadow_image"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_alignBottom="#+id/img"
android:src="#drawable/bottom_shadow"/>
<ProgressBar
android:id="#+id/progress_load_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="70dp"
style="#android:style/Widget.ProgressBar.Small"/>
<TextView
android:id="#+id/author"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawablePadding="10dp"
android:ellipsize="end"
android:maxLines="1"
android:textColor="#fff"
android:singleLine="true"
android:layout_marginRight="160dp"
android:layout_marginLeft="10dp"
android:text="Author"
android:gravity="bottom"
android:layout_alignLeft="#+id/title"
android:layout_alignStart="#+id/title"
android:layout_alignRight="#+id/layoutDate"
android:layout_alignTop="#+id/layoutDate"
android:layout_alignEnd="#+id/layoutDate"/>
<FrameLayout
android:id="#+id/layoutDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/img"
android:background="#fff"
android:padding="5dp"
android:layout_alignParentRight="true"
android:layout_marginRight="20dp"
android:layout_marginTop="-50dp">
<ImageView
android:src="#drawable/ic_date"
android:layout_width="18dp"
android:layout_height="18dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/publishedAt"
android:textColor="#606060"
android:layout_marginLeft="27dp"
android:layout_marginRight="10dp"
android:text="01 January 1999"/>
</FrameLayout>
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/img"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="10dp"
android:text="Title"
android:textColor="#fff"
android:textSize="17sp" />
<TextView
android:id="#+id/desc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="5dp"
android:text="Desc"
android:textColor="#fff" />
<TextView
android:id="#+id/source"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="26dp"
android:text="Source"
android:textColor="#fff" />
<TextView
android:id="#+id/time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="46dp"
android:text="Time"
android:textColor="#fff" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
</FrameLayout>
The repsonse from the https://earnezy.in/android_shop/newsapi2.php is a JSON object not array. So use please below code to fetch news items correctly.
private void jsonRequest() {
jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,JSON_URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray articles = response.optJSONArray("articles")
JSONObject jsonObject = null;
for (int i=0;i<articles.length();i++){
try {
jsonObject = articles.getJSONObject(i);
News news = new News();
news.setAuthor(jsonObject.getString("author"));
news.setDescription(jsonObject.getString("description"));
news.setTitle(jsonObject.getString("title"));
news.setPublishedAt(jsonObject.getString("publishedAt"));
newsList.add(news);
} catch (JSONException e) {
e.printStackTrace();
}
}
setUpRecyclerView(newsList);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(jsonObjectRequest);
}
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();
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.
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;
}
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