Related
I currently working with a project and stuck on the radio button which getting only the checked radio in xml, I search many case regarding with this concern and still got the same problem.
here is the activity which toasting only the checked radio in xml
package com.example.kapoyei.hatidtubiganapp;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.kapoyei.hatidtubiganapp.helper.Http;
import com.example.kapoyei.hatidtubiganapp.helper.Network;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
public class ClientActivity extends Activity implements View.OnClickListener {
public static String jsonObject;
SharedPreferences sharedPref;
Intent i;
Button btnLogout, btnBreakPoint;
Spinner spnStation;
ImageView btnReserve, btnStationList, btnPending, btnHistory;
TextView txtSelectDate;
EditText no_container;
RadioGroup radioGroup;
RadioButton radioButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnReserve = (ImageView) findViewById(R.id.btnReserve);
btnStationList = (ImageView) findViewById(R.id.btnStation);
btnPending = (ImageView) findViewById(R.id.btnPending);
btnHistory = (ImageView) findViewById(R.id.btnHistory);
btnPending.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
i = new Intent(ClientActivity.this, PendingClientOrderActivity.class);
startActivity(i);
}
});
btnStationList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
i = new Intent(ClientActivity.this, StationList.class);
startActivity(i);
}
});
btnReserve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(ClientActivity.this);
LayoutInflater inflater = getLayoutInflater();
view = inflater.inflate(R.layout.layout_dialog_reserve, null);
spnStation = (Spinner) view.findViewById(R.id.spnStation);
txtSelectDate = (TextView) view.findViewById(R.id.txtDate);
no_container = (EditText) view.findViewById(R.id.etContainer);
radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
radioButton = (RadioButton) view.findViewById(radioGroup.getCheckedRadioButtonId());
btnBreakPoint = (Button) view.findViewById(R.id.btnBreakPoint);
final Calendar c = Calendar.getInstance();
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, day);
String dateFormat = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat, Locale.US);
txtSelectDate.setText(sdf.format(c.getTime()));
}
};
txtSelectDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new DatePickerDialog(ClientActivity.this,
date,
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH)).show();
}
});
btnBreakPoint.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(no_container.getText().toString().isEmpty() || txtSelectDate.getText().toString().equalsIgnoreCase("-- CLICK TO DATE DELIVER --")) {
Toast.makeText(getApplicationContext(), "All fields require", Toast.LENGTH_SHORT).show();
} else {
/*Bundle bundle = new Bundle();
bundle.putString("station", spnStation.getSelectedItem().toString());
bundle.putString("date", txtSelectDate.getText().toString());
bundle.putString("no_container", no_container.getText().toString());
bundle.putString("type", Integer.toString(radioGroup.getCheckedRadioButtonId()));
i = new Intent(ClientActivity.this, CheckOut.class);
i.putExtras(bundle);
startActivity(i);*/
String typeOrder = radioButton.getText().toString();
Toast.makeText(getApplicationContext(), typeOrder, Toast.LENGTH_LONG).show();
}
}
});
Network network = new Network(getApplicationContext());
if(network.isNetwork()) {
new ClientActivity.GetStationList().execute();
} else {
Toast.makeText(getApplicationContext(), "Coud not get stations", Toast.LENGTH_SHORT).show();
}
builder.setView(view);
builder.setCancelable(true);
AlertDialog dialog = builder.create();
dialog.show();
}
});
btnHistory.setOnClickListener(this);
btnLogout.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if(view.getId() == R.id.btnLogout) {
finish();
sharedPref = getSharedPreferences("ht", MODE_PRIVATE);
SharedPreferences.Editor modify = sharedPref.edit();
modify.putBoolean("login", false);
modify.putString("id", "");
modify.putString("auth", "");
modify.apply();
i = new Intent(ClientActivity.this, LoginActivity.class);
startActivity(i);
}
if(view.getId() == R.id.btnHistory) {
i = new Intent(ClientActivity.this, HistoryActivity.class);
startActivity(i);
}
}
public class GetStationList extends AsyncTask<Void, Void, String> {
ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ClientActivity.this);
pd.setMessage("Getting station ...");
pd.setCancelable(false);
pd.show();
}
#Override
protected void onPostExecute(String result) {
pd.cancel();
json(result);
}
#Override
protected String doInBackground(Void... voids) {
String data = "";
jsonObject = "";
try {
String link = (String) Http.url + "?type=getstationlist";
URL getURL = new URL(link);
HttpURLConnection httpURLConnection = (HttpURLConnection) getURL.openConnection();
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
InputStream is = (InputStream) httpURLConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while((data = reader.readLine()) != null) {
jsonObject += data;
}
Log.i("", jsonObject);
return jsonObject;
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
public void json(String json) {
List<String> collectionName = new ArrayList<>();
if(json != null) {
try {
JSONObject jobj = new JSONObject(json);
JSONArray jarray = jobj.getJSONArray("stationlist");
String name = "";
String id = "";
for(int i = 0; i < jarray.length(); i++) {
JSONObject obj = jarray.getJSONObject(i);
name = obj.getString("name");
collectionName.add(name);
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(getBaseContext(), android.R.layout.simple_list_item_1, collectionName);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnStation.setAdapter(adapter);
} catch(Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Connection problem", Toast.LENGTH_SHORT).show();
}
}
}
}
and here is the xml where located the layout of my radio
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Station"
android:layout_margin="10dp"
android:textSize="20sp"/>
<Spinner
android:id="#+id/spnStation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Date"
android:layout_margin="10dp"
android:textSize="20sp"/>
<TextView
android:id="#+id/txtDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="-- CLICK TO DATE DELIVER --"
android:textSize="15sp"
android:layout_margin="10dp"
android:layout_gravity="center"
android:textAlignment="center"/>
<EditText
android:id="#+id/etContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="No. Of Containers"
android:layout_margin="10dp"/>
<RadioGroup
android:id="#+id/radioGroup"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioButton
android:id="#+id/Gallon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Gallon"
android:checked="true"/>
<RadioButton
android:id="#+id/Litre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Litre" />
</RadioGroup>
<Button
android:id="#+id/btnBreakPoint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_margin="10dp"
android:text="Proceed to Check Out" />
</LinearLayout>
</RelativeLayout>
You can apply the below codes:
int radioid = radioButtonGroup.getCheckedRadioButtonId();
View radio_button= radioButtonGroup.findViewById(radioButtonID);
int index = radioButtonGroup.indexOfChild(radioButton);
If the RadioGroup contains other Views (like a TextView) then the indexOfChild() method will return wrong index.
To get selected RadioButton Text on RadioGroup follow the below code:
RadioButton radio = (RadioButton) radioButtonGroup.getChildAt(index);
String text = radio.getText().toString();
Why this is happened? Because before you click Break Point button, you change the radio button id but not bind it to your variable, your variable still storing the old value. You need to add this code
radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
radioButton = (RadioButton) view.findViewById(radioGroup.getCheckedRadioButtonId());
above
String typeOrder = radioButton.getText().toString();
so it will shown
btnBreakPoint.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
...
radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
radioButton = (RadioButton) view.findViewById(radioGroup.getCheckedRadioButtonId());
String typeOrder = radioButton.getText().toString();
...
}
or you can move the scope of radioGroup assignment to onCreate scope
Hello i am new to android.i was creating a simple google cloud appengine app with endpoint.i was using using this tutorial https://github.com/GoogleCloudPlatform/gradle-appengine-templates/tree/master/HelloEndpoints .but the thing is i want to show the result in a textview not in a toast.
Layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/lay1">
<EditText
android:id="#+id/edt1"
android:layout_width="match_parent"
android:layout_height="100dp"
android:hint="Enter Number"
android:inputType="number"
android:textSize="24sp" />
<EditText
android:id="#+id/edt2"
android:layout_width="match_parent"
android:layout_height="100dp"
android:hint="Enter Number"
android:inputType="number"
android:textSize="24sp" />
<TextView
android:id="#+id/tv1"
android:layout_width="match_parent"
android:layout_height="100dp"
android:hint="Result Will be Here"
android:textSize="24sp" />
<Button
android:id="#+id/btnAdd"
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="Add" />
</LinearLayout>
GoogleAppEngActivity.java (main activity)
package com.ontech.googleappengine;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Pair;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class GoogleAppEngActivity extends AppCompatActivity {
Button btnAdd;
TextView tv1;
//String val1,val2;
EditText edt1,edt2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_app_eng);
edt1=(EditText)findViewById(R.id.edt1);
edt2=(EditText)findViewById(R.id.edt2);
tv1=(TextView)findViewById(R.id.tv1);
btnAdd =(Button)findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String temp = "";
temp = edt1.getText().toString();
temp += "+";
temp += edt2.getText().toString();
new EndpointsAsyncTask().execute(new Pair<Context, String>(GoogleAppEngActivity.this, temp));
// tv1.setText( new EndpointsAsyncTask().);
}
});
// new EndpointsAsyncTask().execute(new Pair<Context, String>(this, "Manfred"));
}
public TextView getTextView(){
TextView txtView=(TextView)findViewById(R.id.tv1);
return txtView;
}
}
EndpointsAsyncTask.java
package com.ontech.googleappengine;
//package com.ontech.googleappengine;
import android.content.Context;
import android.os.AsyncTask;
import android.text.Layout;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import com.ontech.myapplication.backend.myApi.MyApi;
import java.io.IOException;
/**
* Created by on 05-11-2015.
*/
public class EndpointsAsyncTask extends AsyncTask<Pair<Context, String>, Void, String> {
private static MyApi myApiService = null;
private Context context;
#Override
protected String doInBackground(Pair<Context, String>... params) {
if (myApiService == null) { // Only do this once
/* MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});*/
MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
.setRootUrl("https://leafy-display-112017.appspot.com/_ah/api/");
// end options for devappserver
myApiService = builder.build();
}
context = params[0].first;
String name = params[0].second;
try {
return myApiService.sayHi(name).execute().getData();
} catch (IOException e) {
return e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
}
My endpoint.java
package com.ontech.myapplication.backend;
import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiNamespace;
import javax.inject.Named;
/**
* An endpoint class we are exposing
*/
#Api(
name = "myApi",
version = "v1",
namespace = #ApiNamespace(
ownerDomain = "backend.myapplication.ontech.com",
ownerName = "backend.myapplication.ontech.com",
packagePath = ""
)
)
public class MyEndpoint {
/**
* A simple endpoint method that takes a name and says Hi back
*/
#ApiMethod(name = "sayHi")
public MyBean sayHi(#Named("name") String name) {
MyBean response = new MyBean();
String val1, val2;
val1 = name.substring(0, name.indexOf("+"));
val2 = name.substring(name.indexOf("+") + 1);
int res = Integer.parseInt(val1) + Integer.parseInt(val2);
// response.setData("Hi, " + name);
response.setData(Integer.toString(res));
return response;
}
}
MyBean.java
package com.ontech.myapplication.backend;
/**
* The object model for the data we are sending through endpoints
*/
public class MyBean {
private String myData;
public String getData() {
return myData;
}
public void setData(String data) {
myData = data;
}
}
Pass TextView as parameter to Constructor of EndpointsAsyncTask in which you want to show result as done below.
public class EndpointsAsyncTask extends AsyncTask<Pair<Context, String>, Void, String> {
private static MyApi myApiService = null;
private Context context;
private TextView textView
public EndpointsAsyncTask(Context context,TextView mtextView) {
// TODO Auto-generated constructor stub
this.context=context;
this.textView=mtextView;
}
#Override
protected String doInBackground(Pair<Context, String>... params) {
if (myApiService == null) { // Only do this once
/* MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});*/
MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
.setRootUrl("https://leafy-display-112017.appspot.com/_ah/api/");
// end options for devappserver
myApiService = builder.build();
}
context = params[0].first;
String name = params[0].second;
try {
return myApiService.sayHi(name).execute().getData();
} catch (IOException e) {
return e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
textView.setText(result);
}
}
call AsyncTask from you Activity or Fragment
new EndpointsAsyncTask(context,yourTextView).execute(yourParams);
In EndpointsAsyncTask.java replace
#Override
protected void onPostExecute(String result) {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
With
#Override
protected void onPostExecute(String result) {
GoogleAppEngActivity.getTextView().setText(result);
}
change to:new EndpointsAsyncTask(tv1) in GoogleAppEngActivity class
and add next code to EndpointsAsyncTask class
TextView view;
public EndpointsAsyncTask(TextView tv) {
view = tv;
}
and replace Toast.makeText(context, result, Toast.LENGTH_LONG).show();
to view.setText(result);
I'll suggest making EndpointsAsyncTask an inner class of your activity. Get a reference to textView in postExecute and update it there. Something like this
Ideally, the UI elements belonging to an activity should be changed in the activity itself, and no where else. Try following the presentation pattern.
A small example:
1. Create an interface - ActivityPresenter with methods signifying events with parameters as the input data required for the views to change. An example would be:
void onServerResponse(ServerResponse resp);
Make the activity implement this interface. That is, you define what UI changes to make in the activity when the server response arrives.
When you call a service / asynctask from the activity to do some task asynchronously for you, send the activity presenter reference. Call the presenter.onServerResponse(response) from your service / asynctask.
For this purpose you can use callback interface:
Create a public interface:
public interface AsyncTaskResponse {
void asyncTaskFinish(String output);
}
Now override the method of callback interface and define the action need to do i.e set the TextView value. After that pass it to async task class:
package com.ontech.googleappengine;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Pair;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class GoogleAppEngActivity extends AppCompatActivity {
Button btnAdd;
final TextView tv1;
//String val1,val2;
EditText edt1,edt2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_app_eng);
edt1=(EditText)findViewById(R.id.edt1);
edt2=(EditText)findViewById(R.id.edt2);
tv1=(TextView)findViewById(R.id.tv1);
btnAdd =(Button)findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String temp = "";
temp = edt1.getText().toString();
temp += "+";
temp += edt2.getText().toString();
new EndpointsAsyncTask(new AsyncTaskResponse() {
#Override
public void asyncTaskFinish(String response) {
tv1.setText(response);
}
};).execute(new Pair<Context, String>(GoogleAppEngActivity.this, temp));
// tv1.setText( new EndpointsAsyncTask().);
}
});
// new EndpointsAsyncTask(new AsyncTaskResponse().execute(new Pair<Context, String>(this, "Manfred"));
}
public TextView getTextView(){
TextView txtView=(TextView)findViewById(R.id.tv1);
return txtView;
}
}
Now in async task class call the Callback interface method and pass response String to set edit text value:
package com.ontech.googleappengine;
//package com.ontech.googleappengine;
import android.content.Context;
import android.os.AsyncTask;
import android.text.Layout;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import com.ontech.myapplication.backend.myApi.MyApi;
import java.io.IOException;
/**
* Created by on 05-11-2015.
*/
public class EndpointsAsyncTask extends AsyncTask<Pair<Context, String>, Void, String> {
private static MyApi myApiService = null;
private Context context;
private AsyncTaskResponse asyncCallback;
public EndpointsAsyncTask(AsyncTaskResponse asyncTaskResponse){
asyncCallback = asyncTaskResponse;
}
#Override
protected String doInBackground(Pair<Context, String>... params) {
if (myApiService == null) { // Only do this once
/* MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});*/
MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
.setRootUrl("https://leafy-display-112017.appspot.com/_ah/api/");
// end options for devappserver
myApiService = builder.build();
}
context = params[0].first;
String name = params[0].second;
try {
return myApiService.sayHi(name).execute().getData();
} catch (IOException e) {
return e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
//Toast.makeText(context, result, Toast.LENGTH_LONG).show();
asyncCallback.asyncTaskFinish(result); // call the method of callback interface
}
}
I have 2 spinners in my application. I have loaded all the items got from json response. But now I want to implement connection between these 2 Spinners. When select an item in spinner 1 then spinner 2 should load the content according to the spinner 1 selection.
This is what happens now,
Spinner 1 loads
1, 2, 3, 4
Spinner 2 loads
1.1, 1.2, 2.1, 2.2, 3.1, 4.1, 4.2
But what I want to happen is,
1st stage
Spinner 1 loads
1, 2, 3, 4
Spinner 2 loads
Nothing
2nd stage
user selecting number 1 in spinner 1 then spinner 2 should load only 1.1, 1.2.
Current Code
#Override
public void onTaskCompleted(JSONArray responseJson) {
try {
List<String> crust = new ArrayList<String>();
List<String> description = new ArrayList<String>();
List<String> extraDescription = new ArrayList<String>();
for (int i = 0; i < responseJson.length(); ++i) {
JSONObject object = responseJson.getJSONObject(i);
if ((object.getString("MainCategoryID")).equals("1")
&& (object.getString("SubCategoryID")).equals("1")) {
JSONArray subMenuArray = object
.getJSONArray("SubMenuEntity");
for (int j = 0; j < subMenuArray.length(); ++j) {
JSONObject subMenuObject = subMenuArray
.getJSONObject(j);
Log.i("Crust", subMenuObject.getString("Crust"));
crust.add(subMenuObject.getString("Crust"));
Log.i("Description",
subMenuObject.getString("Description"));
description.add(subMenuObject.getString("Description"));
}
}
crustSP = (Spinner) findViewById(R.id.sp_crust);
ArrayAdapter<String> dataAdapterCru = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, crust);
dataAdapterCru
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
crustSP.setAdapter(dataAdapterCru);
sizeSP = (Spinner) findViewById(R.id.sp_pizza_size);
ArrayAdapter<String> dataAdapterDes = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, description);
dataAdapterDes
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sizeSP.setAdapter(dataAdapterDes);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
what should I do to achieve this? Any help will be appreciated.
Latest code
ArrayAdapter<String> dataAdapterCru = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, crust);
crust = Utils.removeDuplicatesFromList(crust);
dataAdapterCru
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
crustSP.setAdapter(dataAdapterCru);
crustSP.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onNothingSelected(AdapterView<?> arg0) {
}
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
String crustSelectedItem = crustSP.getSelectedItem()
.toString();
getFilteredDescriptions(crustSelectedItem, description);
}
});
then sending selected crust value
List<String> getFilteredDescriptions(String crustSelectedItem,
List<String> description) {
List<String> resultDescription = new ArrayList<String>();
crustSelectedItem = crustSP.getSelectedItem().toString();
if (description == null || description.isEmpty())
return resultDescription;
for (int i = 0; i < description.size(); i++) {
description = Utils.removeDuplicatesFromList(description);
if (!description.get(i).contains(crustSelectedItem))
continue;
resultDescription.add(description.get(i));
}
return resultDescription;
}
Now resultDescription has selected crust, respective description values.
this is the place I'm receiving the resultDescription
sizeSP.setOnItemSelectedListener(new MyOnItemSelectedListener());
ArrayAdapter<String> dataAdapterDes = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item,
resultDescription); //resultDescription cannot be resolved to a variable
dataAdapterDes
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sizeSP.setAdapter(dataAdapterDes);
sizeSP.setAdapter(new NothingSelectedSpinnerAdapter(
dataAdapterDes,
R.layout.contact_spinner_row_nothing_selected, this));
To make the relationship between two spinners ;), follow below steps
1) Have the data in the two lists respectively for Spinner1 and Spinner2.
2) Load first list data into Spinner1.
3) Apply onItemSelectedListener listener on Spinner.
4) When user selects item your onItemSelected listener
would be called. you will get the selected position and selected item.
5) Have a method which can filter out data from list2 based on selected item you got in point 4)
6) Set list data which you got in point 4 to Spinner2.
And you have made the relationship.
Edit for point 5 I have written below method. pass selected Crust/Value in this method and this will return you Size/Description list for your Spinner2.
List<String> getFilteredDescriptions(String crust,List<String> descs){
List<String> result = new ArrayList<String>();
if(descs == null || descs.isEmpty())
return result;
for (int i = 0; i < descs.size(); i++) {
if(!descs.get(i).contains(crust)) //ignore all descriptions which doesnt have same Crust
continue;
result.add(descs.get(i)); // Change
}
return result;
}
Here is the example
I have to Spinner , one is for to select the department another one is select the executive engineer, when particular department will selected then their associated executive engineers name will be filled on second spinner.
case_list_selection.xml layout
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff"
android:orientation="vertical"
android:weightSum="4" >
<LinearLayout
android:id="#+id/llDept"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_margin="10dp"
android:layout_weight="1"
android:background="#fff"
android:orientation="horizontal"
android:weightSum="2" >
<TextView
android:id="#+id/tvDept"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:text="Department :"
android:textColor="#000"
android:textSize="20sp" />
<Spinner
android:id="#+id/spinnerDept"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/tvDept"
android:layout_weight="1"
android:prompt="#string/dept_prompt"
android:layout_gravity="center_vertical"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/llEE"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_below="#+id/llDept"
android:layout_margin="10dp"
android:layout_weight="1"
android:background="#fff"
android:orientation="horizontal"
android:weightSum="2" >
<TextView
android:id="#+id/tvExecutiveEngineer"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_below="#+id/tvDept"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:text="Executive Engineer :"
android:textColor="#000"
android:textSize="20sp" />
<Spinner
android:id="#+id/spinnerExecutiveEngineer"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_below="#+id/tvDept"
android:layout_toRightOf="#+id/tvExecutiveEngineer"
android:layout_weight="1"
android:prompt="#string/exec_prompt"
android:layout_gravity="center_vertical"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/llFromDate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="2"
android:layout_margin="10dp"
>
<Button
android:id="#+id/btnFromDate"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text=" From Date "
android:textColor="#000000"
android:textSize="17sp"
android:background="#drawable/bg"
android:textStyle="bold"
/>
<EditText
android:id="#+id/txtFromDate"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint=" From Date "
android:textColor="#000000"
android:textSize="17sp"
android:gravity="center"
android:enabled="false"
android:focusable="false"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/llToDate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:weightSum="2"
android:layout_margin="10dp"
>
<Button
android:id="#+id/btnToDate"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text=" To Date "
android:textColor="#000000"
android:textSize="17sp"
android:background="#drawable/bg"
android:textStyle="bold"
/>
<EditText
android:id="#+id/txtToDate"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/btnToDate"
android:layout_weight="1"
android:hint=" To Date "
android:textColor="#000000"
android:textSize="17sp"
android:gravity="center"
android:enabled="false"
android:focusable="false"
/>
</LinearLayout>
<RelativeLayout
android:id="#+id/llBtn"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_margin="10dp"
android:layout_weight="2"
android:background="#fff"
>
<Button
android:id="#+id/btnSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00728f"
android:drawableRight="#drawable/search"
android:layout_centerInParent="true"
android:padding="5dp"
android:text=" Search "
android:textColor="#FFF"
android:textSize="18sp" />
</RelativeLayout>
</LinearLayout>
CaseListSelection.java class
package com.smartcity;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.city.data.ExceutiveNamesCollection;
import com.city.webservices.Department_Webservice;
import com.city.webservices.GetExecutive_Webservices;
import com.smartcity.R;
public class CaseListSelection extends Activity{
Context context;
Spinner spinnerDept,spinnerExecutiveEngineer;
ArrayList<ExceutiveNamesCollection> listEE,listExcecutiveNames;
String executiveNames[];
ArrayAdapter<String> dataAdapter;
String selectedDept, selectedEE,selectedDeptId,selectedEEId;
Button btnSearch;
SimpleDateFormat fmtDateAndTime =new SimpleDateFormat("yyyy-MM-dd");
EditText txtFromDate,txtToDate;
Calendar myCalendar;
String fromdate,todate;
public static int posDept,posEE;
int pos;
public String TAG ="CaseListSelection";
#Override
protected void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.case_list_selection);
context=this;
spinnerDept = (Spinner) findViewById(R.id.spinnerDept);
new Department_Webservice(context,dataAdapter,spinnerDept).execute();
btnSearch = (Button) findViewById(R.id.btnSearch);
spinnerExecutiveEngineer = (Spinner) findViewById(R.id.spinnerExecutiveEngineer);
spinnerDept.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onNothingSelected(AdapterView<?> arg0) { }
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
selectedDept = spinnerDept.getSelectedItem().toString();
selectedDeptId = Department_Webservice.deptId[position];
//Toast.makeText(context, "Selected selectedDeptId : "+selectedDeptId, 2).show();
posDept = position;
new GetExecutive_Webservices(context,selectedDeptId,dataAdapter,spinnerExecutiveEngineer).execute();
}
});
spinnerExecutiveEngineer.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onNothingSelected(AdapterView<?> arg0) { }
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
selectedEE = spinnerExecutiveEngineer.getSelectedItem().toString();
selectedEEId = GetExecutive_Webservices.exceutiveIds[position];
//Toast.makeText(context, "Selected EE : "+selectedEE, 2).show();
pos = position;
posEE = position;
}
});
Log.v("selectedDeptId", "<<<<<<<<<<<"+selectedDeptId);
btnSearch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
fromdate = txtFromDate.getText().toString();
todate = txtToDate.getText().toString();
Log.v(TAG, "selectedDeptId="+selectedDeptId);
Log.v(TAG, "selectedEEId="+selectedEEId);
Log.v(TAG, "fromdate="+fromdate);
Log.v(TAG, "todate="+todate);
Intent i = new Intent(context, CaseList.class);
i.putExtra("DeptId", selectedDeptId);
i.putExtra("Executive_Id", selectedEEId);
i.putExtra("position", pos);
// i.putExtra("Dept", selectedDept);
// i.putExtra("EE", selectedEE);
i.putExtra("FromDate", fromdate);
i.putExtra("ToDate", todate);
startActivity(i);
}
});
myCalendar = Calendar.getInstance();
txtFromDate = (EditText) findViewById(R.id.txtFromDate);
txtToDate = (EditText)findViewById(R.id.txtToDate);
Button btnFromDate = (Button) findViewById(R.id.btnFromDate);
btnFromDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new DatePickerDialog(context, d, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
Button btnToDate = (Button) findViewById(R.id.btnToDate);
btnToDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new DatePickerDialog(context, todateListener, myCalendar
.get(Calendar.YEAR), myCalendar
.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
}catch(Exception e)
{
e.printStackTrace();
}
}
DatePickerDialog.OnDateSetListener d = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateFromDate();
}
};
DatePickerDialog.OnDateSetListener todateListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateToDate();
}
};
private void updateFromDate() {
txtFromDate.setText(fmtDateAndTime.format(myCalendar.getTime()));
}
private void updateToDate() {
txtToDate.setText(fmtDateAndTime.format(myCalendar.getTime()));
if (txtFromDate.getText().toString()!=null || txtToDate.getText().toString()!=null)
{
try {
fromdate = txtFromDate.getText().toString();
todate = txtToDate.getText().toString();
Date dateFrom = fmtDateAndTime.parse(fromdate);
Date dateTo = fmtDateAndTime.parse(todate);
if (dateTo.before(dateFrom))
{
Toast.makeText(context, "To Date should be greater than From date!", 2).show();
txtToDate.setText("Invalid date");
}
else
{
txtToDate.setText(fmtDateAndTime.format(myCalendar.getTime()));
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
Toast.makeText(context, "Please select the valid date!", 2).show();
}
}
}
Department_Webservice.java asynk class to fill department list
package com.city.webservices;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import com.city.data.DeptBean;
import com.city.data.HttpUrl;
import com.smartcity.CityApplication;
public class Department_Webservice extends AsyncTask<Void, Void, Void>
{
Context contxt;
InputStream is;
ProgressDialog pDialog;
DeptBean beanlist;
ArrayList<DeptBean>listDept;
public String TAG = "Department_Webservice";
HttpResponse response;
String str = "";
ArrayAdapter<String> dataAdapter;
public static String deptNames[],deptId[];
Spinner spinnerDept;
public Department_Webservice(Context ctx,ArrayAdapter<String> dataAdapter,Spinner spinnerDept) {
this.contxt = ctx;
this.dataAdapter = dataAdapter;
this.spinnerDept = spinnerDept;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(contxt);
pDialog.setIndeterminate(false);
pDialog.setMessage("Please Wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try
{
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost(HttpUrl.get_department);
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
try {
if(response.toString()!=null){
JSONArray jarray = new JSONArray(str);
listDept = new ArrayList<DeptBean>();
for(int i = 0; i<jarray.length();i++)
{
JSONObject jobj = jarray.getJSONObject(i);
beanlist = new DeptBean();
beanlist.setDeptId(jobj.getString("jobid"));
beanlist.setDeptName(jobj.getString("role"));
listDept.add(beanlist);
}
Log.v(TAG, "listDept size>>>>>>>>>> " + listDept.size());
}
} catch (Exception e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
if(response.toString()!=null)
{
CityApplication.setDeptBeanlist(listDept);
deptNames = new String[listDept.size()];
deptId = new String[listDept.size()];
for (int i=0; i<listDept.size(); i++)
{
deptNames[i] = listDept.get(i).getDeptName();
deptId[i] = listDept.get(i).getDeptId();
}
dataAdapter = new ArrayAdapter<String>(contxt,
android.R.layout.simple_spinner_item, deptNames);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerDept.setAdapter(dataAdapter);
}
else
{
new AlertDialog.Builder(contxt).setTitle("Message").setMessage("Server is not responding." ).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
}
}
}
GetExecutive_Webservices.java asynk class to fill the associated list of executive names
package com.city.webservices;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import com.city.data.ExecutiveBean;
import com.city.data.HttpUrl;
public class GetExecutive_Webservices extends AsyncTask<Void, Void, Void> {
Context contxt;
InputStream is;
ProgressDialog pDialog;
String deptId;
public static ArrayList<ExecutiveBean> alist;
public String TAG = "GetExecutive_Webservices";
ArrayAdapter<String> dataAdapter;
Spinner spinnerExecutive;
public static String exceutiveNames[],exceutiveIds[];
String str = "";
HttpResponse response;
public GetExecutive_Webservices(Context ctx, String deptId,
ArrayAdapter<String> dataAdapter, Spinner spinnerExecutive) {
this.contxt = ctx;
this.deptId = deptId;
this.dataAdapter = dataAdapter;
this.spinnerExecutive = spinnerExecutive;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(contxt);
pDialog.setIndeterminate(false);
pDialog.setMessage("Please Wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("department_id", deptId));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(HttpUrl.get_executive);
httpPost.setEntity(new UrlEncodedFormEntity(params1));
Log.v(TAG, "params1" + params1);
response = httpClient.execute(httpPost);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
Log.v(TAG, "str>>>>>>>>>>>>>>>" + str);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (response.toString() != null) {
alist = new ArrayList<ExecutiveBean>();
JSONArray jaray = new JSONArray(str);
for (int i = 0; i < jaray.length(); i++) {
JSONObject jobj = jaray.getJSONObject(i);
ExecutiveBean bean = new ExecutiveBean();
bean.setExecutiveId(jobj.getString("id"));
bean.setExecutiveName(jobj.getString("username"));
alist.add(bean);
Log.v(TAG, "Username>>>>>>>>>>" + jobj.getString("username"));
}
Log.v(TAG, "executive list size>>>>>>>>>>" + alist.size());
}
} catch (Exception e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
try {
pDialog.dismiss();
if (response.toString() != null) {
exceutiveNames = new String[alist.size()];
exceutiveIds = new String[alist.size()];
for (int i=0; i<alist.size(); i++)
{
exceutiveNames[i] = alist.get(i).getExecutiveName();
exceutiveIds[i] = alist.get(i).getExecutiveId();
}
dataAdapter = new ArrayAdapter<String>(contxt,
android.R.layout.simple_spinner_item, exceutiveNames);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerExecutive.setAdapter(dataAdapter);
} else {
new AlertDialog.Builder(contxt)
.setTitle("Message")
.setMessage("Server is not responding.")
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
}).create().show();
}
} catch (Exception e) {
Log.e("JSON Parser", "onPostExecute" + e.toString());
}
}
}
Here is HttpUrl.get_department & HttpUrl.get_executive is the url of the method of webservices
DeptBean & ExecutiveBean is the Getter Setter
Hope this post will help you
I have made an activity in that one ListView is ther,In that ListView each listItem is having an editText named "qty",which can be edited,one textView is there which displays "price",I need is when i edit the edittext and if the entered value is more than some limi the textView value will change,After that i have to pass them as a parameter to an api as below:
http://yehki.epagestore.in/app_api/updateCart.php?customer_id=41&product_id=30&quantity=90&product_id=23&quantity=90
from that i will get subtotal's of eact item and have to set them to each item in the list,can anyone please help me for it?My code is as below..Please help me save my life...thank you
main.java
package com.epe.yehki.ui;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.epe.yehki.adapter.CartAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.example.yehki.R;
public class CartListActivity extends Activity {
private ProgressDialog pDialog;
Intent in = null;
ListView lv;
JSONObject jsonObj;
ArrayList<HashMap<String, String>> cartList;
Bitmap bitmap;;
private CartAdapter cartContent;
JSONArray carts = null;
ImageView back;
TextView tv_place_order, tv_home;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_cart_list);
lv = (ListView) findViewById(R.id.cart_list);
back = (ImageView) findViewById(R.id.iv_bak);
tv_place_order = (TextView) findViewById(R.id.tv_place_order);
tv_home = (TextView) findViewById(R.id.tv_home);
cartList = new ArrayList<HashMap<String, String>>();
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
// execute the cartList api()...........!!!!
new GetCartList().execute();
// listView ClickEvent
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
lv.removeViewAt(position);
cartContent.notifyDataSetChanged();
}
});
tv_home.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
in = new Intent(CartListActivity.this, HomeActivity.class);
startActivity(in);
}
});
tv_place_order.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
/*
* CART LIST PRODUCT LIST...............!!!!!!!!!
*/
private class GetCartList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CartListActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
String cartUrl = Const.API_CART_LIST + "?customer_id=" + Pref.getValue(CartListActivity.this, Const.PREF_CUSTOMER_ID, "");
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(cartUrl, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
if (jsonObj.has(Const.TAG_PRO_LIST)) {
carts = jsonObj.getJSONArray(Const.TAG_PRO_LIST);
if (carts != null && carts.length() != 0) {
// looping through All Contacts
for (int i = 0; i < carts.length(); i++) {
JSONObject c = carts.getJSONObject(i);
String proId = c.getString(Const.TAG_PRODUCT_ID);
String proName = c.getString(Const.TAG_PRODUCT_NAME);
String wPrice = c.getString(Const.TAG_WHOLESALE_PRICE);
String rPrice = c.getString(Const.TAG_RETAIL_PRICE);
String qty = c.getString(Const.TAG_QUANTITY);
String proimg = Const.API_HOST + "/" + c.getString(Const.TAG_PRODUCT_IMG);
HashMap<String, String> cartProduct = new HashMap<String, String>();
cartProduct.put(Const.TAG_PRODUCT_ID, proId);
cartProduct.put(Const.TAG_PRODUCT_NAME, proName);
cartProduct.put(Const.TAG_PRODUCT_IMG, proimg);
cartProduct.put(Const.TAG_WHOLESALE_PRICE, wPrice);
cartProduct.put(Const.TAG_RETAIL_PRICE, rPrice);
cartProduct.put(Const.TAG_QUANTITY, qty);
cartList.add(cartProduct);
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
*
* */
cartContent = new CartAdapter(CartListActivity.this, cartList);
lv.setAdapter(cartContent);
}
}
}
In ListAdapter, getItem() should return an item using which you populate the Views
#Override
public HashMap<String, String> getItem(int paramInt) {
return cartArray.get(paramInt);
}
To get all values,
final CartAdapter adapter = (CardAdapter) lv.getAdapter();
for (int i = 0; i < adapter.getCount(); i++) {
final HashMap<String, String> item = adapter.getItem(i);
final String quantity = item.get(Const.TAG_QUANTITY); // value of EditText of one row
}
I have written a code to get all the videos related to a specific user in YouTube as follows:
import java.util.ArrayList;
import java.util.Collection;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import com.example.tstnetconnwithjson.tables.custome;
import com.example.tstnetconnwithjson.tables.videos;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
Button search; ;
TextView name ;
ListView listview ;
ArrayList<videos > videolist;
ArrayAdapter< videos > adapter ;
AlertDialog.Builder alert ;
ProgressDialog progressdialog ;
EditText name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videolist = new ArrayList<videos>();
adapter = new ArrayAdapter<videos>(this, android.R.layout.simple_list_item_1 , android.R.id.text1,videolist);
name=(EditText) findViewById(R.id.editText1);
alert = new Builder(this);
alert.setTitle("Warnning" ) ;
alert.setMessage("You want to connect to the internet ..? " );
alert.setNegativeButton("No ", null);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
String username=name.getText().toString();
new connection().execute("https://gdata.youtube.com/feeds/api/videos?author="+username+"&v=2&alt=jsonc");
}
});
progressdialog = new ProgressDialog(this);
progressdialog.setMessage("Wait Loading .... ");
progressdialog.setCancelable(false);
search = (Button) findViewById(R.id.button1);
name = (TextView) findViewById(R.id.textView1);
listview = (ListView) findViewById(R.id.listView1);
listview.setAdapter(adapter);
search.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
alert.show();
}
});
}
class connection extends AsyncTask<String, Integer, String>{
#Override
protected void onPreExecute() {
progressdialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
String s = GetUrlBody(arg0[0]);
return s;
}
#Override
protected void onPostExecute(String result) {
try{
JSONObject jo =(JSONObject) new JSONTokener(result).nextValue();
JSONObject feed = jo.optJSONObject("data");
JSONArray entry = feed.optJSONArray("items");
for(int i = 0 ; i<entry.length() ; i++){
String title = entry.getJSONObject(i).getString("title");
String thumbURL = entry.getJSONObject(i).getJSONObject("thumbnail").getString("sqDefault");
Log.d("after get image", "ok")
String url;
try {
url = entry.getJSONObject(i).getJSONObject("player").getString("mobile");
} catch (JSONException ignore) {
url = entry.getJSONObject(i).getJSONObject("player").getString("default");
}
String description = entry.getJSONObject(i).getString("description");
Log.d("after get description", "ok");
videos videoobject=new videos();
videoobject.setDecscrption(description);
videoobject.setImageurl(thumbURL);
videoobject.setVediourl(url);
videoobject.setVideoname(title);
videolist.add(videoobject);
}
listview.setAdapter(new custome(MainActivity.this,videolist));
Log.d("AFTER set custome ", "before notify changes");
adapter.notifyDataSetChanged();
}catch(Exception exception) {
Log.d("exception ", "nock nock nock....");
Log.e("json ", exception.getMessage());
}
progressdialog.dismiss();
super.onPostExecute(result);
}
String GetUrlBody (String Url ){
HttpClient client = new DefaultHttpClient();
HttpGet gethttp = new HttpGet(Url);
try{
HttpResponse response = client.execute(gethttp);
if(response.getStatusLine().getStatusCode() == 200){
String save =
EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
return save;
}else {
return "Not Found";
}
}catch(Exception exception){}
return null;
}
}
}
Where the custome class is extends from base adapter in order to have list view with image view set to video image and text view set to video title.
In log cat messages the result are existed but my list view returns empty.
Can any one tell me why?
here is the code for costume list view:
public class custome extends BaseAdapter {
ArrayList<videos> data=new ArrayList<videos>();
android.content.Context context1;
android.widget.TextView name;
ImageView picture;
public custome(Context context,ArrayList<videos>arrayList) {
// TODO Auto-generated constructor stub
context=context;
arrayList=data;
}
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return data.get(arg0);
}
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
public View getView(int arg0, View arg1, ViewGroup arg2) {
View view=arg1;
if(view==null)
{
LayoutInflater layoutInflater=(LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view=layoutInflater.inflate(R.layout.listvideo,null);
}
name=(TextView) view.findViewById(R.id.textView1);
picture=(ImageView) view.findViewById(R.id.imageView1);
videos video = data.get(arg0);
name.setText(video.getVideoname());
URL url = null;
try {
url = new URL(video.getImageurl());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
picture.setImageBitmap(bitmap);
return view;
}
}
The problem is in your assigning code of custome constructor:
Use this constructor:
public custome(Context context,ArrayList<videos> arrayList) {
context=context;
//arrayList=data;<<< WRONG
data=arrayList;//<<<<<<< Correct way of assigning
}
You are overriding your adapter here:
listview.setAdapter(new custome(MainActivity.this,videolist));
Remove this line