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
Related
I am adding side menu screen content as a Currencyconverter. When i am clicking to calculate currency it is not getting & App is crashing. I have used yahoo API for currency converter.
Facing Error in GetJson() & onClick() in Fragments. Please see code help me for same . i am stuck why this is happening ?
In 1st image is you can see the side menu & 2nd image come after clicking currency converter (via side menu click).
Currencyconverter.java
import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import info.androidhive.customlistviewvolley.R;
public class CurrencyConverter extends Fragment {
public CurrencyConverter() {
}
public int to;
public int from;
public String[] val;
public String s;
public Handler handler;
/**
* Called when the activity is first created.
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.currency_converter, container, false);
/* public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);*/
Spinner s1 = (Spinner) rootView.findViewById(R.id.spinner1);
Spinner s2 = (Spinner) rootView.findViewById(R.id.spinner2);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this.getActivity(), R.array.name, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
val = getResources().getStringArray(R.array.value);
s1.setAdapter(adapter);
s2.setAdapter(adapter);
s1.setOnItemSelectedListener(new spinOne(1));
s2.setOnItemSelectedListener(new spinOne(2));
Button b = (Button) rootView.findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View View) {
TextView t = (TextView) View.findViewById(R.id.textView4);
if (from == to) {
Toast.makeText(getActivity().getApplicationContext(), "Invalid", 4000).show();
} else {
try {
s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
String exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
t.setText(exResult);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public String getJson(String url)throws ClientProtocolException, IOException {
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
});
return rootView;
}
public class spinOne implements AdapterView.OnItemSelectedListener
{
int ide;
spinOne(int i)
{
ide =i;
}
public void onItemSelected(AdapterView<?> parent, View view,
int index, long id) {
if(ide == 1)
from = index;
else if(ide == 2)
to = index;
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
}
CurrencyConverter.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF"
>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#FFFFFF">
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/one"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/in"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/equal"
android:textAppearance="?android:attr/textAppearanceLarge" />
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="122dp"
android:gravity="center"
android:background="#ffffff">
<RelativeLayout
android:id="#+id/relativeLayout2"
android:layout_width="match_parent"
android:layout_height="120dp"
android:gravity="center"
android:background="#ffffff">
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/result"
android:textSize="35dp"
/>
</RelativeLayout>
</RelativeLayout>
<Button
android:id="#+id/button1"
android:layout_marginTop="10dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/calculate" />
</LinearLayout>
</ScrollView>
Error:
FATAL EXCEPTION: main Process: info.androidhive.customlistviewvolley, PID: 8469
android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at info.androidhive.customlistviewvolley.model.CurrencyConverter$1.getJson(CurrencyConverter.java:98)
at info.androidhive.customlistviewvolley.model.CurrencyConverter$1.onClick(CurrencyConverter.java:76)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
As it said "NetworkOnMainThreadException" do not hit api direclty instead use AsyncTask for it .
Just define asynctask first
class Calculate extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... args) {
s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
String exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
return null;
}
#Override
protected void onPostExecute(String file_url) {
t.setText(exResult);
}
And call AsyncTask there
if (from == to) {
Toast.makeText(getActivity().getApplicationContext(), "Invalid", 4000).show();
} else {
new Calculate ().excute();
}
Answer:
Updated
CurrencyConverter.java
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import info.androidhive.customlistviewvolley.R;
public class CurrencyConverter extends Fragment {
public CurrencyConverter() {
}
TextView t;
public int to;
public int from;
public String[] val;
public String s;
String exResult;
public Handler handler;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.currency_converter, container, false);
t= (TextView) rootView.findViewById(R.id.textView4);
Spinner s1 = (Spinner) rootView.findViewById(R.id.spinner1);
Spinner s2 = (Spinner) rootView.findViewById(R.id.spinner2);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this.getActivity(), R.array.name, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
val = getResources().getStringArray(R.array.value);
s1.setAdapter(adapter);
s2.setAdapter(adapter);
s1.setOnItemSelectedListener(new spinOne(1));
s2.setOnItemSelectedListener(new spinOne(2));
Button b = (Button) rootView.findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View View) {
if (from == to) {
Toast.makeText(getActivity().getApplicationContext(), "Invalid", 4000).show();
} else {
new calculate().execute();
}
}
});
return rootView;
}
public class calculate extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... args) {
try {
s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return exResult;
}
#Override
protected void onPostExecute(String exResult) {
t.setText(exResult);
}
}
public String getJson(String url)throws IOException {
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
public class spinOne implements AdapterView.OnItemSelectedListener
{
int ide;
spinOne(int i)
{
ide =i;
}
public void onItemSelected(AdapterView<?> parent, View view,
int index, long id) {
if(ide == 1)
from = index;
else if(ide == 2)
to = index;
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
}
I have developed a layout which has 2 textboxes and 1 button. At the first, the button is appear and two textboxes are disappeared. However, I dont know how can I change the visibility of textboxes and other components to appear when the insert button is pressed. Please explain simply because I am new in android.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:orientation="vertical"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".Main3Activity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:id="#+id/textView"
android:visibility="gone" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editTextName"
android:visibility="gone" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address"
android:id="#+id/textView2"
android:visibility="gone" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editTextAddress"
android:visibility="gone" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Insert"
android:onClick="insert"
android:id="#+id/button" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textViewResult" />
</LinearLayout>
Main2Activity
package com.example.alan.mainactivity;
import org.apache.http.util.EntityUtils;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
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.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.view.View;
import android.widget.Toast;
import android.view.View.OnClickListener;
public class Main2Activity extends ActionBarActivity {
public static final String USER_NAME1 = "USERNAME";
String myJSON;
private EditText editTextName;
private EditText editTextAdd;
private static final String TAG_RESULTS="result";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_ADD ="address";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
Button btn_insert=(Button)findViewById(R.id.button);
btn_insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView= (TextView)findViewById(R.id.textView);
textView.setVisibility(View.VISIBLE);
//Similarly the other views.....
}
});
public void insert(View view){
String name = editTextName.getText().toString();
String add = editTextAdd.getText().toString();
insertToDatabase(name, add);
}
private void insertToDatabase(String name, String add){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String paramAddress = params[1];
String name = editTextName.getText().toString();
String add = editTextAdd.getText().toString();
Intent intent = getIntent();
String username = intent.getStringExtra(MainActivity.USER_NAME).toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("address", add));
nameValuePairs.add(new BasicNameValuePair("user", username));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"http://www.oobac.com/app/insert-db.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "success";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
TextView textViewResult = (TextView) findViewById(R.id.textViewResult);
textViewResult.setText("Inserted");
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, add);
}
//-----------------------
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
Intent intent = getIntent();
String username = intent.getStringExtra(MainActivity.USER_NAME);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextAdd = (EditText) findViewById(R.id.editTextAddress);
TextView textView = (TextView) findViewById(R.id.textView3);
textView.setText("Welcome " + username);
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData();
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String address = c.getString(TAG_ADD);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_ID,id);
persons.put(TAG_NAME,name);
persons.put(TAG_ADD,address);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
Main2Activity.this, personList, R.layout.list_item,
new String[]{TAG_ID,TAG_NAME,TAG_ADD},
new int[]{R.id.id, R.id.name, R.id.address}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
//--------------------------------------------
Intent intent = getIntent();
String username = intent.getStringExtra(MainActivity.USER_NAME);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", username));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.oobac.com/app/amir.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
String st = EntityUtils.toString(response.getEntity());
Log.d("TK SUPPORT", "In the try Loop" + st);
myJSON = st;
} catch (Exception e) {
Log.d("TK SUPPORT", "Connection Error : " + e.toString());
}
return "OK";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
SAMPLE SNIPPET
replace your onCreate method to this method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
Intent intent = getIntent();
String username = intent.getStringExtra(MainActivity.USER_NAME);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextAdd = (EditText) findViewById(R.id.editTextAddress);
TextView textView = (TextView) findViewById(R.id.textView3);
Button btn_insert=(Button)findViewById(R.id.button);
btn_insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView= (TextView)findViewById(R.id.textView);
textView.setVisibility(View.VISIBLE);
//Similarly the other views.....
}
});
textView.setText("Welcome " + username);
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData();
}
Try this:
EditText name = (EditText)findViewById(R.id.editTextName);
name.setVisibility(View.GONE);
Declare a class variable like this
private TextView yourTextView;
You should get the instance of your TextView like this
yourTextView = (TextView)findViewById(R.id.your_editText);
Then on button click, setVisibility to visible
Button mButton = (Button)findViewById(R.id.m_button);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yourTextView.setVisibility(View.VISIBLE);
}
});
To hide, setVisibility to Gone
yourTextView.setVisibility(View.GONE);
Use the setVisibility property to hide your views.
yourView.setVisibility(View.GONE);
View.GONE This view is invisible, and it doesn't take any space for layout purposes.
Also
yourView.setVisibility(View.INVISIBLE);
View.INVISIBLE This view is invisible, but it still takes up space for layout purposes.
Button btn_insert=(Button)findViewById(R.id.button);
btn_insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView= (TextView)findViewById(R.id.textView);
textView.setVisibility(View.VISIBLE);
//Similarly the other views.....
}
});
Firstly, You are setting android:onClick="insert" in layout xml and you are also setting click listener in onCreate method too. So either remove from xml or onCreate listener. Secondly, in onClick, TextView textView=
(TextView)findViewById(R.id.textView);
textView.setVisibility(View.VISIBLE);
Hope this helps.
In Simple way Just put your onClicklistener() of button inside onCreate() method like this ..
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
Intent intent = getIntent();
String username = intent.getStringExtra(MainActivity.USER_NAME);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextAdd = (EditText) findViewById(R.id.editTextAddress);
TextView textView = (TextView) findViewById(R.id.textView3);
Button btn_insert=(Button)findViewById(R.id.button);
btn_insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView= (TextView)findViewById(R.id.textView);
textView.setVisibility(View.VISIBLE);
//do it here whatever u want to do on press of button
//Similarly the other views.....
}
});
textView.setText("Welcome " + username);
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData();
}
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 am new to Android. I can't get my ListView to populate. I am aware that this question has been asked on SO multiple times before and I have tried the things suggested in other questions (e.g. making sure my orientation is set to vertical, calling notifyDataSetChanged etc) and it still won't work. My activity class is as follows:
package com.michaelnares.twitterclient;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
import twitter4j.*;
import twitter4j.conf.ConfigurationBuilder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Created by michael on 01/05/2014.
*/
public class SearchActivity extends Activity {
EditText queryEditText = null;
String queryText = null;
private Context context = this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
queryEditText = (EditText) findViewById(R.id.queryEditText);
queryText = (queryEditText.getText().toString());
final Context context = this;
Button queryButton = (Button) findViewById(R.id.queryButton);
queryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (queryText.equals(null)) {
Toast.makeText(context, "You did not enter a query", Toast.LENGTH_SHORT).show();
} else {
new SearchAsyncTask().execute();
}
}
});
} // ends onCreate()
private class SearchAsyncTask extends AsyncTask<String, String, ArrayList<String>>
{
private ProgressDialog dialog = new ProgressDialog(SearchActivity.this);
private ArrayList<String> searchResults;
#Override
protected void onPreExecute()
{
super.onPreExecute();
dialog.setMessage("Getting data...");
dialog.setIndeterminate(false);
dialog.setCancelable(true);
dialog.show();
}
#Override
protected ArrayList<String> doInBackground(String... strings) {
APIClient client = new APIClient();
searchResults = client.getQueryResults(queryText);
return searchResults;
}
#Override
protected void onPostExecute(ArrayList<String> results)
{
dialog.dismiss();
results.addAll(searchResults);
final ListView searchListView = (ListView) findViewById(R.id.searchListView);
final ArrayAdapter adapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, results);
adapter.notifyDataSetChanged();
searchListView.setAdapter(adapter);
}
}
} //ends class
and my XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp" >
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/search"
android:textSize="25dp"/>
<EditText android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/queryEditText"
android:ems="20"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/query"
android:id="#+id/queryButton"
android:textSize="15dp"/>
<ListView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/searchListView">
</ListView>
</LinearLayout>
Here is my API client class also:
package com.michaelnares.twitterclient;
import android.util.Log;
import twitter4j.*;
import twitter4j.conf.ConfigurationBuilder;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Created by michael on 01/05/2014.
*/
public class APIClient
{
ArrayList<String> statusArrayList = new ArrayList<String>();
ArrayList<String> searchArrayList = new ArrayList<String>();
public ArrayList<String> getHomeTimeline() {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(AuthConstants.API_KEY)
.setOAuthConsumerSecret(AuthConstants.API_SECRET)
.setOAuthAccessToken(AuthConstants.ACCESS_TOKEN)
.setOAuthAccessTokenSecret(AuthConstants.ACCESS_TOKEN_SECRET);
try {
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
List<Status> statuses = twitter.getHomeTimeline();
statusArrayList.clear();
for (Status status : statuses)
{
statusArrayList.add(status.toString());
}
}
catch (TwitterException e)
{
Log.e(LogConstants.LOG, "Failed to get home timeline tweets: " + e.getErrorMessage());
}
return statusArrayList;
} // ends getHomeTimeline() method
public ArrayList<String> getQueryResults(String userQuery)
{
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(AuthConstants.API_KEY)
.setOAuthConsumerSecret(AuthConstants.API_SECRET)
.setOAuthAccessToken(AuthConstants.ACCESS_TOKEN)
.setOAuthAccessTokenSecret(AuthConstants.ACCESS_TOKEN_SECRET);
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
searchArrayList.clear();
try {
Query query = new Query(userQuery);
QueryResult result;
result = twitter.search(query);
List<Status> tweets = result.getTweets();
int count = 0;
searchArrayList.clear();
for (Iterator<Status> i = tweets.iterator(); i.hasNext();)
{
Status tweet = i.next();
count++;
if (count == 10)
{
break;
}
searchArrayList.add("#" + tweet.getUser().getScreenName() + " - " + tweet.getText());
} // ends for loop
} // ends try block
catch (TwitterException e)
{
Log.e(LogConstants.LOG, "Failed to search tweets: " + e.getErrorMessage());
}
return searchArrayList;
} // ends getQueryResults() method
} // ends class
I'm really struggling to work out what the issue is.
I am A new guy in Android. I try to develop a list that can show the song name and author at the same line. The source data is from a online XML file
The following is the code I try to use in my program.
However, I only be able to display the author name in the list.
I would to ask how I should modify the code so that I can show the song name and author at the same line in the list?
The Format of online XML file I try to read
<recipes>
<song>
<id>1</id>
<title>Sing A Song</title>
<songs_author>ACM</songs_author>
</song>
<song>
<id>2</id>
<title>DO Re Me</title>
<songs_author>BBC/songs_author>
</song>
</recepies>
src/com.mobile/SongsActivity
package com.mobile;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class SongsActivity extends Activity implements OnItemClickListener {
protected static final int DIALOG_KEY = 0;
ListView mListView;
Button mClear;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
this.setProgressBarIndeterminateVisibility(false);
setContentView(R.layout.Songs);
mListView = (ListView) findViewById(R.id.listView1);
mListView.setTextFilterEnabled(true);
mListView.setOnItemClickListener(this);
LoadRecipesTask1 mLoadRecipesTask = new LoadRecipesTask1();
mLoadRecipesTask.execute("http://123.com/mobile/Songs_list.php");
mClear = (Button) findViewById(R.id.button3);
mClear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mListView.setAdapter(null);
}
});
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Datum datum = (Datum) mListView.getItemAtPosition(position);
Uri uri = Uri.parse("http://123.com/mobile/Songs.php?Songsid=" + datum.getId());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
this.startActivity(intent);
}
public static ArrayList<Datum> parse(String url) throws IOException, XmlPullParserException {
final ArrayList<Datum> results = new ArrayList<Datum>();
URL input = new URL(url);
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(input.openStream(), null);
int eventType = xpp.getEventType();
String currentTag = null;
Integer id = null;
String title = null;
String Songs_author = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
currentTag = xpp.getName();
} else if (eventType == XmlPullParser.TEXT) {
if ("id".equals(currentTag)) {
id = Integer.valueOf(xpp.getText());
}
if ("title".equals(currentTag)) {
title = xpp.getText();
}
if ("Songs_author".equals(currentTag)) {
Songs_author = xpp.getText();
}
} else if (eventType == XmlPullParser.END_TAG) {
if ("song".equals(xpp.getName())) {
results.add(new Datum(id, title, Songs_author));
}
}
eventType = xpp.next();
}
return results;
}
protected class LoadRecipesTask1 extends AsyncTask<String, Void, ArrayList<Datum>> {
#Override
protected void onPreExecute() {
SongsActivity.this.setProgressBarIndeterminateVisibility(true);
}
#Override
protected ArrayList<Datum> doInBackground(String... urls) {
ArrayList<Datum> datumList = new ArrayList<Datum>();
try {
datumList = parse(urls[0]);
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
return datumList;
}
#Override
protected void onPostExecute(ArrayList<Datum> result) {
mListView.setAdapter(new ArrayAdapter<Datum>(SongsActivity.this, R.layout.list_item, result));
//SongsActivity.this.setProgressBarIndeterminateVisibility(false);
}
}
}
src/com.mobile/Datum
package com.mobile;
public class Datum {
int id;
String title;
String songs_author;
public Datum(int id, String title, String songs_author) {
this.id = id;
this.title = title;
this.songs_author= songs_author;
}
public String toString() {
return songs_author;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String get Songs_author() {
return Songs_author;
}
}
res/layout/songs.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button android:text="Refresh 1" android:id="#+id/button1"
android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1"></Button>
<Button android:text="Clear" android:id="#+id/button3"
android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1"></Button>
</LinearLayout>
<ListView android:id="#+id/listView1" android:layout_height="fill_parent"
android:layout_width="fill_parent"></ListView>
</LinearLayout>
res/layout/list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
Just make Custom List View using array adapter.
refer this example..
http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/
The web is full of tutorial and example of ListView using Custom Adapter. You will have to spend some time trying to learn them. No shortcuts. You can one of them here or you can select one of the books from Amazon.