Cards will not populate with movie names from TMDB API - java

I am creating an app for a project where you can swipe through movie names and images, for now I am just trying to get the names working but my cards will not populate with the movie names. I had some trouble with the array adapter but I think it's working now and in the correct place. I am using a library from github for the cards and it's worked for other programs just can't get it work with this. Maybe it's because of the model class? just lost when there is no real errors. Item.xml is the design of the card with it's text and background and activity_main.xml is where I reference the library. hellotext is the textview in item.xml. Any help is appreicated!
public class MainActivity extends AppCompatActivity {
private ArrayList<String> al;
private ArrayAdapter<MovieModelClass> arrayAdapter;
private ArrayList<MovieModelClass> movieList = new ArrayList<>();
private int i;
String moviename;
private static String JSON_URL = "https://api.themoviedb.org/3/movie/popular?api_key=8099f5720bad1f61f020fdbc855f73db";
//List<MovieModelClass> movieList;
//#InjectView(R.id.frame) SwipeFlingAdapterView flingContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetData getData = new GetData();
getData.execute();
//AddArray();
// ButterKnife.inject(this);
//this add is the name of the card, with each add another card is added
//adds into array
//the array has a text and a layout we create
//this layout is the card in itself textview picture ect...
//this is when it actually swipes(clicks and movies)
SwipeFlingAdapterView flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
flingContainer.setAdapter(arrayAdapter);
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
//every time a card is completely removed he just removes it from the array
//notifies the adapter of this change
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
movieList.remove(0);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
Toast.makeText(MainActivity.this, "left", Toast.LENGTH_SHORT).show();
}
#Override
public void onRightCardExit(Object dataObject) {
Toast.makeText(MainActivity.this, "right", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
// movieList.add();
// arrayAdapter.notifyDataSetChanged();
// Log.d("LIST", "notified");
// i++;
}
#Override
public void onScroll(float scrollProgressPercent) {
/* View view = flingContainer.getSelectedView();
view.findViewById(R.id.item_swipe_right_indicator).setAlpha(scrollProgressPercent < 0 ? -scrollProgressPercent : 0);
view.findViewById(R.id.item_swipe_left_indicator).setAlpha(scrollProgressPercent > 0 ? scrollProgressPercent : 0);*/
}
});
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
Toast.makeText(MainActivity.this, "click", Toast.LENGTH_SHORT).show();
}
});
}
Api (same class)
public class GetData extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... strings) {
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(JSON_URL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int data = isr.read();
while (data != -1) {
current += (char) data;
data = isr.read();
}
return current;
} catch (MalformedURLException e) {
e.printStackTrace();;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
// urlConnection.disconnect();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(#org.jetbrains.annotations.NotNull String s){
try{
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for(int i = 0; i< jsonArray.length(); i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
MovieModelClass model = new MovieModelClass();
// model.setId(jsonObject1.getString("vote_average"));
model.setName(jsonObject1.getString("title"));
// model.setImg(jsonObject1.getString("poster_path"));
moviename = jsonObject1.getString("title");
model.setName(moviename);
movieList = new ArrayList<>();
movieList.add(model);
arrayAdapter = new ArrayAdapter<>(getApplicationContext(), R.layout.item, R.id.helloText, movieList);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Update***
I fixed the null problem BUT my cards now populate with my project name so I just see one card with com.project300.populateswipecards... any help?
private ArrayList<String> al;
private ArrayAdapter<MovieModelClass> arrayAdapter;
private ArrayList<MovieModelClass> movieList = new ArrayList<>();
private int i;
String moviename = "";
Context context;
SwipeFlingAdapterView flingContainer;
private static String JSON_URL = "https://api.themoviedb.org/3/movie/popular?api_key=8099f5720bad1f61f020fdbc855f73db";
//List<MovieModelClass> movieList;
//#InjectView(R.id.frame) SwipeFlingAdapterView flingContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
GetData getData = new GetData();
getData.execute();
//AddArray();
// ButterKnife.inject(this);
//this add is the name of the card, with each add another card is added
//adds into array
//the array has a text and a layout we create
//this layout is the card in itself textview picture ect...
//this is when it actually swipes(clicks and movies)
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
//every time a card is completely removed he just removes it from the array
//notifies the adapter of this change
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
// Log.d("LIST", "removed object!");
// movieList.remove(0);
// arrayAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
Toast.makeText(MainActivity.this, "left", Toast.LENGTH_SHORT).show();
}
#Override
public void onRightCardExit(Object dataObject) {
Toast.makeText(MainActivity.this, "right", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
// movieList.add();
// arrayAdapter.notifyDataSetChanged();
// Log.d("LIST", "notified");
// i++;
}
#Override
public void onScroll(float scrollProgressPercent) {
/* View view = flingContainer.getSelectedView();
view.findViewById(R.id.item_swipe_right_indicator).setAlpha(scrollProgressPercent < 0 ? -scrollProgressPercent : 0);
view.findViewById(R.id.item_swipe_left_indicator).setAlpha(scrollProgressPercent > 0 ? scrollProgressPercent : 0);*/
}
});
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
Toast.makeText(MainActivity.this, "click", Toast.LENGTH_SHORT).show();
}
});
}
public class GetData extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... strings) {
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(JSON_URL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int data = isr.read();
while (data != -1) {
current += (char) data;
data = isr.read();
}
return current;
} catch (MalformedURLException e) {
e.printStackTrace();;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
// urlConnection.disconnect();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(#org.jetbrains.annotations.NotNull String s){
try{
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for(int i = 0; i< jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
MovieModelClass model = new MovieModelClass();
movieList = new ArrayList<>();
// model.setId(jsonObject1.getString("vote_average"));
// model.setName(jsonObject1.getString("title"));
// model.setImg(jsonObject1.getString("poster_path"));
moviename = jsonObject1.getString("title");
model.setName(moviename);
movieList.add(model);
arrayAdapter = new ArrayAdapter<>(MainActivity.this, R.layout.item, R.id.helloText, movieList);
flingContainer.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}

At the end of your onPostExecute() method, I see this:
arrayAdapter = new ArrayAdapter<>(getApplicationContext(), R.layout.item, R.id.helloText, movieList);
I think you're assuming that this will update the list of cards, since earlier in onCreate() you have written this:
flingContainer.setAdapter(arrayAdapter);
However, that is not how the new keyword and Java object references work. These two adapters are completely separate, and flingContainer doesn't "see" the adapter you create in your task.
The easiest way to solve this is likely to re-set the adapter after you create it.
arrayAdapter = new ArrayAdapter<>(getApplicationContext(), R.layout.item, R.id.helloText, movieList);
flingContainer.setAdapter(arrayAdapter);
Now the problem seems to be this for loop:
for(int i = 0; i< jsonArray.length(); i++) {
// ...
movieList = new ArrayList<>();
// ...
movieList.add(model);
arrayAdapter = new ArrayAdapter<>(MainActivity.this, R.layout.item, R.id.helloText, movieList);
flingContainer.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
You need to move the ArrayList creation and adapter logic outside of the loop.
movieList = new ArrayList<>();
for(int i = 0; i< jsonArray.length(); i++) {
// ...
movieList.add(model);
}
arrayAdapter = new ArrayAdapter<>(MainActivity.this, R.layout.item, R.id.helloText, movieList);
flingContainer.setAdapter(arrayAdapter);

Related

RecyclerView Returning 'true' instead of JSON

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);
}

JSON ListView filter not working

So I've got a project to make a simple job board app. I've retrieved my JSON data and have it displaying on my app but I want to be able to use a SearchView filter but I don't know how to access my SimpleAdapter from outside of an inner-class
Here is my code:
public class jobcategories extends Activity{
private TextView jobData;
private ProgressDialog myprocessingdialog;
ArrayAdapter<String> adapter;
ArrayList<HashMap<String, String>> jobList;
private ListView lv;
private SearchView sv;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jobcategories);
myprocessingdialog = new ProgressDialog(this);
jobList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
sv = (SearchView) findViewById(R.id.search);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
return false;
}
#Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
new JSONTask().execute("https://apidata.com");
}
public class JSONTask extends AsyncTask<String,String, String>{
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//Showing Progress dialogue
myprocessingdialog.setTitle("Please Wait..");
myprocessingdialog.setMessage("Loading");
myprocessingdialog.setCancelable(false);
myprocessingdialog.setIndeterminate(false);
myprocessingdialog.show();
}
#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);
}
String finalJson = buffer.toString();
JSONArray parentObject = new JSONArray(finalJson);
for (int i=0; i < parentObject.length(); i++) {
JSONObject job = parentObject.getJSONObject(i);
String JobTitle = job.getString("title");
String JobLocation = job.getString("location");
String finalTitle = JobTitle + " in " + JobLocation;
String JobCompany = "advert by "+job.getString("company");
String JobDescription = job.getString("description");
String JobApply = "How to Apply: " + job.getString("apply");
HashMap<String, String> jobs = new HashMap<>();
jobs.put("title", finalTitle);
jobs.put("company", JobCompany);
jobs.put("description", JobDescription);
jobs.put("apply", JobApply);
jobList.add(jobs);
}
}catch (MalformedURLException e){
Toast.makeText(getApplicationContext(), "Error...the job server is down..." + e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "error parsing..." + e.toString(), Toast.LENGTH_LONG).show();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String results) {
super.onPostExecute(results);
myprocessingdialog.cancel();
ListAdapter adapter = new SimpleAdapter(
jobcategories.this, jobList,
R.layout.list_item, new String[]{"title", "company", "description", "apply"},
new int[]{R.id.title, R.id.company, R.id.description, R.id.apply});
lv.setAdapter(adapter);
}
}
}
Any help would be appreciated, am pretty new to android so if there is a better way for me to filter the data then I am open to changing the code.
Create an interface called OnJsonResultListener like so:
public interface OnJsonResultListener {
void onResult(String result);
}
Then make your Activity/Fragment implement that interface and do whatever with your simple adapter and the result from there. Then make the AsyncTask take a OnJsonResultListener in the constructor. Then in the onPostExecute method, call listener.onResult(results);
This is a simple way of making a callback.

I am trying to show data using api . but data is not showing in custom listView . list is empty

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);

how to add data in list view from background class

I am getting this exception
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
Below is the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page2);
lv = (ListView) findViewById(R.id.list_view);
btnNew = (Button)findViewById(R.id.btnAddNew);
btnNew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent moveToNewUser = new Intent(getApplication(),ExecutiveInfo2.class);
moveToNewUser.putExtra("ClickType","1");
startActivity(moveToNewUser);
}
});
new Connection2().execute();
// Listview Data
}
private class Connection2 extends AsyncTask {
#Override
protected Object doInBackground(Object... arg0) {
test2();
return null;
}
#Override
protected void onPostExecute(Object s) {
super.onPostExecute(s);
}
}
public void test2() {
HttpURLConnection connection = null;
try {
sharedpreferences = getSharedPreferences("MyPrefs", this.MODE_PRIVATE);
String storedUUID = sharedpreferences.getString("UUID", "");
String url2= "http://crm.xqicai.com/sales/getExecutiveInfo?UUID="+storedUUID;
//String url = "http://crm.xqicai.com/sales/login";
URL postUrl = new URL(url2);
connection = (HttpURLConnection) postUrl.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));// 设置编�,�则中文乱�
while (true) {
String str = reader.readLine();
if (str == null) {
break;
}
System.out.println(str);
JSONObject mainObject = new JSONObject(str);
Status = mainObject.getString("status");
int j=0;
if(Status.equals("0"))
{
JSONObject uniObject = mainObject.getJSONObject("data");
JSONArray a = uniObject.getJSONArray("data");
for (int i = 0; i < a.length(); i++) {
JSONObject json_obj = a.getJSONObject(i);
String demo = json_obj.getString("realName");
fetchedNames[j]= demo;
j++;
}
// Adding items to listview
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fetchedNames);
lv.setAdapter(adapter);
}
else
{
JSONObject mainObject2 = new JSONObject(str);
errorMsg = mainObject2.getString("msg");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_SHORT).show();
}
});
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
I'm only a beginner, so please forgive me for asking possibly a stupid question.
What line is giving the error? The problem is that you update a view created in the main thread, in your AsyncTask (a different thread). You should update this view in the onPostExecute of your AsyncTask (this is done in your main thread). I don't see immediately where you update the view.
EDIT:
Your problem should be solved if you put these two lines
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fetchedNames);
lv.setAdapter(adapter);
below this line:
lv = (ListView) findViewById(R.id.list_view);
or in the:
protected void onPostExecute(Object s)
Test that:
ListView lv...
lv.post(new Runnable() {
#Override
public void run() {
//Update UI;
lv.setAdapter(...);
}
})
you can try use Handler with sendEmptyMessage() inside asynctask to pass by exception.
ex.
Handler mHandler = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message inputMessage) {
// Adding items to listview
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fetchedNames);
lv.setAdapter(adapter);
}
});
note for code bellow:
//call mHandler.sendEmpyMessage() in asynctask:
if(Status.equals("0"))
{
JSONObject uniObject = mainObject.getJSONObject("data");
JSONArray a = uniObject.getJSONArray("data");
for (int i = 0; i < a.length(); i++) {
JSONObject json_obj = a.getJSONObject(i);
String demo = json_obj.getString("realName");
fetchedNames[j]= demo;
j++;
}
// Adding items to listview
mHandler.sendEmpyMessage(0); //0 or any number is identify code from you want use to check with every action

Spinner data duplicated when list is clicked

In Activity B there has a spinner where the data were get from MySQL (Table location).
Activity B
private ArrayList<String> froms;
private JSONArray resultFrom;
public void addItemsOnFrom() {
travelFrom = (Spinner) findViewById(R.id.travelFrom);
StringRequest stringRequest = new StringRequest(Configs.FROM_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
resultFrom = j.getJSONArray(Configs.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getFrom(resultFrom);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getFrom(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
froms.add(json.getString(Configs.TAG_LOCATION));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
travelFrom.setAdapter(new ArrayAdapter<String>(Add_Details_Information.this, android.R.layout.simple_spinner_dropdown_item, froms));
}
When save button is clicked, it will return the selected value(OFFICE) to Activity A listView. And in Activity A, when the list is pressed, it will intent to Activity B. In this time, the spinner in Activity B will display the selected item first(OFFICE).
**Table location** // table location has 2 data
NONE
OFFICE
Assume OFFICE is selected in B. When list is clicked, I want OFFICE display first in spinner B.
Code in Activity B for display OFFICE first.
if(getIntent().getExtras()!=null)
{
final String from = getIntent().getStringExtra("from");
selectedItemFrom(from);
}
public void selectedItemFrom(final String value)// display OFFICE first
{
travelFrom = (Spinner) findViewById(R.id.travelFrom);
StringRequest stringRequest = new StringRequest(Configs.FROM_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(Configs.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getFrom(result, value);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getFrom(JSONArray j, String value) {
int position = 0;
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
froms.add(json.getString(Configs.TAG_LOCATION));
if (froms.get(i).equalsIgnoreCase(value)) {
position = i;
//Toast.makeText(getApplicationContext(),position+"",Toast.LENGTH_LONG).show();
break;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
travelFrom.setAdapter(new ArrayAdapter<String>(Add_Details_Information.this, android.R.layout.simple_spinner_dropdown_item, froms));
travelFrom.setSelection(position);
}
The OFFICE can display first, but the problem is when I checked the spinner B, it shows NONE,OFFICE,NONE OFFICE ..Why the spinner data will get duplicated ? Thanks
I think problem is in this line travelFrom.setAdapter(new ArrayAdapter<String>(Add_Details_Information.this, android.R.layout.simple_spinner_dropdown_item, froms));...But how to solve??? Anyone?
And sometimes the spinner will display the selected item first but sometimes it will not...What are the better way to write?
Edit
{"result":[{"name":"NONE"},{"name":"OFFICE"}]}
I put forms.clear in beginning of both getFrom method now. But the problem is when I select NONE and return to A, then goes to B again,the spinner now has NONE only...
Please try something like this.
This activity will expect a Intent with the key "from" that is set to either "NONE" or "OFFICE". If the intent does not have the data, then it will default to whatever was inserted into the Spinner first.
public class MainActivity extends AppCompatActivity {
private Spinner travelFrom;
private ArrayAdapter<String> mSpinnerAdapter;
private List<String> mSpinnerData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String from = null;
Bundle extras = getIntent().getExtras();
if (extras != null) {
from = extras.getString("from");
}
setupFromSpinner(from);
}
private void setupFromSpinner(final String value) {
travelFrom = (Spinner) findViewById(R.id.travelFrom);
mSpinnerData = new ArrayList<String>();
mSpinnerAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, mSpinnerData);
mSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
travelFrom.setAdapter(mSpinnerAdapter);
JsonObjectRequest req = new JsonObjectRequest(Configs.FROM_URL,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
mSpinnerData.clear();
try {
JSONArray resultFrom = response.getJSONArray("result");
for (int i = 0; i < resultFrom.length(); i++) {
JSONObject fromObj = resultFrom.getJSONObject(i);
String name = fromObj.getString("name");
mSpinnerData.add(name);
}
mSpinnerAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
if (value != null) {
int position = mSpinnerAdapter.getPosition(value);
travelFrom.setSelection(position);
} else {
travelFrom.setSelection(0);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(req);
}
}
add froms.clear() to this piece of code;
private void getFrom(JSONArray j) {
//Traversing through all the items in the json array
froms.clear();
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
froms.add(json.getString(Configs.TAG_LOCATION));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
travelFrom.setAdapter(new ArrayAdapter<String>(Add_Details_Information.this, android.R.layout.simple_spinner_dropdown_item, froms));
}

Categories

Resources