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()));
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 developed a search function and it worked successfully. The class responsible for the search is called from onQueryTextSubmit and there was nothing wrong with it.
Now I wanted to add other thing that is a button in the same activity of the search bar that when it's clicked all data from the database is displayed in cardView. When I added the code the onQueryTextSubmit method is no longer working plus the button isn't displaying the data. I do not know where is the problem. Here is the code for the whole activity.
PS: for some reason it says that showdata() method is never used.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.find_skill);
button = (Button) findViewById(R.id.button);
recyclerView = (RecyclerView) findViewById(R.id.recyclerViewer);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listView = (ListView) findViewById(R.id.searchList);
searchView = (SearchView) findViewById(R.id.searchView);
noData = (ImageView) findViewById(R.id.nodata);
noNetwork = (ImageView) findViewById(R.id.nonetwork);
urlAdress = "http://skillsexchangecyprus.com/SEC/ss.php";
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
getData();
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
SenderReceiver sr = new SenderReceiver(FindSkill.this, urlAdress,listView, query,noData,noNetwork);
sr.execute();
return false;
}
#Override
public boolean onQueryTextChange(String query) {
return false;
}});}
private void getData() {
class GetData extends AsyncTask<Void, Void, String> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(FindSkill.this, "Fetching Data", "Please wait...", false, false);
}
#Override
protected void onPostExecute(String res) {
super.onPostExecute(res);
progressDialog.dismiss();
parseJSON(res);
}
#Override
protected String doInBackground(Void... params) {
BufferedReader bufferedReader = null;
try {
URL url = new URL(Config.GET_URL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetData gd = new GetData();
gd.execute();
}
public void showData(){
adapter = new CardAdapter(Config.skills,Config.ids);
recyclerView.setAdapter(adapter);
}
private void parseJSON(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray array = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
config = new Config(array.length());
for (int i = 0; i < array.length(); i++) {
JSONObject j = array.getJSONObject(i);
Config.skills[i] = getSkill(j);
Config.ids[i] = getId(j);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private String getSkill(JSONObject j){
String name = null;
try {
name = j.getString(Config.JSON_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
return name;
}
private String getId(JSONObject j){
String id = null;
try {
id = j.getString(Config.JSON_ID);
} catch (JSONException e) {
e.printStackTrace();
}
return id;
}
This is the Config class:
public class Config {
public static String[] skills;
public static String[] ids;
public static final String GET_URL = "http://skillsexchangecyprus.com/SEC/mainList.php";
public static final String JSON_ID = "id";
public static final String JSON_NAME = "skill";
public static final String TAG_JSON_ARRAY="result";
public Config(int i) {
skills = new String[i];
ids = new String[i];
}
}
Card Adapter class:
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
List<ListItem> items;
public CardAdapter(String[] skills, String[] ids){
super();
items = new ArrayList<>();
for(int i =0; i<items.size(); i++){
ListItem item = new ListItem();
item.setSkill(skills[i]);
item.setId(ids[i]);
items.add(item);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ListItem myAdapter = items.get(position);
holder.skillName.setText(myAdapter.getSkill());
holder.skillId.setText(String.valueOf(myAdapter.getId()));
}
#Override
public int getItemCount() {
return items.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView skillId;
public TextView skillName;
public ViewHolder(View itemView) {
super(itemView);
skillId = (TextView) itemView.findViewById(R.id.skillId);
skillName = (TextView) itemView.findViewById(R.id.skillName);
}
}
}
You did't call your showData() method. You need to create an instance of CardAdapter and set this adapter to your recyclerView.
Update OnCreate() method as below:
..............
....................
urlAdress = "http://skillsexchangecyprus.com/SEC/ss.php";
config = new Config(INITIAL_VALUE);
// Adapter
adapter = new CardAdapter(config.skills,config.ids);
recyclerView.setAdapter(adapter);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
getData();
}
});
....................
..............................
Use adapter.notifyDataSetChanged() to update recyclerView with new items.
Update parseJson() method as below:
private void parseJSON(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray array = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
config = new Config(array.length());
for (int i = 0; i < array.length(); i++) {
JSONObject j = array.getJSONObject(i);
config.skills[i] = getSkill(j);
config.ids[i] = getId(j);
// Update
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
In your CardAdapter constructor, use skills.length instead of items.size()
public CardAdapter(String[] skills, String[] ids){
super();
items = new ArrayList<>();
for(int i = 0; i < skills.length; i++){
ListItem item = new ListItem();
item.setSkill(skills[i]);
item.setId(ids[i]);
items.add(item);
}
}
Hope this will work~
I am displaying hotels in listview with checkbox,image and text. when user click on checkbox then put that checked hotel_id into bundle. And pass to it's super class.
When i am selected hotels and click on button on main activity my logcat shows NullPointerException. I will check my code with debugger. I can find getting Bundle=null. So please help to find the hotel_id when click's on checkbox and send that all selected hotel_id to its main Activity.
Here is my ListViewAdapter class.
public class ListViewAdapter extends BaseAdapter {
Context context;
LayoutInflater inflater;
ArrayList<Product> AllMenu = new ArrayList<>();
ImageLoader imageLoader;
int checkCounter = 0;
public ListViewAdapter(Context context, ArrayList<Product> itemlist) {
this.context = context;
AllMenu = itemlist;
imageLoader = new ImageLoader(context);
checkCounter = 0;
}
public int getCount() {
return AllMenu.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return 0;
}
public View getView(final int position, final View convertView, final ViewGroup parent) {
// Declare Variables
final Product tempMenu = AllMenu.get(position);
final CheckBox c;
final ImageView image_path;
final TextView name, location, desc;
final Bundle b = new Bundle();
final Intent intent = new Intent(context.getApplicationContext(),Hotels.class);
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View view = inflater.inflate(R.layout.viewpage, parent, false);
// Get the position
c = (CheckBox) view.findViewById(R.id.mycheckbox);
name = (TextView) view.findViewById(R.id.fh_name);
location = (TextView) view.findViewById(R.id.fh_loc);
desc = (TextView) view.findViewById(R.id.fh_desc);
image_path = (ImageView) view.findViewById(R.id.image_all_main);
c.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (c.isChecked() && checkCounter >= 3) {
AllMenu.get(position).setSelected(false);
c.setChecked(false);
Toast.makeText(context, "You can select max 3 hotels!!", Toast.LENGTH_SHORT).show();
} else {
Product p = (AllMenu).get(position);
p.setSelected(c.isChecked());
if (c.isChecked()) {
checkCounter++;
} else {
checkCounter--;
}
}
StringBuffer responseText = new StringBuffer();
responseText.append("The following were selected...");
ArrayList<Product> p = AllMenu;
for (int i = 0; i < p.size(); i++) {
Product pp = p.get(i);
if (pp.isSelected()) {
//here is i want hotel id when i am cliked on hotel.
//and save it into bundle and i am get bundle into it's super class
String[] h = new String[0];
b.putStringArray(String.valueOf(pp.getId()),hid);
intent.putExtras(b);
//Here is how i can pass custom object to string
responseText.append("\n" + pp.getName() + "\t");
responseText.append("\t" + pp.getLocation());
}
}
Toast.makeText(context, responseText, Toast.LENGTH_SHORT).show();
}
});
c.setTag(tempMenu);
c.setChecked(tempMenu.isSelected());
name.setText(tempMenu.getName());
location.setText(tempMenu.getLocation());
desc.setText(tempMenu.getDescription().trim());
imageLoader.DisplayImage(tempMenu.getImage_path(), image_path);
return view;
}
}
And i will get that bundle into this Hotels.class
Here is my Hotels.class
public class Hotels extends Activity
{
// Declare Variables
JSONArray jsonarray = null;
private static final String TAG_ID= "id";
public static final String TAG_NAME = "name";
public static final String TAG_LOCATION = "location";
public static final String TAG_DESC = "description";
String f_date,l_date;
int[] hotel_id = new int[0];
ProgressDialog loading;
ListView list;
Button booknow;
ListViewAdapter adapter;
private ArrayList<Product> itemlist;
Product product;
static String Array = "MyHotels";
View view;
CheckBox click;
String hotel = "http://app.goholidays.info/getHotelData.php";
String booking = "http://app.goholidays.info/insertIntoBooking.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_item_layout);
product = new Product();
itemlist = new ArrayList<Product>();
new ReadJSON().execute();
click = (CheckBox) findViewById(R.id.mycheckbox);
booknow = (Button) findViewById(R.id.bookhotel);
product = new Product();
list = (ListView) findViewById(R.id.myimagelist);
Calendar c = Calendar.getInstance();
System.out.println("Current time => "+c.getTime());
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Hotels.this);
SharedPreferences.Editor editor = sp.edit();
final String user_id = sp.getString("id", TAG_ID);
final String start_date = sp.getString("start_date", f_date);
final String end_date = sp.getString("end_date", l_date );
final String chk_status = df.format(c.getTime());
booknow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//here i want get all selected hotel_id into bundle.
//And i want pass that hotel_id to my database.
Bundle bundle = getIntent().getExtras();
String[] hotel_id = bundle.getStringArray(String.valueOf(product.getId()));
Submit(start_date,end_date,hotel_id,chk_status,user_id);
}
});
}
class ReadJSON extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(Hotels.this,"Fetching Data","Please wait...",false,false);
}
#Override
protected String doInBackground(String... args) {
Product tempMenu;
try {
JSONObject jsonobject = JSONfunctions.getJSONfromURL(hotel);
jsonarray = jsonobject.optJSONArray(Array);
//parse date for dateList
for (int i = 0; i < jsonarray.length(); i++) {
tempMenu = new Product();
jsonobject = jsonarray.getJSONObject(i);
tempMenu.setId(jsonobject.getInt("hotel_id"));
tempMenu.setName(jsonobject.getString("name"));
tempMenu.setLocation(jsonobject.getString("location"));
tempMenu.setImage_path(jsonobject.getString("image_name"));
tempMenu.setDescription(jsonobject.getString("description"));
tempMenu.setFacility1(jsonobject.getString("facility1"));
tempMenu.setFacility2(jsonobject.getString("facility2"));
tempMenu.setFacility3(jsonobject.getString("facility3"));
tempMenu.setFacility4(jsonobject.getString("facility4"));
tempMenu.setStar(jsonobject.getString("star"));
itemlist.add(tempMenu);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
adapter = new ListViewAdapter(Hotels.this, itemlist);
list.setAdapter(adapter);
loading.dismiss();
}
}
private void Submit(final String start_date, final String end_date, final String[] hotel_id, final String chk_status, final String user_id) {
class BackTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String start_dtae = params[0];
String end_date = params[1];
String hotel_id = params[2];
String user_id = params[3];
String chk_status = params[4];
try {
URL url = new URL(booking);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream os = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
String data = URLEncoder.encode("start_date", "UTF-8") +"="+URLEncoder.encode(start_dtae, "UTF-8") + "&" +
URLEncoder.encode("end_date", "UTF-8") +"="+URLEncoder.encode(end_date, "UTF-8") + "&" +
URLEncoder.encode("hotel_id", "UTF-8") +"="+URLEncoder.encode(hotel_id, "UTF-8") + "&" +
URLEncoder.encode("user_id", "UTF-8") +"="+URLEncoder.encode(user_id, "UTF-8") + "&" +
URLEncoder.encode("chk_status", "UTF-8") +"="+URLEncoder.encode(chk_status, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
os.close();
InputStream is = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
String responce = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
responce += line;
}
bufferedReader.close();
is.close();
httpURLConnection.disconnect();
return responce;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(),"Book Success"+result,Toast.LENGTH_SHORT).show();
}
}
BackTask lg=new BackTask();
lg.execute(start_date, end_date, chk_status, String.valueOf(hotel_id), user_id);
}
}
My custom object class is here.
public class Product extends HashMap<String, String> {
private String name;
private int hotel_id;
private String description;
private String location;
private String image_path;
boolean selected;
public boolean isSelected(){
return selected;
}
public void setSelected(boolean selected){
this.selected = selected;
}
public void setId (int hotel_id) { this.hotel_id = hotel_id;}
public int getId() {
return hotel_id;
}
public void setName (String name) { this.name = name;}
public String getName() {
return name;
}
public void setLocation(String location) {
this.location = location;
}
public String getLocation() {
return location;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public void setImage_path(String image_path) {
this.image_path = image_path;
}
public String getImage_path() {
return image_path;
}
}
The problem is you are only putting data to intent. It is just worth if You put bundle or data inside intent object with using startActivity.
If you want to get selected Hotel id's just make a public array like:-
public class Hotels extends Activity
{
public ArrayList<Integer> hotel_ids=new ArrayList<>();
}
and inside adapter while selecting check box put id in arrayList with the use of context as below and if unchecked remove hotel_id from that array list :-
c.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (c.isChecked() && checkCounter >= 3) {
AllMenu.get(position).setSelected(false);
c.setChecked(false);
Toast.makeText(context, "You can select max 3 hotels!!", Toast.LENGTH_SHORT).show();
} else {
Product p = (AllMenu).get(position);
p.setSelected(c.isChecked());
if (c.isChecked()) {
if(context instanceof Hotels){
((Hotels)context).hotel_ids.add(p.getId());
}
checkCounter++;
} else {
if(context instanceof Hotels){
((Hotels)context).hotel_ids.remove(p.getId());
}
checkCounter--;
}
}
}
}
It may help you out. With the above one you will always find selected Hotel_ids.
you can do something like this.
1> in getview method you can do checked listener like below
viewHolder.chkbox.setOnCheckedChangeListener(new CheckUpdateListener(itemList.get(position));
2> make new class for CheckUpdatelistener with argument constructor of model class
private final class CheckUpdateListener implements CompoundButton.OnCheckedChangeListener {
private final Product product;
private CheckUpdateListener(Product product) {
this.product = product;
}
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.i("onCheckedChanged", "isChecked: " + isChecked);
product.setChecked(isChecked);
notifyDataSetChanged();
}
}
3> in main activity on button click listener you can do code like this
Arraylist<Product> selectedProduct = new ArrayList<>();
if (itemList.size() > 0) {
for (int i = 0; i < itemList.size(); i++) {
if (itemList.get(i).isChecked()) {
try {
selectedProduct.add(itemList.get(i));
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
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.