AsyncTask + JSON parsing to Listview only sometimes shows data - android

Sometimes it shows data, sometimes it shows nothing.
public class HomeFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.home_fragment, container, false);
arraylist1 = new ArrayList<>();
listOfNews = (ListView) view.findViewById(R.id.listView);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute("url");
}
});
return view;
}
public class ReadJSON extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... url) {
String st = readURL(url[0]);
Log.d("st", st);
return st;
}
#Override
protected void onPostExecute(String content) {
try {
JSONObject jsonObject = new JSONObject(content);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
Log.d(i+":jsonArray object", jsonArray.toString() + " size= " + jsonArray.length());
JSONObject productObject = jsonArray.getJSONObject(i);
JSONObject img = productObject.getJSONObject("image");
JSONObject da = img.getJSONObject("data");
arraylist1.add(new HotNews(
da.getString("filename"),
productObject.getString("title"),
productObject.getString("article_by"),
productObject.getString("date_publish"),
productObject.getString("short_description")
));
}
Log.d("jsonArray news list1", arraylist1.size() + "");
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new ListViewAdapter(view.getContext(), R.layout.list_view_adapter, arraylist1);
listOfNews.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
private static String readURL(String theUrl) {
StringBuilder content = new StringBuilder();
try {
//create url object
URL url = new URL(theUrl);
//create url connection
URLConnection urlConnection = url.openConnection();
//wrap the urlconnection in a bufferedreader
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line + "\n");
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
}
public class ListViewAdapter extends ArrayAdapter<HotNews> {
public ListViewAdapter(Context context, int resource, ArrayList<HotNews> arrayList) {
super(context, resource,arrayList);
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arrayList = arrayList;
this.context = context;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
v = mInflater.inflate(R.layout.list_view_adapter, parent, false);
}
image = (ImageView) v.findViewById(R.id.imagetitle);
title = (TextView) v.findViewById(R.id.txtTitle);
doer = (TextView) v.findViewById(R.id.doer);
date = (TextView) v.findViewById(R.id.txtdate);
text = (TextView) v.findViewById(R.id.text);
final HotNews news = getItem(position);
Picasso.with(getContext()).load("url" + news.getImage()).noFade().into(image);
title.setText(news.getTitle());
doer.setText(news.getDoer());
date.setText(news.getDate());
text.setText(news.getContent());
return v;
}
}

try this code :
public class HomeFragment extends Fragment {
private View view;
private ArrayList<HotNews> arraylist1;
private ListView listOfNews;
private int SUCCESS = 1;
private int FAILS = 0;
private int NO_DATA = 2;
private int ERROR = -1;
private ListViewAdapter adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.home_fragment, container, false);
arraylist1 = new ArrayList<>();
listOfNews = (ListView) view.findViewById(R.id.listView);
adapter = new ListViewAdapter();
listOfNews.setAdapter(adapter);
new ReadJSON().execute("url");
return view;
}
public class ReadJSON extends AsyncTask<String, Integer, Integer> {
#Override
protected Integer doInBackground(String... url) {
String response = readURL(url[0]);
Log.d("response ", response);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("data");
arraylist1.clear();
if(jsonArray.length()>0) {
for (int i = 0; i < jsonArray.length(); i++) {
Log.d(i + ":jsonArray object", jsonArray.toString() + " size= " + jsonArray.length());
JSONObject productObject = jsonArray.getJSONObject(i);
JSONObject img = productObject.getJSONObject("image");
JSONObject da = img.getJSONObject("data");
arraylist1.add(new HotNews(
da.getString("filename"),
productObject.getString("title"),
productObject.getString("article_by"),
productObject.getString("date_publish"),
productObject.getString("short_description")
));
}
}else{
return NO_DATA;
}
Log.d("jsonArray news list1", arraylist1.size() + "");
} catch (Exception e) {
e.printStackTrace();
return ERROR;
}
return SUCCESS;
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
Log.d("parseResponse", integer + "");
if(integer==SUCCESS){
adapter.notifyDataSetChanged();
}else if(integer==ERROR){
Toast.makeText(getActivity(),"Server or Exception Error!", Toast.LENGTH_SHORT).show();
}else if(integer==NO_DATA){
Toast.makeText(getActivity(),"No Data!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(),"Some thing went wrong!", Toast.LENGTH_SHORT).show();
}
}
}
class ListViewAdapter extends BaseAdapter{
#Override
public int getCount() {
return arraylist1.size();
}
#Override
public Object getItem(int position) {
return arraylist1.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ListViewHolder holder;
if (v == null) {
v = LayoutInflater.from(getActivity()).inflate(R.layout.list_view_adapter, parent, false);
holder = new ListViewHolder(v);
v.setTag(holder);
}else{
holder = (ListViewHolder)v.getTag();
}
final HotNews news = arraylist1.get(position);
holder.title.setText(news.getTitle());
holder.doer.setText(news.getDoer());
holder.date.setText(news.getDate());
holder.text.setText(news.getContent());
Picasso.with(getContext()).load("url" + news.getImage()).noFade().into(holder.image);
return v;
}
class ListViewHolder {
private ImageView image;
private TextView title,doer,date,text;
public ListViewHolder(View v){
image = (ImageView) v.findViewById(R.id.imagetitle);
title = (TextView) v.findViewById(R.id.txtTitle);
doer = (TextView) v.findViewById(R.id.doer);
date = (TextView) v.findViewById(R.id.txtdate);
text = (TextView) v.findViewById(R.id.text);
}
}
}
private static String readURL(String theUrl) {
StringBuilder content = new StringBuilder();
try {
//create url object
URL url = new URL(theUrl);
//create url connection
URLConnection urlConnection = url.openConnection();
//wrap the urlconnection in a bufferedreader
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line + "\n");
}
bufferedReader.close();
}
catch (Exception e) {
e.printStackTrace();
}
return content.toString();
}
}

You are seeing this error, which is crashing the entire loop. You may be requesting 10 objects, but at the first object without that image attribute, it is exiting.
W/System.err: org.json.JSONException: No value for image
So, recommendation (other than using Retrofit to manage your JSON API's) would be to use the optType() methods rather than the getType() methods of the JSON objects.
For example,
JSONObject img = productObject.optJSONObject("image");
This will set img to null when the "image" attribute does not exist.
Just be aware of that later in case you have a NullPointerException when trying to use img on this line
JSONObject da = img.getJSONObject("data");

Related

Having trouble with JSON Webservice

I am trying to get JSON data to app, but getting JSON Exception
MainActivity
public class MainActivity extends AppCompatActivity {
private ListView mListView;
private List<Project> projects = new ArrayList<>();
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.listView);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading....");
progressDialog.setCancelable(false);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
}
});
Button mFilterButton = (Button) findViewById(R.id.filter_button);
mFilterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(MainActivity.this,v);
popupMenu.inflate(R.menu.filter_menu);
popupMenu.show();
}
});
Button mSortButton = (Button) findViewById(R.id.sort_button);
mSortButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(MainActivity.this,v);
popupMenu.inflate(R.menu.sort_menu);
popupMenu.show();
}
});
new GSONExecution().execute();
}
private class GSONExecution extends AsyncTask<Void, Void, Boolean>{
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
#Override
protected Boolean doInBackground(Void... params) {
String urlString = "http://starlord.hackerearth.com/kickstarter";
try {
URL url = new URL(urlString);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("GET");
int res = httpURLConnection.getResponseCode();
if (res == 200){
InputStream inputStream = httpURLConnection.getInputStream();
String s = convertStreamToString(inputStream);
Log.v("Response :" , " is "+ s);
JSONObject rootObject = new JSONObject(s);
JSONArray jsonArray = rootObject.getJSONArray("");
for (int i=0; i<=jsonArray.length(); i++){
JSONObject contactObject = jsonArray.getJSONObject(i);
String titleValue = contactObject.getString("title");
Integer pledgedValue = contactObject.getInt("amt.pledged");
Integer backersValue = contactObject.getInt("num.backers");
Project project = new Project();
project.setPleadges(pledgedValue);
project.setBackers(backersValue);
project.settitle(titleValue);
projects.add(project);
Log.v("Object details : " , " : " + pledgedValue + " : " + backersValue);
}
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(Boolean isOperationCompleted) {
super.onPostExecute(isOperationCompleted);
if (isOperationCompleted){
if (progressDialog.isShowing()){
progressDialog.dismiss();
}
ProjectAdapter adapter = new ProjectAdapter(MainActivity.this, projects);
mListView.setAdapter(adapter);
}
}
#NonNull
private String convertStreamToString(InputStream inputStream) {
StringBuilder stringBuilder = new StringBuilder();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"),8);
String line;
while ((line = bufferedReader.readLine()) != null)
stringBuilder.append(line).append("\n");
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
}
}
Project
public class Project {
String mtitle;
Integer mPleadges;
Integer mBackers;
String mNoDays;
public String gettitle() {
return mtitle;
}
public void settitle(String mtitle) {
this.mtitle = mtitle;
}
public Integer getPleadges() {
return mPleadges;
}
public void setPleadges(Integer mPleadges) {
this.mPleadges = mPleadges;
}
public Integer getBackers() {
return mBackers;
}
public void setBackers(Integer mBackers) {
this.mBackers = mBackers;
}
public String getNoDays() {
return mNoDays;
}
public void setNoDays(String mNoDays) {
this.mNoDays = mNoDays;
}
}
ProjectAdapter
class ProjectAdapter extends BaseAdapter{
private List<Project> mList;
private Context mContext;
public ProjectAdapter(MainActivity mainActivity, List<Project> projects) {
this.mList = projects;
this.mContext = mainActivity;
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.project_details,null,false);
final TextView projectName = (TextView) convertView.findViewById(R.id.projectName);
TextView pleadge = (TextView) convertView.findViewById(R.id.pledges);
TextView backers = (TextView) convertView.findViewById(R.id.backers);
projectName.setText(mList.get(position).gettitle());
pleadge.setText(mList.get(position).getPleadges());
backers.setText(mList.get(position).getBackers());
return convertView;
}
}
I am getting org.json.JSONException: Value
at org.json.JSON.typeMismatch(JSON.java:111)
I hope you understand problem, I am still in learning stage so please give brief answer so that i can understand.
You are getting JSONArray from Response and trying to hold on JSONObject which causes org.json.JSONException: Value at org.json.JSON.typeMismatch(JSON.java:111) error
Try this
try {
JSONArray jsonArrayLST = new JSONArray(s);
for (int i = 0; i < jsonArrayLST.length(); i++) {
JSONObject contactObject= jsonArrayLST.getJSONObject(i);
String titleValue = contactObject.getString("title");
Integer pledgedValue = contactObject.getInt("amt.pledged");
Integer backersValue = contactObject.getInt("num.backers");
Project project = new Project();
project.setPleadges(pledgedValue);
project.setBackers(backersValue);
project.settitle(titleValue);
projects.add(project);
Log.v("Object details : " , " : " + pledgedValue + " : " + backersValue);
}
} catch (JSONException e) {
e.printStackTrace();
}
Also, you need to change in your adapter while setting item to textview, because your are setting int value which causes you android.content.res.Resources$NotFoundException: String resource ID error
pleadge.setText(String.valueOf(mList.get(position).getPleadges()));
backers.setText(String.valueOf(mList.get(position).getBackers()));

ArrayList returning null after the data saved to ArrayList?

I am working in setting the data to the spinner by using the custom adapter, in that i am getting the data from web server json data are saved to the list but when i set the data the saved data to the textview it shows exception list is null
public class PhotoCommnFragment extends android.support.v4.app.Fragment {
EditText rechargeMobileNumber,rechargeAmount;
Spinner selectMenu;
int flags[] = {R.drawable.airteltv, R.drawable.aircel, R.drawable.dishtv, R.drawable.sundirect, R.drawable.tatasky, R.drawable.videocon};
List<SpinnerMenu> selectedNetwork = new ArrayList<>();
public PhotoCommnFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tab_mobile, container, false);
mobileRecahrgeHistory();
rechargeMobileNumber = (EditText)rootView.findViewById(R.id.recharge_mobile_number);
rechargeAmount = (EditText)rootView.findViewById(R.id.recharge_amount);
selectMenu = (Spinner)rootView.findViewById(R.id.selectNetwork);
settingSpinnerDropDown();
return rootView;
}
public void mobileRecahrgeHistory(){
Ion.with(this)
.load("http://192.168.1.105/TotalRecharge/?api=ol&uid=1")
.asJsonObject().withResponse()
.setCallback(new FutureCallback<Response<JsonObject>>() {
#Override
public void onCompleted(Exception e, Response<JsonObject> result) {
JSONObject json = null;
try {
json = new JSONObject(result.getResult().toString());
} catch (JSONException e1) {
e1.printStackTrace();
}
// Create the root JSONObject from the JSON string.
JSONObject jsonRootObject = null;
jsonRootObject = json.optJSONObject("DS");
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("LST");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = null;
try {
jsonObject = jsonArray.getJSONObject(i);
} catch (JSONException e1) {
e1.printStackTrace();
}
String iph = null;
String oid = jsonObject.optString("OID").toString();
String ocd = jsonObject.optString("OCD").toString();
String opd = jsonObject.optString("OPE").toString();
String mil = jsonObject.optString("MIL").toString();
String mxl = jsonObject.optString("MXL").toString();
try {
iph = jsonObject.getString("IPH").toString();
} catch (JSONException e1) {
e1.printStackTrace();
}
String urldisplay = "http://192.168.1.105/TotalRecharge/"+iph;
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e3) {
e3.printStackTrace();
}
SpinnerMenu spinnerData = new SpinnerMenu();
spinnerData.setOid(oid);
spinnerData.setOcd(ocd);
spinnerData.setOpd(opd);
spinnerData.setMil(mil);
spinnerData.setMix(mxl);
spinnerData.setImage(mIcon11);
selectedNetwork.add(spinnerData);
}
}
});
}
public void settingSpinnerDropDown(){
Fragment_DTH_Main_Spinner_Adapter customAdapter=new Fragment_DTH_Main_Spinner_Adapter(getActivity(),R.layout.fragment_dth_main_spinner_items,R.id.serviceName,selectedNetwork);
selectMenu.setAdapter(customAdapter);
}
}
The data first set to the SpinnerMenu(Model Class) and then model class data is set to the list.
This is my custom adapter for setting data to spinner
public class Fragment_DTH_Main_Spinner_Adapter extends ArrayAdapter<SpinnerMenu> {
Context context;
int flags[];
List<SpinnerMenu> countryNames;
LayoutInflater inflter;
public Fragment_DTH_Main_Spinner_Adapter(FragmentActivity activity, int resouceId, int textviewId, List<SpinnerMenu> data) {
// super(activity, R.layout.fragment_dth_main_spinner_items,userstories);
super(activity,resouceId,textviewId,data);
this.countryNames = data;
}
public class ViewHolder
{
TextView names;
ImageView icon;
}
// #Override
public int getCount() {
return countryNames.size();
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.fragment_dth_main_spinner_items, parent, false);
// convertView = inflter.inflate(fragment_dth_main_spinner_items, null);
SpinnerMenu spinnerData = countryNames.get(position);
ViewHolder viewHolder;
View result;
if(convertView == null){
viewHolder = new ViewHolder();
viewHolder.icon = (ImageView) convertView.findViewById(R.id.imageView);
viewHolder.names = (TextView) convertView.findViewById(R.id.serviceName);
result = convertView;
}
else {
viewHolder = (ViewHolder) convertView.getTag();
result=convertView;
}
viewHolder.icon.setImageBitmap(spinnerData.getImage());
viewHolder.names.setText(spinnerData.getOpd());
return convertView;
}
}
Please help me how to solve this

Populate data into listview using json parsom with restful api

I have to run json format which is shown in below
and have to parse this data into listview
and for this i tried following code
MainActivity
swipeRefreshLayout.setOnRefreshListener(this);
// swipeRefreshLayout.setRefreshing(true);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
SyncMethod("http://52.26.35.210/api/web/v1/api-beautician/country-state-city");
}
}
);
notification_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String postloadid = actorsList.get(position).gettitle();
String source_addoc=actorsList.get(position).gettitle();
Constants.vCountry=actorsList.get(position).gettitle();
Toast.makeText(getApplicationContext(),"Selecting "+ Constants.vCountry+" State ", Toast.LENGTH_LONG).show();
finish();
}
});
}
public void init()
{
norecord=(LinearLayout)findViewById(R.id.norecord);
notification_listview=(ListView)findViewById(R.id.listView_notification);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
}
#Override
public void onRefresh()
{
swipeRefreshLayout.setRefreshing(false);
SyncMethod("http://52.26.35.210/api/web/v1/api-beautician/country-state-city");
}
private static String pad(int c)
{
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
#Override
public void onResume()
{
super.onResume();
swipeRefreshLayout.setRefreshing(false);
SyncMethod("http://52.26.35.210/api/web/v1/api-beautician/country-state-city");
}
public void SyncMethod(final String GetUrl)
{
Log.i("Url.............", GetUrl);
final Thread background = new Thread(new Runnable() {
// After call for background.start this run method call
public void run() {
try {
String url = GetUrl;
String SetServerString = "";
// document all_stuff = null;
SetServerString = fetchResult(url);
threadMsg(SetServerString);
} catch (Throwable t) {
Log.e("Animation", "Thread exception " + t);
}
}
private void threadMsg(String msg) {
if (!msg.equals(null) && !msg.equals("")) {
Message msgObj = handler11.obtainMessage();
Bundle b = new Bundle();
b.putString("message", msg);
msgObj.setData(b);
handler11.sendMessage(msgObj);
}
}
// Define the Handler that receives messages from the thread and update the progress
private final Handler handler11 = new Handler() {
public void handleMessage(Message msg) {
try {
String aResponse = msg.getData().getString("message");
Log.e("Exam", "screen>>" + aResponse);
swipeRefreshLayout.setRefreshing(false);
JSONObject jobj = new JSONObject(aResponse);
Log.e("Home Get draft--", jobj.toString());
String status = jobj.getString("status");
Log.e("Myorder Homestatusdraft",status);
Log.e("--------------------", "----------------------------------");
if (status.equalsIgnoreCase("true"))
{
actorsList = new ArrayList<Doctortype_method>();
JSONArray array = new JSONArray();
array = jobj.getJSONArray("response");
if(actorsList.size()>0){
actorsList.clear();
}
for(int i=0;i<array.length();i++)
{
JSONObject jsonChildNode = array.getJSONObject(i);
actorsList.add(new Doctortype_method(jsonChildNode.optString("State id"),jsonChildNode.optString("State name")));
}
if (getApplicationContext() != null)
{
if (adapter == null)
{
adapter = new Doctortype_Adapter(getApplicationContext(),actorsList);
notification_listview.setAdapter(adapter);
} else {
adapter.notifyDataSetChanged();
}
}
if(actorsList.size()==0)
{
norecord.setVisibility(View.VISIBLE);
}
}
else
{
swipeRefreshLayout.setRefreshing(false);
norecord.setVisibility(View.VISIBLE);
// UF.msg(message + "");
}
} catch (Exception e) {
}
}
};
});
// Start Thread
background.start();
}
public String fetchResult(String urlString) throws JSONException {
StringBuilder builder;
BufferedReader reader;
URLConnection connection = null;
URL url = null;
String line;
builder = new StringBuilder();
reader = null;
try {
url = new URL(urlString);
connection = url.openConnection();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
//Log.d("DATA", builder.toString());
} catch (Exception e) {
}
//JSONArray arr=new JSONArray(builder.toString());
return builder.toString();
}
}
For this i also add adapter as well as arraylist.
but when i run this application api is not called perfectly..
hope anyone a]can help me..
here i add adapter and arraylist
Adapter
public Doctortype_Adapter(Context context, ArrayList<Doctortype_method> objects) {
super(context, R.layout.list_doctortype, objects);
this.context = context;
this.vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.actorList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
//View v = convertView;
View rowView;
ViewHolder vh;
if (convertView == null) {
rowView = vi.inflate(R.layout.list_doctortype, null);
setViewHolder(rowView);
} else {
rowView = convertView;
}
vh = (ViewHolder) rowView.getTag();
vh.title.setText(Html.fromHtml(actorList.get(position).gettitle()));
vh.subtitle.setText(Html.fromHtml(actorList.get(position).getsubtitle()));
/* String image=actorList.get(position).getid();
UrlImageViewHelper.setUrlDrawable(vh.dimage, image.toString(), R.drawable.no_img);*/
return rowView;
}
static class ViewHolder {
public TextView title, subtitle;
}
private void setViewHolder(View rowView) {
ViewHolder vh = new ViewHolder();
vh.title = (TextView) rowView.findViewById(R.id.tvProfileName);
vh.subtitle = (TextView) rowView.findViewById(R.id.tvDesc);
}
}
arraylist
public Doctortype_method( String title, String subtitle) {
super();
this.title = title;
this.subtitle = subtitle;
}
public String gettitle() {
return title;
}
public void settitle(String title) {
this.title = title;
}
public String getsubtitle()
{
return subtitle;
}
public void setsubtitle(String subtitle) {
this.subtitle = subtitle;
}
there is no error but when i run this code api is not called and i didnt get the output i want.
Thnx in advance..
if (status.equalsIgnoreCase("true")) is wrong because you getting status:1 so it is if (status.equalsIgnoreCase("1")) try this and then change this array = jobj.getJSONArray("response"); to array = jobj.getJSONArray("data"); your JSONArray key is "data"
And replace this also
actorsList.add(new Doctortype_method(jsonChildNode.optString("State id"),jsonChildNode.optString("State name")));
with
actorsList.add(new Doctortype_method(jsonChildNode.optString("countryID"),jsonChildNode.optString("vCountry")));
hope this helps. if this doesn't help feel free to ask
EDIT:
I cant understand what you want but have a look at this
-> you need to create baseAdapter for listview and set that adapter into the listview with your arraylist
FOR FETCHING YOUR ABOVE DATA YOU NEED TO DO BELOW CODE:
String data;//your entire JSON data as String
try {
JSONObject object = new JSONObject(data);
String status = object.getString("status");
JSONArray dataArray = object.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
JSONObject json1 = dataArray.getJSONObject(i);
String countryID = json1.getString("countryID");
String vCountry = json1.getString("vCountry");
}
} catch (JSONException e) {
e.printStackTrace();
}
Now if you want to show this vCountry in listview you have to add vCountry in ArrayList and then in listview.setAdapter you have to pass this ArrayList which is filled by vCountry. Hope you understand now. If you want adapter and listview code please check this link http://www.vogella.com/tutorials/AndroidListView/article.html
Finally i got the right answer.
May anyone get help from this in future.
ActivityClass.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city_list_item);
lv_city = (ListView)findViewById(R.id.listView_city);
Bundle b=getIntent().getExtras();
city_stateid = b.getString("stateid");
city_statename=b.getString("stateName");
city_countryid=b.getString("country");
lv_city.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
page_cityname = cityist.get(position).getCityName();
SharedPreferences sp=getSharedPreferences("abc",MODE_WORLD_WRITEABLE);
SharedPreferences.Editor edit=sp.edit();
edit.putString("city_name", page_cityname);
edit.commit();
Toast.makeText(getApplicationContext(),"Selected city & State"+page_cityname + "-" +city_statename, Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), NextActivity.class);
/*i.putExtra("cityname", page_cityname);*/
startActivity(i);
}
});
}
#Override
public void onResume() {
super.onResume();
params12 = new ArrayList<NameValuePair>();
params12.add(new BasicNameValuePair("type", city_type));
params12.add(new BasicNameValuePair("stateID", city_stateid));
params12.add(new BasicNameValuePair("countryID", city_countryid));
new Sync().execute();
}
class Sync extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(Void... params) {
String obj;//new JSONArray();
try {
// obj=getJSONFromUrl("Your posting path", params11);
obj = getJSONFromUrl("http://52.26.35.210/api/web/v1/api-beautician/country-state-city", params12);
return obj;
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
Log.e("Result of geting data", "" + result);
try {
Log.e("Exam", "screen>>" + result);
JSONObject get_res = new JSONObject(result);
String status = get_res.getString("status");
Log.e("Exam", "screen33333>>" + status);
if (status.equalsIgnoreCase("1")) {
cityist = new ArrayList<city_method>();
JSONArray array = new JSONArray();
array = get_res.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
cityist.add(new city_method(array.getJSONObject(i).getString("cityID"),array.getJSONObject(i).getString("cityName")));
}
if (getApplicationContext() != null)
{
if (adapter == null)
{
adapter = new city_Adapter(getApplicationContext(),cityist);
lv_city.setAdapter(adapter);
} else {
adapter.notifyDataSetChanged();
}
}
}
} catch (Exception e) {
}
}
}
public String fetchResult(String urlString) throws JSONException {
StringBuilder builder;
BufferedReader reader;
URLConnection connection = null;
URL url = null;
String line;
builder = new StringBuilder();
reader = null;
try {
url = new URL(urlString);
connection = url.openConnection();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
//Log.d("DATA", builder.toString());
} catch (Exception e) {
}
//JSONArray arr=new JSONArray(builder.toString());
return builder.toString();
}
public String getJSONFromUrl(String url, List<NameValuePair> params) {
InputStream is = null;
String json = "";
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
//sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
}
Adapterclass.java
public class city_Adapter extends ArrayAdapter<city_method> {
ArrayList<city_method> citylist;
LayoutInflater vi;
Context context;
public city_Adapter(Context context, ArrayList<city_method> items) {
super(context, R.layout.list_doctortype, items);
this.context = context;
this.vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.citylist = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
//View v = convertView;
View rowView;
city_Adapter.ViewHolder vh;
if (convertView == null) {
rowView = vi.inflate(R.layout.program_list, null);
setViewHolder(rowView);
} else {
rowView = convertView;
}
vh = (city_Adapter.ViewHolder) rowView.getTag();
vh.cityid.setText((citylist.get(position).getCityID()));
vh.cityname.setText((citylist.get(position).getCityName()));
return rowView;
}
static class ViewHolder {
private TextView cityid,cityname;
}
private void setViewHolder(View rowView) {
ViewHolder vh = new ViewHolder();
vh.cityid = (TextView) rowView.findViewById(R.id.cityid);
vh.cityname = (TextView) rowView.findViewById(R.id.cityname);
rowView.setTag(vh);
}
}
Methodclass.java
public class city_method {
private String cityID,cityName;
public String getCityID() {
return cityID;
}
public void setCityID(String cityID) {
this.cityID = cityID;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public city_method(String cityID, String cityName) {
this.cityID = cityID;
this.cityName = cityName;
}
}

ListView does not show any data, getCount() returns 0, getView() never calls

I am trying to fetch data using AsyncTask & displaying into a ListView. It never calls getView(), I checked getCount() return always 0.
MainActivityFragment.java
public class MainActivityFragment extends Fragment {
private final String LOG_TAG = MainActivityFragment.class.getSimpleName();
SourceAdapter adapter;
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
adapter = new SourceAdapter(getActivity());
ListView listView = (ListView) rootView.findViewById(R.id.listView);
listView.setAdapter(adapter);
Log.d(LOG_TAG,"after list view set to adapter");
return rootView;
}
#Override
public void onStart() {
new FetchDataTask().execute();
super.onStart();
}
public class FetchDataTask extends AsyncTask<String, Void, SourceObject[]>{
private final String LOG_TAG = FetchDataTask.class.getSimpleName();
private SourceObject[] getSourceDataFromJson(String jsonStr)throws JSONException{
JSONArray jsonArray = new JSONArray(jsonStr);
SourceObject[] sourceObjects = new SourceObject[jsonArray.length()];
for (int i=0; i<jsonArray.length();i++){
sourceObjects[i] = new SourceObject(
jsonArray.getJSONObject(i).getJSONObject("commit").getJSONObject("author").getString("name"),
jsonArray.getJSONObject(i).getJSONObject("commit").getJSONObject("author").getString("name"),
jsonArray.getJSONObject(i).getJSONObject("commit").getString("message")
);
}
return sourceObjects;
}
#Override
protected SourceObject[] doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String jsonStr = null;
try {
String baseUrl = "https://api.github.com/repos/rails/rails/commits";
URL url = new URL(baseUrl);
Log.d(LOG_TAG,"URL IS "+url);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null)
return null;
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null){
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
jsonStr = buffer.toString();
Log.d(LOG_TAG,"JSON STRING "+jsonStr);
}catch (IOException e){
Log.e(LOG_TAG, "ERROR"+e);
return null;
}finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return getSourceDataFromJson(jsonStr);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(SourceObject[] strings) {
adapter.notifyDataSetChanged();
super.onPostExecute(strings);
}
}
}
SourceAdapter.java
public class SourceAdapter extends BaseAdapter {
private final String LOG_TAG = SourceAdapter.class.getSimpleName();
Context context;
ArrayList<SourceObject> objects = new ArrayList<SourceObject>();
public SourceAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
Log.d(LOG_TAG,"getCount called "+objects.size());
return objects.size();
}
#Override
public Object getItem(int position) {
Log.d(LOG_TAG,"getItem called");
return objects.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.d(LOG_TAG,"get view method is called");
SourceObject sourceObject = (SourceObject) getItem(position);
if (convertView == null){
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_source,parent,false);
}
TextView personName = (TextView) convertView.findViewById(R.id.person_name);
TextView commit = (TextView) convertView.findViewById(R.id.xxx);
TextView commitMessage = (TextView) convertView.findViewById(R.id.commit_message);
personName.setText(sourceObject.getPersonName());
commit.setText(sourceObject.getCommit());
commitMessage.setText(sourceObject.getCommitMessage());
return convertView;
}
}
Please help.
You are not setting data retrieved from AsyncTask to adapter.
Add this method to your adapter class:
public void setItems(SourceObject[] items) {
this.objects = new ArrayList<SourceObject>();
for(SourceObject item : items){
this.objects.add(item);
}
this.notifyDataSetChanged();
}
And change onPostExecute of AsyncTask to:
#Override
protected void onPostExecute(SourceObject[] strings) {
adapter.setItems(strings);
super.onPostExecute(strings);
}

Call BaseAdapter In Fragment Close Application

Call BaseAdapter In Fragment Close Application
Comment in line spinner.setAdapter(new Category_Adapter(getActivity(), categorylist));
Work
Error Log
Class FragmentNews
public class FragmentNews extends Fragment {
ArrayList<Category> categorylist = new ArrayList<Category>();
#Override
public View onCreateView(final LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
final View rootView = inflater.inflate(R.layout.fragment_news,
container, false);
Spinner spinner = (Spinner) rootView.findViewById(R.id.category);
new fechPosts().execute("");
return rootView;
}
class fechPosts extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
ringProgressDialog = new ProgressDialog(getActivity());
ringProgressDialog.setMessage("در حال ارسال پیام");
ringProgressDialog.setCancelable(true);
ringProgressDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String result = fetch(params[0]);
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Activity myActivity = getActivity();
spinner.setAdapter(new Category_Adapter(getActivity(), categorylist));
ringProgressDialog.dismiss();
}
}
public String fetch(String titel) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = null;
httppost = new HttpGet(
"http://mynikan.ir/paliz/mobile/GetAllProduct.php");
String r = "ok";
String result = null;
InputStream inputStream = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
JSONArray array = null;
try {
array = new JSONArray(result);
} catch (JSONException e) {
e.printStackTrace();
}
if (array.length() != 0) {
for (int i = 0; i < array.length(); i++) {
JSONObject json_data;
try {
json_data = array.getJSONObject(i);
Category obj = new Category();
obj.Image = json_data.getString("Product_Image");
obj.Title = json_data.getString("Price");
categorylist.add(obj);
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return r;
}
Class Adapter
public class Category_Adapter extends BaseAdapter {
public String[] items;
public LayoutInflater myinflater;
Context context;
static class ViewHolder
{
TextView text;
TextView price;
ImageView im;
}
public int[] picmenu;
ArrayList<Category> categorylist = new ArrayList<Category>();
public Category_Adapter(Context c, ArrayList<Category> pthemop) {
myinflater = LayoutInflater.from(c);
context = c;
categorylist = pthemop;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return categorylist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
// /////
if (convertView == null) {
convertView = myinflater.inflate(R.layout.snipper_single, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.im = (ImageView) convertView.findViewById(R.id.image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(categorylist.get(position).Title);
Picasso.with(context).load(categorylist.get(position).Image)
.into(holder.im);
return convertView;
}}
Class Category
public class Category {
String Title;
String Image;
}
Here:
spinner.setAdapter(new Category_Adapter(getActivity(), categorylist));
line causing issue because spinner object of Spinner is null.
In onCreateView method creating new object instead of initializing object which is using in spinner.
Change onCreateView method as:
spinner = (Spinner) rootView.findViewById(R.id.category);
new fechPosts().execute("");

Categories

Resources