I have an app which downloads YouTube JSON data. The code works perfectly in a desktop app, but not in android (the list is null when trying to iterate through it). Here's my code which matters:
public String DownloadJSONData(){
BufferedReader reader = null;
String webc = "";
try{
URL url = new URL("http://gdata.youtube.com/feeds/api/users/thecovery/uploads?v=2&alt=json");
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while((read = reader.read(chars)) != -1){
buffer.append(chars,0,read);
}
webc = buffer.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
return webc;
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println(webc);
return webc;
}
public void GetData() throws JSONException {
JSONObject obj = new JSONObject(DownloadJSONData());
JSONArray feed = obj.getJSONObject("feed").getJSONArray("entry");
for(int i = 0; i < feed.length(); i++){
EPISODE_NAME.add(feed.getJSONObject(i).getJSONObject("title").getString("$t"));
EPISODE_LINK.add(feed.getJSONObject(i).getJSONArray("link").getJSONObject(0).getString("href"));
}
ListView episodes = (ListView) findViewById(R.id.episodeChooser);
ArrayAdapter<String> episodesSource = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,EPISODE_NAME);
}
}
In the onCreate method, I call the GetData() method, and I try to set the adapter to the ListView from the EPISODE_NAME ArrayList, but it's null. I also tried to set the adapter after the method, in onCreate, but no luck. Anyone can help?
It works fine
Add Below permission in Manifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
ManiActivity.java
public class MainActivity extends Activity {
private ListView listView;
private List<FeedsDTO> feedsList = new ArrayList<FeedsDTO>();
private FeedsDTO dto = null;
private BackgroundThread backgroundThread;
private CustomAdapter customAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listview);
backgroundThread = new BackgroundThread();
backgroundThread.execute();
}
private void setListViewAdapter(){
customAdapter = new CustomAdapter(this, R.layout.listitem, feedsList);
listView.setAdapter(customAdapter);
}
private class BackgroundThread extends AsyncTask<Void, Void, String> {
private ProgressDialog progressBar = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar = new ProgressDialog(MainActivity.this);
progressBar.setCancelable(false);
progressBar.show();
}
#Override
protected String doInBackground(Void... params) {
BufferedReader reader = null;
String webc = "";
try{
URL url = new URL("http://gdata.youtube.com/feeds/api/users/thecovery/uploads?v=2&alt=json");
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while((read = reader.read(chars)) != -1){
buffer.append(chars,0,read);
}
webc = buffer.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
return webc;
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println(webc);
return webc;
}
#Override
protected void onPostExecute(String result) {
JSONObject obj;
try {
obj = new JSONObject(result);
JSONArray feed = obj.getJSONObject("feed").getJSONArray("entry");
Log.i("=======", "========="+feed.length());
for(int i = 0; i < feed.length(); i++){
dto = new FeedsDTO();
dto.setName(feed.getJSONObject(i).getJSONObject("title").getString("$t"));
dto.setLink(feed.getJSONObject(i).getJSONArray("link").getJSONObject(0).getString("href"));
feedsList.add(dto);
dto = null;
}
Log.i("=======LIst Size", "========="+feedsList.size());
progressBar.dismiss();
setListViewAdapter();
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(result);
}
}
}
CustomAdapter.java
public class CustomAdapter extends ArrayAdapter<FeedsDTO>{
private LayoutInflater inflater;
private int layoutID;
public CustomAdapter(Context cntx, int resource, List<FeedsDTO> objects) {
super(cntx, resource, objects);
this.inflater =(LayoutInflater) cntx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.layoutID = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
try {
ViewHolder holder = null;
if (convertView == null) {
convertView = inflater.inflate(layoutID, null);
holder = new ViewHolder();
holder.NameTV = (TextView) convertView.findViewById(R.id.textview);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
FeedsDTO feedsDTO = getItem(position);
holder.NameTV.setText(feedsDTO.getName());
feedsDTO = null;
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
private class ViewHolder{
TextView NameTV;
}
}
FeedsDTO.java
public class FeedsDTO {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
private String link;
}
listitem.xlm:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textview"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</TextView>
I hope this code will work perfectly
Most apps include several different activities that allow the user to
perform different actions. Whether an activity is the main activity
that's created when the user clicks your app icon or a different
activity that your app starts in response to a user action, the system
creates every new instance of Activity by calling its onCreate()
method.
You must implement the onCreate() method to perform basic application
startup logic that should happen only once for the entire life of the
activity. For example, your implementation of onCreate() should define
the user interface and possibly instantiate some class-scope
variables.
For example, the following example of the onCreate() method shows some
code that performs some fundamental setup for the activity, such as
declaring the user interface (defined in an XML layout file), defining
member variables, and configuring some of the UI.
You are basically mixing stuff left and right. First create your Interface in the onCreate() and do the logic in onStart().
You should read the android lifecycle. See here
Related
Here I am trying to display the name and price of the test.
and I'm taking a recycler view to do the same using the JET Parsing GET method.
But I'm not getting anything in my business and showing myself black there.
here is my code
please help me find the solution.
Model class
public class TestListsModel {
public String test_price;
public String testlist_id;
public String test_name;
}
This is my Adapter:
public class AdapterTestList extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private LayoutInflater inflater;
List<TestListsModel> data= Collections.emptyList();
TestListsModel current;
int currentPos=0;
// create constructor to innitilize context and data sent from MainActivity
public AdapterTestList(Context context, List<TestListsModel> data){
this.context=context;
inflater= LayoutInflater.from(context);
this.data=data;
}
// Inflate the layout when viewholder created
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.test_list_row, parent,false);
MyHolder holder=new MyHolder(view);
return holder;
}
// Bind data
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
// Get current position of item in recyclerview to bind data and assign values from list
MyHolder myHolder= (MyHolder) holder;
TestListsModel current=data.get(position);
myHolder.testName.setText(current.test_name);
myHolder.testPrice.setText( current.test_price);
// load image into imageview using glide
/* Glide.with(context).load("http://192.168.1.7/test/images/" + current.fishImage)
.placeholder(R.drawable.ic_img_error)
.error(R.drawable.ic_img_error)
.into(myHolder.ivFish);*/
}
// return total item from List
#Override
public int getItemCount() {
return data.size();
}
class MyHolder extends RecyclerView.ViewHolder{
TextView testName;
TextView testPrice;
// create constructor to get widget reference
public MyHolder(View itemView) {
super(itemView);
testName = (TextView) itemView.findViewById(R.id.test_name);
testPrice = (TextView) itemView.findViewById(R.id.price_name);
}
}
}
This is my Activity Class:
public class HealthServicesActivity extends AppCompatActivity implements View.OnClickListener {
SharePreferenceManager<LoginModel> sharePreferenceManager;
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView testListRecylerView;
private AdapterTestList mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_health_services);
ButterKnife.bind(this);
sharePreferenceManager = new SharePreferenceManager<>(getApplicationContext());
dayTimeDisplay();
new AsyncLogin().execute();
}
private class AsyncLogin extends AsyncTask<String, String, String> {
//ProgressDialog pdLoading = new ProgressDialog(getApplicationContext());
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
/* pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();*/
}
#Override
protected String doInBackground(String... params) {
try {
String url_test="http://192.168.1.80/aoplnew/api/users/gettestlist/"+sharePreferenceManager.getUserLoginData(LoginModel.class).getResult().getCenterId();
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
//url = new URL("http://192.168.1.7/test/example.json");
url = new URL(url_test);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("[]");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
//pdLoading.dismiss();
List<TestListsModel> data=new ArrayList<>();
//pdLoading.dismiss();
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
TestListsModel testData = new TestListsModel();
testData.testlist_id= json_data.getString("testlist_id");
testData.test_name= json_data.getString("test_name");
testData.test_price= json_data.getString("test_price");
data.add(testData);
}
// Setup and Handover data to recyclerview
testListRecylerView = (RecyclerView)findViewById(R.id.test_list_recycler_view);
mAdapter = new AdapterTestList(HealthServicesActivity.this, data);
testListRecylerView.setAdapter(mAdapter);
testListRecylerView.setLayoutManager(new LinearLayoutManager(HealthServicesActivity.this));
} catch (JSONException e) {
Toast.makeText(HealthServicesActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
Thanks in advance for any answer!
You need to set the setLayoutManager before the setting the adapter like below. In your code, you have setAdapter() before the setLayoutManager therefore your adapter not set properly.
Refer this for the further explanation https://developer.android.com/guide/topics/ui/layout/recyclerview
testListRecylerView = (RecyclerView)findViewById(R.id.test_list_recycler_view);
mAdapter = new AdapterTestList(HealthServicesActivity.this, data);
/**
* SET THE LAYOUT MANAGER BEFORE SETTING THE ADAPTER
*/
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(HealthServicesActivity.this);
testListRecylerView.setLayoutManager(mLayoutManager);
testListRecylerView.setItemAnimator(new DefaultItemAnimator());
/**
* AND THAN SET THE ADAPTER
*/
testListRecylerView.setAdapter(mAdapter);
Im new to android development have very basic knowledge of this whatever i have achieved till now is achieved using this website or youtube videos i'm stuck in AsyncTask (Earlier i was using .get() on Create View and it was working fine but UI Was blocked until task is finished. To Avoid UI Blocking i was advice to remove .get() function from OnCreateView() function now after removing this im not being able to get any data from AsyncTask). I did that but now i'm not being able to create view i did lots of research but unable to get this strength
Here is my Codes Please Help how to create view from this
OnCreateView() :-
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View GView = inflater.inflate(R.layout.fragment_dashboard, container, false);
progressBarHolder = (FrameLayout) GView.findViewById(R.id.progressBarHolder);
GridView gridView = (GridView) GView.findViewById(R.id.gridView);
//Toast.makeText(getActivity(),Json_String,Toast.LENGTH_LONG).show();
String finalResult = null;
try{
finalResult = String.valueOf(new JSONTask().execute("https://www.example.in/android_api/dashboard_data",JsonData()));
Toast.makeText(getActivity(),Json_String,Toast.LENGTH_LONG).show();
JSONObject parentObject = null;
parentObject = new JSONObject(finalResult);
if(((String) parentObject.names().get(0)).matches("error")){
JSONObject jObj = parentObject.getJSONObject("error");
errorThrow(jObj.getString("Description"));
} else if(((String) parentObject.names().get(0)).matches("success")){
JSONObject jObj = parentObject.getJSONObject("success");
JSONArray arrajson = jObj.getJSONArray("data");
String arrayCount = Integer.toString(arrajson.length());
String[] type = new String[arrajson.length()];
Integer[] count = new Integer[arrajson.length()];
for (int i=0; i<arrajson.length();i++){
JSONObject jsonObject = arrajson.getJSONObject(i);
type[i] = jsonObject.getString("type");
count[i] = jsonObject.getInt("count");
}
CustomAdpter customAdpter = new CustomAdpter(DashboardFragment.this,type,count);
gridView.setAdapter(customAdpter);
return GView;
}
} catch (JSONException e) {
e.printStackTrace();
}
return GView;
}
Base Adapter Code :-
class CustomAdpter extends BaseAdapter {
String[] type;
Integer[] count;
public CustomAdpter(DashboardFragment dashboardFragment, String[] type, Integer[] count){
this.count = count;
this.type = type;
}
#Override
public int getCount() {
return type.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = getLayoutInflater().inflate(R.layout.grid_single_itme,null);
TextView textView = (TextView) view.findViewById(R.id.TextView1);
TextView textView1 = (TextView) view.findViewById(R.id.textView2);
textView.setText(String.valueOf(count[i]));
textView1.setText(type[i]);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(),"Booking Item Clicked",Toast.LENGTH_LONG).show();
}
});
return view;
}
}
AsyncTask Code :-
public class JSONTask extends AsyncTask<String,String,String> {
private ProgressDialog mProgressDialog;
int progress;
public JSONTask(){
mProgressDialog = new ProgressDialog(getContext());
mProgressDialog.setMax(100);
mProgressDialog.setProgress(0);
}
#Override
protected void onPreExecute(){
mProgressDialog = ProgressDialog.show(getContext(),"Loading","Loading Data...",true,false);
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
final String finalJson = params[1];
String json = finalJson;
try{
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestProperty("A-APK-API", "******");
connection.setRequestProperty("Authorization", "Basic **:**");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.connect();
OutputStream stream = connection.getOutputStream();
OutputStreamWriter streams = new OutputStreamWriter(stream, "UTF-8");
stream.write(json.getBytes("UTF-8"));
stream.close();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
StringBuffer buffer = new StringBuffer();
String line = "";
while((line = reader.readLine()) != null){
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(connection != null){
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e){
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String result){
super.onPostExecute(result);
Json_String = result;
Toast.makeText(getContext(),result,Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
}
}
Please help me here
You cannot get a result from asynctask when you dont use .get().
So change that statement. Start only the asynctask.
Then put all the code after that line in onPostExecute() of the AsyncTask.
Thats all.
you should change way you are creating the Adapter and attaching
you should do this
1.At first get the data in List,ArrayList etc. via AsyncTask, doInBackGround method
then on the onPostExecute method retrieve the data and create Adapter and attach it to your View
While you are getting data you can show some ProgressDialog.
If your AsyncTask is in other separate class then use interface to get the data from your AsyncTask class
look at this https://stackoverflow.com/a/47373959/8197737
Am an newbie to android ...kindly help me guys...I have 2 strings in my sample webservice(Not in an array) and I want to populate it in the listview .I wrote code to populate with a single string.But I don't know how to populate with 2nd strings below to 1st string in listview.Any suggestion will be appreciated.
Here is my complete code
HTTPURLCONNECT
class HttpULRConnect {
public static String getData(String uri){
BufferedReader reader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
Log.d("testhtt2","test");
String line;
while ((line= reader.readLine())!=null) {
sb.append(line+"\n");
}
Log.d("test44", sb.toString());
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
finally{
if (reader!=null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}}}
Here is my FETCH.java
public class Fetch extends Activity {
ArrayList<Flowers> flowersList = new ArrayList<Flowers>();
String url ="http://113.193.30.155/MobileService/MobileService.asmx/GetSampleData";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fetch);
new BackTask().execute(url);
}
public class BackTask extends AsyncTask<String,String,String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
String content =HttpULRConnect.getData(url);
return content;
}
#Override
protected void onPostExecute(String s) {
try {
JSONArray ar = new JSONArray(s);
for (int i = 0; i < ar.length(); i++) {
JSONObject jsonobject = ar.getJSONObject(i);
Flowers flowers = new Flowers();
flowers.setName(jsonobject.getString("NAME"));
flowersList.add(flowers);
}
}
catch (JSONException e){
e.printStackTrace();
}
FlowerAdapter adapter = new FlowerAdapter(Fetch.this, R.layout.flower_lis_item, flowersList);
ListView lv = (ListView) findViewById(R.id.listView);
lv.setAdapter(adapter);
}
}
static class Flowers {
public String getName() {
return NAME;
}
public void setName(String name) {
this.NAME = name;
}
private String NAME;
}
public static class FlowerAdapter extends ArrayAdapter<Flowers> {
private ArrayList<Flowers> items;
private Context mContext;
public FlowerAdapter(Context context, int textViewResourceID, ArrayList<Flowers> items){
super(context,textViewResourceID,items);
mContext = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
Flowers flowers = items.get(position);
if(v==null){
LayoutInflater inflater =(LayoutInflater) getContext().getSystemService(LAYOUT_INFLATER_SERVICE);
v=inflater.inflate(R.layout.flower_lis_item,null);
}
TextView title = (TextView)v.findViewById(R.id.textView3);
TextView text =(TextView)v.findViewById(R.id.textView2);
if (title != null) {
title.setText(flowers.getName());
text.setText(flowers.getName());
}
return v;
}
}
}
I am trying to show data in custom listView using API
there is no error but data is not shown in custom list .i made separate
class for asyncTask ,Adapters and model.
code of asyncTask is
public class CourseOutlinesTask extends AsyncTask<String, String, String> {
ProgressDialog dialog;
Context context;
private ArrayList<CourseModel> postList = new ArrayList<CourseModel>();
private ListView listView;
private View root;
TrainerCourseAdapter adapter;
String json_string;
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//close process dialog
if (this.dialog != null) {
this.dialog.dismiss();
}
//parse json
try {
JSONObject jsonParse = new JSONObject(result);
JSONArray query = jsonParse.getJSONArray("courses");
for (int i = 0; i < query.length(); i++) {
try {
JSONObject jsonParser = query.getJSONObject(i);
CourseModel post = new CourseModel();
post.setId(jsonParser.getInt("id"));
post.setTitle(jsonParser.getString("title"));
post.setStatus(jsonParser.getString("status"));
post.setDescription(jsonParser.getString("description"));
System.out.println(post.getStatus()+"asdadasdad");
System.out.println(post);
postList.add(post);
TrainerCourseAdapter adapter = new TrainerCourseAdapter(context,postList);
}catch (Exception e) {
System.out.println(e);
}
// Parsing json
post.setDescription(obj.getString("description"));
// ****Handle CreationDate-Object
// Genre is json array
}
} else {
MyAppUtil.getToast(getApplicationContext(), message);
}*/
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
code of my adapter class is
public class TrainerCourseAdapter extends BaseAdapter {
private List list;
private Context context;
private static LayoutInflater inflater = null;
String [] cName;
String [] cDetail;
String [] created;
String [] cStatus;
TextView c_name,c_detail,c_date,c_status;
ArrayList<CourseModel> itemList;
Context mcontext;
public TrainerCourseAdapter(Context context,List list) {
mcontext = context;
itemList = (ArrayList<CourseModel>) list;
}
#Override
public int getCount() {
return itemList.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
public void setItemList(ArrayList<CourseModel> itemList) {
this.itemList = itemList;
}
public class Holder
{
TextView c_name;
TextView c_detail;
TextView c_date ;
Button c_status;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
Holder holder = new Holder();
View rowView;
rowView = inflater.inflate(R.layout.row_courses_list, viewGroup,false);
this.c_name = (TextView) rowView.findViewById(R.id.txt_courseName);
this.c_detail = (TextView) rowView.findViewById(R.id.txt_courseDetail);
this.c_date = (TextView) rowView.findViewById(R.id.txt_courseDate);
this.c_status = (Button) rowView.findViewById(R.id.btn_courseStatus);
System.out.println("Mudassir Don");
final CourseModel data = itemList.get(i);
this.c_name.setText(data.getTitle());
this.c_detail.setText(data.getDescription());
this.c_status.setText(data.getStatus());
this.c_date.setText(data.getId());
System.out.println(c_date);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "You Clicked "+ cName[i], Toast.LENGTH_LONG).show();
}
});
return rowView;
}
}
code of activity is
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_outlines);
CourseOutlinesTask task = new CourseOutlinesTask();
task.execute("http://mantis.vu.edu.pk/bridging_the_gap/public/viewCourseOutlines");
mylist = task.viewResult();
listView = (ListView) findViewById(R.id.course_listView);
listView.setAdapter(new TrainerCourseAdapter(CourseOutlinesActivity.this,mylist ) {
});
You need to assign your custom Adapter to listView.
yourListView.setAdapter(yourAdapter);
In your case, inside onPostExecute method of CourseOutlinesTask you should write it.
TrainerCourseAdapter adapter = new TrainerCourseAdapter(context,postList);
listView = (ListView) findViewById(R.id.course_listView);
listview.setAdapter(adapter);
Hope this helps.
You need to write a interface and get response in your activity and set adapter to list view
like.
TrainerCourseAdapter adapter = new TrainerCourseAdapter(context,postList);
listView = (ListView) findViewById(R.id.course_listView);
listview.setAdapter(adapter);
You can use callBack interface to get itemArraylist data to your activity class.
After getting itemlist data in activity class you can set adapter to listview.
TrainerCourseAdapter adapter = new TrainerCourseAdapter(context, postList);
listView = (ListView) findViewById(R.id.course_listView);
listview.setAdapter(adapter);
// You can create interface in your CourseOutlinesClass with two method onSuccess() and onFailure() and in onPostExecute() send arraylist data using this interface to activity , then set adapter to fill data in listview.
Use the below code:-
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_outlines);
listView = (ListView) findViewById(R.id.course_listView);
new CourseOutlinesTask().execute("http://mantis.vu.edu.pk/bridging_the_gap/public/viewCourseOutlines");
}
and in postExecute of your AsyncTask setAdapter to listView
TrainerCourseAdapter adapter = new TrainerCourseAdapter(context,postList);
listView.setAdapter(adapter);
I would like to populate my Listview using a loop, I have recently attempted to populate it in a very inefficient way by making multiple calls for the data from SQL. When I realized just how inefficient it was I began to pull the data from the server in one go by making use of arrays. I am having trouble changing my code for this to work.
What I need to do is find a way of looping through the below array of JSONArrays (Which is not the hard part for me), but to do so I need to have my GetSocietyDataASyncTask return the above array and find a way of passing it to the OnCreate/done method in SocietySearch.java (Alot of the Society objects in my code can be ignored and somehow replaced with List societies)
Now I believe that I have included all of the relevant code but if you need to see anything else please do not hesitate to ask me.
The data that is received by Java from my database looks like this:
[{"society_id":1,"name":"TestName1","email":"Test#email1","description":"TestDes1"},
{"society_id":2,"name":"TestName2","email":"Test#email2","description":"TestDes2"}]
SocietySearch Class:
public class SocietySearch extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_society_search);
Society society = new Society(-1, null, null, null);
ServerRequests serverRequest1 = new ServerRequests(SocietySearch.this);
serverRequest1.GetSocietyDataAsyncTask(society, new GetSocietyCallback() {
#Override
public void done(final Society returnedSociety) {
ListView lv = (ListView) findViewById(R.id.ListView);
List<ListViewItem> items = new ArrayList<>();
items.add(new ListViewItem() {{
ThumbnailResource = R.drawable.test;
Title = returnedSociety.socName;
Subtitle = returnedSociety.socDes;
}});
CustomListViewAdapter adapter = new CustomListViewAdapter(SocietySearch.this, items);
lv.setAdapter(adapter);
}
});
}
class ListViewItem {
public int ThumbnailResource;
public String Title;
public String Subtitle;
}
Relevant Part Of ServerRequests Class:
public class getSocietyDataAsyncTask extends AsyncTask<Void, Void, Society> {
Society society;
GetSocietyCallback societyCallback;
public getSocietyDataAsyncTask(Society society, GetSocietyCallback societyCallback) {
this.society = society;
this.societyCallback = societyCallback;
}
#Override
protected Society doInBackground(Void... params) {
BufferedReader reader = null;
Society returnedSociety = null;
List<Society> societies = new ArrayList<>();
try {
URL url = new URL(SERVER_ADDRESS + "/getsocietydata.php");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(CONNECTION_TIMEOUT);
con.setReadTimeout(CONNECTION_TIMEOUT);
con.setRequestMethod("POST");
con.setDoOutput(true);
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null) { //Read until there is something available
sb.append(line + "\n"); //Read and save line by line
}
line = sb.toString(); //Saving complete data received in string
//Check values received in Logcat
Log.i("custom_check", "The values received in the store part are as follows:");
Log.i("custom_check", line);
JSONArray ja = new JSONArray(line);
if (ja != null && ja.length() == 0) {
returnedSociety = null;
} else {
for (int i = 0; i <ja.length(); i++) {
JSONObject json = ja.optJSONObject(i);
//Storing each Json in a variable
int society_id = json.getInt("society_id");
String socName = json.getString("name");
String socEmail = json.getString("email");
String socDes = json.getString("description");
returnedSociety = new Society(society_id, socName, socEmail, socDes);
societies.add(returnedSociety);
}
return returnedSociety;
}
} catch (Exception e) {
e.printStackTrace();
Log.d("Sample", "Error has occurred!\n" + e.toString());
}
finally {
if (reader != null) {
try {
reader.close(); //Closing the
} catch (IOException e) {
e.printStackTrace();
}
}
}
return returnedSociety;
}
#Override
protected void onPostExecute(Society returnedSociety) {
super.onPostExecute(returnedSociety);
progressDialog.dismiss();
societyCallback.done(returnedSociety);
}
}
CustomListViewAdapter.java:
public class CustomListViewAdapter extends BaseAdapter {
LayoutInflater inflater;
List<SocietySearch.ListViewItem> items;
public CustomListViewAdapter(Activity context, List<SocietySearch.ListViewItem> items) {
super();
this.items = items;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
//Auto-generated method stub
return items.size(); // TODO Maybe this can be my sql count?
}
#Override
public Object getItem(int position) {
//Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
//Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
//Auto-generated method stub
ListViewItem item = items.get(position);
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.item_row, null);
ImageView test = (ImageView) vi.findViewById(R.id.imgThumbnail);
TextView txtTitle = (TextView) vi.findViewById(R.id.txtTitle);
TextView txtSubTitle = (TextView) vi.findViewById(R.id.txtSubTitle);
test.setImageResource(item.ThumbnailResource);
txtTitle.setText(item.Title);
txtSubTitle.setText(item.Subtitle);
return vi;
}
}
ListView Layour file (item_row.xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dip">
<ImageView
android:id="#+id/imgThumbnail"
android:layout_width="78dip"
android:layout_height="78dip"
android:layout_alignParentLeft="true"
android:layout_centerInParent="true"
android:layout_marginLeft="-3dip"
android:scaleType="centerInside"></ImageView>
<TextView
android:id="#+id/txtTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="6dip"
android:layout_marginTop="6dip"
android:layout_toRightOf="#+id/imgThumbnail"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceLarge"></TextView>
<TextView
android:id="#+id/txtSubTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtTitle"
android:layout_marginLeft="6dip"
android:layout_marginTop="3dip"
android:layout_toRightOf="#+id/imgThumbnail"
android:text="TextView"></TextView>
</RelativeLayout>
Take a look at ArrayAdapter and specifically #notifyDataSetChanged. (notifyDataSetChanged example). You can setup the ListView in #onCreate like you have and store off a reference to the underlying Adapter. Initially the Adapter will be empty, but when data comes in simply add it to the Adapter and call #notifyDataSetChanged as guided in the example.