RecyclerView doesn't show data - android
Its my first time when I'm trying to use RecyclerView. My app do request to get array of documents data. I wrote my own adapter for RecyclerView, TaskAsync class which extend from AsyncTask. And when do request all data which I need, but I don't know why those data doesn't show in my recycler view. pls help. I read many post about recyclerView, but I think in my adapter something goes wrong.
Acts class and into this class I have TaskAsync
public class Acts extends Fragment{
private String direction, limit, existingToken;
private SharedPreferences sharedPreferences;
private ArrayList<Document> documentsList;
private TextView docCategory;
private EditText search;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private DocumentAdapter documentAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View act = inflater.inflate(R.layout.two_sided_docs, container, false);
View header = getActivity().getLayoutInflater().inflate(R.layout.document_list_header, null);
docCategory = (TextView)header.findViewById(R.id.docs_category_one);
search = (EditText)header.findViewById(R.id.search_text_one);
recyclerView = (RecyclerView) act.findViewById(R.id.documentListView2);
documentsList = new ArrayList<Document>();
documentAdapter = new DocumentAdapter(act.getContext(), documentsList, Document.DOCUMENT_TYPE.ACT);
layoutManager = new LinearLayoutManager(act.getContext());
recyclerView.setAdapter(documentAdapter);
recyclerView.setLayoutManager(layoutManager);
sharedPreferences = getContext().getSharedPreferences(Constants.PROJECT, Context.MODE_PRIVATE);
existingToken = sharedPreferences.getString(Constants.TOKEN, "");
direction = "in";
limit = "50";
new TestAsync(getActivity()).execute(Urls.ACTS_FEED);
return act;
}
public class TestAsync extends AsyncTask<String, Void, String> {
private Activity activity;
private ProgressDialog progressDialog;
private OkHttpClient okHttpClient;
private Request request;
private RequestBody formBody;
public TestAsync(Activity activity) {
this.activity = activity;
progressDialog = new ProgressDialog(this.activity);
}
#Override
protected String doInBackground(String... params) {
Log.i("sadasd", "asdasd");
URL url;
try {
url = new URL(params[0]);
okHttpClient = new OkHttpClient();
formBody = new FormBody.Builder()
.add(Constants.DIRECTION, Constants.IN)
.add(Constants.LIMIT, Constants.docs_limit)
.build();
request = new Request.Builder()
.url(url.toString())
.addHeader(Constants.AUTH_TOKEN, existingToken)
.post(formBody)
.build();
Response response = null;
response = okHttpClient.newCall(request).execute();
return response.body().string();
} catch (MalformedURLException e) {
Log.i("test", "test1");
e.printStackTrace();
} catch (IOException e) {
Log.i("test", "test2");
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setTitle(R.string.wait);
progressDialog.setMessage("load");
progressDialog.setCancelable(false);
progressDialog.show();
Log.i("test", "test3");
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.i("test", "test4" + s);
AlertView.showAlertView(activity, Messages.CONNECTION_ERROR, s, Messages.OK);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
} else if (s == null) {
Log.i("test", "test5");
AlertView.showAlertView(activity, Messages.CONNECTION_ERROR, Messages.NO_INTERNET, Messages.OK);
} else {
Log.i("test", "test6");
try {
Log.i("test", "test7");
JSONObject jsonObject = new JSONObject(s);
int code = Integer.valueOf(jsonObject.getString(Constants.CODE));
if (code == Codes.OK) {
Log.i("test", "test8");
String header = jsonObject.getString("act_header");
JSONArray arr = new JSONArray(header);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
Document document = null;
String docId;
String docNum;
String docTotalPrice;
String senderCompany;
String receiverCompany;
BigInteger timestamp;
String docStatus;
String documentInternalType;
docId = jsonPart.getString("id");
docNum = jsonPart.getString("act_num");
docTotalPrice = jsonPart.getString("total_price");
senderCompany = jsonPart.getString("sender_company_name");
receiverCompany = jsonPart.getString("receiver_company_name");
timestamp = BigInteger.valueOf(Long.valueOf(jsonPart.getString("timestamp")));
docStatus = jsonPart.getString("status");
documentInternalType = jsonPart.getString("documentInternaltyep");
document = new Document(docId, docNum, docTotalPrice, senderCompany, receiverCompany, timestamp, docStatus, documentInternalType);
Log.i("document", document.toString());
documentsList.add(document);
documentAdapter.notifyDataSetChanged();
}
} else {
Log.i("error", "error");
AlertView.showAlertView(activity, Messages.ERROR, jsonObject.getString(Constants.MESSAGE), Messages.OK);
}
} catch (JSONException e) {
AlertView.showAlertView(activity, Messages.CONNECTION_ERROR, Messages.NO_INTERNET, Messages.OK);
e.printStackTrace();
}
}
}
}
}
And this is my DocumentAdapter class:
public class DocumentAdapter extends RecyclerView.Adapter<DocumentAdapter.ViewHolder> {
private Context context;
private ArrayList<Document> docData;
private Document.DOCUMENT_TYPE documentType;
private static LayoutInflater inflater = null;
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView datetime;
TextView senderOrReceiverCompany;
TextView docInfo;
TextView docCost;
ImageView arrow;
TextView docStatus;
ViewHolder(View v) {
super(v);
datetime = (TextView) v.findViewById(R.id.datetime);
senderOrReceiverCompany = (TextView) v.findViewById(R.id.senderc);
docInfo = (TextView) v.findViewById(R.id.docInfo);
docCost = (TextView) v.findViewById(R.id.cost);
arrow = (ImageView) v.findViewById(R.id.arrow_icon);
docStatus = (TextView) v.findViewById(R.id.doc_st_sign);
}
}
public DocumentAdapter(Context context, ArrayList<Document> docData, Document.DOCUMENT_TYPE documentType) {
this.context = context;
this.docData = docData;
this.documentType = documentType;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context cn = parent.getContext();
LayoutInflater inf = LayoutInflater.from(context);
View documentView = inf.inflate(R.layout.list_adapter_row, parent, false);
ViewHolder viewHolder = new ViewHolder(documentView);
return viewHolder;
}
#Override
public int getItemCount() {
return docData.size();
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Document document = docData.get(position);
TextView datetime;
TextView senderOrReceiverCompany;
TextView docInfo;
TextView docCost;
ImageView arrow;
TextView docStatus;
datetime = holder.datetime;
datetime.setText(document.getTimestamp());
senderOrReceiverCompany = holder.senderOrReceiverCompany;
senderOrReceiverCompany.setText(document.getSenderCompany());
docInfo = holder.docInfo;
docInfo.setText(String.format(Constants.ACT_TITLE, document.getDocNum(), document.getTimestamp()));
docCost = holder.docCost;
docStatus = holder.docStatus;
switch (documentType) {
case ACT:
docCost.setText(String.valueOf(Math.round(Double.valueOf(document.getDocTotalPrice()))) + Constants.KZT);
break;
case SHIPPING_LIST:
docCost.setText(String.valueOf(Math.round(Double.valueOf(document.getDocTotalPrice()))) + Constants.KZT);
break;
case COMMON_DOCUMENT:
docCost.setText(" ");
break;
case INVOICE:
docCost.setText(String.valueOf(Math.round(Double.valueOf(document.getDocTotalPrice()))) + Constants.KZT);
String colorful = "";
switch (document.getDocStatus()) {
case "0":
colorful = Constants.DOCUMENT_INVOICE_STATUS.get(document.getDocStatus());
break;
case "1":
colorful = "<font color='#008000'>" + Constants.DOCUMENT_INVOICE_STATUS.get(document.getDocStatus()) + "</font>";
break;
case "2":
colorful = "<font color='#FFA500'>" + Constants.DOCUMENT_INVOICE_STATUS.get(document.getDocStatus()) + "</font>";
break;
case "3":
colorful = "<font color='#EE0000'>" + Constants.DOCUMENT_INVOICE_STATUS.get(document.getDocStatus()) + "</font>";
break;
default:
colorful = "<font color='#EE0000'>" + Constants.DOCUMENT_INVOICE_STATUS.get(document.getDocStatus()) + "</font>";
break;
}
docStatus.setText(Html.fromHtml(Constants.DOCUMENT_INVOICE_TYPE.get(document.getDocumentInternalType()) + " | " + colorful));
break;
case PAYMENT_INVOICE:
docCost.setText(String.valueOf(Math.round(Double.valueOf(document.getDocTotalPrice()))) + Constants.KZT);
break;
case RECON:
docCost.setText(" ");
break;
default:
docCost.setText(document.getDocTotalPrice());
break;
}
if (!documentType.equals(Document.DOCUMENT_TYPE.INVOICE)) {
switch (document.getDocStatus()) {
case "1":
docStatus.setText(Html.fromHtml(Constants.DOCUMENT_INTERNAL_TYPE.get(document.getDocumentInternalType()) + " | " + "<font color='#800080'>" + Constants.DOCUMENT_STATUS.get(document.getDocStatus()) + "</font>"));
break;
case "2":
docStatus.setText(Html.fromHtml(Constants.DOCUMENT_INTERNAL_TYPE.get(document.getDocumentInternalType()) + " | " + "<font color='#800080'>" + Constants.DOCUMENT_STATUS.get(document.getDocStatus()) + "</font>"));
break;
case "3":
docStatus.setText(Html.fromHtml(Constants.DOCUMENT_INTERNAL_TYPE.get(document.getDocumentInternalType()) + " | " + "<font color='#FFA500'>" + Constants.DOCUMENT_STATUS.get(document.getDocStatus()) + "</font>"));
break;
case "4":
docStatus.setText(Html.fromHtml(Constants.DOCUMENT_INTERNAL_TYPE.get(document.getDocumentInternalType()) + " | " + "<font color='#008000'>" + Constants.DOCUMENT_STATUS.get(document.getDocStatus()) + "</font>"));
break;
case "6":
docStatus.setText(Html.fromHtml(Constants.DOCUMENT_INTERNAL_TYPE.get(document.getDocumentInternalType()) + " | " + "<font color='#EE0000'>" + Constants.DOCUMENT_STATUS.get(document.getDocStatus()) + "</font>"));
break;
case "7":
docStatus.setText(Html.fromHtml(Constants.DOCUMENT_INTERNAL_TYPE.get(document.getDocumentInternalType()) + " | " + "<font color='#EE0000'>" + Constants.DOCUMENT_STATUS.get(document.getDocStatus()) + "</font>"));
break;
default:
docStatus.setText(Html.fromHtml(Constants.DOCUMENT_INTERNAL_TYPE.get(document.getDocumentInternalType()) + " | " + "<font color='#800080'>" + Constants.DOCUMENT_STATUS.get(document.getDocStatus()) + "</font>"));
break;
}
}
arrow = holder.arrow;
}
private Context getContext() {
return context;
}
}
And this is my layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/documentListView2"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
UPDATE
this what I got after request:
test: test4{"code": 0, "act_header": [{"status": 1, "sender_company_name": "\u0422\u041e\u041e\"\u0410\u0441\u0435\u043c-2\"", "receiver_company_name": "\u0422\u041e\u041e\"\u0410\u0441\u0435\u043c-2\"", "total_price": "1.000000", "create_date": "10.05.2017", "descri...
and after Log.i("test", "test4" + s) nothing shows into android monitoring
I don't know why my data doesn't record
Pass getActivity() as your Context in all the Fragment class. Try changing it like the following code.
This line:
documentAdapter = new DocumentAdapter(getActivity(), documentsList, Document.DOCUMENT_TYPE.ACT);
This line:
layoutManager = new LinearLayoutManager(getActivity());
And this line:
sharedPreferences = getActivity().getSharedPreferences(Constants.PROJECT, Context.MODE_PRIVATE);
I think the problem is with this line
documentAdapter = new DocumentAdapter(act.getContext(), documentsList, Document.DOCUMENT_TYPE.ACT);
Here, you are passing empty list which does not have any data. And in Adapter in getItemCount() method, you will get size as 0. so there is no data to display.
Try this.
In onPostExecute() method, after for loop where you parse your data call this line.
documentAdapter = new DocumentAdapter(act.getContext(), documentsList, Document.DOCUMENT_TYPE.ACT);
documentAdapter.notifyDataSetChanged();
May be this will solve your issue.
In my case a problem was in assigning RecyclerView's adapter to itself.
private lateinit var adapter: MyAdapter
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.recycler_view_layout, container, false)
val layoutManager = LinearLayoutManager(context)
adapter = MyAdapter(listOf(MyAdapter.Item(1, "dfg")))
view.recycler_view.apply {
this.layoutManager = layoutManager
this.adapter = adapter
this.setHasFixedSize(true)
}
return view
}
After many hours I removed apply operator and understood that compiler recognized layoutManager as local variable, while adapter was recognized as recycler_view.adapter.
Related
How can I rearrange the data from database in a ListView?
everyone. I have an ArrayList of the data and a ListView to showing up the list of the data. Now what I want to do is rearrange the data when I press the button and sort the data in which data has the highest result. Here is my code: public class MainActivity extends AppCompatActivity { private TextView mTextMessage; String[] dataDetail; ArrayList<dataDetail> allDetail = new ArrayList<>(); ListView detailList; final Context context = this; final int min = 0; final int max = 10; final int random = new Random().nextInt((max - min) + 1) + min; Button reorder = findViewById(R.id.arrangeId); private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { #Override public boolean onNavigationItemSelected(#NonNull MenuItem item) { switch (item.getItemId()) { case R.id.navigation_home: mTextMessage.setText(R.string.title_home); return true; case R.id.navigation_dashboard: mTextMessage.setText(R.string.title_dashboard); return true; } return false; } }; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); detailList = findViewById(R.id.dataView); mTextMessage = (TextView) findViewById(R.id.message); BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation); navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); new GetData().execute(); } private class GetData extends AsyncTask<Void, Void, ArrayList<dataDetail>> { protected ArrayList<dataDetail> doInBackground(Void... voids) { HttpURLConnection urlConnection; InputStream in = null; try { URL url = new URL("http://10.0.2.2:8080/projectServer/DataDetailDB?getdata=true"); urlConnection = (HttpURLConnection) url.openConnection(); in = new BufferedInputStream(urlConnection.getInputStream()); } catch (IOException e) { e.printStackTrace(); } String response = convertStreamToString(in); System.out.println("Server response = " + response); try { JSONArray jsonArray = new JSONArray(response); dataDetail = new String[jsonArray.length()]; for (int i = 0; i < jsonArray.length(); i++) { final String customerName = jsonArray.getJSONObject(i).get("customerName").toString(); final String carName = jsonArray.getJSONObject(i).get("carName").toString(); final String appointmentDate = jsonArray.getJSONObject(i).get("appointmentDate").toString(); final String email = jsonArray.getJSONObject(i).get("email").toString(); final String issueDescribe = jsonArray.getJSONObject(i).get("issueDescribe").toString(); final String timeForJob = jsonArray.getJSONObject(i).get("timeForJob").toString(); final String costForJob = jsonArray.getJSONObject(i).get("costForJob").toString(); final String reliableOnCar = jsonArray.getJSONObject(i).get("reliableOnCar").toString(); final String distanceJob = jsonArray.getJSONObject(i).get("distance").toString(); dataDetail tData = new dataDetail(customerName, carName, appointmentDate, email, issueDescribe, timeForJob, costForJob, reliableOnCar, distanceJob); allDetail.add(tData); System.out.println("customername = " + customerName + "carname = " + carName + "appointmentdate = " + appointmentDate + "email = " + email + "describe = " + issueDescribe + "time = " + timeForJob + "cost = " + costForJob + "reliable = " + reliableOnCar + "dis = " + distanceJob); dataDetail [i] = "Name: " + customerName + "\n" + "Appointment Date: " + appointmentDate; reorder.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { float finalResult = random * Float.parseFloat(timeForJob) + random * Float.parseFloat(reliableOnCar) + random * Float.parseFloat(distanceJob) + random * Float.parseFloat(costForJob); System.out.print("Test result " + finalResult + " "); /* Trying to sort the data here which has the highest finalResult * will going to the top of the list */ allDetail = new ArrayList<String>(Arrays.asList(dataDetail)); Collections.sort(allDetail); ArrayAdapter newList = new ArrayAdapter(context, android.R.layout.simple_list_item_1, dataDetail); newList.setAdapter(theList); } }); } } catch (JSONException e) { e.printStackTrace(); } return null; } protected void onPostExecute(ArrayList<dataDetail> dataDetailArrayList) { super.onPostExecute(dataDetailArrayList); ArrayAdapter theList = new ArrayAdapter(context, android.R.layout.simple_list_item_1, dataDetail); detailList.setAdapter(theList); } } public String convertStreamToString(InputStream is) { java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } } But when I try to use sort I get the error says it's incompatible types. allDetail = new ArrayList<String>(Arrays.asList(dataDetail)); Collections.sort(allDetail); The finalResult will do the calculation and get the final result for every data it retrieves from the database. And now I just want to reorder it automatically, This is the logcat: Please anyone can help how can I do the rearrange for the listview?
Collections.sort() will work. Its your problem related to how your are storing your data in list
How do I use onResume and onPause method when I am pressed back button
I have a custom adapter for recyclerview using json webservices. I had to parse the url one by one and show cardview using onscrolllistener(). My question is when I pressed the back button and after I open in recent app (that time onResume called) it will show only which url called at the time of onPause called. So how can I refresh the listview when I call onResume. Thanks in Advance, Here my code synepet.. public class MainActivity extends AppCompatActivity { private RecyclerView mRecyclerView; private RecyclerView.Adapter mAdapter; private GridLayoutManager mGridManager; private ProgressBar mProgressBar; private static String url = "https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=UCGyZswzm4G-wEfRQHgMSAuw&maxResults=50&key=AIzaSyCi0ApXYk08YpzyEO8jYJanaud-Epti6ks&pageToken=CDIQAQ"; JSONArray contacts = null; private String mNextToken; JSONObject jsonObj; private boolean loading = true; int visibleItemCount, totalItemCount, pastVisiblesItems; private List<PlayListItem> mContactList = new ArrayList<PlayListItem>(); private PlayListItem mContact; private Bundle mbundle; String name2 = "Arasu"; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); mProgressBar = (ProgressBar) findViewById(R.id.progressBar); mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view); mRecyclerView.setHasFixedSize(true); // Calling async task to get json new GetContacts().execute(); mAdapter = new CardAdapter(MainActivity.this, mContactList); mRecyclerView.setAdapter(mAdapter); getScreenOrientation(); } #Override public void onResume() { super.onResume(); } #Override protected void onPause() { super.onPause(); System.out.println("Size2---->" + mContactList.size()); } private class GetContacts extends AsyncTask<Void, Void, Void> { #Override protected void onPreExecute() { super.onPreExecute(); // Showing progress dialog mProgressBar.setVisibility(View.VISIBLE); mProgressBar.setMax(100); } #Override protected Void doInBackground(Void... arg0) { // Creating service handler class instance ServiceHandler sh = new ServiceHandler(); // Making a request to url and getting response String jsonArray = sh.makeServiceCall(url, ServiceHandler.GET); //Log.d("Response: ", "> " + jsonArray); if (jsonArray != null) { try { jsonObj = new JSONObject(jsonArray); if (jsonObj.has("nextPageToken")) { loading = true; mNextToken = jsonObj.getString("nextPageToken"); } else { loading = false; } // Getting JSON Array node contacts = jsonObj.getJSONArray("items"); // looping through All Contacts for (int i = 0; i < contacts.length(); i++) { JSONObject c = contacts.getJSONObject(i); String title = c.getJSONObject("snippet").getString("title"); String time = c.getJSONObject("snippet").getString("publishedAt"); String playlist_id = c.get("id").toString(); // Find Screen size and set the Image for this size DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); double x = Math.pow(dm.widthPixels / dm.xdpi, 2); double y = Math.pow(dm.heightPixels / dm.ydpi, 2); double screenInches = Math.sqrt(x + y); int inch = (int) Math.round(screenInches); String image = null; try { if (inch <= 4) { image = c.getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("medium").getString("url"); } else if (inch > 4 && inch <= 6) { image = c.getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("medium").getString("url"); } else if (inch > 6 && inch <= 10) { image = c.getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("medium").getString("url"); } else { image = c.getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("default").getString("url"); } } catch (IndexOutOfBoundsException e) { e.printStackTrace(); } mContact = new PlayListItem(); mContact.setmTitle(title); mContact.setmID(playlist_id); mContact.setmTime(time); mContact.setmThumbnailURL(image); mContact.setmNextToken(mNextToken); mContactList.add(mContact); } } catch (JSONException e) { e.printStackTrace(); } } else { Log.e("ServiceHandler", "Couldn't get any data from the url"); } return null; } #Override protected void onPostExecute(Void result) { super.onPostExecute(result); // Dismiss the progress dialog if (mProgressBar.isShown()) mProgressBar.setVisibility(ProgressBar.GONE); mAdapter.notifyDataSetChanged(); mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() { #Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); visibleItemCount = mGridManager.getChildCount(); totalItemCount = mGridManager.getItemCount(); pastVisiblesItems = mGridManager.findFirstVisibleItemPosition(); if (loading) { if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) { Log.v("...", "Last Item Wow !"); if (jsonObj.has("nextPageToken")) { url = "https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=UCGyZswzm4G-wEfRQHgMSAuw&maxResults=50&key=AIzaSyCi0ApXYk08YpzyEO8jYJanaud-Epti6ks&pageToken=" + mNextToken; System.out.println("url--->" + url); new GetContacts().execute(); } else { url = "https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=UCGyZswzm4G-wEfRQHgMSAuw&maxResults=50&key=AIzaSyCi0ApXYk08YpzyEO8jYJanaud-Epti6ks&pageToken=" + mNextToken; System.out.println("url----else--->" + url); new GetContacts().execute(); } loading = false; } } } }); } } } public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> { private List<PlayListItem> mItems; private Activity activity; public ImageLoader imageLoader; public CardAdapter(Activity activity, List<PlayListItem> items) { this.activity = activity; this.mItems = items; imageLoader = new ImageLoader(activity.getApplicationContext()); } #Override public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View v = LayoutInflater.from(viewGroup.getContext()) .inflate(R.layout.recycler_outer_playlist_cardview, viewGroup, false); ViewHolder viewHolder = new ViewHolder(v); return viewHolder; } #Override public void onBindViewHolder(ViewHolder viewHolder, final int i) { System.out.println("Title Value is----------->"+mItems.get(0)); PlayListItem nature = mItems.get(i); Log.d("Title Value is","----------->"+nature.getmTitle()); viewHolder.tvTitle.setText(nature.getmTitle()); final String playListID = nature.getmID(); final String thumnailsURL = nature.getmThumbnailURL(); final Calendar c = Calendar.getInstance(); int cur_year = c.get(Calendar.YEAR); int cur_month = c.get(Calendar.MONTH) + 1; int cur_day = c.get(Calendar.DAY_OF_MONTH); int cur_hour = c.get(Calendar.HOUR_OF_DAY); int cur_minute = c.get(Calendar.MINUTE); // Getting updated date from url String string = nature.getmTime(); String[] parts = string.split("-"); String part1 = parts[0]; // 004 String part2 = parts[1]; // 034556 String part3 = parts[2]; String[] part4 = part3.split("T"); String part5 = part4[0]; String part6 = part4[1]; // Toast.makeText(activity, "Given Date is : " + part1 + "/" + part2 + "/" + part3, Toast.LENGTH_LONG).show(); // Log.d("Updated Current Day", part5); int giv_yr = Integer.parseInt(part1); int giv_mnt = Integer.parseInt(part2); int giv_day = Integer.parseInt(part5); // Difference Two dates int day_yr = 0, day_mnt = 0, day_day = 0; if (cur_year >= giv_yr) { if (cur_year >= giv_yr) { day_yr = cur_year - giv_yr; } else { day_yr = giv_yr - cur_year; } if (cur_month >= giv_mnt) { day_mnt = cur_month - giv_mnt; } else { day_mnt = giv_mnt - cur_month; } if (cur_day >= giv_day) { day_day = cur_day - giv_day; } else { day_day = giv_day - cur_day; } } String yr = Integer.toString(day_yr); String mnt = Integer.toString(day_mnt); String days = Integer.toString(day_day); if (day_day == 0) viewHolder.tvTime.setText("Updated Today"); else if (day_day < 7) viewHolder.tvTime.setText("Updated " + days + " Days ago"); else if (day_day < 30) { int week = day_day / 7; String Week = Integer.toString(week); viewHolder.tvTime.setText("Updated " + Week + " Weeks ago"); } else { viewHolder.tvTime.setText("Updated " + mnt + " Months ago"); } //imageLoader.DisplayImage(nature.getmThumbnailURL(), viewHolder.imgThumbnail); Picasso.with(activity) .load(nature.getmThumbnailURL()) /*.placeholder(R.drawable.my_thumnail)*/ .into(viewHolder.imgThumbnail); viewHolder.item_view.setOnClickListener(new OnClickListener() { #Override public void onClick(View v) { Intent intent = new Intent(activity, VideoPlayActivity.class); intent.putExtra("PLAYLIST_ID", playListID); intent.putExtra("THUMNAIL_URL", thumnailsURL); v.getContext().startActivity(intent); } }); /*System.out.println("URL -------------->"+nature.getmThumbnailURL()); // String img_url = nature.getmThumbnailURL(); try { URL url = new URL(nature.getmThumbnailURL()); Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream()); System.out.println("Image bmp -------------->"+bmp); //imageView.setImageBitmap(bmp); viewHolder.imgThumbnail.setImageBitmap(bmp); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }*/ } #Override public int getItemCount() { return mItems.size(); } class ViewHolder extends RecyclerView.ViewHolder { public ImageView imgThumbnail; public TextView tvTitle; public TextView tvID; public TextView tvTime; public View item_view; public ViewHolder(View itemView) { super(itemView); imgThumbnail = (ImageView) itemView.findViewById(R.id.img_thumbnail); tvTitle = (TextView) itemView.findViewById(R.id.tv_title); //tvID = (TextView) itemView.findViewById(R.id.tv_id); tvTime = (TextView) itemView.findViewById(R.id.tv_time); item_view = itemView; } } }
I made a small mistake declaring String URL as static but it should be final also assign to another String variable. Finally set the adapter and notifyDataSetChanged where placed in onStart(). private final static String URL = "https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=UCGyZswzm4G-wEfRQHgMSAuw&maxResults=50&key=AIzaSyCi0ApXYk08YpzyEO8jYJanaud-Epti6ks&pageToken=CDIQAQ"; private String url = URL; JSONArray contacts = null; private String mNextToken; JSONObject jsonObj; private boolean loading = true; int visibleItemCount, totalItemCount, pastVisiblesItems; private List<PlayListItem> mContactList; private PlayListItem mContact; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); mProgressBar = (ProgressBar) findViewById(R.id.progressBar); mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view); mRecyclerView.setHasFixedSize(true); // Calling async task to get json if (mContactList == null) mContactList = new ArrayList<PlayListItem>(); System.out.println("onCreate :: Size2---->" + mContactList.size()); } #Override protected void onStart() { super.onStart(); if (mContactList != null) mContactList.clear(); url = URL; new GetContacts().execute(); if (mAdapter == null) mAdapter = new CardAdapter(MainActivity.this, mContactList); mRecyclerView.setAdapter(mAdapter); mAdapter.notifyDataSetChanged(); getScreenOrientation(); System.out.println("onStart :: Size2---->" + mContactList.size()); } #Override protected void onResume() { ActivitySwitcher.animationIn(findViewById(R.id.container_first), getWindowManager()); super.onResume(); System.out.println("onResume :: Size2---->" + mContactList.size()); mAdapter.notifyDataSetChanged(); }
Android ListView on Ready or on Initialized listener
I am having a listview which I am populating from a database. The listview is taking some time(<300ms) to populate the list. If I am doing a smoothScrollToPosition on the onActivityCreated function it is doing nothing. On the OnCreate function I had to wait for ~200ms before I could call smoothScrollToPosition before which even the ListView Object is not initialized. I can use the getViewTreeObserver as below which runs fine but it requires the minimum sdk version 16. I was trying to get it working for version 14~15. mListView.getViewTreeObserver().addOnGlobalLayoutListener( new ViewTreeObserver.OnGlobalLayoutListener() { #Override public void onGlobalLayout() { mListView.smoothScrollToPosition(adapter.getCount()); // unregister listener (this is important) mListView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } }); The code I am having - public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); list = new ArrayList<Chat>(); db = new DBAdapter(getContext()); adapter = new CustomChatAdapter(getContext(), list); Log.d("ListView1", "Value of f: " + f); thread= new Thread(){ #Override public void run(){ try { synchronized(this){ wait(200); } } catch(InterruptedException ex){ Log.d("ListView1", "Interrupted Exception: " +ex.toString()); } Log.d("ListView1", "Adapter Count: " +adapter.getCount()); mListView.smoothScrollToPosition(adapter.getCount()); } }; getMsg("1", getActivity().getIntent().getStringExtra("key")); thread.start(); Log.d("ListView1", "Adapter Count: " +adapter.getCount()); //mListView.smoothScrollToPosition(adapter.getCount()); } public void getMsg(String myid, String friend_id) { list.clear(); try { Cursor cur = db.get_friend_shouts(myid,friend_id); String img_id1 = ""; String img_id2 =""; if (cur != null) { if (cur.moveToFirst()) { do { img_id1 = cur.getString(cur.getColumnIndex("image_id")); img_id1 = img_id1 == null ? "null" : img_id1; img_id2 = cur.getString(cur.getColumnIndex("r_img_id")); img_id2 = img_id2 == null ? "null" : img_id2; list.add(new Chat( img_id1 , cur.getString(cur.getColumnIndex("firstname")) + " " + cur.getString(cur.getColumnIndex("lastname")), cur.getString(cur.getColumnIndex("user_id")), cur.getString(cur.getColumnIndex("shout_msg")) , img_id2, cur.getString(cur.getColumnIndex("r_firstname")) + " " + cur.getString(cur.getColumnIndex("r_lastname")) , cur.getString(cur.getColumnIndex("r_user_id")) , cur.getString(cur.getColumnIndex("rec_time")) )); //Log.d("ListView1", "User details: " + cur.getString(cur.getColumnIndex("user_id")) + " " + cur.getString(cur.getColumnIndex("firstname")) + cur.getString(cur.getColumnIndex("lastname")) + " " + cur.getString(cur.getColumnIndex("image_id"))); } while (cur.moveToNext()); } } adapter.notifyDataSetChanged(); if(mListView!=null) mListView.smoothScrollToPosition(adapter.getCount()); } catch (Exception e) { Log.d("ListView1", "getMsg Error: " + e.toString()); } } The ArrayAdapter class - public class CustomChatAdapter extends ArrayAdapter<Chat> { private final Context context; private final List<Chat> list; public CustomChatAdapter(Context context, ArrayList<Chat> presidents) { super(context, R.layout.chatrowlayout, presidents); this.context = context; this.list = presidents; } static class ViewContainer { public ImageView imageView; public TextView txtMsg; public ImageView imageView1; public TextView txtTime; } #Override public View getView(int position, View view, ViewGroup parent) { ViewContainer viewContainer; View rowView = view; //---print the index of the row to examine--- //Log.d("ListView1",String.valueOf(position)); //if(rowView == null) { viewContainer = new ViewContainer(); LayoutInflater inflater = LayoutInflater.from(context); rowView= inflater.inflate(R.layout.chatrowlayout, null, true); viewContainer.txtMsg = (TextView) rowView.findViewById(R.id.msgText); viewContainer.imageView = (ImageView) rowView.findViewById(R.id.icon1); viewContainer.imageView1 = (ImageView) rowView.findViewById(R.id.icon2); viewContainer.txtTime = (TextView) rowView.findViewById(R.id.timeText); rowView.setTag(viewContainer); /*} else { viewContainer = (ViewContainer) rowView.getTag(); }*/ viewContainer.txtMsg.setText(list.get(position).getMsg()); viewContainer.txtTime.setText(list.get(position).getMsg_time()); if(list.get(position).getS_id().equals("1")) { viewContainer.imageView.setImageBitmap(BitmapFactory.decodeFile(new Info().p + File.separator+ "image_" + list.get(position).getPic_id1() + ".jpeg" )); viewContainer.imageView1.setAlpha(0); viewContainer.txtMsg.setGravity(Gravity.LEFT); } else { viewContainer.imageView1.setImageBitmap(BitmapFactory.decodeFile(new Info().p + File.separator+ "image_" + list.get(position).getPic_id1() + ".jpeg" )); viewContainer.imageView.setAlpha(0); viewContainer.txtMsg.setGravity(Gravity.RIGHT); } return rowView; } }
removeGlobalOnLayoutListerner for pre SDK 16, addOnGlobalLayout works for pre 16.
OnCreate is too early. You should wait for the layout to be inflated. Smooth scrolling in onResume should do the trick: #Override protected void onResume() { mListView.smoothScrollToPosition(adapter.getCount()); }
How to call AsyncTask class in the fragment class, when i call is not go in the AsyncTask it will return null view what i do?
How to call AsyncTask class in the fragment class, when i call is not go in the AsyncTask it will return null view what i do ? And my view is created in postExecute afetr i got all the data from doInbackground. public class ShowResultsFragment extends android.support.v4.app.Fragment { Context context; ArrayList<Semester> semesterArrayList; LayoutInflater inflaterView; ViewGroup containerView; View newView; #Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { this.inflaterView = inflater; this.containerView = container; context = container.getContext(); new StudentResultAsyncTask().execute(); return newView; } public class StudentResultAsyncTask extends AsyncTask { JSONObject jsonObject = null; ProgressDialog pDialog; String jsondata = "{\"1\" :[{\"subName\":\"EG\",\"subCode\":\"1009\",\"subCredit\":\"5\",\"subGrade\":\"AA\"}," + "{\"subName\":\"ES\",\"subCode\":\"2009\",\"subCredit\":\"6\",\"subGrade\":\"DD\"}," + "{\"subName\":\"EME\",\"subCode\":\"3009\",\"subCredit\":\"6\",\"subGrade\":\"FF\"}," + "{\"subName\":\"EEE\",\"subCode\":\"4009\",\"subCredit\":\"7\",\"subGrade\":\"BC\"}," + "{\"subName\":\"MOS\",\"subCode\":\"5009\",\"subCredit\":\"6\",\"subGrade\":\"FF\"}," + "{\"subName\":\"M-1\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"CD\"}," + "{\"subName\":\"EE\",\"subCode\":\"45090\",\"subCredit\":\"4\",\"subGrade\":\"AB\"}," + "{\"subName\":\"ECE\",\"subCode\":\"10090\",\"subCredit\":\"5\",\"subGrade\":\"FF\"}," + "{\"SPI\":\"1.4\",\"CPI\":\"4.67\"}]," + "\"2\":[{\"subName\":\"M-2\",\"subCode\":\"111009\",\"subCredit\":\"6\",\"subGrade\":\"DD\"}," + "{\"subName\":\"Workshop\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," + "{\"subName\":\"CPU\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"FF\"}," + "{\"subName\":\"EG\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"CC\"}," + "{\"subName\":\"M-4\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"CD\"}," + "{\"subName\":\"AE\",\"subCode\":\"103309\",\"subCredit\":\"6\",\"subGrade\":\"CD\"}," + "{\"subName\":\"EG-1\",\"subCode\":\"11119\",\"subCredit\":\"6\",\"subGrade\":\"CD\"}," + "{\"subName\":\"AE\",\"subCode\":\"8876\",\"subCredit\":\"6\",\"subGrade\":\"FF\"}," + "{\"SPI\":\"2.5\",\"CPI\":\"6.67\"}]," + "\"3\":[{\"subName\":\"M-3\",\"subCode\":\"111009\",\"subCredit\":\"6\",\"subGrade\":\"AA\"}," + "{\"subName\":\"BE\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," + "{\"subName\":\"DLD\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"BB\"}," + "{\"subName\":\"NCS\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"BC\"}," + "{\"subName\":\"M-4\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"CC\"}," + "{\"subName\":\"AE\",\"subCode\":\"103309\",\"subCredit\":\"6\",\"subGrade\":\"CD\"}," + "{\"SPI\":\"6.50\",\"CPI\":\"0.67\"}]," + "\"4\":[{\"subName\":\"AAS\",\"subCode\":\"111009\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," + "{\"subName\":\"C++\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," + "{\"subName\":\"Management-1\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," + "{\"subName\":\"EG\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," + "{\"subName\":\"M-4\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," + "{\"subName\":\"AE\",\"subCode\":\"103309\",\"subCredit\":\"6\",\"subGrade\":\"DD\"}," + "{\"SPI\":\"9.50\",\"CPI\":\"5.67\"}]," + "\"5\":[{\"subName\":\"WAD\",\"subCode\":\"111022209\",\"subCredit\":\"6\",\"subGrade\":\"FF\"}," + "{\"subName\":\"AES\",\"subCode\":\"703309\",\"subCredit\":\"6\",\"subGrade\":\"DD\"}," + "{\"SPI\":\"5.50\",\"CPI\":\"5.67\",\"CGPA\":\"5.67\"}]," + "\"6\":[{\"subName\":\"SP\",\"subCode\":\"66622209\",\"subCredit\":\"6\",\"subGrade\":\"FF\"}," + "{\"subName\":\"Parallel\",\"subCode\":\"66622209\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," + "{\"subName\":\"Java\",\"subCode\":\"66622209\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," + "{\"subName\":\"COA\",\"subCode\":\"66622209\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," + "{\"subName\":\"Management\",\"subCode\":\"66622209\",\"subCredit\":\"6\",\"subGrade\":\"FF\"}," + "{\"subName\":\"TOC\",\"subCode\":\"703309\",\"subCredit\":\"6\",\"subGrade\":\"DD\"}," + "{\"SPI\":\"5.50\",\"CPI\":\"5.67\",\"CGPA\":\"6.07\"}]," + "\"7\":[{\"subName\":\"CD\",\"subCode\":\"12522209\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," + "{\"subName\":\"WCMP\",\"subCode\":\"12522209\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," + "{\"subName\":\"SP\",\"subCode\":\"12522209\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," + "{\"subName\":\"Advance Java\",\"subCode\":\"703309\",\"subCredit\":\"6\",\"subGrade\":\"FF\"}," + "{\"SPI\":\"8.90\",\"CPI\":\"6.09\",\"CGPA\":\"7.77\"}]," + "\"8\":[{\"subName\":\"Android\",\"subCode\":\77022209\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," + "{\"subName\":\"PP\",\"subCode\":2209\",\"subCredit\":\"6\",\"subGrade\":\"BB\"}," + "{\"subName\":\"DS\",\"subCode\":\"7309\",\"subCredit\":\"6\",\"subGrade\":\"DD\"}," + "{\"SPI\":\"5.70\",\"CPI\":\"5.97\",\"CGPA\":\"6.85\"}]}"; #Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(context); pDialog.setMessage("Loading..."); pDialog.show(); } #Override protected String doInBackground(String... params1) { String key; Iterator<String> iter; int length; /* List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(c.getResources().getString(R.string.keyUsername), Utility.getUsername(c))); JSONParser jp=new JSONParser(); //jp.makeHttpRequest(c.getResources().getString(R.string.server_name)+ c.getResources().getString(R.string.login_file), "POST", params); */ //Todo : delete comment when data is come from server. try { jsonObject = new JSONObject(jsondata); } catch (JSONException e) { e.printStackTrace(); } iter = jsonObject.keys(); semesterArrayList = new ArrayList<>(); while (iter.hasNext()) { key = iter.next(); try { JSONArray jsonArray = jsonObject.getJSONArray(key); length = jsonArray.length(); ArrayList<SubjectDetails> saveSubDetailsArrayList = new ArrayList<>(); Semester semDetail = new Semester(); semDetail.setSemester(key); for (int i = 0; i < length; i++) { JSONObject jsonObject1 = jsonArray.getJSONObject(i); SubjectDetails subDetails = new SubjectDetails(); if (i == length - 1) { Float spi = Float.valueOf(jsonObject1.getString(getResources().getString(R.string.server_key_result_SPI))); Float cpi = Float.valueOf(jsonObject1.getString(getResources().getString(R.string.server_key_result_CPI))); semDetail.setSpi(spi); semDetail.setCpi(cpi); if (key.equals("5") || key.equals("6") || key.equals("7") || key.equals("8")) { Float cgpi = Float.valueOf(jsonObject1.getString(getResources().getString(R.string.server_key_result_CGPA))); semDetail.setCgpi(cgpi); } } else { String subname = jsonObject1.getString(getResources().getString(R.string.server_key_result_subName)); String subcode = jsonObject1.getString(getResources().getString(R.string.server_key_result_subCode)); String subcredit = jsonObject1.getString(getResources().getString(R.string.server_key_result_subCredit)); String subgrade = jsonObject1.getString(getResources().getString(R.string.server_key_result_subGrade)); subDetails.setSubname(subname); subDetails.setSubcode(subcode); subDetails.setSubcredit(subcredit); subDetails.setSubgrade(subgrade); saveSubDetailsArrayList.add(subDetails); semDetail.setGetSubjectDetails(saveSubDetailsArrayList); } } semesterArrayList.add(semDetail); } catch (JSONException e) { e.printStackTrace(); } } return null; } #Override protected void onPostExecute(String s) { super.onPostExecute(s); ListView lv = (ListView) newView.findViewById(R.id.listview); lv.setAdapter(new ShowResultAdapter(semesterArrayList, context)); pDialog.dismiss(); } } and this is my Adapter class... public class ShowResultAdapter extends BaseAdapter { ArrayList<Semester> semesterArrayList; Context c; LinearLayout linearHeader; ShowResultAdapter(ArrayList<Semester> saveDetails, Context context) { semesterArrayList = saveDetails; c = context; } #Override public int getCount() { return semesterArrayList.size(); } #Override public Object getItem(int position) { return null; } #Override public long getItemId(int position) { return 0; } #Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; LinearLayout linearSub; LinearLayout linearSpiCpiCgpa; LayoutInflater inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.layout_result_adapter, null); LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.linear); TextView sem = new TextView(c); sem.setGravity(Gravity.CENTER_HORIZONTAL); sem.setTextSize(20); sem.setPadding(0, 0, 0, 10); sem.setTextColor(Color.WHITE); sem.setText(c.getResources().getString(R.string.result_Semester) + " " + ":" + " " + semesterArrayList.get(position).getSemester()); sem.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG); linearLayout.addView(sem); linearHeader = new LinearLayout(c); linearHeader.setOrientation(LinearLayout.HORIZONTAL); linearHeader.setWeightSum(4); TextView name = new TextView(c); setHeader(name, c.getResources().getString(R.string.server_key_result_subName)); linearHeader.addView(name); TextView code = new TextView(c); setHeader(code, c.getResources().getString(R.string.server_key_result_subCode)); linearHeader.addView(code); TextView credit = new TextView(c); setHeader(credit, c.getResources().getString(R.string.server_key_result_subCredit)); linearHeader.addView(credit); TextView grade = new TextView(c); setHeader(grade, c.getResources().getString(R.string.server_key_result_subGrade)); linearHeader.addView(grade); linearLayout.addView(linearHeader); if (semesterArrayList.get(position).getSemester().equals("1") || semesterArrayList.get(position).getSemester().equals("2") || semesterArrayList.get(position).getSemester().equals("3") || semesterArrayList.get(position).getSemester().equals("4")) { linearSpiCpiCgpa = new LinearLayout(c); linearSpiCpiCgpa.setOrientation(LinearLayout.HORIZONTAL); linearSpiCpiCgpa.setWeightSum(4); for (int i = 0; i < semesterArrayList.get(position).getGetSubjectDetails().size(); i++) { linearSub = new LinearLayout(c); linearSub.setLayoutParams(new TableLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 4)); linearSub.setOrientation(LinearLayout.HORIZONTAL); TextView subname = new TextView(c); setSubject(subname); TextView subcode = new TextView(c); setSubject(subcode); TextView subcredit = new TextView(c); setSubject(subcredit); TextView subgrade = new TextView(c); setSubject(subgrade); subgrade.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); subname.setText(semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubname()); subcode.setText(semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubcode()); subcredit.setText(semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubcredit()); subgrade.setText(semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubgrade()); if (semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubgrade().equals("FF")) { subgrade.setTextColor(Color.parseColor("#ff0000")); } linearSub.addView(subname); linearSub.addView(subcode); linearSub.addView(subcredit); linearSub.addView(subgrade); linearLayout.addView(linearSub); } TextView spi = new TextView(c); setSpiCpiCgpa(spi); TextView cpi = new TextView(c); setSpiCpiCgpa(cpi); spi.setText(c.getResources().getString(R.string.server_key_result_SPI) + " " + ":" + " " + semesterArrayList.get(position).getSpi()); cpi.setText(c.getResources().getString(R.string.server_key_result_CPI) + " " + ":" + " " + semesterArrayList.get(position).getCpi()); linearSpiCpiCgpa.addView(spi); linearSpiCpiCgpa.addView(cpi); linearLayout.addView(linearSpiCpiCgpa); } else { linearSpiCpiCgpa = new LinearLayout(c); linearSpiCpiCgpa.setOrientation(LinearLayout.HORIZONTAL); linearSpiCpiCgpa.setWeightSum(6); for (int i = 0; i < semesterArrayList.get(position).getGetSubjectDetails().size(); i++) { linearSub = new LinearLayout(c); linearSub.setOrientation(LinearLayout.HORIZONTAL); linearSub.setLayoutParams(new TableLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 4)); TextView subname = new TextView(c); setSubject(subname); TextView subcode = new TextView(c); setSubject(subcode); TextView subcredit = new TextView(c); setSubject(subcredit); TextView subgrade = new TextView(c); setSubject(subgrade); subname.setText(semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubname()); subcode.setText(semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubcode()); subcredit.setText(semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubcredit()); subgrade.setText(semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubgrade()); linearSub.addView(subname); linearSub.addView(subcode); linearSub.addView(subcredit); linearSub.addView(subgrade); linearLayout.addView(linearSub); } TextView spi = new TextView(c); setSpiCpiCgpa(spi); TextView cpi = new TextView(c); setSpiCpiCgpa(cpi); TextView cgpi = new TextView(c); setSpiCpiCgpa(cgpi); spi.setText(c.getResources().getString(R.string.server_key_result_SPI) + " " + ":" + " " + semesterArrayList.get(position).getSpi()); cpi.setText(c.getResources().getString(R.string.server_key_result_CPI) + " " + ":" + " " + semesterArrayList.get(position).getCpi()); cgpi.setText(c.getResources().getString(R.string.server_key_result_CGPA) + " " + ":" + " " + semesterArrayList.get(position).getCgpi()); linearSpiCpiCgpa.addView(spi); linearSpiCpiCgpa.addView(cpi); linearSpiCpiCgpa.addView(cgpi); linearLayout.addView(linearSpiCpiCgpa); } return view; } public void setHeader(TextView txtObj, String setText) { txtObj.setPadding(0, 0, 0, 10); txtObj.setGravity(Gravity.CENTER_HORIZONTAL); txtObj.setBackgroundResource(R.drawable.whiteborder); txtObj.setTextColor(Color.WHITE); txtObj.setBackgroundColor(Color.parseColor("#80000000")); txtObj.setTextSize(16); txtObj.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); txtObj.setLayoutParams(new TableLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1)); txtObj.setText(setText); } public void setSubject(TextView txtObj) { txtObj.setLayoutParams(new TableLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 1)); txtObj.setPadding(5, 5, 5, 5); txtObj.setBackgroundResource(R.drawable.resultborder); txtObj.setTextColor(Color.WHITE); txtObj.setGravity(Gravity.CENTER); } public void setSpiCpiCgpa(TextView txtObj) { txtObj.setPadding(5, 5, 5, 5); txtObj.setGravity(Gravity.CENTER_HORIZONTAL); txtObj.setTextColor(Color.WHITE); txtObj.setBackgroundResource(R.drawable.resultborder); txtObj.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); txtObj.setLayoutParams(new TableLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 2)); } }
You didn't inflate your View. How do you expect it to not return null? You should inflate the View in onCreateView() rather than in onPostExecute() Change it like this. ShowResultAdapter adapter = null; #Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { this.inflaterView = inflater; this.containerView = container; context = container.getContext(); newView = inflaterView.inflate(R.layout.your_layout, null); lv = (ListView) newView.findViewById(R.id.listview); // Define lv at class level adapter = new ShowResultAdapter(semesterArrayList, getActivity()) lv.setAdapter(adapter); new StudentResultAsyncTask().execute(); return newView; } In your onPostExecute() method do this protected void onPostExecute(String s) { super.onPostExecute(s); adapter.notifyDataSetChanged(); pDialog.dismiss(); }
Following from the suggestions made by Rohit5k2, alter your getcount() method in your adapter to respond to null data: #Override public int getCount() { if (semesterArrayList == null) { return 0; } return semesterArrayList.size(); } When you first call setAdapter() on the ListView in Rohit's answer, the data will be null as it is only populated in onPostExecute(). However, if you make the above adjustment, then all will happen is that the list will be empty until the data is populated.
ArrayList within array adapter remains null
I am new to android and my list view is not working correctly. The list displays all the data from an array list as a single row. My MainActivity looks like this: public class MainActivity extends FragmentActivity implements OnClickListener{ .. ArrayList<StorylineData> storylineData; ArrayList<SummaryData> summary; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mSpinnerAPI = (Spinner) findViewById(R.id.spinnerAPI); mButtonSubmit = (Button) findViewById(R.id.buttonSubmit); mEditTextResponse = (ListView) findViewById(R.id.editResponse); mProgressRequest = (ProgressBar) findViewById(R.id.progressRequest); mButtonSubmit.setOnClickListener(this); storylineData = new ArrayList<StorylineData>(); ... #Override public void onClick(View v) { toggleProgress(true); switch (mSpinnerAPI.getSelectedItemPosition()) { case 0: // Authenticate ... case 4: // Get Summary Day MovesAPI.getSummary_SingleDay(summaryHandler, "20150418", null);//Date changed to "20150117" break; ... case 10: // Get Storyline Day MovesAPI.getStoryline_SingleDay(storylineHandler, "20150418", "20140714T073812Z", false);//Date changed to "20150418" "null changed to"20140714T073812Z" break; ... toggleProgress(false); break; } } ... private MovesHandler<ArrayList<StorylineData>> storylineHandler = new MovesHandler<ArrayList<StorylineData>>() { #Override public void onSuccess(ArrayList<StorylineData> result) { toggleProgress(false); updateResponse( "Date:\t" + result.get(0).getDate() + "\n" + "-----------Activity 1 Summary--------\t" + "\n" + "Activity:\t" + result.get(0).getActivity().toString() + "\n"//returns 1587 with .getCaloriesIdle() ... + "-----------Activity 2 Summary---------\t" + "\n" + "Activity:\t" + result.get(0).getSummary().get(0).getActivity() + "\n"//returns 1587 with .getCaloriesIdle() ... + "-----------Segments---------\t" + "\n" + "Type:\t" + result.get(0).getSegments().get(0).getType() + "\n"//returns 1587 with .getCaloriesIdle() ... } public void updateResponse(final String message) { MainActivity.this.runOnUiThread(new Runnable() { #Override public void run() { mButtonSubmit.setText(message); StorylineAdapter adapter = new StorylineAdapter(MainActivity.this, R.layout.item_storyline, storylineData); mEditTextResponse.setAdapter(adapter); } }); } } My ArrayAdapter class looks like this: public class StorylineAdapter extends ArrayAdapter<StorylineData> { private Context context; private ArrayList<StorylineData> storylineData; public StorylineAdapter(Context context, int resource, ArrayList<StorylineData> objects) { super(context, resource, objects); this.context = context; this.storylineData = objects; } #Override public View getView(int position, View convertView, ViewGroup parent){ LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.item_storyline, parent, false); //Display in the TextView widget StorylineData storylineData1 = storylineData.get(position); TextView tv = (TextView) view.findViewById(R.id.textView1); tv.setText(storylineData1.getDistance()); return view; } #Override public int getCount() { if (storylineData!=null) { return storylineData.size(); } else { Log.e("Adapter", "Summary array is null"); return 0; } } } Here is my parser class: public class StorylineData extends ArrayList<StorylineData> { ...Getters/Setters... /** * Parse a {#link org.json.JSONObject} from storyline {#link org.json.JSONArray}, then return the corresponding {#link StorylineData} object. * * #param jsonObject : the storyline JSON object received from server * #return corresponding {#link StorylineData} */ public static StorylineData parse(JSONObject jsonObject) throws JSONException { if (jsonObject != null) { StorylineData storylineData = new StorylineData(); storylineData.date = jsonObject.optString("date"); storylineData.caloriesIdle = jsonObject.optInt("caloriesIdle"); storylineData.lastUpdate = jsonObject.optString("lastUpdate"); storylineData.summary = new ArrayList<SummaryData>(); storylineData.segments = new ArrayList<SegmentData>(); /**Get the data associated with the array named summary **To get a specific JSONArray: Summary*/ JSONArray summariesJsonArray = jsonObject.optJSONArray("summary"); if (summariesJsonArray != null) for (int i = 0; i < summariesJsonArray.length(); i++) { /**each time through array will need to get a reference of current object*/ JSONObject summaryJsonObject = summariesJsonArray.optJSONObject(i); if (summaryJsonObject != null) { /**===============Translate data from json to Java=================*/ /**Create a new OBJECT OF ARRAY STORYLINE/SUMMARY*/ ArrayList<SummaryData> summary = new ArrayList<SummaryData>(); // initialisation must be outside the loop storylineData.setSummary(summary); /**Get summary from json into java*/ summariesJsonArray.getJSONObject(i).getString("distance"); /**Get date from json into java*/ String date = summaryJsonObject.optString("date"); storylineData.setDate(date); /**Get group from json into java*/ String group = summaryJsonObject.optString("group");//Get name using key e.g. date storylineData.setGroup(group); ... storylineData.summary.add(SummaryData.parse(summaryJsonObject)); Log.d("StorylineDataCls \t sJo", summaryJsonObject.toString() + "Log\n"); System.out.println("print distance" + summariesJsonArray.getJSONObject(i).getString("distance")); System.out.println("print summary" + summaryJsonObject); } } JSONArray segmentsJsonArray = jsonObject.optJSONArray("segments"); if (segmentsJsonArray != null) { for (int i = 0; i < segmentsJsonArray.length(); i++) { JSONObject segment = segmentsJsonArray.optJSONObject(i); if (segment != null) { ArrayList<SegmentData> segments = new ArrayList<SegmentData>(); // initialisation must be outside the loop storylineData.setSegments(segments); String type = segment.optString("type"); storylineData.setType(type); ... storylineData.segments.add(SegmentData.parse(segment)); Log.d("StorylineDataCls \t sSo", segment.toString()); } } } return storylineData; } return null; } }