我必须运行json格式,如下所示 并且必须将这些数据解析为listview
为此我尝试了以下代码
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();
}
}
为此,我还添加了适配器和arraylist。 但是当我运行这个应用程序时,api并没有被完美地称为.. 希望有人能帮助我..
这里我添加了适配器和arraylist
适配器
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);
}
}
数组列表
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;
}
没有错误,但是当我运行此代码api没有被调用,我没有得到我想要的输出。 Thnx提前..
答案 0 :(得分:0)
if (status.equalsIgnoreCase("true"))
错误,因为您获得status:1
因此if (status.equalsIgnoreCase("1"))
尝试此操作,然后将此array = jobj.getJSONArray("response");
更改为array = jobj.getJSONArray("data");
您的JSONArray密钥为{{1} }}
并替换它
"data"
带
actorsList.add(new Doctortype_method(jsonChildNode.optString("State id"),jsonChildNode.optString("State name")));
希望这会有所帮助。如果这没有帮助随意询问
编辑:
我无法理解你想要的东西,但看看这个 - &GT;你需要为listview创建baseAdapter并使用你的arraylist
将该适配器设置到listview中为了获取上面的数据,你需要做以下代码:
actorsList.add(new Doctortype_method(jsonChildNode.optString("countryID"),jsonChildNode.optString("vCountry")));
现在,如果要在listview中显示此vCountry,则必须在ArrayList中添加vCountry,然后在listview.setAdapter中,您必须传递由vCountry填充的此ArrayList。希望你现在明白。如果您需要适配器和列表视图代码,请查看此链接http://www.vogella.com/tutorials/AndroidListView/article.html
答案 1 :(得分:0)
最后我得到了正确的答案。 今后任何人都可以从中获得帮助。
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;
}
}