Loading parsed JSONArray into a recyclerView - java

I am trying to load the result of an API call into a recyclerView. I created a data model to hold the array of results (strings) to be used in populating the recyclerView Adapter. But once the JSON file is parsed, the application crashes on the call to "setValues" of the data model but the result displays accurately on the logcat.
my code is below:
MainActivity
package com.limitless.googlebooks;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.Loader;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.NetworkInterface;
import java.util.ArrayList;
import static android.text.TextUtils.isEmpty;
public class MainActivity extends AppCompatActivity
implements LoaderManager.LoaderCallbacks<String> {
private EditText bookImput;
private RecyclerView recyclerView;
private ProgressBar progressBar;
private static Books books;
ArrayList<Books> booksArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bookImput = findViewById(R.id.bookInput);
progressBar = findViewById(R.id.progressBar);
recyclerView = findViewById(R.id.bookRecyclerView);
booksArray = new ArrayList<>();
BooksAdapter adapter = new BooksAdapter(booksArray);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
if(LoaderManager.getInstance(this).getLoader(0) != null){
LoaderManager.getInstance(this).initLoader(0,null, this);
}
}
public void searchBooks(View view) {
String queryText = bookImput.getText().toString();
InputMethodManager methodManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
if(methodManager != null){
methodManager.hideSoftInputFromWindow(view.getWindowToken(),
methodManager.HIDE_NOT_ALWAYS);
}
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = null;
if(connectivityManager != null){
networkInfo = connectivityManager.getActiveNetworkInfo();
}
if(networkInfo != null && !isEmpty(queryText) && networkInfo.isConnected()){
Bundle queryBundle = new Bundle();
queryBundle.putString("queryString", queryText);
LoaderManager.getInstance(this).restartLoader(0, queryBundle, this);
progressBar.setVisibility(View.VISIBLE);
}else {
if(isEmpty(queryText)){
Toast.makeText(this, R.string.emptyquery, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, R.string.no_internet, Toast.LENGTH_SHORT).show();
}
}
}
#NonNull
#Override
public Loader<String> onCreateLoader(int id, #Nullable Bundle args) {
String queryString = "";
if(args != null){
queryString = args.getString("queryString");
}
return new BookLoader(this, queryString);
}
#Override
public void onLoadFinished(#NonNull Loader<String> loader, String data) {
try{
JSONObject jsonObject = new JSONObject(data);
JSONArray itemsArray = jsonObject.getJSONArray("items");
int i = 0;
String title = null;
String authors = null;
String publisher = null;
String date = null;
while(i < itemsArray.length() && title == null && authors == null && date == null){
JSONObject book = itemsArray.getJSONObject(i);
JSONObject volumeInfo = book.getJSONObject("volumeInfo");
try{
title = volumeInfo.getString("title");
authors = volumeInfo.getString("authors");
publisher = volumeInfo.getString("publisher");
date = volumeInfo.getString("publishedDate");
} catch (JSONException e) {
e.printStackTrace();
}
i++;
}
if(title != null && authors != null && date != null){
books.setBookName(title);
books.setAuthorsName(authors);
books.setPublisher(publisher);
books.setPublishedDate(date);
booksArray.add(books);
}else {
books.setBookName(String.valueOf(R.string.no_results));
books.setAuthorsName("");
books.setPublisher("");
books.setPublishedDate("");;
}
}catch (JSONException e){
books.setBookName(String.valueOf(R.string.error));
books.setAuthorsName("");
books.setPublisher("");
books.setPublishedDate("");
e.printStackTrace();
}
}
#Override
public void onLoaderReset(#NonNull Loader<String> loader) {
}
}
Data Model
package com.limitless.googlebooks;
public class Books {
private String bookName;
private String authorsName;
private String publisher;
private String publishedDate;
public Books(String bookName, String authorsName, String publisher, String publishedDate) {
this.bookName = bookName;
this.authorsName = authorsName;
this.publisher = publisher;
this.publishedDate = publishedDate;
}
public Books(){}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getAuthorsName() {
return authorsName;
}
public void setAuthorsName(String authorsName) {
this.authorsName = authorsName;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getPublishedDate() {
return publishedDate;
}
public void setPublishedDate(String publishedDate) {
this.publishedDate = publishedDate;
}
}
Adapter Class
package com.limitless.googlebooks;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class BooksAdapter extends RecyclerView.Adapter<BooksAdapter.BooksHolder>{
ArrayList<Books> booksArrayList;
public BooksAdapter(ArrayList<Books> booksArray){
this.booksArrayList = booksArray;
}
#NonNull
#Override
public BooksHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
View itemView = LayoutInflater.from(context).inflate(R.layout.booklist, parent, false);
return new BooksHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull BooksHolder holder, int position) {
Books books = booksArrayList.get(position);
holder.bind(books);
}
#Override
public int getItemCount() {
return booksArrayList.size();
}
public class BooksHolder extends RecyclerView.ViewHolder {
private TextView bookName;
private TextView authorsName;
private TextView publisher;
private TextView publishedDate;
public BooksHolder(#NonNull View itemView) {
super(itemView);
bookName = itemView.findViewById(R.id.bookTitle);
authorsName = itemView.findViewById(R.id.authorsName);
publisher = itemView.findViewById(R.id.publisher);
publishedDate = itemView.findViewById(R.id.publishedDate);
}
public void bind(Books books){
bookName.setText(books.getBookName());
authorsName.setText(books.getAuthorsName());
publisher.setText(books.getPublisher());
publishedDate.setText(books.getPublishedDate());
}
}
}

In your MainActivity:
These
public class MainActivity extends AppCompatActivity
implements LoaderManager.LoaderCallbacks<String> {
....
private static Books books;
ArrayList<Books> booksArray;
Becomes:
public class MainActivity extends AppCompatActivity
implements LoaderManager.LoaderCallbacks<String> {
....
private Books books;
private ArrayList<Books> booksArray;
private BooksAdapter adapter;
In onCreate():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
........
adapter = new BooksAdapter(booksArray);
........
........
}
Now in onLoadFinished():
This:
if(title != null && authors != null && date != null){
books.setBookName(title);
books.setAuthorsName(authors);
books.setPublisher(publisher);
books.setPublishedDate(date);
booksArray.add(books);
}else {
books.setBookName(String.valueOf(R.string.no_results));
books.setAuthorsName("");
books.setPublisher("");
books.setPublishedDate("");;
}
}catch (JSONException e){
books.setBookName(String.valueOf(R.string.error));
books.setAuthorsName("");
books.setPublisher("");
books.setPublishedDate("");
e.printStackTrace();
}
Becomes:
if(title != null && authors != null && date != null){
books = new Books(title,authors,publisher,date);
booksArray.add(books);
adapter.notifyDataSetChanged();
}else {
books = new Books(String.valueOf(R.string.no_results),"","","");
//if you want to add them to array add them, if not then don't
booksArray.add(books);
adapter.notifyDataSetChanged();
}
}catch (JSONException e){
books = new Books(String.valueOf(R.string.error),"","","");
//if you want to add them to array add them, if not then don't
booksArray.add(books);
adapter.notifyDataSetChanged();
e.printStackTrace();
}

Related

Can't pass null for argument 'pathString' in child() error

ModelOrderUser.java
package my.anupamroy.smartcanteenapp.models;
public class ModelOrderUser {
String orderId,orderTime,orderStatus,orderCost,orderBy,orderTo;
public ModelOrderUser(){
}
public ModelOrderUser(String orderId, String orderTime, String orderStatus, String orderCost, String orderBy, String orderTo) {
this.orderId = orderId;
this.orderTime = orderTime;
this.orderStatus = orderStatus;
this.orderCost = orderCost;
this.orderBy = orderBy;
this.orderTo = orderTo;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public String getOrderTime() {
return orderTime;
}
public void setOrderTime(String orderTime) {
this.orderTime = orderTime;
}
public String getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(String orderStatus) {
this.orderStatus = orderStatus;
}
public String getOrderCost() {
return orderCost;
}
public void setOrderCost(String orderCost) {
this.orderCost = orderCost;
}
public String getOrderBy() {
return orderBy;
}
public void setOrderBy(String orderBy) {
this.orderBy = orderBy;
}
public String getOrderTo() {
return orderTo;
}
public void setOrderTo(String orderTo) {
this.orderTo = orderTo;
}
}
AdapterOrderUser.java
package my.anupamroy.smartcanteenapp.adapters;
import android.content.Context;
import android.text.Layout;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Calendar;
import my.anupamroy.smartcanteenapp.R;
import my.anupamroy.smartcanteenapp.models.ModelOrderUser;
public class AdapterOrderUser extends RecyclerView.Adapter<AdapterOrderUser.HolderOrderUser>{
private Context context;
private ArrayList<ModelOrderUser> orderUserList;
public AdapterOrderUser(Context context, ArrayList<ModelOrderUser> orderUserList) {
this.context = context;
this.orderUserList = orderUserList;
}
#NonNull
#Override
public HolderOrderUser onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//inflate layout
View view = LayoutInflater.from(context).inflate(R.layout.row_order_user,parent,false);
return new HolderOrderUser(view);
}
#Override
public void onBindViewHolder(#NonNull HolderOrderUser holder, int position) {
//get data
ModelOrderUser modelOrderUser=orderUserList.get(position);
String orderId = modelOrderUser.getOrderId();
String orderBy = modelOrderUser.getOrderBy();
String orderCost = modelOrderUser.getOrderCost();
String orderStatus = modelOrderUser.getOrderStatus();
String orderTime = modelOrderUser.getOrderTime();
String orderTo = modelOrderUser.getOrderTo();
//get shop info
loadShopInfo(modelOrderUser,holder);
//set data
holder.amountTv.setText("Amount: ₹" +orderCost);
holder.statusTv.setText(orderStatus);
holder.orderIdTv.setText("OrderID:"+orderId);
// change order status text color
if(orderStatus.equals("In Progress")){
holder.statusTv.setTextColor(context.getResources().getColor(R.color.colorPrimary));
}
else if(orderStatus.equals("Completed")){
holder.statusTv.setTextColor(context.getResources().getColor(R.color.colorGreen));
}
else if(orderStatus.equals("Cancelled")){
holder.statusTv.setTextColor(context.getResources().getColor(R.color.colorRed));
}
//convert timestamp to proper format
Calendar calendar =Calendar.getInstance();
calendar.setTimeInMillis(Long.parseLong(orderTime));
String formatedDate= DateFormat.format("dd/MM/yyy",calendar).toString();
holder.dateTv.setText(formatedDate);
}
private void loadShopInfo(ModelOrderUser modelOrderUser, final HolderOrderUser holder) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");
ref.child(modelOrderUser.getOrderTo())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String shopName =""+dataSnapshot.child("shopName").getValue();
holder.shopNameTv.setText(shopName);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public int getItemCount() {
return orderUserList.size();
}
//view holder class
class HolderOrderUser extends RecyclerView.ViewHolder{
private TextView orderIdTv,dateTv,shopNameTv,amountTv,statusTv;
public HolderOrderUser(#NonNull View itemView) {
super(itemView);
//init views of layout
orderIdTv=itemView.findViewById(R.id.orderIdTv);
dateTv=itemView.findViewById(R.id.dateTv);
shopNameTv=itemView.findViewById(R.id.shopNameTv);
amountTv=itemView.findViewById(R.id.amountTv);
statusTv=itemView.findViewById(R.id.statusTv);
}
}
}
I am facing the following while executing don't know what is happening
java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
at com.google.firebase.database.DatabaseReference.child(DatabaseReference.java:96)
at my.anupamroy.smartcanteenapp.adapters.AdapterOrderUser.loadShopInfo(AdapterOrderUser.java:84)
at my.anupamroy.smartcanteenapp.adapters.AdapterOrderUser.onBindViewHolder(AdapterOrderUser.java:56)
at my.anupamroy.smartcanteenapp.adapters.AdapterOrderUser.onBindViewHolder(AdapterOrderUser.java:26)
Please help me out with this error
don't know why the code is throwing errors for me
please help me out
I am getting errors in lines number 84,56,26

NullPointerException in adapter holding viewholders

ElementAdapter class
package com.example.sierendeelementeninbreda;
import android.content.Context;
import android.view.ViewGroup;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class ElementAdapter extends RecyclerView.Adapter<ElementAdapter.ViewHolder> {
private static final String TAG = ElementAdapter.class.getSimpleName();
private List<Element> mElements = new ArrayList<>();
private final ElementOnClickHandler mElementClickHandler;
public ElementAdapter(List<Element> mElements, ElementOnClickHandler mElementClickHandler) {
this.mElements = mElements;
this.mElementClickHandler = mElementClickHandler;
}
#NonNull
#Override
public ElementAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
Log.v(TAG, "++++++++ onCreateViewHolder - viewGroup-class: " + viewGroup.getClass().getSimpleName());
Log.v(TAG, "++++++++ onCreateViewHolder - viewGroup-resourceName: " + viewGroup.getContext().getResources().getResourceName(viewGroup.getId()));
Log.v(TAG, "++++++++ onCreateViewHolder - viewGroup-resourceEntryName: " + viewGroup.getContext().getResources().getResourceEntryName(viewGroup.getId()));
Context context = viewGroup.getContext();
LayoutInflater inflator = LayoutInflater.from(context);
// create a new view
View elementListItem = inflator.inflate(R.layout.element_item, viewGroup, false);
ElementAdapter.ViewHolder viewHolder = new ViewHolder(elementListItem);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Log.v(TAG, "++++ onBindViewHolder-type: " + holder.getClass().getSimpleName());
holder.title.setText(mElements.get(position).getTitle());
holder.geographicalLocation.setText(mElements.get(position).getGeographicalLocation());
holder.identificationNumber.setText(mElements.get(position).getIdentificationNumber());
Picasso.get()
.load(mElements.get(position).getImage())
.into(holder.image);
}
#Override
public int getItemCount() {
return mElements.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//one drinkItem has 3 views
// Provide a reference to each view in the drinkItem
private ImageView image;
private TextView title;
private TextView geographicalLocation;
private TextView identificationNumber;
public ViewHolder(View listItemView) {
super(listItemView);
title = (TextView) listItemView.findViewById(R.id.element_item_name);
geographicalLocation = (TextView) listItemView.findViewById(R.id.element_Location);
identificationNumber = (TextView) listItemView.findViewById(R.id.element_idNumber);
image = (ImageView) listItemView.findViewById(R.id.element_item_imageview);
// image.setOnClickListener(this);
// name.setOnClickListener(this);
// description.setOnClickListener(this);
// listItemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int itemIndex = getAdapterPosition();
mElementClickHandler.onElementClick(view, itemIndex);
}
}
}
NetworkUtils class
package com.example.sierendeelementeninbreda;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Scanner;
public class NetworkUtils extends AsyncTask<String, Void, String> {
private static final String TAG = NetworkUtils.class.getSimpleName();
private OnElementApiListener listener;
private final static String url = "https://services7.arcgis.com/21GdwfcLrnTpiju8/arcgis/rest/services/Sierende_elementen/FeatureServer/0/query?where=1%3D1&outFields=*&outSR=4326&f=json";
public NetworkUtils(OnElementApiListener listener) {
this.listener = listener;
}
#Override
protected String doInBackground(String... input) {
//De methode begint met een log zodat je kunt zien wat er gebeurt in de run.
Log.d(TAG, "doInBackground was called");
String response = null;
HttpURLConnection httpURLConnection = null;
// ToDo: Url maken op basis van internet adres
try {
URL mUrl = new URL(url);
URLConnection mConnection = mUrl.openConnection();
httpURLConnection = (HttpURLConnection) mConnection;
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.connect();
int responseCode = httpURLConnection.getResponseCode();
if(responseCode != HttpURLConnection.HTTP_OK){
Log.e(TAG, "Aanroep naar de server is mislukt!");
} else {
InputStream in = httpURLConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
response = scanner.next();
}
}
Log.d(TAG, response);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(httpURLConnection != null)
httpURLConnection.disconnect();
}
return response;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.d(TAG, "onPreExecute: ");
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
Log.i(TAG, "createElementFromJson called");
ArrayList<Element> elements = new ArrayList<>();
if (response == null || response.equals("")) {
Log.e(TAG, "onPostExecute: empty response!");
return;
}
try {
JSONObject jsonResults = new JSONObject(response);
JSONArray elementList = jsonResults.getJSONArray("features");
Log.d(TAG, "onPostExecute: " + jsonResults);
Log.i(TAG, "elementArray length = " + elementList.length());
for(int i = 0; i < elementList.length(); i++) {
JSONObject element = elementList.getJSONObject(i);
//all info
JSONObject elementAttributes = element.getJSONObject("attributes");
String image = elementAttributes.getString("URL");
String title = elementAttributes.getString("AANDUIDINGOBJECT");
String geographicalLocation = elementAttributes.getString("GEOGRAFISCHELIGGING");
String identificationNumber = elementAttributes.getString("IDENTIFICATIE");
Element element_item = new Element(title, geographicalLocation, identificationNumber);
element_item.setImage(image);
elements.add(element_item);
Log.i(TAG, String.valueOf(elements.size()));
}
listener.onElementAvailable(elements);
} catch (JSONException e) {
e.printStackTrace();
}
}
public interface OnElementApiListener {
void onElementAvailable(ArrayList<Element> elements);
}
MainActivity class
package com.example.sierendeelementeninbreda;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity
implements View.OnClickListener,NetworkUtils.OnElementApiListener,
ElementOnClickHandler{
private static String TAG = MainActivity.class.getName();
private final static String url = "https://services7.arcgis.com/21GdwfcLrnTpiju8/arcgis/rest/services/Sierende_elementen/FeatureServer/0/query?where=1=1&outFields=&outSR=4326&f=json";
private ArrayList<Element> mElementList;
private RecyclerView elementRecyclerView;
private ElementAdapter mElementAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
elementRecyclerView= findViewById(R.id.recyclerView_element_list);
elementRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mElementAdapter = new ElementAdapter(mElementList,this);
elementRecyclerView.setAdapter(mElementAdapter);
// Start background task
NetworkUtils networkingTask = new NetworkUtils(this);
networkingTask.execute(url);
}
#Override
public void onElementAvailable(ArrayList<Element> elements) {
Log.i(TAG, "elements = " + elements.size());
this.mElementList = new ArrayList<>();
mElementList.clear();
mElementList.addAll(elements);
mElementAdapter.notifyDataSetChanged();
Log.i(TAG, "new elements = " + mElementList.size());
}
#Override
public void onElementClick(View view, int itemIndex) {
Log.v(TAG, "clicked on " + view.getClass().getSimpleName());
int viewId = view.getId();
Context context = this;
String toastMessage = "";
// if (viewId == R.id.product_imageview) {
// toastMessage = "clicked on image of drink item";
// } else if (viewId == R.id.product_item_name || viewId == R.id.product_item_description) {
// toastMessage = "clicked on name or description of drink item";
// } else if (viewId == R.id.product_list_item) {
// toastMessage = "clicked on drink list-item nr: " + itemIndex;
// }
Toast.makeText(context, toastMessage, Toast.LENGTH_LONG)
.show();
}
#Override
public void onClick(View v) {
}
}
Error
D/NetworkUtils: onPreExecute:
D/NetworkUtils: doInBackground was called
D/HostConnection: HostConnection::get() New Host Connection established 0xd4a13c30, tid 27630
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sierendeelementeninbreda, PID: 27595
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at com.example.sierendeelementeninbreda.ElementAdapter.getItemCount(ElementAdapter.java:64)
at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:4044)
at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3849)
at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4404)
at android.view.View.layout(View.java:21912)
at android.view.ViewGroup.layout(ViewGroup.java:6260)
That is the error I get when I run the app, I have tried solving this by looking things up but it is not working. The NullPointerException happens in line 64 of my adapter class. The app basically uses an API to get data from a site and then showcases it in a recylerView.
your not init mElementList before passed to adapter so when adapter call size method
will throw null pointer
edit your code here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
elementRecyclerView= findViewById(R.id.recyclerView_element_list);
elementRecyclerView.setLayoutManager(new LinearLayoutManager(this));
// init mElementList here
mElementList = new ArrayList<>();
mElementAdapter = new ElementAdapter(mElementList,this);
elementRecyclerView.setAdapter(mElementAdapter);
// Start background task
NetworkUtils networkingTask = new NetworkUtils(this);
networkingTask.execute(url);
}
It is always better to do null check
#Override
public int getItemCount() {
if(mElements!=null)
return mElements.size();
else return 0
}
and initialize mElements in constructor

Not able to display the listView in android while getting the JSON data

This is my MainActivity.java :
package example.com.getdata;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
public static final String JSON_URL = "http://172.31.131.52:8081/application/status";
private Button buttonGet;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonGet = (Button) findViewById(R.id.button2);
}
private void sendRequest(){
StringRequest stringRequest = new StringRequest(JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.getMessage(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String json) {
Product product = new Product(json);
ArrayList<JSONObject> listItems= product.parseJSON();
listView = (ListView) findViewById(R.id.list_view);
CustomList customerList = new CustomList(this,R.layout.list_view_layout,R.id.textViewName, listItems);
//customerList.notifyDataSetChanged();
listView.setAdapter(customerList);
}
public void clickHere(View v) {
sendRequest();
}
}
Product.java
package example.com.getdata;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import static com.android.volley.VolleyLog.TAG;
public class Product {
public String productName;
public String description;
public int priceInDollars;
//public int productID;
public static final String KEY_Name = "productName";
public static final String KEY_Desc = "description";
//public static final String KEY_ID= "ProductID";
public static final String KEY_Price ="priceInDollars" ;
private JSONArray users = null;
private String json;
public Product(String json){
this.json =json;
}
protected ArrayList<JSONObject> parseJSON(){
JSONArray jsonArray=null;
ArrayList<JSONObject> aList=new ArrayList<JSONObject>();
try {
jsonArray = new JSONArray(json);
Log.d("Debugging...", jsonArray.toString());
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jo = jsonArray.getJSONObject(i);
productName = jo.getString(KEY_Name);
description = jo.getString(KEY_Desc);
priceInDollars = jo.getInt(KEY_Price);
aList.add(jsonArray.getJSONObject(i));
// productID = jo.getInt(KEY_ID);
}
return aList;
}
else {
Log.d(TAG, "parseJSON: Null condition");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
CustomList.java
package example.com.getdata;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class CustomList extends ArrayAdapter<String> {
private ArrayList<JSONObject> list;
private int vg;
private Activity context;
public CustomList(Activity context,int vg, int id, ArrayList<JSONObject> list ) {
super(context,R.layout.list_view_layout, id);
this.vg = vg;
this.context = context;
this.list=list;
// this.productID=productID;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View listViewItem = inflater.inflate(vg, parent, false);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
TextView textViewDescription = (TextView) listViewItem.findViewById(R.id.textViewDescription);
TextView textViewPrice = (TextView) listViewItem.findViewById(R.id.textViewPrice);
// TextView textViewID = (TextView) listViewItem.findViewById(R.id.textViewID);
try {
textViewName.setText(list.get(position).getString("productName"));
textViewDescription.setText(list.get(position).getString("description"));
textViewPrice.setText(list.get(position).getString("priceInDollars"));
}
catch (JSONException e) {
e.printStackTrace();
}
// textViewID.setText(productID);
return listViewItem;
}
}
I have tried and searched for answers online and I am still not able to figure out the problem. I am unable to see the list of objects. Through debugging, I am sure that the objects are read into the json objects, still I am not able to display the objects in a listView.
Any help is appreciated.
You need to crate constructor with all variables of Product class and put all values in Product class object and add into ArrayList .
See Product Class :
public class Product {
public String productName;
public String description;
public int priceInDollars;
//public int productID;
public static final String KEY_Name = "productName";
public static final String KEY_Desc = "description";
//public static final String KEY_ID= "ProductID";
public static final String KEY_Price ="priceInDollars" ;
private JSONArray users = null;
private String json;
public Product(String productName, String json, JSONArray users, int priceInDollars, String description) {
this.productName = productName;
this.json = json;
this.users = users;
this.priceInDollars = priceInDollars;
this.description = description;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public static String getKEY_Name() {
return KEY_Name;
}
public static String getKEY_Price() {
return KEY_Price;
}
public String getJson() {
return json;
}
public void setJson(String json) {
this.json = json;
}
public JSONArray getUsers() {
return users;
}
public void setUsers(JSONArray users) {
this.users = users;
}
public static String getKEY_Desc() {
return KEY_Desc;
}
public int getPriceInDollars() {
return priceInDollars;
}
public void setPriceInDollars(int priceInDollars) {
this.priceInDollars = priceInDollars;
}
}
And When your are parsing your data you need to change like below code:
protected ArrayList<Product> parseJSON(){
JSONArray jsonArray=null;
ArrayList<Product> aList=new ArrayList<Product>();
try {
jsonArray = new JSONArray(json);
Log.d("Debugging...", jsonArray.toString());
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jo = jsonArray.getJSONObject(i);
String productName = jo.optString(KEY_Name);
String description = jo.optString(KEY_Desc);
String priceInDollars = jo.optInt(KEY_Price);
Product product = new Product(productName,json,
jsonArray.getJSONObject(i),priceInDollars,description);
aList.add(product);
// productID = jo.getInt(KEY_ID);
}
return aList;
}
else {
Log.d(TAG, "parseJSON: Null condition");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Also you need to change in Adapter class where you have passes ArrayList<JsonArray> in this case you have to pass ArrayList<Product>.
You missed
#override
public int getCount()
{
return list.size();
}
and make sure you either "setAdapter" on your listview after getting the json or call "notifydatasetchanged" method
Use
super(context,R.layout.list_view_layout, list);
instead of
super(context,R.layout.list_view_layout, id);
Make sure getCount() is properly implemented in Adapterclass:
#Override
public int getCount(){
return list.size();
}
Extend the CustomList class as:
type JSONObject
instead of
type String

Custom listView adapter, model, JSONParsing not working

I'm designing a listview that displays food information list from php server.
the url I passed is a php file after I convert it to json file. the list is not shown and whent I press refresh from menu I keep getting
(app stopped working) ..
here is FoodView.java Activity
import android.content.Context;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import alsaad.layla.mysqldemo.Models.FoodModel;
import static android.R.attr.resource;
import static android.content.Context.LAYOUT_INFLATER_SERVICE;
public class FoodView extends AppCompatActivity {
private ListView lvFood;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_view);
lvFood = (ListView) findViewById(R.id.lvFood);
}
public class JSONTask extends AsyncTask<String, String, List<FoodModel>> {
#Override
protected List<FoodModel> doInBackground(String... params) {
HttpURLConnection httpURLConnection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
List<FoodModel> foodModelList = new ArrayList<>();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
FoodModel foodModel = new FoodModel();
foodModel.setFood(finalObject.getString("name"));
//foodModel.setStatus(finalObject.getString("status"));
foodModel.setAmount(finalObject.getInt("amount"));
foodModel.setDescription(finalObject.getString("description"));
foodModel.setDate(finalObject.getInt("exDate"));
foodModelList.add(foodModel);
}
return foodModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<FoodModel> result) {
super.onPostExecute(result);
FoodAdapter adapter = new FoodAdapter(getApplicationContext(), R.layout.row, result);
lvFood.setAdapter(adapter);
}}
public class FoodAdapter extends ArrayAdapter {
private List<FoodModel> foodModelList;
private int resource;
private LayoutInflater inflater;
public FoodAdapter(Context context, int resource, List<FoodModel> objects) {
super(context, resource, objects);
foodModelList = objects;
this.resource = resource;
inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(resource, null);
}
ImageView ivIcon;
TextView foodName, txt_amount, txt_desc, txt_date, txt_status;
ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
foodName = (TextView) convertView.findViewById(R.id.foodName);
txt_amount = (TextView) convertView.findViewById(R.id.txt_amount);
txt_desc = (TextView) convertView.findViewById(R.id.txt_desc);
// txt_status = (TextView) convertView.findViewById(R.id.txt_status);
txt_date = (TextView) convertView.findViewById(R.id.txt_date);
foodName.setText(foodModelList.get(position).getFood());
txt_amount.setText("Amount: " + foodModelList.get(position).getAmount());
txt_desc.setText(foodModelList.get(position).getDescription());
// txt_status.setText(foodModelList.get(position).getStatus());
txt_date.setText("Date: " + foodModelList.get(position).getDate());
return convertView;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.navigation_drawer, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
new JSONTask().execute("http://10.0.3.2/MySqlDemo/food.php");
return true;
}
return super.onOptionsItemSelected(item);
}
}
FoodModel.java
public class FoodModel {
private String food;
//private enum status;
private int amount;
private String image;
private String description;
private int date;
public int getDate() {
return date;
}
public void setDate(int date) {
this.date = date;
}
public String getFood() {
return food;
}
public void setFood(String food) {
this.food = food;
}
//public String getStatus() {
// return status;
// }
// public void setStatus(String status) {
// this.status = status;
//}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
}
the logcat error:
02-20 05:06:08.084 4514-4514/alsaad.layla.mysqldemo E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
at android.widget.ListView.setAdapter(ListView.java:462)
at alsaad.layla.mysqldemo.FoodView$JSONTask.onPostExecute(FoodView.java:128)
at alsaad.layla.mysqldemo.FoodView$JSONTask.onPostExecute(FoodView.java:54)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
It seems like you are getting an exception in your for loop that's why it goes into an exception and returns null, so it shows a null pointer exception. Please replace getString() with optSting() and getInt() with optInt().
Solution:- Please put break point in your for loop and find it out otherwise use below option.
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
FoodModel foodModel = new FoodModel();
foodModel.setFood(finalObject.optString("name"));
//foodModel.setStatus(finalObject.optString("status"));
foodModel.setAmount(finalObject.optInt("amount"));
foodModel.setDescription(finalObject.optString("description"));
foodModel.setDate(finalObject.optInt("exDate"));
foodModelList.add(foodModel);
}
return null; replace with return new ArrayList<>(); to get from crash.
The method getCount() within the ArrayAdater returns the lenght of the object list atached to the adapter:
/**
* {#inheritDoc}
*/
public int getCount() {
return mObjects.size();
}
As you are using a custom ArrayAdapter i think you must Override this function to make it returns the size of your own objects list:
public int getCount() {
return foodModelList.size();
}
Why are you using ArrayAdapter instead i would suggest you to use BaseAdapter
It is the issue when you object is not able to get instance of ArrayAdpter and hence returning null pointer exception at getCount()

i want to send Listview Data to Another Activity in Android using json

I want to send a Listview Data to another Activity.
check my code:
ActorAdapater.java
package anyname;
import java.io.InputStream;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
actorList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
holder.tvName = (TextView) v.findViewById(R.id.tvName);
holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
holder.tvDOB = (TextView) v.findViewById(R.id.tvDateOfBirth);
holder.tvCountry = (TextView) v.findViewById(R.id.tvCountry);
holder.tvHeight = (TextView) v.findViewById(R.id.tvHeight);
holder.tvSpouse = (TextView) v.findViewById(R.id.tvSpouse);
holder.tvChildren = (TextView) v.findViewById(R.id.tvChildren);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imageview.setImageResource(R.drawable.ic_launcher);
new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
holder.tvName.setText(actorList.get(position).getName());
holder.tvDescription.setText(actorList.get(position).getDescription());
holder.tvDOB.setText("B'day: " + actorList.get(position).getDob());
holder.tvCountry.setText(actorList.get(position).getCountry());
holder.tvHeight.setText("Height: " + actorList.get(position).getHeight());
holder.tvSpouse.setText("Spouse: " + actorList.get(position).getSpouse());
holder.tvChildren.setText("Children: " + actorList.get(position).getChildren());
return v;
}
static class ViewHolder {
public ImageView imageview;
public TextView tvName;
public TextView tvDescription;
public TextView tvDOB;
public TextView tvCountry;
public TextView tvHeight;
public TextView tvSpouse;
public TextView tvChildren;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
Actors.java
public class Actors {
private String name;
private String description;
private String dob;
private String country;
private String height;
private String spouse;
private String children;
private String image;
public Actors() {
// TODO Auto-generated constructor stub
}
public Actors(String name, String description, String dob, String country,
String height, String spouse, String children, String image) {
super();
this.name = name;
this.description = description;
this.dob = dob;
this.country = country;
this.height = height;
this.spouse = spouse;
this.children = children;
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getSpouse() {
return spouse;
}
public void setSpouse(String spouse) {
this.spouse = spouse;
}
public String getChildren() {
return children;
}
public void setChildren(String children) {
this.children = children;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
MainActivity.java
package ANYNAME;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class MainActivity extends Activity {
ArrayList<Actors> actorsList;
ActorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actorsList = new ArrayList<Actors>();
new JSONAsyncTask().execute("json link here.xml");
ListView listview = (ListView)findViewById(R.id.list);
adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), actorsList.get(position).getName(), Toast.LENGTH_LONG).show();
}
});
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("name"));
actor.setDescription(object.getString("description"));
actor.setDob(object.getString("dob"));
actor.setCountry(object.getString("country"));
actor.setHeight(object.getString("height"));
actor.setSpouse(object.getString("spouse"));
actor.setChildren(object.getString("children"));
actor.setImage(object.getString("image"));
actorsList.add(actor);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
When users Click on Listview Content & Pass Listview Data to NewActivity.java
You can use Intent to pass data from one Activity to another.
Intent intent=new Intent(MainActivity.this,NewActivity.class);
intent.putExtra("key",value);//
......
startActivity(intent);
In your NewActivity access value as:
variable=getIntent().getXXX("key");
Try to use GSON library to generate json (String) from your model. Put it to the Intent and start new Activity.
you can use shared SharedPrefences
SharedPreferences pref = getSharedPreferences("MYPrefrences", 0);
For save
Editor prefsEditor = pref.edit();
Gson gson = new Gson();
String json = gson.toJson("MyObject");
prefsEditor.putString("MyObject", json);
prefsEditor.commit();
For get
Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
Actor actor = gson.fromJson(json, Actor.class);
Implement Serializable (http://developer.android.com/reference/java/io/Serializable.html) in your Actors.java class. In your setOnItemClickListener, use the following code:
Intent newIntent = new Intent(thisActivity.this, NextActivity.class);
newIntent.putExtra("key", value);
startActivity(newIntent);
In your NextActivity.class, you can get back the object like this:
Intent intent = getIntent();
YourClass object = intent.getSerializableExtra("key");
This will give you the whole object, with all its properties.
Replace your code with this,
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
Actors myActor = actorsList.get(position);
// create JSON object from the above object with getter methods
JSONObject myActorJSON = new JSONObject();
myActorJSON.put("name", myActor.getName());
myActorJSON.put("description", myActor.getDescription());
myActorJSON.put("dob", myActor.getDOB());
myActorJSON.put("country", myActor.getCountry());
myActorJSON.put("height", myActor.getHeight());
myActorJSON.put("spouse", myActor.getSpouse());
myActorJSON.put("children", myActor.getChildren());
myActorJSON.put("image", myActor.getImage());
//you can send the Actors object or JSONObject to the new Activity
// through intent as
Intent i = new Intent(this, NewActivity.class);
i.putExtra("ACTOR_OBJECT", myActor); //Actors class should extend serializable interface
i.putExtra("ACTOR_JSON_OBJECT", myActorJSON.toString());
startActivity(i);
}
and
//Now in NewActivity.class extract tha data from intent as
Intent i = getIntent();
Actors receivedActorObject = (Actors)i.getSerializableExtra("ACTOR_OBJECT");
String JSONString = i.getStringExtra("ACTOR_JSON_OBJECT");
try {
JSONObject receivedActorJSON = new JSONObject(JSONString);
} catch (JSONException e) {
e.printStackTrace();
}
Let me know if it works for you...
And do mark it as an answer so that it would be useful to others...
On your onClick method
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), actorsList.get(position).getName(), Toast.LENGTH_LONG).show();
Actor selectedActor = actorsList.get(position);
JSONObject obj = new JsonObject();
obj.put("name",selectedActor.getName());
//add other values of actor like that
Intent i = new Intent(MainActirity.this,otherActivity.class);
i.putExtra("Actor",obj.toString());
startActivity(i);
}
In your receiving activity
Intent i = getIntent();
JSONObject obj = new JSONObject(i.getStringExtra("Actor"));
Also have a look at Intent

Categories

Resources