Im able to populate spinner but cant access it - android

public void editarEstadoSala(final Sala sala) {
ArrayAdapter<Pelicula> adapter;
CambiarDatosSalaWorker cambiarDatosSalaWorker = new CambiarDatosSalaWorker(this);
cambiarDatosSalaWorker.execute();
List<Pelicula> listaPelicula=cambiarDatosSalaWorker.getLista();
LinearLayout layout = new LinearLayout(PortalAdmin.this);
layout.setOrientation(LinearLayout.VERTICAL);
//////
final AlertDialog.Builder builder = new AlertDialog.Builder(PortalAdmin.this);
builder.setTitle("Rellena los datos");
final EditText butacas = new EditText(PortalAdmin.this);
final EditText precio = new EditText(PortalAdmin.this);
final TextView pelicula = new TextView(PortalAdmin.this);
final Spinner spinner = new Spinner(PortalAdmin.this);
pelicula.setText("Pelicula seleccionada");
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
butacas.setInputType(InputType.TYPE_CLASS_NUMBER);
butacas.setHint("Numero butacas libres");
precio.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
precio.setHint("Precio entrada");
spinner.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
adapter = new ArrayAdapter<Pelicula>(PortalAdmin.this, android.R.layout.simple_spinner_item , listaPelicula);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
String item = (String) parent.getItemAtPosition(position);
pelicula.setText(item);
} // to close the onItemSelected
public void onNothingSelected(AdapterView<?> parent)
{
Toast toast = Toast.makeText(PortalAdmin.this,
"nada",
Toast.LENGTH_SHORT);
toast.show();
}
});
layout.addView(butacas);
layout.addView(precio);
layout.addView(pelicula);
layout.addView(spinner);
builder.setView(layout);
// Set up the buttons
builder.setPositiveButton("Subir", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
I just cant make any progress here, the spinner is populated (List, comes from another class) but i cant do nothing with that data, Log.e doesnt show nothing so my code doesnt reach the spinner.setOnItemSelectedListener.
Sorry for my english guys, im learning code and english and im pretty bad at both.

Ok, the problem was here
CambiarDatosSalaWorker cambiarDatosSalaWorker = new CambiarDatosSalaWorker(this);
cambiarDatosSalaWorker.execute();
List<Pelicula> listaPelicula=cambiarDatosSalaWorker.getLista();
I was using my class "CambiarDatosSalaWorker" wrong and the code there was wrong too haha
Here is the class now,
public class CambiarDatosSalaWorker extends AsyncTask<Void, Void, List<Pelicula>> {
#Override
protected List<Pelicula> doInBackground(Void... params) {
String result = "";
String line = "";
List<Pelicula> lista = new ArrayList<>();
String datosPelicula = "here is the url where I get the info about the movies in my database";
try {
URL url = new URL(datosPelicula);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
result = "";
line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
int ndatos = result.split("-_-").length;
//String id, String nombre, String genero, String sinopsis, String url_imagen
for (int i = 0; i < ndatos; i++) {
Pelicula p = new Pelicula(result.split("-_-")[i].split("-")[0], result.split("-_-")[i].split("-")[1], result.split("-_-")[i].split("-")[2], result.split("-_-")[i].split("-")[3], result.split("-_-")[i].split("-")[4]);
System.out.println("id " + result.split("-_-")[i].split("-")[0]);
System.out.println("nombre " + result.split("-_-")[i].split("-")[1]);
System.out.println("genero " + result.split("-_-")[i].split("-")[2]);
System.out.println("sinopsis " + result.split("-_-")[i].split("-")[3]);
System.out.println("url " + result.split("-_-")[i].split("-")[4]);
lista.add(p);
}
return lista;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<Pelicula> peliculas) {
super.onPostExecute(peliculas);
}
}
Now it returns a List, I dont need a variable and method getList (wrong way to use the class).
And in my Activity I change to this...
//code
List<Pelicula> listaPelicula = null;
CambiarDatosSalaWorker cambiarDatosSalaWorker = new CambiarDatosSalaWorker();
try {
listaPelicula = cambiarDatosSalaWorker.execute().get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
//code
------ > listaPelicula = cambiarDatosSalaWorker.execute().get();
Now my spinner works just fine.

Related

Change content of listview on button click(on same screen)

So In my MainActivity There are 3 rooms(coming from server).when i click on them popup is open.This popup will having shown the list of roomId(clicked on listview item).This works fine.
Now I need like this.In popup on click of next button next roomId with api to get its module is call and update the listview.
How i do this?
Problem is:-whenever going to do always it open with new popup.
As shown in picture I need to change the content of listview on toolbar's right arrow button.
My listview is in popup.so when i change content of listview this another new popup open for new list.
This is my 1st listview(where I load all images)
modules_list.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0,
android.view.View arg1, int arg2, long arg3) {
editor.putInt("response_position",arg2).commit();
editor.putString("roomid",response.getRooms()[arg2+1].getRooms_id().getRoomId()).commit();
String serverURL = "http://dashboard.droidhomes.in/api/module?room_id=" + response.getRooms()[arg2].getRooms_id().getRoomId();
// Use AsyncTask execute Method To Prevent ANR11 Problem
new GetallModules().execute(serverURL);
}
});
GetAllmodules class to get all modules and switches of Room:-
private class GetallModules extends AsyncTask<String, Void, Void> {
// Required initialization
// private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(
MainActivity.this);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
Dialog.setMessage("Please wait..");
Dialog.show();
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader = null;
try {
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
pref = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
editor = pref.edit();
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String auth_token = pref.getString("auth_token", "");
conn.setRequestProperty("Authorization", auth_token);
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 + "\n");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (Exception ex) {
Error = ex.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
// Content=Content.replaceAll("<string>","");
// Content=Content.replaceAll("</string>", "");
Dialog.dismiss();
if (Error != null) {
Toast toast = Toast.makeText(getApplicationContext(),
"Bad request", Toast.LENGTH_LONG);
toast.show();
// uiUpdate.setText("Output : " + Error);
} else {
// Show Response Json On Screen (activity)
// uiUpdate.setText(Content);
/****************** Start Parse Response JSON Data *************/
// String OutputData = "";
// JSONObject jsonResponse;
Gson gson = new Gson();
final SearchResponse response = gson.fromJson(Content,
SearchResponse.class);
if (response.getStatus() == true) {
//response.getAuth_token()
if (response.getModule().length > 0) {
LayoutInflater li1 = LayoutInflater.from(MainActivity.this);
View promptsView = li1.inflate(R.layout.prompts_modulesdialog1, null);
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setView(promptsView);
ListView list_modules = (ListView) promptsView.findViewById(R.id.lv_modules);
TextView tv_roomname = (TextView) promptsView.findViewById(R.id.tv_roomName);
ImageView iv_left=(ImageView)promptsView.findViewById(R.id.iv_left);
ImageView iv_right=(ImageView)promptsView.findViewById(R.id.iv_right);
ArrayList<String> switches = new ArrayList<String>();
iv_right.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String room_id=pref.getString("roomid","");
String serverURL = "http://dashboard.droidhomes.in/api/module?room_id=" + room_id;
// Use AsyncTask execute Method To Prevent ANR11 Problem
new GetallModules().execute(serverURL);
}
});
for (int i = 0; i < response.getModule().length; i++) {
tv_roomname.setText(response.getModule()[i].getRoom_title());
for (int j = 0; j < response.getModule()[i].getSwitches().length; j++) {
if (response.getModule()[i].getModule_name().equals(response.getModule()[i].getSwitches()[j].getModule_name_switches())) {
switches.add(response.getModule()[i].getSwitches()[j].getSwitch_name());
}
}
}
ToggleButtonListAdapter t1=new ToggleButtonListAdapter(MainActivity.this, switches);
list_modules.setAdapter(t1);
t1.notifyDataSetChanged();
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
} else {
Toast.makeText(getApplicationContext(), "No module defined for this room!!!!!!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "status:-" + response.getStatus(), Toast.LENGTH_SHORT).show();
}
}
}
}
Same Scenario like this.
please help me!!

Android: populate second spinner depending on the selection of first spinner

How can I do this: I have 2 Spinners in my app and one is for Departament and other is for Doctor, when I select one department in Departament spinner I want my second spinner to show only the doctor's who belong to that department. I'm using MYSQL Database to fetching data from two different tables. I populate both table with a urlconection. Here is my code:
int id_departament;
String[] nume_doctor = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.programare_online, container, false);
sp = (Spinner) view.findViewById(R.id.spinner1);
adapter = new ArrayAdapter<String>(getActivity(), R.layout.spinner1_layout, R.id.txt1, listItems);
sp.setAdapter(adapter);
sp.setFocusable(true);
sp.clearFocus();
sp2 = (Spinner) view.findViewById(R.id.spinner2);
adapter2 = new ArrayAdapter<String>(getActivity(), R.layout.spinner2_layout, R.id.txt2, listItems2);
sp2.setAdapter(adapter2);
sp2.setFocusable(true);
sp2.clearFocus();
return view;
}
this is the BlackTask
private class BackTask extends AsyncTask<Void, Void, Void> {
ArrayList<String> list;
ArrayList<String> list2;
protected void onPreExecute() {
super.onPreExecute();
list = new ArrayList<>();
list2 = new ArrayList<>();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
InputStream is2 = null;
String result2 = "";
so here I open the connection with database
try {
URL url = new URL("http://192.168.1.5/clinicco/departament.php");
urlConnection = (HttpURLConnection) url.openConnection(); //here open the connection with database
urlConnection.connect(); //here connect to database
is = urlConnection.getInputStream(); //here open the stream for reading data from database
URL url2 = new URL("http://192.168.1.5/clinicco/doctori.php");
urlConnection2 = (HttpURLConnection) url2.openConnection();
urlConnection2.connect(); //here connect to database
is2 = urlConnection2.getInputStream(); //here open the stream for reading data from database
} catch (IOException e) {
e.printStackTrace();
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line = null;
while ((line = reader.readLine()) != null) {
result += line;
}
is.close();
BufferedReader reader2 = new BufferedReader(new InputStreamReader(is2, "utf-8"));
String line2 = null;
while ((line2 = reader2.readLine()) != null) {
result2 += line2;
}
is2.close();
//result=sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
//id_departament = jsonObject.getInt("id_departament");
// add departament's name to arraylist
list.add(jsonObject.getString("nume_departament"));
}
JSONArray jArray2 = new JSONArray(result2);
JSONObject jsonObject2=null;
nume_doctor=new String[jArray2.length()];
id_departament = jsonObject2.getInt("id_departament");
for (int i = 0; i < jArray2.length(); i++) {
jsonObject2 = jArray2.getJSONObject(i);
list2.add(jsonObject2.getString("nume_doctor"));
id_departament = jsonObject2.getInt("id_departament");
nume_doctor[i] = jsonObject2.getString("nume_doctor");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
this is onPostExecute with the OnItemselectedLiSTENER
protected void onPostExecute(Void result) {
listItems.addAll(list);
adapter.notifyDataSetChanged();
listItems2.addAll(list2);
adapter2.notifyDataSetChanged();
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
// TODO Auto-generated method stu
// sp.getSelectedItem().toString();
int pos = sp.getSelectedItemPosition();
sp2.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
sp2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
// TODO Auto-generated method stub
// sp2.getSelectedItem().toString();
sp.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
public void onStart() {
super.onStart();
BackTask bt = new BackTask();
bt.execute();
}

how to setText() from adapterclass

i have created a custom alertbar on context menu, which is on the list viewed from json parsing. what i want is to get a details(name of the specific person on which the context menu is opened). i want to set Text in the on the alertbar.
Thank you very much for help.
enter code here
public class MyConnectionAsyncTask extends AsyncTask> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle("Connecting...");
progressDialog.show();
}
#Override
protected List<MyconnectionManager> doInBackground(String... params) {
try {
URL url = new URL(params[0]);// taking params from execute method
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();//opening connection
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));//putting data into buffer from input stream
String result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
String json_str = result.toString();
JSONObject parentObject = new JSONObject(json_str);
JSONArray parentArray = parentObject.getJSONArray("result_array");//ARRAY name from API will come here
ArrayList<MyconnectionManager> connectionManagerList = new ArrayList<MyconnectionManager>();//created a list bc we have list of connections
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
MyconnectionManager myconnectionManager = new MyconnectionManager(getActivity());
myconnectionManager.setFullname_myConnection(finalObject.getString("fullname"));
myconnectionManager.setProfilePic_myConnection(finalObject.getString("profile_pic"));
myconnectionManager.setPosition_myconnection(finalObject.getString("position"));
myconnectionManager.setCompany_myConnection(finalObject.getString("company"));
myconnectionManager.setLocation_myConnection(finalObject.getString("location"));
connectionManagerList.add(myconnectionManager);//adding to list
}
return connectionManagerList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<MyconnectionManager> result) {
super.onPostExecute(result);
progressDialog.dismiss();
MyConnectionAdapter adapter = new MyConnectionAdapter(getActivity(), R.layout.single_row_my_connections, result);//creating adpater here
connectionList.setAdapter(adapter);
}
}
adpater Class is below
public class MyConnectionAdapter extends ArrayAdapter {
private List<MyconnectionManager> myconnectionManagerList;
private int resource;
LayoutInflater inflater;
public MyConnectionAdapter(Context context, int resource, List objects) {
super(context, resource, objects);
this.resource = resource;// resource has the layout view so we can also give resource below instead of layout
myconnectionManagerList = objects;
inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.single_row_my_connections, null);//we can give resource here
}
ImageView imageView;
TextView name, company, location, position_company;
imageView = (ImageView) convertView.findViewById(R.id.iv_profile_pic_myconnection);
name = (TextView) convertView.findViewById(R.id.tvname_myconncetion);
company = (TextView) convertView.findViewById(R.id.tvCompany_myconnection);
location = (TextView) convertView.findViewById(R.id.tvlocation_myconnections);
position_company = (TextView) convertView.findViewById(R.id.tvPosition_myconnection);
ImageLoader.getInstance().displayImage(myconnectionManagerList.get(position).getProfilePic_myConnection(), imageView);
name.setText(myconnectionManagerList.get(position).getFullname_myConnection());
company.setText(myconnectionManagerList.get(position).getCompany_myConnection());
location.setText(myconnectionManagerList.get(position).getLocation_myConnection());
position_company.setText(myconnectionManagerList.get(position).getPosition_myconnection());
return convertView;
}
}
context menu is below
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderIcon(R.drawable.small_logo);
menu.setHeaderTitle("Choose Action");
menu.add(0, 1, 0, "Send Message");
menu.add(0,2,1,"Remove Connection");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getItemId()==1){
Toast.makeText(getActivity(),"Send Message",Toast.LENGTH_SHORT).show();
View view=LayoutInflater.from(getActivity()).inflate(R.layout.send_message_layout,null,false);
final EditText et_sub= (EditText) view.findViewById(R.id.et_sub_send_Message);
final EditText et_msg= (EditText) view.findViewById(R.id.etMessage_send_Message);
TextView name= (TextView) view.findViewById(R.id.tv_name_send_message);
name.setText("To: ");//name of user will come here
AlertDialog.Builder ab=new AlertDialog.Builder(getActivity());
ab.setTitle("Send Message");
ab.setView(view);
ab.setNegativeButton("Cancel", null);
ab.setPositiveButton("Send", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String sub = et_sub.getText().toString();
String msg = et_msg.getText().toString();
Toast.makeText(getActivity(), sub + " " + msg, Toast.LENGTH_SHORT).show();
}
});
ab.show();
}else {
Toast.makeText(getActivity(),"Remove Connection",Toast.LENGTH_SHORT).show();
}
return true;
}
You can use
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
int listPosition = info.position;
String nameoOfUser = ((TextView)info.targetView.findViewById(R.id.YOUR_TEXTVIEW_ID)).getText().toString();
name.setText("To: " + nameoOfUser );
}
TextView textViewItem = (TextView)convertView.findViewById(R.id.textViewItem);
textViewItem.setText("your text");

how to Get selected spinner item's Id from JSON response?

Outline:
I have to get some operators list from server.
Below is my JSON data
{"PrepaidServiceList":[{"operator_id":"2","operator_name":"Reliance GSM"},{"operator_id":"9","operator_name":"TATA CDMA\/Walky"},{"operator_id":"10","operator_name":"Virgin GSM - TATA"},{"operator_id":"17","operator_name":"Docomo Mobile"},{"operator_id":"18","operator_name":"Idea Mobile"},{"operator_id":"35","operator_name":"T24 (DOCOMO)"},{"operator_id":"22","operator_name":"VodaFone Mobile"},{"operator_id":"28","operator_name":"MTS DataCard"},{"operator_id":"29","operator_name":"Reliance CDMA\/NetConnect\/Land Line"},{"operator_id":"30","operator_name":"TATA Photon"},{"operator_id":"32","operator_name":"Idea Netsetter"},{"operator_id":"33","operator_name":"MTS Prepaid"},{"operator_id":"38","operator_name":"Bsnl - Data\/Validity"},{"operator_id":"39","operator_name":"Bsnl Topup"},{"operator_id":"41","operator_name":"Bsnl Data Card"},{"operator_id":"45","operator_name":"Aircel"},{"operator_id":"46","operator_name":"Aircel Pocket Internet"},{"operator_id":"52","operator_name":"Virgin CDMA - TATA"},{"operator_id":"53","operator_name":"Docomo Special"},{"operator_id":"55","operator_name":"Videocon"},{"operator_id":"56","operator_name":"MTNL Mumbai"},{"operator_id":"57","operator_name":"MTNL Mumbai Special"},{"operator_id":"58","operator_name":"Uninor"},{"operator_id":"59","operator_name":"MTNL Delhi"},{"operator_id":"60","operator_name":"MTNL Delhi Special"},{"operator_id":"61","operator_name":"Uninor Special"},{"operator_id":"62","operator_name":"Videocon Special"},{"operator_id":"63","operator_name":"MTNL Delhi"},{"operator_id":"64","operator_name":"MTNL Mumbai"}]}
JSON data has "operator_id" and "operator_name".
I have to get both from url and display only "operator_name" in a spinner.
I Have already implemented the above. Please find the main_activity for reference
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
plans = (TextView)findViewById(R.id.browseplans);
plans.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(getApplicationContext(), BrowsePlans.class);
in.putExtra("operator_id", id_click);
startActivity(in);
}
});
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyHHmmss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+5:30"));
currentDateandTime = sdf.format(new Date());
apikey = API_KEY.toString();
currentDateandTime.toString();
codetohash = currentDateandTime + apikey;
SHA1Hash = computeSha1OfString(codetohash);
uri = new Uri.Builder()
.scheme("http")
.authority("xxx.in")
.path("atm")
.appendQueryParameter("op", "GetPrepaidServiceList")
.appendQueryParameter("responseType", "json")
.appendQueryParameter("time", currentDateandTime)
.appendQueryParameter("clientId", ClientId)
.appendQueryParameter("hash", SHA1Hash)
.build();
stringUri = uri.toString();
new DataFromServer().execute();
} //end onCreate()
private class DataFromServer extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(String... params) {
try {
url = new URL(stringUri);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Host", "xxx.in");
/* Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("val1", from)
.appendQueryParameter("val2", to);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();*/
conn.connect();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
text = sb.toString();
} catch (Exception ex) {
ex.toString();
} finally {
try {
reader.close();
} catch (Exception ex) {
ex.toString();
}
}
/*//only for json object not array
JSONObject parentObject = new JSONObject(text);
name = parentObject.getString("Hello");*/
try {
JSONObject jsonObj = new JSONObject(text);
// Getting JSON Array node
JSONArray jsonArray = jsonObj.getJSONArray("PrepaidServiceList");
// looping through All Contacts
for (int i = 0; i < jsonArray.length(); i++) {
c = jsonArray.getJSONObject(i);
id = c.getString("operator_id");
name = c.getString("operator_name");
list.add(name);
}
} catch (Exception e) {
e.toString();
}
return null;
}
#Override
protected void onPostExecute(Void unused) {
ArrayAdapter adapter =
new ArrayAdapter(getApplication(), R.layout.list_item, R.id.text1, list);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
int item = spinner.getSelectedItemPosition();
id_click = spinner.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
Problem:
I am able to get user selected "operator_name" from spinner using "onItemSelectedListener".
But i need the "operator_id" of user selected "operator_name"
I have to pass the exact user selected "operator_id" to another class.
If i directly pass the operator_id, it has only the last id which is not the user selected one.
I am confused and don't know how to implement this.
Any Help would be greatly appreciated.
Thanks.
Try this way it worked for me
class LoadAlbums extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {
ArrayAdapter<String> adaptercountry ;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
data = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(COUNTRY_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node your array
country_list = jsonObj.getJSONArray(COUNTRY_LIST);
// looping through All Contacts
for (int i = 0; i < country_list.length(); i++) {
JSONObject c = country_list.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(OP_ID, c.getString(OP_ID));
map.put(OP_NAME,c.getString(OP_NAME));
data.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return data;
}
protected void onPostExecute(ArrayList<HashMap<String,String>> result) {
super.onPostExecute(result);
String[] arrConuntry=new String[data.size()];
for(int index=0;index<data.size();index++){
HashMap<String, String> map=data.get(index);
arrConuntry[index]=map.get(OP_NAME);
}
// pass arrConuntry array to ArrayAdapter<String> constroctor :
adaptercountry = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item,
arrConuntry);
spcountry.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View w) {
new AlertDialog.Builder(getActivity())
.setTitle("Select")
.setAdapter(adaptercountry, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
spcountry.setText(adaptercountry.getItem(which).toString());
try {
cname=country_list.getJSONObject(which).getString("operator_id");
Log.d("Response: ", "> " + cname);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dialog.dismiss();
}
}).create().show();
}
});
}
In this case you can modify the AsyncTask to return in the doInBackground() method a List<HashMap<Integer, String>>. So you can store both operator_id and operator_name in the list and display each wanted item in the spinner.
Hope it helps!!!
Create a new ArrayList like
operator_List = new ArrayList<String>();
Add value in ArrayList like
opt_code.setName(jsonobject.optString("operator_name"));
opt_code.setId(jsonobject.optString("operator_id"));
list.add(opt_code);
datalist.add(jsonobject.optString("operator_name"));
operator_List .add(jsonobject.getString("operator_id")
and get operator_id
protected void onPostExecute(Void unused) {
ArrayAdapter adapter =
new ArrayAdapter(getApplication(), R.layout.list_item, R.id.text1, list);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
id_click = spinner.getSelectedItemPosition();
String opt_code = operator_List.get(position);
String selectedItem = arg0.getItemAtPosition(position).toString();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
May be help you
Your can get Whole object of selected Spinner item use below code:
Object item = arg0.getItemAtPosition(position);

how to parsing with json from 2 different server?

i need help here.
i wanna do parse with json from 2 url server and then show the array at 1 listview.
this's my code.
public class MainActivity extends Activity {
private JSONObject jObject;
private String jsonResult ="";
private JSONObject jObject2;
private String jsonResult2 ="";
private String url = "http://10.0.2.2/kota/daftarkota.php";
private String url2 = "http://10.0.2.2/kota/delkota.php";
private String url3 = "http://www.hatsa.byethost33.com/kota_daftarkota.php";
String[] daftarid;
String[] daftarnama;
String[] daftarlatitude;
String[] daftarlongitude;
Menu menu;
public static MainActivity ma;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ma=this;
RefreshList();
}
public void RefreshList() {
try {
jsonResult = getRequest(url);
jObject = new JSONObject(jsonResult);
JSONArray menuitemArray = jObject.getJSONArray("kota");
daftarid = new String[menuitemArray.length()];
daftarnama = new String[menuitemArray.length()];
daftarlatitude = new String[menuitemArray.length()];
daftarlongitude = new String[menuitemArray.length()];
for (int i = 0; i < menuitemArray.length(); i++)
{
daftarid[i] = menuitemArray.getJSONObject(i).getString("id").toString();
daftarnama[i] = menuitemArray.getJSONObject(i).getString("nama").toString();
daftarlatitude[i] = menuitemArray.getJSONObject(i).getString("latitude").toString();
daftarlongitude[i] = menuitemArray.getJSONObject(i).getString("longitude").toString();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
jsonResult2 = getRequest(url3);
jObject2 = new JSONObject(jsonResult2);
JSONArray menuitemArray = jObject2.getJSONArray("kota");
daftarid = new String[menuitemArray.length()];
daftarnama = new String[menuitemArray.length()];
daftarlatitude = new String[menuitemArray.length()];
daftarlongitude = new String[menuitemArray.length()];
for (int i = 0; i < menuitemArray.length(); i++)
{
daftarid[i] = menuitemArray.getJSONObject(i).getString("id").toString();
daftarnama[i] = menuitemArray.getJSONObject(i).getString("nama").toString();
daftarlatitude[i] = menuitemArray.getJSONObject(i).getString("latitude").toString();
daftarlongitude[i] = menuitemArray.getJSONObject(i).getString("longitude").toString();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ListView ListView01 = (ListView)findViewById(R.id.ListView01);
ListView01.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, daftarnama));
ListView01.setSelected(true);
ListView01.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
final String selectionid = daftarid[arg2];
final String selectionnama = daftarnama[arg2];
final String selectionlatitude = daftarlatitude[arg2];
final String selectionlongitude = daftarlongitude[arg2];
final CharSequence[] dialogitem = {"Edit", "Delete"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Pilih ?");
builder.setItems(dialogitem, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch(item){
case 0 :
Intent i = new Intent(getApplicationContext(), EditActivity.class);
i.putExtra("id", selectionid);
i.putExtra("nama", selectionnama);
i.putExtra("latitude", selectionlatitude);
i.putExtra("longitude", selectionlongitude);
startActivity(i);
break;
case 1 :
getRequest(url2 + "?id=" + selectionid);
RefreshList();
break;
}
}
});
builder.create().show();
}});
((ArrayAdapter)ListView01.getAdapter()).notifyDataSetInvalidated();
}
/**
* Method untuk Mengirimkan data ke server
*/
public String getRequest(String Url){
String sret="";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(Url);
try{
HttpResponse response = client.execute(request);
sret =request(response);
}catch(Exception ex){
Toast.makeText(this,"Gagal "+sret, Toast.LENGTH_SHORT).show();
}
return sret;
}
/**
* Method untuk Menerima data dari server
*/
public static String request(HttpResponse response){
String result = "";
try{
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
}catch(Exception ex){
result = "Error";
}
return result;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
this.menu = menu;
menu.add(0, 1, 0, "Tambah").setIcon(android.R.drawable.btn_plus);
menu.add(0, 2, 0, "Refresh").setIcon(android.R.drawable.ic_menu_rotate);
menu.add(0, 3, 0, "Exit").setIcon(android.R.drawable.ic_menu_close_clear_cancel);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1:
Intent i = new Intent(MainActivity.this, AddActivity.class);
startActivity(i);
return true;
case 2:
RefreshList();
return true;
case 3:
finish();
return true;
}
return false;
}
}
if i run it, the listview only show me the array from 'url' and there's nothing from 'url3'.
i don't know how should my code is, if i wanna make the listview show the array from 'url' and 'url3'.
thanks. :)
It actually looks the other way around. I guess you see the data from url3, since you create the array daftarnama twice - the second time with the data from url3. Use a List<String> instead of the array. Create the list just once and then add all the items from both urls. Also, you should rethink your code. You have a lot of duplicate code here (DRY - don't repeat yourself).

Categories

Resources