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;
}
}
}
Related
My RecyclerView is returning the Boolean value 'true' for some odd reason.
I can't seem to fix the issue
This is the output I am getting
It should display text from the JSON
JSON LINK - https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=c80ddd850a524fe5975cad881d6f4aba
I am accessing the 'articles' JSON array and I want to display the title
MainActivity code:
public class MainActivity extends AppCompatActivity {
RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
MyAdapter mViewAdapter;
List<News> news_list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ParseNewsJSON().execute();
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
//mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
mViewAdapter = new MyAdapter(new ArrayList<News>());
mRecyclerView.setAdapter(mViewAdapter);
}
public class ParseNewsJSON extends AsyncTask<String, Void, String> {
private final String JSON_URL = "https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=c80ddd850a524fe5975cad881d6f4aba";
String result = "";
ArrayList<String> article_heading = new ArrayList<>();
#Override
protected String doInBackground(String... strings) {
try {
URL url = new URL(JSON_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("articles");
for (int i = 0; i < jsonArray.length(); i++) {
News news = new News();
news.setHeading(String.valueOf(article_heading.add(jsonArray.getJSONObject(i).optString("title"))));
// article_heading.add(jsonArray.getJSONObject(i).optString("title"));
Log.d("news_JSON", article_heading.toString());
Log.d("news", news.getHeading().toString());
news_list.add(news);
}
} catch (JSONException e) {
e.printStackTrace();
}
mViewAdapter = new MyAdapter(news_list);
mRecyclerView.setAdapter(mViewAdapter);
mViewAdapter.notifyDataSetChanged();
super.onPostExecute(s);
}
}
}
MyAdapter Code:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<News> newsArticleList;
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView title;
//description, genre;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.textView_articleHeading);
// description = (TextView) itemView.findViewById(R.id.textView_description);
// image = (TextView) itemView.findViewById(R.id.rating);
}
}
public MyAdapter (List<News> newsArticleList){
this.newsArticleList = newsArticleList;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_main, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyAdapter.ViewHolder holder, int position) {
News news = newsArticleList.get(position);
holder.title.setText(news.getHeading());
}
#Override
public int getItemCount() {
return newsArticleList.size();
}
}
News.Java;
public class News {
private String heading;
//private String descrpiton;
private String img;
public String getHeading() {
return heading;
}
public void setHeading(String heading) {
this.heading = heading;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
}
Your problem is here
news.setHeading(String.valueOf(article_heading.add(jsonArray.getJSONObject(i).optString("title"))));
article_heading is an ArrayList, the method add returns a boolean to whether the list has changed due to your call or not.
You are not adding the title, you are adding the return of the ArrayList method, what you need is to change that line to that
String title = jsonArray.getJSONObject(i).optString("title");
article_heading.add(title);
news.setHeading(title);
change your onPostExecute as below
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("articles");
for (int i = 0; i < jsonArray.length(); i++) {
News news = new News();
String headingFromJson = jsonArray.getJSONObject(i).getString("title");
article_heading.add(headingFromJson);
news.setHeading(headingFromJson);
// article_heading.add(jsonArray.getJSONObject(i).optString("title"));
Log.d("news_JSON", article_heading.toString());
Log.d("news", news.getHeading().toString());
news_list.add(news);
}
} catch (JSONException e) {
e.printStackTrace();
}
mViewAdapter = new MyAdapter(news_list);
mRecyclerView.setAdapter(mViewAdapter);
mViewAdapter.notifyDataSetChanged();
super.onPostExecute(s);
}
You are setting the heading of the news in a wrong way.
You should be doing the following in your Aynctask:
news.setHeading(jsonArray.getJsonObject(i).getString("title"));
You are instead putting the title inside the arraylist using add method. And putting the result of the add method as the heading. Add method of arraylist returns a boolean value indicating if the addition to list was successful or not. Thus you keep getting true instead of the actual text
Try this:
In yout ParseNewsJSON class onpostexecute()
Change to :
for (int i = 0; i < jsonArray.length(); i++) {
News news = new News();
news.setHeading(jsonArray.getJSONObject(i).optString("title"));
news_list.add(news);
}
Instead of:
for (int i = 0; i < jsonArray.length(); i++) {
News news = new News();
news.setHeading(String.valueOf(article_heading.add(jsonArray.getJSONObject(i).optString("title"))));
// article_heading.add(jsonArray.getJSONObject(i).optString("title"));
Log.d("news_JSON", article_heading.toString());
Log.d("news", news.getHeading().toString());
news_list.add(news);
}
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 have some problem with my JSON code.
I want to display a list that contain text and image. The text and image stored on my online database, i using JSON for taking them down to my android app.
The JSON doesn't display any error, the text are displayed but the image are not appear.
I check the logcat and there's no error for this process. I using viewAdapter for displaying the image on the list.
Please master help me, can you gimme some simple explanation how to solve this??
Thanks...
NB. This is my code for HomeFragment.java (where i doing the JSON).
public class HomeFragment extends Fragment implements InternetConnectionListener, ApiHandler.ApiHandlerListener {
private static final String ARG_SECTION_NUMBER = "section_number";
private final int CATEGORY_ACTION = 1;
private CategorySelectionCallbacks mCallbacks;
private ArrayList<Category> categoryList;
private ListView categoryListView;
private String Error = null;
private InternetConnectionListener internetConnectionListener;
public HomeFragment() {
}
public static HomeFragment newInstance(int sectionNumber) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((HomeActivity) activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
try {
mCallbacks = (CategorySelectionCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement CategorySelectionCallbacks.");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
categoryListView = (ListView) rootView.findViewById(R.id.categoryListView);
return rootView;
}
#Override
public void onResume() {
super.onResume();
if (UtilMethods.isConnectedToInternet(getActivity())) {
initCategoryList();
} else {
internetConnectionListener = (InternetConnectionListener) HomeFragment.this;
showNoInternetDialog(getActivity(), internetConnectionListener,
getResources().getString(R.string.no_internet),
getResources().getString(R.string.no_internet_text),
getResources().getString(R.string.retry_string),
getResources().getString(R.string.exit_string), CATEGORY_ACTION);
}
}
public class getCategList extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
/**
* json is populating from text file. To make api call use ApiHandler class
*
* <CODE>ApiHandler apiHandler = new ApiHandler(this, URL_GET_CATEGORY);</CODE> <BR>
* <CODE>apiHandler.doApiRequest(ApiHandler.REQUEST_GET);</CODE> <BR>
*
* You will get the response in onSuccessResponse(String tag, String jsonString) method
* if successful api call has done. Do the parsing as the following.
*/
URL hp = null;
try {
hp = new URL(
getString(R.string.liveurl) + "foodcategory.php");
Log.d("URL", "" + hp);
URLConnection hpCon = hp.openConnection();
hpCon.connect();
InputStream input = hpCon.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(input));
String x = "";
x = r.readLine();
String total = "";
while (x != null) {
total += x;
x = r.readLine();
}
Log.d("UR1L", "" + total);
JSONArray j = new JSONArray(total);
Log.d("URL1", "" + j.length());
categoryList = new ArrayList<Category>();
for (int i = 0; i < j.length(); i++) {
Category category = new Category();// buat variabel category
JSONObject Obj;
Obj = j.getJSONObject(i); //sama sperti yang lama, cman ini lebih mempersingkat karena getJSONObject cm d tulis sekali aja disini
category.setId(Obj.getString(JF_ID));
category.setTitle(Obj.getString(JF_TITLE));
category.setIconUrl(Obj.getString(JF_ICON));
if (!TextUtils.isEmpty(Obj.getString(JF_BACKGROUND_IMAGE))) {
category.setImageUrl(Obj.getString(JF_BACKGROUND_IMAGE));
}
Log.d("URL1",""+Obj.getString(JF_TITLE));
categoryList.add(category);
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
categoryListView.setAdapter(new CategoryAdapter(getActivity(), mCallbacks, categoryList));
}
});
}catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Error = e.getMessage();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Error = e.getMessage();
} catch (JSONException e) {
// TODO Auto-generated catch block
Error = e.getMessage();
e.printStackTrace();
} catch (NullPointerException e) {
// TODO: handle exception
Error = e.getMessage();
}
return null;
}
}
//! function for populate category list
private void initCategoryList() {
new getCategList().execute();
}
#Override
public void onConnectionEstablished(int code) {
if (code == CATEGORY_ACTION) {
initCategoryList();
}
}
#Override
public void onUserCanceled(int code) {
if (code == CATEGORY_ACTION) {
getActivity().finish();
}
}
//! catch json response from here
#Override
public void onSuccessResponse(String tag, String jsonString) {
//! do same parsing as done in initCategoryList()
}
//! detect response error here
#Override
public void onFailureResponse(String tag) {
}
//! callback interface listen by HomeActivity to detect user click on category
public static interface CategorySelectionCallbacks {
void onCategorySelected(String catID, String title);
}
}
This code for categoryAdapter.java (where i put the result of JSON to the list)
public class CategoryAdapter extends ArrayAdapter<Category> implements View.OnClickListener {
private final LayoutInflater inflater;
private final ArrayList<Category> categoryList;
private Activity activity;
private HomeFragment.CategorySelectionCallbacks mCallbacks;
private String dummyUrl = "http://www.howiwork.org";
AbsListView.LayoutParams params;
public CategoryAdapter(Activity activity, HomeFragment.CategorySelectionCallbacks mCallbacks, ArrayList<Category> categoryList) {
super(activity, R.layout.layout_category_list);
this.activity = activity;
this.inflater = LayoutInflater.from(activity.getApplicationContext());
this.categoryList = categoryList;
this.mCallbacks = mCallbacks;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder row;
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_category_list, null);
row = new ViewHolder();
row.bannerImage = (ImageView) convertView.findViewById(R.id.catBannerImageView);
row.categoryImage = (ImageView) convertView.findViewById(R.id.catImageView);
row.categoryName = (TextView) convertView.findViewById(R.id.catNameTV);
} else {
row = (ViewHolder) convertView.getTag();
}
Category category = categoryList.get(position);
Picasso.with(activity).load(UtilMethods
.getDrawableFromFileName(activity,category.getIconUrl()))
.tag(category.getIconUrl())
.into(row.categoryImage);
row.categoryName.setText(category.getTitle());
Picasso.with(activity)
.load(UtilMethods.getDrawableFromFileName(activity,category.getImageUrl()))
.placeholder(R.drawable.img_banner_placeholder)
.tag(category.getIconUrl())
.fit()
.into(row.bannerImage);
row.bannerImage.setOnClickListener(this);
row.categoryImage.setTag(position);
row.categoryName.setTag(position);
row.bannerImage.setTag(position);
return convertView;
}
#Override
public int getCount() {
return categoryList.size();
}
#Override
public void onClick(View v) {
int position = Integer.parseInt(v.getTag().toString());
mCallbacks.onCategorySelected(categoryList.get(position).getId(),
categoryList.get(position).getTitle());
}
private static class ViewHolder {
public ImageView bannerImage;
public TextView categoryName;
public ImageView categoryImage;
}
}
Try this.
Picasso.with(activity).load(category.getIconUrl())
.into(row.categoryImage);
If it worked !. You Check the UtilMethods.getDrawableFromFileName() !!!
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
the listviews not loaded in the main i not find as data load.
I shows the main vacuum
please help.
pFragment.java
public class pFragment extends Fragment{
private ListView plistView;
public String url = "http://192.168.0.104/sproyect/getmovil";
AdaptadorPublicaciones adapter;
JSONObject jsonobject;
JSONArray jsonarray;
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.public_listv, container, false);
}
public void onActivityCreated(Bundle state) {
super.onActivityCreated(state);
(new AsyncListViewLoader()).execute(url);
adapter = new AdaptadorPublicaciones(new ArrayList<Publicaciones>(), getActivity());
plistView = (ListView)getView().findViewById(R.id.plistView);
plistView.setAdapter(adapter);
}
private class AsyncListViewLoader extends AsyncTask<String, Void, List<Publicaciones>>{
private final ProgressDialog dialog = new ProgressDialog(getActivity());
protected void onPostExecute(List<Publicaciones> result){
super.onPostExecute(result);
dialog.dismiss();
adapter.setItemList(result);
adapter.notifyDataSetChanged();
}
protected void onPreExecute(){
super.onPreExecute();
dialog.setMessage("Cargando informacion");
dialog.show();
}
#Override
protected List<Publicaciones> doInBackground(String... params) {
List<Publicaciones> result = new ArrayList<Publicaciones>();
try {
URL u = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection)u.openConnection();
conn.setRequestMethod("GET");
conn.connect();
InputStream is = conn.getInputStream();
byte[] b = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while( is.read(b) != -1)
baos.write(b);
String JSONResp = new String(baos.toByteArray());
JSONArray arr = new JSONArray(JSONResp);
for (int i = 0; i < arr.length(); i++) {
result.add(convertItem(arr.getJSONObject(i)));
}
return result;
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
}
private Publicaciones convertItem(JSONObject obj) throws JSONException {
String titulo = obj.getString("titulo");
String estado = obj.getString("estatus");
String fechap = obj.getString("fechreg");
int idpublic = obj.getInt("idpublic");
int avatar = R.drawable.notif;
return new Publicaciones(idpublic, titulo, estado, fechap, avatar);
}
}
AdaptadorPublicaciones.java
public class AdaptadorPublicaciones extends ArrayAdapter<Publicaciones>{
private List<Publicaciones> itemlist;
private Context context;
public AdaptadorPublicaciones(List<Publicaciones> itemlist, Context context){
super(context,android.R.layout.simple_list_item_1,itemlist);
this.itemlist = itemlist;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.list_views,parent, false);
}
Publicaciones pb = itemlist.get(position);
//AVATAR
ImageView avatar = (ImageView)v.findViewById(R.id.imgAvatar);
//avatar.setImageResource(resultp.get("avatar"));
//TITULO
TextView titulo = (TextView)v.findViewById(R.id.txTitulo);
titulo.setText(pb.getTitulo());
//DISPONIBILIDAD
TextView dispo = (TextView)v.findViewById(R.id.txDisponibilidad);
dispo.setText(pb.getEstado());
//FECHA
TextView fechap = (TextView)v.findViewById(R.id.txFecha);
fechap.setText(pb.getFechap());
//ID PUBLICACION OCULTO
TextView hdp = (TextView)v.findViewById(R.id.txhpublic);
hdp.setText(""+ pb.getIdpublic());
return v;
}
public List<Publicaciones> getList(){
return itemlist;
}
public void setItemList(List<Publicaciones> ilist){
this.itemlist = ilist;
}
#Override
public int getCount() {
if(itemlist != null)
return itemlist.size();
return 0;
}
#Override
public Publicaciones getItem(int position) {
if(itemlist != null)
return itemlist.get(position);
return null;
}
#Override
public long getItemId(int position) {
if(itemlist != null)
return itemlist.get(position).hashCode();
return 0;
}
}
Publicaciones.java
public class Publicaciones{
private int idpublic;
private String titulo;
private String estado;
private int avatar;
private String fechap;
public Publicaciones(int idpublic, String titulo, String estado, String fechap, int avatar) {
super();
this.idpublic = idpublic;
this.titulo = titulo;
this.estado = estado;
this.fechap = fechap;
this.avatar = avatar;
}
public int getAvatar() {
return avatar;
}
public int getIdpublic() {
return idpublic;
}
public String getTitulo() {
return titulo;
}
public String getEstado() {
return estado;
}
public String getFechap() {
return fechap;
}
}
en the json de retorno muestra este error:
11-09 19:43:45.545: W/System.err(608): org.json.JSONException: A JSONArray text must start with '[' at character 1 of {"publicaciones":[{"titulo":"Aperturado curso de ofimatica en los nuevos laboratorios.","estatus":"nuevo","idpublic":"9","avatar":"nivel_ofimatica.jpg","fechreg":"2013-11-07"},{"titulo":"Disponible curso sobre el manejador de bases de datos mysql.","estatus":"nuevo","idpublic":"8","avatar":"nivel_desarrollado_web.png","fechreg":"2013-11-06"}]}??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
Try
Change
plistView = (ListView)getView().findViewById(R.id.plistView);
To
plistView = (ListView) getActivity().findViewById(R.id.plistView);
And also
public void onActivityCreated(Bundle state) {
super.onActivityCreated(state);
(new AsyncListViewLoader()).execute(url);
adapter = new AdaptadorPublicaciones(new ArrayList<Publicaciones>(), getActivity());
plistView = (ListView)getView().findViewById(R.id.plistView);
plistView.setAdapter(adapter);
}
To
public void onActivityCreated(Bundle state) {
super.onActivityCreated(state);
(new AsyncListViewLoader()).execute(url);
plistView = (ListView)getView().findViewById(R.id.plistView);
}
and
protected void onPostExecute(List<Publicaciones> result){
super.onPostExecute(result);
dialog.dismiss();
adapter.setItemList(result);
adapter.notifyDataSetChanged();
}
To
protected void onPostExecute(List<Publicaciones> result){
super.onPostExecute(result);
dialog.dismiss();
adapter = new AdaptadorPublicaciones(result, getActivity());
plistView.setAdapter(adapter);
}
Edited:-
Change
JSONArray arr = new JSONArray(JSONResp);
for (int i = 0; i < arr.length(); i++) {
result.add(convertItem(arr.getJSONObject(i)));
}
To
JSONObject json=new JSONObject(JSONResp);
JSONArray arr=json.getJSONArray("publicaciones");
for (int i = 0; i < arr.length(); i++) {
result.add(convertItem(arr.getJSONObject(i)));
}