There is a gridview in which I want to display a image. I want to use this json below to diplay image in my gridview. I have an ImageAdapter class in ImageAdapter class I have AsynTask that get json but I don't know how to using it to diplaly image in gridview.
How can I display image using this json?
{"countries":[{"id":"1","first_name":"man","last_name":"woman","username":"man","password":"4f70432e636970de9929bcc6f1b72412","email":"man#gmail.com","photo":"http:\/\/vulcan.wr.usgs.gov\/Imgs\/Jpg\/MSH\/Images\/MSH64_aerial_view_st_helens_from_NE_09-64_med.jpg","frame":"http:\/\/easy4us.files.wordpress.com\/2011\/02\/frame-1-4.jpg"}]}
ImageAdapter
public class ImageAdapter extends BaseAdapter {
public String url_select = "http://192.168.10.104/adchara1/";
private Context mContext;
public ImageAdapter(Context c){
mContext = c;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if(convertView == null){
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85,85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
}else{
imageView = (ImageView) convertView;
}
//imageView.setImageResource(mthumbIds[position]);
return imageView;
}
public class Task extends AsyncTask<String, String, Void>{
InputStream is = null;
String result = "";
#Override
protected Void doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag","Error in http connection " + e.toString());
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error Converting result " + e.toString());
}
return null;
}
protected void onPostExecute(Void v){
try {
JSONObject jObject = new JSONObject(result);
JSONArray jArray = jObject.getJSONArray("countries");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
String photo = jsonObject.getString("photo");
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridview = (GridView) findViewById(R.id.gridView);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
Intent i = new Intent(MainActivity.this, FullImageActivity.class);
i.putExtra("imagePath", position);
startActivity(i);
Toast.makeText(MainActivity.this, "" + (position + 1), Toast.LENGTH_SHORT).show();
}
});
}
}
This example may help you
It is one of the sample example
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("(link for fetching json data)");
myReq.Method = WebRequestMethods.Http.Get;
myReq.Accept = "apllication/json";
var response = (HttpWebResponse)myReq.GetResponse();
string myString= response.GetResponseHeader("Registration_Status");
using (var sr = new StreamReader(response.GetResponseStream()))
{
json = sr.ReadToEnd();
StreamWriter sw = new StreamWriter(#"D:\others\DemoCreatingCustomEvents\TextFile1.txt");
sw.Write(label1.Content.ToString());
sw.Close();
}
}
string json="";
private void button1_Click(object sender, RoutedEventArgs e)
{
ProductCategory deserializedProdCategory = new ProductCategory();
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
DataContractJsonSerializer ser = new DataContractJsonSerializer(deserializedProdCategory.GetType());
deserializedProdCategory = ser.ReadObject(ms) as ProductCategory;
ms.Close();
//you can fetch the data here and it is shown in label
label1.Content = deserializedProdCategory.ProdCategory[1].Product_ID + "//" + deserializedProdCategory.ProdCategory[1].Product_Name;
}
public class ProductCategory
{
public List<Product> ProdCategory = new List<Product>();
public ProductCategory()
{
ProdCategory = new List<Product>();
}
}
public class Product
{
public int Product_ID { get; set; }
public string Product_Code { get; set; }
public string Product_Name { get; set; }
public Uri Image_Small { get; set; }
}
Entity layer for your code
public class Country
{
public string id { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string username { get; set; }
public string password { get; set; }
public string email { get; set; }
public string photo { get; set; }
public string frame { get; set; }
}
public class MyData
{
public List<Country> countries { get; set; }
}
By using this you can modify it by seeing the above example
Related
I am very new in android.I my app I retrieve data from mysql database to list view. In my database table has a status column I also retrieve that value but I can not save into a variable. my concept to save status is if status value=0 a green image show side of that row.when status value change that colour will change.
Data Retrieve class
private class bookingList extends AsyncTask<String, String, Void> {
InputStream is = null;
String result = "";
#Override
protected void onPreExecute() {
findViewById(R.id.clientloadingPanel).setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(String... params) {
String url_select = "http://www.mybusket.com/webapi/carrental/booking/get_client_bookings.php?vclientid="+Clientid; //this clientid comes from global variable class
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url_select);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
httpGet.setURI(new URI(url_select));
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
// read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error converting result " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
try {
lv5 = (ListView)findViewById(R.id.lv5);
lv5.setAdapter(customClientBookingList);
JSONObject object = new JSONObject(result);
JSONArray jsonArray = object.getJSONArray("booking");
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject obj = jsonArray.getJSONObject(i);
Log.d("data",""+obj);
ClientBookingData clientBookingData = new ClientBookingData();
clientBookingData.setBdate(obj.getString("bdate"));
clientBookingData.setBrand(obj.getString("brand"));
clientBookingData.setCarno(obj.getString("carno"));
clientBookingData.setBfees(obj.getString("bfees"));
clientBookingData.setAdvance(obj.getString("advance"));
clientBookingData.setDue(obj.getString("due"));
clientBookingData.setBookingid(obj.getInt("bookingid"));
clientBookingData.setStatus(obj.getInt("status"));
clientBookingLists.add(clientBookingData);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
findViewById(R.id.clientloadingPanel).setVisibility(View.GONE);
}
}
Data set Class
private int bookingid,status;
private String bdate,carno,brand,bfees,advance,due;
public ClientBookingData(){}
public int getBookingid() {
return bookingid;
}
public void setBookingid(int bookingid) {
this.bookingid = bookingid;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getBdate() {
return bdate;
}
public void setBdate(String bdate) {
this.bdate = bdate;
}
public String getCarno() {
return carno;
}
public void setCarno(String carno) {
this.carno = carno;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getBfees() {
return bfees;
}
public void setBfees(String bfees) {
this.bfees = bfees;
}
public String getAdvance() {
return advance;
}
public void setAdvance(String advance) {
this.advance = advance;
}
public String getDue() {
return due;
}
public void setDue(String due) {
this.due = due;
}
public ClientBookingData(int bookingid, int status, String bdate, String carno, String brand, String bfees, String advance, String due) {
this.bookingid = bookingid;
this.status = status;
this.bdate = bdate;
this.carno = carno;
this.brand = brand;
this.bfees = bfees;
this.advance = advance;
this.due = due;
}
Adapter class
private Activity activity;
private LayoutInflater inflater;
private List<ClientBookingData> Items;
public CustomClientBookingList(){}
public CustomClientBookingList(Activity activity, List<ClientBookingData> Items) {
this.activity = activity;
this.Items = Items;
}
#Override
public int getCount() {
return Items.size();
}
#Override
public Object getItem(int location) {
return Items.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.activity_custom_client_booking_list, null,true);
TextView bdate = (TextView)convertView.findViewById(R.id.bdate);
TextView brand = (TextView)convertView.findViewById(R.id.brand);
TextView carno = (TextView)convertView.findViewById(R.id.carno);
TextView advance = (TextView)convertView.findViewById(R.id.advance);
TextView due = (TextView)convertView.findViewById(R.id.due);
TextView bfees = (TextView)convertView.findViewById(R.id.bfees);
// getting data for the row
ClientBookingData m = Items.get(position);
// set data
bdate.setText(m.getBdate());
brand.setText(m.getBrand());
carno.setText(m.getCarno());
advance.setText(m.getAdvance());
due.setText(m.getDue());
bfees.setText(m.getBfees());
return convertView;
}
Right side of each row have a image view with different colour. According to status value colour show.please help me.
You can simply do it like below
inside your getView()
ClientBookingData m = Items.get(position);
if(m.getStatus()==0)
//Your code to set Image Background
else
//Your code to set Image Background
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()));
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;
}
}
I have an app that connects to server sends sql request and get JSON answer as JsonArray.
Its Asynktask in seperate class (HTTPRequest.java is my AsyncTask class, Responce.java its my callback interface class) and it works correct.
when I use it in OrderActivity.java like below
#Override //my interface class function
public void onPostExecute(JSONArray Result) {
load(Result);
}
private void load(JSONArray json) {
for(int i=0;i<json.length();i++){
try {
JSONObject jo = json.getJSONObject(i);
Product p = new Product(
jo.getInt("ID"),
jo.getInt("parent"),
jo.getInt("category"),
jo.getString("Item"),
jo.getDouble("Price")
);
products.add(p);
} catch (JSONException e) {
e.printStackTrace();
}
}
it does work and fills product with data, but when I assign to my class variable JSONArray json
JSONArray json = new JSONArray;
.
.
.
#Override
public void onPostExecute(JSONArray Result) {
json = Result;
}
json is null
//HTTPRequest.java
public class HTTPRequest extends AsyncTask<String, Void, Integer> {
private Context context;
private Responce responce;
JSONArray json;
public HTTPRequest(Context context){
this.context = context;
responce = (Responce)context;
}
#Override
protected Integer doInBackground(String... params) {
OutputStream output;
InputStream inputStream = null;
HttpURLConnection connection = null;
String charset = "UTF-8";
Integer result = 0;
try {
URL uri = new URL(params[0]);
connection = (HttpURLConnection) uri.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "text/plain; charset=" + charset);
output = connection.getOutputStream();
output.write(params[1].getBytes(charset));
output.close();
int statusCode = connection.getResponseCode();
if (statusCode == 200) {
inputStream = new BufferedInputStream(connection.getInputStream());
json = new JSONArray(getJSON(inputStream));
result = 1;
}
} catch (Exception e) {
e.getLocalizedMessage();
}
return result;
}
#Override
protected void onPostExecute(Integer i) {
super.onPostExecute(i);
if(i == 1) {
responce.onPostExecute(json);
} else {
responce.onPostExecute(null);
}
}
private String getJSON(InputStream inputStream) throws IOException, JSONException {
StringBuffer stringBuffer = new StringBuffer();
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = null;
while((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line.toString());
}
result = stringBuffer.toString();
if(null!=inputStream){
inputStream.close();
}
return result;
}
}
//Responce.java
public interface Responce {
public void onPostExecute(JSONArray Result);
}
//OrderActivity.java
public class OrderActivity extends Activity implements Responce{
ArrayList<Product> products = new ArrayList<Product>();
ProductAdapter productAdapter;
OrderItemAdapter orderItemAdapter;
ListView orderlist;
JSONArray ja;
Button btnBack;
Button btnTakeOrder;
ListView picklist;
HTTPRequest httpRequest;
String url = "http://192.168.3.125:8888/data/";
String query = "select * from vwitems order by category desc";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
orderlist =(ListView)findViewById(R.id.orderlist);
orderItemAdapter = new OrderItemAdapter(OrderActivity.this);
btnBack = (Button)findViewById(R.id.btnBack);
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
productAdapter.filter(0);
}
});
btnTakeOrder = (Button)findViewById(R.id.btnTakeOrder);
btnTakeOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer oid = 0;
Order order = new Order(OrderActivity.this);
oid = order.NewOrder(1, 2, 3);
Toast.makeText(OrderActivity.this," " + order.getCount(), LENGTH_SHORT).show();
}
});
orderlist.setAdapter(orderItemAdapter);
picklist = (ListView) findViewById(R.id.picklist);
picklist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int pid = 0;
if (productAdapter.getItem(position).isCategory()) {
pid = productAdapter.getItem(position).getId();
productAdapter.filter(pid);
} else {
OrderItem oi = new OrderItem();
oi.setItemId(productAdapter.getItem(position).getId());
oi.setItem(productAdapter.getItem(position).getItem());
oi.setPrice(productAdapter.getItem(position).getPrice());
search(oi);
}
}
});
httpRequest = new HTTPRequest(this);
httpRequest.execute(url, query);
}
private boolean search(OrderItem oi){
int size = orderItemAdapter.getCount();
int i = 0;
if(size != 0)
for(OrderItem o : orderItemAdapter.getAll()){
if(o.getItemId() == oi.getItemId()){
orderItemAdapter.getItem(i).setQuantity(orderItemAdapter.getItem(i).getQuantity() + 1);
orderItemAdapter.notifyDataSetChanged();
return true;
}
i++;
}
orderItemAdapter.addItem(oi);
orderItemAdapter.notifyDataSetChanged();
return false;
}
private void load(JSONArray json) {
for(int i=0;i<json.length();i++){
try {
JSONObject jo = json.getJSONObject(i);
Product p = new Product(
jo.getInt("ID"),
jo.getInt("parent"),
jo.getInt("category"),
jo.getString("Item"),
jo.getDouble("Price")
);
products.add(p);
} catch (JSONException e) {
e.printStackTrace();
}
}
productAdapter = new ProductAdapter(OrderActivity.this, products);
picklist.setAdapter(productAdapter);
productAdapter.filter(0);
}
#Override
public void onPostExecute(JSONArray Result) {
load(Result);
}
/*
#Override
public void onPostExecute(JSONArray Result) {
json = Result;
}
**/
}
sorry i forgot include this one
//Order.java
public class Order implements Responce{
private Context context;
private JSONArray json = new JSONArray();
private HTTPRequest httpRequest;
private int OrderID;
private Date OrderDate;
private int OrderTable;
private int Waiter;
private byte OrderStatus;
private List<OrderItem> orderItems;
public Order(Context context){
this.context = context;
}
//some code here...
public Integer NewOrder(Integer guests, Integer waiter, Integer ordertable){
String query = "insert into orders(orderdate, guests, waiter, ordertable) VALUES(NOW()," + guests + ", " + waiter + ", " + ordertable + "); SELECT LAST_INSERT_ID() as ID;";
Integer result = 0;
Connect(query);
try {
JSONObject jo = json.getJSONObject(0);
result = jo.getInt("ID");
} catch (JSONException e) {
e.printStackTrace();
}
return result; //here i got 0 if i init result to 0, null or what ever i init my
}
#Override
public void onPostExecute(JSONArray Result) {
json = Result;
}
private void Connect (String query){
httpRequest = new HTTPRequest(context);
httpRequest.execute("http://192.168.3.125:8888/data/", query);
}
}
I want to list my mssql records in android listview. Here is my codes;
activity;
public class YoneticiMenuActivity extends Activity {
JSONObject jsonObject = null;
//JSONArray jsonArray = null;
//public Is isler = new Is();
//public ArrayList<Is> arrayIsler = new ArrayList<Is>();
ListView lvTumIsler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yonetici_menu);
Intent iAl = getIntent();
String mesaj = iAl.getStringExtra(LoginActivity.m);
int mode = Activity.MODE_PRIVATE;
SharedPreferences mSP;
mSP = getSharedPreferences(mesaj, mode);
String baslik = mSP.getString("name", "") + " " + mSP.getString("surname", "") + ", Hoşgeldiniz";
setTitle(baslik);
lvTumIsler = (ListView)findViewById(R.id.lvTumIsler);
new AsyncTaskYonetici("Veriler yükleniyor...").execute();
}
private class AsyncTaskYonetici extends AsyncTask<Void, Void, Void> {
String modalMesaj;
ProgressDialog dialog;
JSONArray jsonArray = null;
JSONObject jsonObject = null;
public Is isler = new Is();
public ArrayList<Is> arrayIsler = new ArrayList<Is>();
//private ListView lvTumIsler;
public AsyncTaskYonetici(String mMesaj) {
this.modalMesaj = mMesaj;
this.dialog = new ProgressDialog(YoneticiMenuActivity.this);
}
#Override
protected void onPreExecute() {
dialog.setMessage(modalMesaj);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String url = "http://www.saklambacjeans.com/skbos/webServiceTumIsler.aspx";
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
String line = null;
try {
if ((line = reader.readLine()) != null) {
jsonArray = new JSONArray(line);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
instream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (ClientProtocolException e) {
Mesaj(e.getMessage());
} catch (IOException e) {
Mesaj(e.getMessage());
} /*catch (JSONException e) {
Mesaj(e.getMessage());
}*/
return null;
}
#Override
protected void onPostExecute(Void str) {
try {
for (int i = 0; i < jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
isler.setP(Integer.parseInt(jsonObject.getString("urunId").toString()),
Integer.parseInt(jsonObject.getString("modelNo").toString()),
jsonObject.getString("modelAd").toString(),
jsonObject.getString("bedenAd").toString(),
Integer.parseInt(jsonObject.getString("adet").toString()),
jsonObject.getString("aciklama").toString(),
jsonObject.getString("kesmeTalimat").toString(),
jsonObject.getString("atolyeTalimat").toString(),
jsonObject.getString("yıkamaTalimat").toString(),
jsonObject.getString("utuTalimat").toString(),
jsonObject.getString("kesimci").toString(),
jsonObject.getString("atolyeci").toString(),
jsonObject.getString("yıkamacı").toString(),
jsonObject.getString("utucu").toString(), jsonObject.getString("kontrolcu").toString());
arrayIsler.add(isler);
}
} catch (JSONException e) {
e.printStackTrace();
}
IsAdapter adapter = new IsAdapter(YoneticiMenuActivity.this, R.layout.layouttumisler, arrayIsler);
lvTumIsler.setAdapter(adapter);
if (dialog.isShowing())
dialog.dismiss();
}
}
private void Mesaj(String s) {
Toast.makeText(this, s, Toast.LENGTH_LONG).show();
}
my adapter;
public class IsAdapter extends ArrayAdapter<Is> {
private ArrayList<Is> arrayIsler;
Context context;
public IsAdapter(Context context, int layoutResourceId, ArrayList<Is> a) {
super(context, layoutResourceId, a);
this.arrayIsler = a;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.layouttumisler, null);
}
Is is = arrayIsler.get(position);
if (is != null) {
TextView tvId = (TextView) row.findViewById(R.id.tvId);
TextView tvModel = (TextView) row.findViewById(R.id.tvModel);
TextView tvAtolye = (TextView) row.findViewById(R.id.tvAtolye);
TextView tvUrunId = (TextView) row.findViewById(R.id.tvUrunId);
TextView tvUrunModel = (TextView) row.findViewById(R.id.tvUrunModel);
TextView tvUrunAtolye = (TextView) row.findViewById(R.id.tvUrunAtolye);
if (tvId != null){
tvId.setText("Ürün No: ");
}
if (tvUrunId != null){
tvUrunId.setText(is.getId());
}
if (tvModel != null){
tvModel.setText("Model: ");
}
if (tvUrunModel != null){
tvUrunModel.setText(is.getModel());
}
if (tvAtolye != null){
tvAtolye.setText("Atolye: ");
}
if (tvUrunAtolye != null){
tvUrunAtolye.setText(is.getAtolye());
}
}
return row;
}
}
my Is class;
public class Is {
public int urunId;
public int modelNo;
public String modelAd;
public String bedenAd;
public int adet;
public String aciklama;
public String kesmeTalimat;
public String atolyeTalimat;
public String yikamaTalimat;
public String utuTalimat;
public String kesimci;
public String atolyeci;
public String yikamaci;
public String utucu;
public String kontrolcu;
public int getId() {return urunId;}
public String getModel() {return modelAd;}
public String getAtolye() {return atolyeci;}
public void setP(int u, int mN, String mA, String bA, int a, String ac, String kT, String aT, String yT, String uT,
String k, String at, String y, String utu, String ko)
{
urunId = u;
modelNo = mN;
modelAd = mA;
bedenAd = bA;
adet = a;
aciklama = ac;
kesmeTalimat = kT;
atolyeTalimat = aT;
yikamaTalimat = yT;
utuTalimat = uT;
kesimci = k;
atolyeci = at;
yikamaci = y;
utucu = utu;
kontrolcu = ko;
}
}
I use listview in main layout and there is 6 textview in layouttumısler. I use IsAdapter in onPostExecute in myAsyncTask but when I execute the app it is stopped.
The mssql records come from web service truely, But I can not list. I take error in IsAdapter getView, in
tvUrunId.setText(is.getId());
please help me...
I made a bad mistake, when I change
public int getId() {return urunId;}
as
public String getId()
{
String s = Integer.toString(urunId);
return s;
}
the code works.