I am new to android. I need to pass values from the spinner to asynctask as an parameter and till now I am successful in showing the results in spinner successfully. Now i need to pass the selected value from the spinner to another activity on a button click (as an parameter to asynctask). Below is the code. Thanks in advance.
BackgroundFetchWorker.java:
public class BackgroundFetchWorker extends AsyncTask<String,Void,String> {
String json_string;
ProgressDialog progressDialog;
Context context;
BackgroundFetchWorker(Context ctx)
{
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type2 = params[0];
String student_fetch_url = "http://pseudoattendance.pe.hu/studentFetch.php";
if (type2.equals("fetchSubject")) {
try {
String semester = params[1];
String stream = params[2];
URL url = new URL(student_fetch_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("semester", "UTF-8") + "=" + URLEncoder.encode(semester, "UTF-8")
+ URLEncoder.encode("stream","UTF-8")+"="+URLEncoder.encode(stream,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = " ";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Fetching Data....");
progressDialog.setMessage("This may take a while..");
progressDialog.show();
}
#Override
protected void onPostExecute(String result) {
progressDialog.dismiss();
String s = result.trim();
if(s.equals("{\"result\":[]}")){
Toast.makeText(context, "ERROR OCCURED", Toast.LENGTH_SHORT).show();
}
else {
json_string = result;
Intent i = new Intent(context, TakeAttendanceActivity.class);
i.putExtra("studentdata", json_string);
context.startActivity(i);
Toast.makeText(context, "Success", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
FacultyWelcomeActivity.java:
public class FacultyWelcomeActivity extends AppCompatActivity implements Spinner.OnItemSelectedListener{
String JSON_STRING;
JSONObject jsonObject;
JSONArray jsonArray;
ContactAdapter contactAdapter;
ListView listView;
//Declaring an Spinner
private Spinner spinner;
private Spinner spinner1;
//An ArrayList for Spinner Items
private ArrayList<String> students;
private ArrayList<String> stream;
//JSON Array
private JSONArray result;
private JSONArray result1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_faculty_welcome);
//Initializing the ArrayList
students = new ArrayList<String>();
stream = new ArrayList<String>();
//Initializing Spinner
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String semesters= parent.getItemAtPosition(position).toString();
String stream= parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinner1 = (Spinner) findViewById(R.id.spinner1);
//Adding an Item Selected Listener to our Spinner
//As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener
getData();
getData1();
listView = (ListView) findViewById(R.id.lectureList);
contactAdapter = new ContactAdapter(this, R.layout.rowlayout);
listView.setAdapter(contactAdapter);
JSON_STRING = getIntent().getExtras().getString("JSON Data");
try {
jsonObject = new JSONObject(JSON_STRING);
jsonArray = jsonObject.getJSONArray("result");
int count = 0;
String sub1, sub2, sub3, sub4;
while (count < jsonArray.length()) {
JSONObject JO = jsonArray.getJSONObject(count);
sub1 = JO.getString("fname");
sub2 = JO.getString("lname");
sub3 = JO.getString("id");
sub4 = JO.getString("email");
Contacts contacts = new Contacts(sub1, sub2, sub3, sub4);
contactAdapter.add(contacts);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void fetchSubject(View view) {
String type2 = "fetchSubject";
String spinnerdata = spinner.getSelectedItem().toString();
String spinner1data = spinner1.getSelectedItem().toString();
BackgroundFetchWorker background = new BackgroundFetchWorker(this);
background.execute(type2,spinnerdata,spinner1data);
}
private void getData1(){
StringRequest stringRequest = new StringRequest(Config2.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result1 = j.getJSONArray(Config2.JSON_ARRAY);
getStudents1(result1);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void getData(){
StringRequest stringRequest = new StringRequest(Config.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
result = j.getJSONArray(Config.JSON_ARRAY);
getStudents(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void getStudents(JSONArray j){
for(int i=0;i<j.length();i++){
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
students.add(json.getString(Config.TAG_SEMESTER));
} catch (JSONException e) {
e.printStackTrace();
}
}
spinner.setAdapter(new ArrayAdapter<String>(FacultyWelcomeActivity.this, android.R.layout.simple_spinner_dropdown_item, students));
}
private void getStudents1(JSONArray j){
//Traversing through all the items in the json array
for(int i=0;i<j.length();i++){
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
stream.add(json.getString(Config2.TAG_STREAM));
} catch (JSONException e) {
e.printStackTrace();
}
}
spinner1.setAdapter(new ArrayAdapter<String>(FacultyWelcomeActivity.this, android.R.layout.simple_spinner_dropdown_item, stream));
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//check which spinner triggered the listener
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}}
You are passing parameters to doInBackground() this way:
background.execute("your string");
Now the string "your string" will be the parameter within doInBackground() callback:
#Override
protected String doInBackground(String... params) {
String type2 = params[0]; // type2 == "your string"
...
}
See docs for more info.
Related
im trying to parse data from SQL Database into Listview.
My PHP script is working because if i run it in the browser i get the content.
If im trying to get the data from my SQL Databse into the listview my app shows nothing.
Here is my MainActivity:
public class Locations extends AppCompatActivity implements AdapterView.OnItemClickListener {
ArrayList<productforloc> arrayList;
ListView lv;
private String TAG = Locations.class.getSimpleName();
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
int i = 1;
private ProgressDialog pDialog;
String name;
// URL to get contacts JSON
private static String url = "Mylink";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
Intent i = getIntent();
String cityname = i.getExtras().getString("cityname");
TextView city = (TextView) findViewById(R.id.ort);
city.setText(cityname);
pDialog = new ProgressDialog(Locations.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
pDialog.show();
arrayList = new ArrayList<>();
lv = (ListView) findViewById(R.id.lv);
lv.setOnItemClickListener((AdapterView.OnItemClickListener) this);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
final ImageButton filteropen = (ImageButton) findViewById(R.id.aufklaupen);
filteropen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout filter = (RelativeLayout) findViewById(R.id.filterloc);
filter.setVisibility(View.VISIBLE);
ImageButton filterclose = (ImageButton) findViewById(R.id.zuklappen);
filterclose.setVisibility(View.VISIBLE);
filteropen.setVisibility(View.INVISIBLE);
}
});
final ImageButton filterclose = (ImageButton) findViewById(R.id.zuklappen);
filterclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout filter = (RelativeLayout) findViewById(R.id.filterloc);
filter.setVisibility(View.INVISIBLE);
ImageButton filteropen = (ImageButton) findViewById(R.id.aufklaupen);
filteropen.setVisibility(View.VISIBLE);
filterclose.setVisibility(View.INVISIBLE);
}
});
}
class ReadJSON extends AsyncTask<String,Integer,String> {
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
try{
JSONObject jo = new JSONObject(content);
JSONArray ja = jo.getJSONArray("contacts");
for(int i=0;i<ja.length();i++){
JSONObject po = ja.getJSONObject(i);
arrayList.add(new productforloc(
po.getString("imageurl"),
po.getString("name"),
po.getString("street"),
po.getString("postalcode"),
po.getString("musicstyle"),
po.getString("musicsecond"),
po.getString("entry"),
po.getString("opening"),
po.getString("agegroup"),
po.getString("urlbtn"),
po.getString("Fsk"),
po.getString("city"),
po.getString("bg")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
final CustomListAdapterforloc adapter = new CustomListAdapterforloc(getApplicationContext(),R.layout.model,arrayList);
lv.setAdapter(adapter);
if(pDialog.isShowing()){
pDialog.dismiss();
}
}
}
private String readURL(String url){
StringBuilder content = new StringBuilder();
try{
URL uri = new URL(url);
URLConnection urlConnection = uri.openConnection();
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) !=null){
content.append(line+"\n");
}
bufferedReader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
productforloc pForloc = arrayList.get(position);
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",pForloc.getName());
intent.putExtra("imageurl",pForloc.getImage());
intent.putExtra("street",pForloc.getStreet());
intent.putExtra("postalcode",pForloc.getPostalcode());
intent.putExtra("entry",pForloc.getEntry());
intent.putExtra("agegroup",pForloc.getAgegroup());
intent.putExtra("opening",pForloc.getOpening());
intent.putExtra("urlbtn",pForloc.getUrlbtn());
intent.putExtra("Fsk",pForloc.getFsk());
intent.putExtra("city",pForloc.getCity());
intent.putExtra("musicstyle",pForloc.getMusicstyle());
intent.putExtra("musicsecond",pForloc.getMusicsecond());
intent.putExtra("bg",pForloc.getBg());
startActivity(intent);
}
/**
* Async task class to get json by making HTTP call
}
*/
}
and here is my Customlistadapter Activity:
public class CustomListAdapterforloc extends ArrayAdapter<productforloc>{
ArrayList<productforloc> products;
Context context;
int resource;
public CustomListAdapterforloc(Context context, int resource, List<productforloc> products) {
super(context, resource, products);
this.products = (ArrayList<productforloc>) products;
this.context = context;
this.resource = resource;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView== null){
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.model,null,true);
}
productforloc product = getItem(position);
ImageView imageView = (ImageView) convertView.findViewById(R.id.imagelist);
Picasso.with(context).load(product.getImage()).into(imageView);
TextView txtName= (TextView) convertView.findViewById(R.id.namelist);
txtName.setText(product.getName());
return convertView;
}
}
i solved it using this code in my MAinActivity:
public class Locations extends AppCompatActivity {
private String TAG = Locations.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "http://partypeople.bplaced.net/loli.php";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.lv);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Locations.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray contacts = new JSONArray(jsonStr);
// Getting JSON Array node
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**3
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Locations.this, contactList,
R.layout.model, new String[]{"name", "email",
"mobile"}, new int[]{R.id.namelist,
});
lv.setAdapter(adapter);
}
}
and used in my CustomlistadapterActivity:
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
Thanks for your input
Override getCount method into adapter class.
"http://soccer.sportsopendata.net/v1/leagues/premier-league/seasons/16-17/standings" - Link Which Iam Trying to parse
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button GetServerData = (Button) findViewById(R.id.GetServerData);
GetServerData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// WebServer Request URL
String serverURL = "http://soccer.sportsopendata.net/v1/leagues/premier-league/seasons/16-17/standings";
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
}
});
}
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
String data = "";
TextView uiUpdate = (TextView) findViewById(R.id.textView2);
TextView jsonParsed = (TextView) findViewById(R.id.textView3);
int sizeData = 0;
EditText serverText = (EditText) findViewById(R.id.textView);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
//Start Progress Dialog (Message)
Dialog.setMessage("Please wait..");
Dialog.show();
try {
// Set Request parameter
data += "&" + URLEncoder.encode("data", "UTF-8") + "=" + serverText.getText();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader = null;
// Send data
try {
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (Exception e) {
Error = e.getMessage();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if (Error != null) {
uiUpdate.setText("Output : " + Error);
}else
{
//Show Response Json Onscreen(Activity)
uiUpdate.setText( Content );
/****************** Start Parse Response JSON Data *************/
String OutputData = "";
try {
JSONObject jsono = new JSONObject(Content);
JSONObject mainObject = jsono.getJSONObject("data");
JSONArray jsonArray = mainObject.getJSONArray("standing");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
// get details2 JSONObject
String position = object.optString("position").toString();
String team = object.optString("team").toString();
OutputData += "Position: " + position + " "
+ "Team Name : " + team + " ";
}
/****************** End Parse Response JSON Data *************/
//Show Parsed Output on screen (activity)
jsonParsed.setText( OutputData );
}catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
**I am Creating a premier league application which shows all the datas needed for a premier league fan. As Iam new to this I am getting confused over json parsing and getting data from apis. So Can anyone Explain to me how to change my code or Some links which would help me correct it.
Above given is my java code of Main Activity.**
Thank You Everyone for Helping out. But I found my answer from the search over the internet. Here I used VOLLEY to call the link.
JSON PARSER CLASS
public class ParseJSON {
public static String[] position1;
public static String[] team;
public static String[] points;
public static final String JSON_ARRAY = "data";
public static final String CHILD_ARRAY = "standings";
public static final String KEY_ID = "position";
public static final String KEY_NAME = "team";
private JSONObject users = null;
private JSONArray user2=null;
private JSONObject user3=null;
private String json;
public ParseJSON(String json){
this.json = json;
}
protected void parseJSON() {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONObject(JSON_ARRAY);
try {
user2=users.getJSONArray(CHILD_ARRAY);
position1 = new String[user2.length()];
team = new String[user2.length()];
points=new String[user2.length()];
for (int i = 0; i < user2.length(); i++) {
JSONObject jo = user2.getJSONObject(i);
try {
user3=jo.getJSONObject("overall");
points[i] = user3.getString("points");
System.out.println("Message me: "+points[i]);
}catch (Exception e)
{
e.printStackTrace();
}
position1[i] = jo.getString(KEY_ID);
team[i] = jo.getString(KEY_NAME);
System.out.println("Message me: "+position1[i]);
System.out.println("Message me: "+team[i]);
}
}catch (Exception e)
{
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Main Activity Class
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final String JSON_URL="http://soccer.sportsopendata.net/v1/leagues/premier-league/seasons/16-17/standings";
private Button buttonGet;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonGet = (Button) findViewById(R.id.buttonGet);
buttonGet.setOnClickListener(this);
listView = (ListView) findViewById(R.id.listView);
}
#Override
public void onClick(View v) {
sendRequest();
}
private void sendRequest() {
final StringRequest stringRequest = new StringRequest(JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String json){
ParseJSON pj = new ParseJSON(json);
pj.parseJSON();
CustomList cl = new CustomList(this, ParseJSON.position1,ParseJSON.team,ParseJSON.points);
listView.setAdapter(cl);
}
}
Custom Class for adding datas to list view
public class CustomList extends ArrayAdapter<String> {
private String[] position1;
private String[] team;
private String[] points;
private Activity context;
public CustomList(Activity context, String[] position1, String[] team, String[] points) {
super(context, R.layout.list_view_layout, position1);
this.context = context;
this.position1 = position1;
this.team = team;
this.points = points;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_view_layout, null, true);
TextView pos1 = (TextView) listViewItem.findViewById(R.id.position1);
TextView teamname = (TextView) listViewItem.findViewById(R.id.teamname);
TextView points1 = (TextView) listViewItem.findViewById(R.id.points);
pos1.setText("Position: "+position1[position]);
teamname.setText("Team: "+team[position]);
points1.setText("Points: "+points[position]);
return listViewItem;
}
}
Step 1 : Use Retroft + RxJava for Asynchronous API calls
Step 2 : Use Gson to Serialize and Deserialize.
Step 3 : Use json to POJO to have a Model Class
Simplify the code.
I am developing an app where on some page user need to select one option from given 4-5 options currently I'm using spinner for this functionality now the question is, if user selects 3rd or 4th option(only single option selection permitted) select how do i insert that particular option in mysql php database.following is the code I'm using right now..
//MainActivity.java
public class MainActivity_D extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
//Declaring an Spinner
private Spinner spinner2, spinner1;
private String str_spinner1, str_spinner2, s_name, s_course;
//An ArrayList for Spinner Items
private ArrayList<String> students1;
private ArrayList<String> students2;
Button mBtnSave;
//JSON Array
private JSONArray result1, result2, result;
//TextViews to display details
private TextView textViewName1;
private TextView textViewName2;
private TextView textViewCourse;
private TextView textViewSession;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity_d);
//Initializing the ArrayList
students1 = new ArrayList<String>();
students2 = new ArrayList<String>();
//Initializing Spinner
//Adding an Item Selected Listener to our Spinner
//As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
spinner1.setOnItemSelectedListener(this);
spinner2.setOnItemSelectedListener(this);
mBtnSave = (Button) findViewById(R.id.button2);
mBtnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitForm();
}
});
//Initializing TextViews
textViewName1 = (TextView) findViewById(R.id.textViewName1);
textViewName2 = (TextView) findViewById(R.id.textViewName2);
// textViewCourse = (TextView) findViewById(R.id.textViewCourse);
// textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
getData1();
getData2();
}
private void submitForm() {
// Submit your form here. your form is valid
//Toast.makeText(this, "Submitting form...", Toast.LENGTH_LONG).show();
// s_name = spinner1.getSelectedItem().toString();
// s_course = spinner2.getSelectedItem().toString();
Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new InsertActivity(this).execute(s_name, s_course);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (parent.getId()){
case R.id.spinner1:
spinner1.setSelection(position);
s_name = (String) spinner1.getSelectedItem();
// getData1();
// showToast("Spinner1: position=" + position);
break;
case R.id.spinner2:
spinner2.setSelection(position);
s_course = (String) spinner2.getSelectedItem();
// getData2();
break;
}
/*if(spinner1.getId()==R.id.spinner1) {
textViewName1.setText(getName(position));
}
else if(spinner2.getId()==R.id.spinner2)
{
textViewName2.setText(getCourse(position));
}
switch (parent.getId()){
case R.id.spinner1:
// getData1();
// showToast("Spinner1: position=" + position);
break;
case R.id.spinner2:
// getData2();
break;
}*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
/* private String getName(int position){
String name="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
name = json.getString(Config.TAG_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return name;
}
private String getCourse(int position){
String course="";
try {
JSONObject json = result.getJSONObject(position);
course = json.getString(Config.TAG_COURSE);
} catch (JSONException e) {
e.printStackTrace();
}
return course;
}*/
private void getData1() {
//Creating a string request
StringRequest stringRequest1 = new StringRequest(Config.DATA_URL1,
new Response.Listener<String>() {
#Override
public void onResponse(String response1) {
JSONObject j1 = null;
try {
//Parsing the fetched Json String to JSON Object
j1 = new JSONObject(response1);
//Storing the Array of JSON String to our JSON Array
result1 = j1.getJSONArray(Config.JSON_ARRAY1);
//Calling method getStudents to get the students from the JSON Array
getStudents1(result1);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error1) {
}
});
//Creating a request queue
RequestQueue requestQueue1 = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue1.add(stringRequest1);
}
private void getStudents1(JSONArray j1) {
//Traversing through all the items in the json array
for (int i = 0; i < j1.length(); i++) {
try {
//Getting json object
JSONObject json1 = j1.getJSONObject(i);
//Adding the name of the student to array list
students1.add(json1.getString(Config.TAG_COURSE));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner1.setAdapter(new ArrayAdapter<String>(MainActivity_D.this, android.R.layout.simple_spinner_dropdown_item, students1));
}
//Initializing TextViews
// textViewCourse = (TextView) findViewById(R.id.textViewCourse);
// textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
private void getData2() {
//Creating a string request
StringRequest stringRequest2 = new StringRequest(Config.DATA_URL2,
new Response.Listener<String>() {
#Override
public void onResponse(String response2) {
JSONObject j2 = null;
try {
//Parsing the fetched Json String to JSON Object
j2 = new JSONObject(response2);
//Storing the Array of JSON String to our JSON Array
result = j2.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents2(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error1) {
}
});
//Creating a request queue
RequestQueue requestQueue2 = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue2.add(stringRequest2);
}
private void getStudents2(JSONArray j2) {
//Traversing through all the items in the json array
for (int i = 0; i < j2.length(); i++) {
try {
//Getting json object
JSONObject json2 = j2.getJSONObject(i);
//Adding the name of the student to array list
students2.add(json2.getString(Config.TAG_USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner2.setAdapter(new ArrayAdapter<String>(MainActivity_D.this, android.R.layout.simple_spinner_dropdown_item, students2));
}
}
//InsertActivity.java
public class InsertActivity extends AsyncTask<String, Void, String> {
private Context context;
Boolean error, success;
public InsertActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String s_name = arg0[0];
// String userName = arg0[1];
String s_course = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?s_name=" + URLEncoder.encode(s_name, "UTF-8");
// data += "&username=" + URLEncoder.encode(userName, "UTF-8");
data += "&s_course=" + URLEncoder.encode(s_course, "UTF-8");
link = "http://insert_s1.php" + data;
// link = "http://example.com/mangoair10/tryrr.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
// return new String("Exception: " + e.getMessage());
// return null;
}
return null;
}
/* #Override
protected void onPostExecute(String result) {
String jsonStr = result;
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("success");
String message_result = jsonObj.getString("message");
if (query_result.equalsIgnoreCase("1")) {
Toast.makeText(context,message_result , Toast.LENGTH_LONG).show();
} else if (query_result.equalsIgnoreCase("-1")) {
Toast.makeText(context, message_result, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}*/
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
Log.e("TAG", String.valueOf(query_result));
// String message_result = jsonObj.getString("message");
/* if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Insert", Toast.LENGTH_LONG).show();
} else if(query_result.equals("FAILURE")){
Toast.makeText(context, "Unable to Insert", Toast.LENGTH_LONG).show();
}*/
} catch (JSONException e) {
e.printStackTrace();
}
}
}
//Config.java
public class Config {
//JSON URL
// public static final String DATA_URL = "http://example.com/jsonphp1.php";
public static final String DATA_URL1 = "http://example.com/jsonphp2.php";
public static final String DATA_URL2 = "http://example.com/jsonphp1.php";
//Tags used in the JSON String
public static final String TAG_USERNAME = "username";
public static final String TAG_NAME = "name";
public static final String TAG_COURSE = "course";
public static final String TAG_SESSION = "session";
//JSON array name
public static final String JSON_ARRAY = "result";
public static final String JSON_ARRAY1 = "result1";
public static final String JSON_ARRAY2 = "result2";
}
//this is my php file
<?php
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
$s_name=$_POST['s_name'];
$s_course=$_POST['s_course'];
Sid=$_GET['id'];
$query = "UPDATE `students` SET s_name = '$s_name', s_course= '$s_course' WHERE id='$id'";
$inserted = mysqli_query($con, $query);
// echo $inserted;
if($inserted) {
echo '{"query_result":"SUCCESS"}';
}
else{
echo '{"query_result":"FAILURE"}';
}
mysqli_close($con);
?>
The error is self explanatory. You are getting an Integer in your response which cannot be converted to a JSONObject. Log your response and check if it is a valid JSON.
In your asyntask onPostExecute method print response like this and post your response then error will be detected
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
Log.e("TAG",jsonStr );
}
Here,I already fetched data from mysql db and this data shows into the spinner Now the problem is, I want to save spinner selected item into mysql database with different table, the item which i select from spinner it should save to database, how can i do this? By using php mysql i insert record into spinner and i want to update the records of register table with spinner selected item.Can i update the register table with spinner selected item values? please suggest me.
java file
public class MainActivity_d3 extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
//Declaring an Spinner
private Spinner spinner2, spinner1;
private String str_spinner1, str_spinner2, s_name, s_course;
//An ArrayList for Spinner Items
private ArrayList<String> students1;
private ArrayList<String> students2;
Button mBtnSave;
//JSON Array
private JSONArray result1, result2, result;
//TextViews to display details
private TextView textViewName1;
private TextView textViewName2;
private TextView textViewCourse;
private TextView textViewSession;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity_d1);
//Initializing the ArrayList
students1 = new ArrayList<String>();
students2 = new ArrayList<String>();
//Initializing Spinner
//Adding an Item Selected Listener to our Spinner
//As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
spinner1.setOnItemSelectedListener(this);
spinner2.setOnItemSelectedListener(this);
mBtnSave = (Button) findViewById(R.id.button2);
mBtnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitForm();
}
});
//Initializing TextViews
textViewName1 = (TextView) findViewById(R.id.textViewName1);
textViewName2 = (TextView) findViewById(R.id.textViewName2);
// textViewCourse = (TextView) findViewById(R.id.textViewCourse);
// textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
getData1();
getData2();
}
private void submitForm() {
// Submit your form here. your form is valid
//Toast.makeText(this, "Submitting form...", Toast.LENGTH_LONG).show();
s_name = spinner1.getSelectedItem().toString();
s_course = spinner2.getSelectedItem().toString();
Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new InsertActivity(this).execute(s_name, s_course);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
/*if(spinner1.getId()==R.id.spinner1) {
textViewName1.setText(getName(position));
}
else if(spinner2.getId()==R.id.spinner2)
{
textViewName2.setText(getCourse(position));
}
/* switch (view.getId()){
case R.id.spinner1:
getData1();
break;
case R.id.spinner2:
getData2();
break;
}*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
/* private String getName(int position){
String name="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
name = json.getString(Config.TAG_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return name;
}
private String getCourse(int position){
String course="";
try {
JSONObject json = result.getJSONObject(position);
course = json.getString(Config.TAG_COURSE);
} catch (JSONException e) {
e.printStackTrace();
}
return course;
}*/
private void getData1() {
//Creating a string request
StringRequest stringRequest1 = new StringRequest(Config.DATA_URL1,
new Response.Listener<String>() {
#Override
public void onResponse(String response1) {
JSONObject j1 = null;
try {
//Parsing the fetched Json String to JSON Object
j1 = new JSONObject(response1);
//Storing the Array of JSON String to our JSON Array
result1 = j1.getJSONArray(Config.JSON_ARRAY1);
//Calling method getStudents to get the students from the JSON Array
getStudents1(result1);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error1) {
}
});
//Creating a request queue
RequestQueue requestQueue1 = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue1.add(stringRequest1);
}
private void getStudents1(JSONArray j1) {
//Traversing through all the items in the json array
for (int i = 0; i < j1.length(); i++) {
try {
//Getting json object
JSONObject json1 = j1.getJSONObject(i);
//Adding the name of the student to array list
students1.add(json1.getString(Config.TAG_COURSE));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner1.setAdapter(new ArrayAdapter<String>(MainActivity_d3.this, android.R.layout.simple_spinner_dropdown_item, students1));
}
//Initializing TextViews
// textViewCourse = (TextView) findViewById(R.id.textViewCourse);
// textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
private void getData2() {
//Creating a string request
StringRequest stringRequest2 = new StringRequest(Config.DATA_URL2,
new Response.Listener<String>() {
#Override
public void onResponse(String response2) {
JSONObject j2 = null;
try {
//Parsing the fetched Json String to JSON Object
j2 = new JSONObject(response2);
//Storing the Array of JSON String to our JSON Array
result = j2.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents2(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error1) {
}
});
//Creating a request queue
RequestQueue requestQueue2 = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue2.add(stringRequest2);
}
private void getStudents2(JSONArray j2) {
//Traversing through all the items in the json array
for (int i = 0; i < j2.length(); i++) {
try {
//Getting json object
JSONObject json2 = j2.getJSONObject(i);
//Adding the name of the student to array list
students2.add(json2.getString(Config.TAG_USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner2.setAdapter(new ArrayAdapter<String>(MainActivity_d3.this, android.R.layout.simple_spinner_dropdown_item, students2));
}
}
//InsertActivity
public class InsertActivity extends AsyncTask<String, Void, String> {
private Context context;
Boolean error, success;
public InsertActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String s_name = arg0[0];
// String userName = arg0[1];
String s_course = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?s_name=" + URLEncoder.encode(s_name, "UTF-8");
// data += "&username=" + URLEncoder.encode(userName, "UTF-8");
data += "&s_course=" + URLEncoder.encode(s_course, "UTF-8");
link = "http://mangoair.in/Spinner/insert_s1.php" + data;
// link = "http://hostogen.com/mangoair10/tryrr.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
// return new String("Exception: " + e.getMessage());
// return null;
}
return null;
}
/* #Override
protected void onPostExecute(String result) {
String jsonStr = result;
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("success");
String message_result = jsonObj.getString("message");
if (query_result.equalsIgnoreCase("1")) {
Toast.makeText(context,message_result , Toast.LENGTH_LONG).show();
} else if (query_result.equalsIgnoreCase("-1")) {
Toast.makeText(context, message_result, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}*/
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equalsIgnoreCase("SUCCESS")) {
Toast.makeText(context, "Data inserted successfully. Signup successfully.", Toast.LENGTH_LONG).show();
} else if (query_result.equalsIgnoreCase("FAILURE")) {
Toast.makeText(context, "Data could not be inserted, fill all records.", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Get the value from the spinner as a string and just pass this string like a normal string
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);
}
}