How to get the values dynamically from Web Service - android

I am new to JSON concept
in below code the the values of "AgentId" and "Type" are changing based on agents but i am
taking constantly like below
jsonReq.put("agentsId", 7); and
jsonReq.put("types", 0);
so i have to change them time to time. How to get it please help me
public class Busi_perfo_infor_Activity extends BaseActivity
{
private ProgressDialog dialog;
private TableLayout tableLayout;
private Handler handler = new Handler();
private Spinner Month_Spinner;
private List<Indi_Busi_Agent_perfo> agentsList = new ArrayList<Indi_Busi_Agent_perfo>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.busi_perfo_info);
Month_Spinner = (Spinner) findViewById(R.id.Current_prvious_month_spinner);
setupHeader();
tableLayout = (TableLayout) findViewById(R.id.Table_busi_perfo);
dialog = new ProgressDialog(this);
dialog.setMessage("Loading...");
dialog.setIndeterminate(true);
dialog.setCancelable(true);
setupBranchSpinner();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, new String[] { "Previous Month",
"Current Month" }) {
};
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Month_Spinner.setAdapter(dataAdapter);
Month_Spinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
updateCollectons();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
private void setupBranchSpinner() {
dialog.show();
new Thread() {
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
dialog.dismiss();
}
});
}
}.start();
}
protected void updateCollectons() {
// TODO Auto-generated method stub
dialog.show();
tableLayout.setVisibility(View.GONE);
final JSONObject json = new JSONObject();
try {
JSONObject jsonReq = new JSONObject(Utilities.loadPref(
getApplicationContext(), "Login", ""));
jsonReq.put("agentsId", 7);
// jsonReq.put("Area", 0);
// jsonReq.put("Mode", 2);
SimpleDateFormat fmtOut = new SimpleDateFormat("dd MMM yyyy");
// dd MMM yyyy
String dateFormat = fmtOut.format(new Date());
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, 1);
if (Month_Spinner.getSelectedItemPosition() == 0) {
cal.add(Calendar.MONTH, -1);
}
String fromdateFormat = fmtOut.format(cal.getTime());
//
jsonReq.put("FromDate", fromdateFormat);
jsonReq.put("ToDate", dateFormat);
jsonReq.put("types", 0);
json.put("AgntPerformanceRequest", jsonReq);
new Thread() {
private Indi_Busi_Agent_perfo info;
public void run() {
String response = WebServices.postRequest(
WebServices.INDIVI_BUSI_PERFO_URL, json,
Busi_perfo_infor_Activity.this);
if (response != null) {
try {
JSONObject jsonResp = new JSONObject(response);
if (jsonResp
.has("AgntPerformanceResult")) {
info = new Indi_Busi_Agent_perfo(
jsonResp.getJSONObject(
"AgntPerformanceResult"));
} else {
Toast.makeText(getApplicationContext(),
"their are no subscribers",
Toast.LENGTH_LONG).show();
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
handler.post(new Runnable() {
#Override
public void run() {
dialog.dismiss();
if (info != null) {
updateCollectionTableView(info);
}
}
});
}
}.start();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void updateCollectionTableView(Indi_Busi_Agent_perfo info) {
tableLayout.setVisibility(View.VISIBLE);
((TextView) findViewById(R.id.bch_name)).setText(Utilities
.getString(info.getBranchName()));
((TextView) findViewById(R.id.busi_Amt)).setText(Utilities
.getDecimalFormat(info.getBusinessAmt()));
}
}
any help will be a suggestion to me
Thank you.

Related

Get selected item from first spinner and send to string request URL

I have tried send selected item from first spinner and i want second spinner show if first spinner selected and send data to string request URL but failed. Example I've been selected number 1 on first spinner and second spinner showing based string URL which already send from first. like this http://192.168.43.66/json/kota/1 and more
public String DataIDProvinsi;
private ArrayList<String>id_provinsi;
private ArrayList<String>nama_provinsi;
private ArrayList<String>id_kota;
private ArrayList<String>nama_kota;
private ArrayList<String>id_kecamatan;
private ArrayList<String>nama_kecamatan;
private JSONArray result;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
nama_provinsi = new ArrayList<String>();
id_provinsi = new ArrayList<String>();
id_kota = new ArrayList<String>();
nama_kota = new ArrayList<String>();
TxtDataProvinsi = (EditText) findViewById(R.id.TxtDataProvinsi);
spinner_provinsi = (Spinner) findViewById(R.id.spinner_provinsi);
spinner_kota = (Spinner) findViewById(R.id.spinner_kota);
spinner_jk = (Spinner) findViewById(R.id.spinner_jk);
TxtIdProvinsi = (TextView) findViewById(R.id.TxtIdProvinsi);
spinner_provinsi.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?>parent, View view, int position, long id){
}
#Override
public void onNothingSelected(AdapterView<?>parent){
TxtIdProvinsi.setText("");
}
});
spinner_kota.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?>parent, View view, int position, long id){
}
#Override
public void onNothingSelected(AdapterView<?>parent){
}
});
TxtIdKota = (TextView) findViewById(R.id.TxtIdKota);
TxtTglLhr = findViewById(R.id.TxtTglLahir);
findViewById(R.id.TxtTglLahir).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDatePickerDialog();
}
});
getDataProvinsi();
getDataKota();
}
private void showDatePickerDialog(){
DatePickerDialog datePickerDialog = new DatePickerDialog(this,
this, Calendar.getInstance().get(Calendar.YEAR),
Calendar.getInstance().get(Calendar.MONTH),
Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
datePickerDialog.show();
}
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
String tanggal = year+"-"+month+"-"+dayOfMonth;
TxtTglLhr.setText(tanggal);
}
public void getDataProvinsi(){
pDialog = new ProgressDialog(RegisterActivity.this);
pDialog.setCancelable(false);
pDialog.setMessage("Mohon Menunggu...");
// showDialog();
StringRequest stringRequestProvinsi = new StringRequest("http://192.168.43.66/json/provinsi/", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getJSONArray("result");
getNamaProvinsi(result);
} catch (JSONException e) {
e.printStackTrace();
}
// hideDialog();
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequestProvinsi);
}
public void getDataKota(){
DataIDProvinsi = spinner_provinsi.getSelectedItem().toString();
StringRequest stringRequestKota = new StringRequest("http://192.168.43.66/json/kota/"+DataIDProvinsi, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getJSONArray("result");
getNamaKota(result);
} catch (JSONException e) {
e.printStackTrace();
}
// hideDialog();
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequestKota);
}
public void getNamaProvinsi(JSONArray j){
for (int i = 0; i < j.length(); i++){
try {
JSONObject jsonProvinsi = j.getJSONObject(i);
id_provinsi.add(jsonProvinsi.getString("id_provinsi"));
//nama_provinsi.add(jsonProvinsi.getString(ProvinsiActivity.TAG_NAMA_PROVINSI));
} catch (JSONException e) {
e.printStackTrace();
}
}
spinner_provinsi.setAdapter(new ArrayAdapter<String>(RegisterActivity.this,
R.layout.support_simple_spinner_dropdown_item, id_provinsi));
}
public void getNamaKota(JSONArray j){
for (int i = 0; i < j.length(); i++){
try {
JSONObject jsonKota = j.getJSONObject(i);
//id_kota.add(jsonKota.getString(KotaActivity.TAG_ID_KOTA));
nama_kota.add(jsonKota.getString("nama_kota"));
} catch (JSONException e) {
e.printStackTrace();
}
}
spinner_kota.setAdapter(new ArrayAdapter<String>(RegisterActivity.this,
R.layout.support_simple_spinner_dropdown_item, nama_kota));
}
private void showDialog(){
if(!pDialog.isShowing())
pDialog.show();
}
private void hideDialog(){
if(pDialog.isShowing())
pDialog.dismiss();
}
}

dynamic spinner consuming rest services creating issue on OnClickListener

I have an android project containing spinner which consumes rest services and is able to get data dynamically
The problem is it gets data when i click the button and not the spinner
I tried setting setOnClickListener function on spinner but it doesn't work
the code is
private Context mContext=HourlyEntry.this;
private Spinner s1;
private String m_DepartmentID=null;
private ArrayList<String> m_Department_list;
private ArrayList<String> m_DepartmentID_list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hourly_entry);
s1=(Spinner)findViewById(R.id.spinner1);
s1.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v == s1)
{
JSONObject login = new JSONObject();
try
{
login.put("EmployeeID","1");
//login.put("Password", etCountry.getText().toString());
JSONObject finaldata = new JSONObject();
finaldata.put("ProjectRequest", login);
final ConnectToServer connect = new ConnectToServer();
connect.extConnectToServer(HourlyEntry.this,
new ConnectToServer.Callback()
{
public void callFinished(String result)
{
//Toast.makeText(getBaseContext(), result,
Toast.LENGTH_LONG).show();
JSONObject resp = null;
try
{
resp = new JSONObject(result);
Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
JSONObject Login1Result = resp.getJSONObject("ProjectResult");
JSONArray DepartmentDetails = Login1Result.getJSONArray("ProjectDetails");
//String strMessage = Login1Result.getString("message");
Toast.makeText(getBaseContext(), Login1Result.getString("ProjectDetails"), Toast.LENGTH_LONG).show();
// List<String> list = new ArrayList<String>();
if (!Login1Result.getString("ProjectDetails").equalsIgnoreCase("null"))
{
//JSONArray DepartmentDetails = Login1Result.getJSONArray("ProjectDetails");
m_Department_list = new ArrayList<String>();
m_DepartmentID_list = new ArrayList<String>();
for (int i = 0; i < DepartmentDetails.length(); i++)
{
JSONObject m_DepartmentDetails = DepartmentDetails.getJSONObject(i);
if (!m_DepartmentDetails.getString("ProjectName").equalsIgnoreCase("null")&& !m_DepartmentDetails.getString("ProjectName").equalsIgnoreCase(""))
{
//list.add(m_DepartmentDetails.getString("ProjectName"));
m_Department_list.add(m_DepartmentDetails.getString("ProjectName"));
//Toast.makeText(getBaseContext(), m_DepartmentDetails.getString("ProjectName"), Toast.LENGTH_LONG).show();
}
if (!m_DepartmentDetails.getString("ProjectID").equalsIgnoreCase("null")&& !m_DepartmentDetails.getString("ProjectID").equalsIgnoreCase(""))
{
m_DepartmentID_list.add(m_DepartmentDetails.getString("ProjectID"));
}
}
}
s1 = (Spinner) findViewById(R.id.spinner1);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, R.layout.spin,m_Department_list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
if (m_DepartmentID_list.contains(m_DepartmentID))
{
s1.setSelection(m_DepartmentID_list.indexOf(m_DepartmentID));
}
}
catch (final JSONException e)
{
}
}
}, "http://aapnapms.azurewebsites.net/Service1/Project", finaldata,
"POST");
connect.execute(finaldata);
if(!validate())
Toast.makeText(getBaseContext(), "Enter some data !", Toast.LENGTH_LONG).show();
}
catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
}
Use
s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
instead of
s1.setOnClickListener(this);

Not getting the correct data on clicking the LISTVIEW

I have 3 list in my fragment i.e. list 1,list2 and list3. And all are interdependent.I'm using AsyncTask for showing these list.
When i click on list 1 its shows some data on list 3 and so on when i clik on list 2 it shows data on list3.
Now the problem is there is a next button,if i don't click on list 2 and press next it does not show the correct data.
list 2 returns null and thus does not functional correct.
Below is the code
public class Browse extends Fragment {
ActionBar actionBar;
ListView listView1, listView2, listView3;
ArrayList<String> englishList = new ArrayList<String>();
ArrayList<String> hindiList = new ArrayList<String>();
ArrayList<String> alist1 = new ArrayList<String>();
ArrayList<String> alist2 = new ArrayList<String>();
String response, reply;
TextView tv2;
Browse_Adapter ListAdapter, ListAdapter1;
Browse_Adapter2 adpter2;
LinearLayout linera_t_Layout_1;
boolean result = false;
TextView prev, next;
int pageno = 0, epp;
String txt;
protected String resourceType;
String s;
Context context;
File dbFile1_,dbFile2_,dbFile;
ProgressDialog loadingDialog;
public String DB1 = "sk1.db";
public String DB2 = "sk2.db";
String global,list1_global="a";
Boolean list_flag;
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.browse, container, false);
actionBar=getActivity().getActionBar();
MainActivity.state="browse";
context=getActivity().getBaseContext();
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US")) {
actionBar.setTitle(getResources().getString(R.string.browse_en));
} else {
actionBar.setTitle(getResources().getString(R.string.browse_hi));
}
/* PREVIOUS AND NEXT TEXTVIEWS CLICKLISTENERS */
prev = (TextView) rootView.findViewById(R.id.prev);
next = (TextView) rootView.findViewById(R.id.next);
// listView 1
listView1 = (ListView) rootView.findViewById(R.id.listView1);
// listView 2
listView2 = (ListView) rootView.findViewById(R.id.listView2);
// listView 3
listView3 = (ListView) rootView.findViewById(R.id.listView3);
listView1.setChoiceMode(1);
listView2.setChoiceMode(1);
listView3.setChoiceMode(1);
View view = inflater.inflate(R.layout.browse, null);
resourceType = (String) view.getTag();
if (resourceType.equals("large")) {
epp = 25;
} else if (resourceType.equals("normal"))
{
epp = 17;
} else if (resourceType.equals("small"))
{
epp = 12;
}
if (!InternetConnection.isInternetOn(context))
{
s= Environment.getExternalStorageDirectory() .toString();
dbFile1_ = new File(s,"sk1.db");
if(!filter.accept(dbFile1_)){
final AlertDialog.Builder alertbox = new AlertDialog.Builder(getActivity());
alertbox.setTitle("Shabdkosh Dictionary");
alertbox.setMessage("Internet connection is not available.");
alertbox.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
}
});
alertbox.show();
}
else{
listView1.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
final TextView textView = (TextView) view
.findViewById(R.id.text);
if (alist1.size() > 0) {
alist1.clear();
}
if (alist2.size() > 0) {
alist2.clear();
}
prev.setVisibility(View.GONE);
pageno = 0;
textView.setBackgroundColor(getResources().getColor(R.color.text_color));
int DELAY = 200;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
textView.setBackgroundColor(getResources().getColor(
R.color.White));
}
}, DELAY);
txt = textView.getText().toString();
list_flag=true;
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US")) {
new brs(getActivity()).execute();
//new brs_wd(getActivity(),pageno,list1_global).execute();
} else {
new brs(getActivity()).execute();
//new brs_wd(getActivity(),pageno,list1_global).execute();
}
}
});
}
}
else{
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
final TextView textView = (TextView) view
.findViewById(R.id.text);
if (alist1.size() > 0) {
alist1.clear();
}
if (alist2.size() > 0) {
alist2.clear();
}
prev.setVisibility(View.GONE);
pageno = 0;
textView.setBackgroundColor(getResources().getColor(R.color.text_color));
int DELAY = 200;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
textView.setBackgroundColor(getResources().getColor(
R.color.White));
}
}, DELAY);
txt = textView.getText().toString();
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US")) {
list_flag=true;//
new brs(getActivity()).execute();
} else {
new brs(getActivity()).execute();
}
}
});
}
prev.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
list_flag=false;
prev.setTextColor((getResources().getColor(R.color.more_changed)));
int DELAY = 200;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
prev.setTextColor((getResources().getColor(R.color.text_color)));
}
}, DELAY);
if (alist2.size() > 0) {
alist2.clear();
}
if (pageno > 0) {
pageno = pageno - 1;
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US")) {
new brs_wd(getActivity(),pageno,global).execute();
} else {
new brs_wd(getActivity(),pageno,global).execute();
}
}
else {
prev.setVisibility(View.GONE);
}
}
});
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
list_flag=false;//
next.setTextColor((getResources().getColor(R.color.more_changed)));
int DELAY = 200;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
next.setTextColor((getResources().getColor(R.color.text_color)));
}
}, DELAY);
prev.setVisibility(View.VISIBLE);
prev.setText("<<Prev");
if (alist2.size() > 0) {
alist2.clear();
}
pageno = pageno + 1;
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US")) {
new brs_wd(getActivity(),pageno,global).execute();
} else {
new brs_wd(getActivity(),pageno,global).execute();
}
}
});
englishList.addAll(Arrays.asList("A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
"T", "U", "V", "W", "X", "Y", "Z"));
hindiList.addAll(Arrays.asList("अ", "आ", "इ", "ई", "उ", "ऊ", "à¤", "à¤",
"ओ", "औ", "अà¤", "आà¤", "ऋ", "क", "ख", "ग", "घ", "ङ", "च", "छ",
"ज", "à¤", "ञ", "ट", "ठ", "ड", "ढ", "ण", "त", "थ", "द", "ध",
"न", "प", "फ", "ब", "भ", "म", "य", "र", "ल", "व", "श", "ष",
"स", "ह", "कà¥à¤·" , "तà¥à¤°","जà¥à¤ž"));
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US"))
{try{
Browse_Adapter listAdapter1 = new Browse_Adapter(context,
R.layout.browse_list_item, englishList);
if(listAdapter1!=null)
listView1.setAdapter(listAdapter1);}
catch(Exception e){e.printStackTrace();}
} else {
Browse_Adapter listAdapter1 = new Browse_Adapter(context,
R.layout.browse_list_item, hindiList);
if(listAdapter1!=null)
listView1.setAdapter(listAdapter1);
}
listView2.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos,long id)
{
String item = (String)parent.getItemAtPosition(pos);
global=item;
if (alist2.size() > 0)
{
alist2.clear();
}
pageno = 0;
final TextView textView = (TextView) view
.findViewById(R.id.text_browsword);
textView.setTextColor(getResources().getColor(
R.color.text_color));
int DELAY = 200;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
textView.setTextColor(getResources().getColor(
R.color.White));
}
}, DELAY);
//list1_global=alist1.get(0);
list_flag=false;
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US")) {
new brs_wd(getActivity(),pageno,item).execute();
} else {
new brs_wd(getActivity(),pageno,item).execute();
}
}
});
listView3.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
final TextView textView = (TextView) view
.findViewById(R.id.text_browsword);
if (InternetConnection.isInternetOn(context)) {
SearchData_DTO.setSearchData_DTO(new SearchData()
.getSearched(textView.getText().toString(),
context));
} else {
SearchData_DTO.setSearchData_DTO(new SearchDataDB()
.getSearchedDB(textView.getText().toString(),
context));
}
Intent i = new Intent(context, Search.class);
i.putExtra("selected", textView.getText().toString().replace("(m)", "").replace("(f)", "") .replace("(n)", ""));
startActivity(i);
}
});
setHasOptionsMenu(true);
return rootView;
}
public void onPrepareOptionsMenu(Menu menu)
{
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US"))
{
menu.removeItem(R.id.English);
menu.removeItem(R.id.Gujarati);
menu.removeItem(R.id.Punjabi);
menu.removeItem(R.id.Bengali);
menu.removeItem(R.id.Marathi);
menu.removeItem(R.id.Talugu);
menu.removeItem(R.id.Tamil);
} else
{
menu.removeItem(R.id.Hindi);
menu.removeItem(R.id.Gujarati);
menu.removeItem(R.id.Punjabi);
menu.removeItem(R.id.Bengali);
menu.removeItem(R.id.Marathi);
menu.removeItem(R.id.Talugu);
menu.removeItem(R.id.Tamil);
}
return;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
item.collapseActionView();
if (R.id.Hindi == item.getItemId()) {
android.support.v4.app.FragmentManager fragmentManager = getChildFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, new Browse());
fragmentTransaction.commit();
}
if (R.id.English == item.getItemId()) {
android.support.v4.app.FragmentManager fragmentManager = getChildFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, new Browse());
fragmentTransaction.commit();
}
return super.onOptionsItemSelected(item);
}
public boolean browseLetter(final String query, final Context context,final String lang, final String tl)
{
if (InternetConnection.isInternetOn(context))
{
try {
response = CustomHttpClient.executeHttpGet(BROWSE_URL+ "sl=" + lang + "&tl=" + tl+ "&t=1&epp=0&p=1&e=" + query);
if (response != null) {
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
alist1.add(arr.getString(i));
}
result = true;
Log.v("--------list1----------", alist1.toString());
}
} catch (Exception e) {
Log.e("/////////////////////////Exception in LIST1 ", e.toString());
}
return true;
} else
{
if (!InternetConnection.isInternetOn(context)) {
s = Environment.getExternalStorageDirectory().toString();
dbFile1_ = new File(s, "sk1.db");
dbFile2_ = new File(s, "sk2.db");
if(dbFile1_.exists()||dbFile2_.exists())
{
/* do something */
alist1 = new ArrayList<String>(new SearchDataDB().ltwo(context,query, lang));
}
else
{
final AlertDialog.Builder alertbox = new AlertDialog.Builder(getActivity());
alertbox.setTitle("Error");
alertbox.setMessage("Internet connection is not available.");
alertbox.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
}
});
alertbox.show();
}
}
try{
Browse_Adapter2 listAdapter2 = new Browse_Adapter2(context,R.layout.browse_list_item, alist1);
if(listAdapter2!=null)
listView2.setAdapter(listAdapter2);
result = true;
}
catch(Exception e){e.printStackTrace();}
}
return result;
}
public String browseWord(final String query, final Context context,final String lang, final String tl, final int epp, final int p,String letter)
{
if (InternetConnection.isInternetOn(context))
{
try {
response = CustomHttpClient.executeHttpGet(BROWSE_WORD+ "sl=" + lang + "&tl=" + tl + "&t=2&epp="+ epp + "&p=" + p + "&e=" + query);//
if (response != null) {
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
alist2.add(arr.getString(i));
}
}
} catch (Exception e)
{
Log.e("/////////////////////////Exception in LIST2 ", e.toString());
}
return response;
} else {
if (!InternetConnection.isInternetOn(context))
{
alist2 = new ArrayList<String>(new SearchDataDB().bword(context, query, lang));
try{
Browse_Adapter2 listAdapter3 = new Browse_Adapter2(context,R.layout.browse_list_item, alist2);
if(listAdapter3!=null)
listView3.setAdapter(listAdapter3);}
catch(Exception e)
{
e.printStackTrace();
}
txt = query;
if (alist2.size() < epp) {
next.setText("");
}
if (pageno == 0)
prev.setVisibility(View.GONE);
}
}
return response;
}
FileFilter filter = new FileFilter() {
#Override
public boolean accept(File pathname) {
if(pathname.isFile()){
return true;
}
else{
return false;
}
}
};
class brs extends AsyncTask<Object ,Object ,Object >
{
//context=getActivity().getBaseContext();
Activity context;
public brs(Activity context)
{
loadingDialog = new ProgressDialog(context);
this.context=context;
}
#Override
protected void onPreExecute()
{
//loadingDialog= new ProgressDialog(getActivity().getBaseContext());
loadingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
loadingDialog.setMessage("Please wait...");
loadingDialog.setCancelable(false);
loadingDialog.show();
super.onPreExecute();
};
#Override
protected Object doInBackground(Object... params)
{
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US"))
{
return browseLetter(txt,context, "en", "hi");
}
else
{
return browseLetter(txt,context, "hi", "en");
}
}
protected void onPostExecute(Object result)
{
try{
if(alist1!=null)
{
//list1_global=alist1.get(0);
Log.v("---------------list1--------------", "list1"+alist1);
Browse_Adapter2 listAdapter2 = new Browse_Adapter2(context,R.layout.browse_list_item, alist1);
if(listAdapter2!=null)
listView2.setAdapter(listAdapter2);}
else{
Log.v("--------------list1--------------", "list1"+alist1);
}
//loadingDialog.dismiss();
}
catch(Exception e)
{
e.printStackTrace();
}
new brs_wd(getActivity(),pageno,list1_global).execute();
//loadingDialog.dismiss();
}
}
class brs_wd extends AsyncTask<Object ,Object ,String>
{
int pg;
Activity context;
String list2word;
public brs_wd(Activity context,int page_no,String list2word)
{
//loadingDialog = new ProgressDialog(context);
this.context=context;
this.pg=page_no;
if(list_flag)
{
this.list2word=txt;
}
else{
this.list2word=list2word;
}
}
#Override
protected void onPreExecute()
{
/*//loadingDialog= new ProgressDialog(getActivity().getBaseContext());
loadingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
loadingDialog.setMessage("Please wait...");
loadingDialog.setCancelable(false);
loadingDialog.show();*/
super.onPreExecute();
};
#Override
protected String doInBackground(Object... params)
{
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US"))
{
return browseWord(list2word, context, "en", "hi", epp, pg,list2word);
}
else
{
return browseWord(list2word, context, "hi", "en", epp, pg,list2word);
}
}
protected void onPostExecute(String query)
{
try{
Log.d("-------------List2--------", alist2+"");
if(alist2!=null){
Browse_Adapter2 listAdapter3 = new Browse_Adapter2(context, R.layout.browse_list_item, alist2);
if(listAdapter3!=null)
listView3.setAdapter(listAdapter3);
txt = query;
if (alist2.size() < epp) {
next.setText("");
} else {
next.setText("Next>>");
}
if (pageno == 0)
prev.setVisibility(View.GONE);}
else{
Log.d("-------------------List2--------------", "empty"+alist2);
}
}
catch(Exception e)
{
e.printStackTrace();
}
loadingDialog.dismiss();
}
}
}
help me for this.

When I press backspace did the AutoCompleteTextView show the suggestion list

My code is following ...
public class NameListActivity extends Activity implements TextWatcher {
private Button add = null;
private AutoCompleteTextView editAuto = null;
private Button chfrlist = null;
private ImageView im = null;
String access_token = new String();
private ImageView infobtn = null;
private PopupWindow popupWindow;
private View view;
private ProgressDialog pd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_name_list);
access_token = MainService.readToken();
add = (Button) findViewById(R.id.add_button);
editAuto = (AutoCompleteTextView) findViewById(R.id.editAuto);
chfrlist = (Button) findViewById(R.id.chfrlistbutton);
im = (ImageView) findViewById(R.id.helpact);
im.setOnClickListener(new ImageListener());
infobtn = (ImageView) findViewById(R.id.informbtn);
initPopupWindow();
infobtn.setOnClickListener(new infobtnListener());
editAuto.addTextChangedListener(this);
add.setOnClickListener(new addListener());
chfrlist.setOnClickListener(new ChfrListListener());
}
public class addListener implements OnClickListener {
public void onClick(View v) {
addTask task = new addTask();
task.execute();
editAuto.setText("");
}
}
public void afterTextChanged(Editable arg0) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
onTextChangedTask task = new onTextChangedTask();
task.execute();
}
public class onTextChangedTask extends AsyncTask<Void, Void, Void> {
ArrayAdapter<String> adapter = null;
String[] userName = null;
String q = null;
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = null;
ArrayList<String> userNameArrayList = new ArrayList<String>();
Weibo weibo = new Weibo();
#Override
protected void onPreExecute() {
weibo.setToken(access_token);
q = editAuto.getText().toString();
System.out.println("start onTextChanged");
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
if (q.length() != 0) {
System.out.println("q is " + q);
String s1 = "https://api.weibo.com/search/suggestions/users.json";
try {
jsonArray = Weibo.client.get(s1,
new PostParameter[] { new PostParameter("q", q) })
.asJSONArray();
} catch (Throwable e) {
System.out.println("这里有个神马异常呢 。。。" + e);
}
System.out.println("return length is " + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
try {
jsonObject = jsonArray.getJSONObject(i);
String sname = jsonObject.getString("screen_name");
userNameArrayList.add(sname);
} catch (JSONException e) {
e.printStackTrace();
}
}
userName = (String[]) userNameArrayList
.toArray(new String[userNameArrayList.size()]);
adapter = new ArrayAdapter<String>(NameListActivity.this,
android.R.layout.simple_dropdown_item_1line, userName);
}
return null;
}
#Override
protected void onPostExecute(Void v) {
System.out.println("post");
editAuto.setAdapter(adapter);
}
}
void showToast(String s) {
Toast toast = Toast.makeText(getApplicationContext(), s,
Toast.LENGTH_LONG);
toast.show();
}
public class addTask extends AsyncTask<Void, Void, Void> {
String s = null;
boolean flag = false;
User user = null;
Weibo weibo = new Weibo();
String screen_name = null;
protected void onPreExecute() {
Toast tt = Toast.makeText(getApplicationContext(), "正在将用户添加到备份名单",
Toast.LENGTH_LONG);
tt.setGravity(Gravity.CENTER, 0, 0);
tt.show();
weibo.setToken(access_token);
screen_name = editAuto.getText().toString();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
if (screen_name.length() != 0) {
Users um = new Users();
try {
user = new User(Weibo.client.get(
"https://api.weibo.com/users/show.json",
new PostParameter[] { new PostParameter(
"screen_name", screen_name) })
.asJSONObject());
} catch (Throwable e) {
e.printStackTrace();
flag = true;
s = new String("您输入的这个用户好像不存在唉");
}
if (user != null) {
ContentValues values = new ContentValues();
values.put("uid", user.getId());
values.put("user_name", user.getName());
SQLiteDatabase db = null;
try {
db = MainService.getDatabase();
} catch (Exception e) {
System.out.println("db error");
finish();
}
Cursor result = db.query("users", new String[] { "uid",
"user_name" }, "uid=?",
new String[] { user.getId() }, null, null, null);
if (result.getCount() == 0)
db.insert("users", null, values);
} else {
flag = true;
s = new String("网络存在问题,检查一下吧");
}
} else {
flag = true;
s = new String("框里输入点东西才能添加啊");
}
return null;
}
#Override
protected void onPostExecute(Void v) {
if (flag == true) {
System.out.println("要打印的是" + s);
showToast(s);
}
}
}
public class infobtnListener implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.println("点击了图片");
ColorDrawable cd = new ColorDrawable(-0000);
popupWindow.setBackgroundDrawable(cd);
// popupWindow.showAsDropDown(v);
popupWindow.showAtLocation(findViewById(R.id.informbtn),
Gravity.LEFT | Gravity.BOTTOM, 0, 100);
}
}
public class ImageListener implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
// Intent t = new Intent(NameListActivity.this,
// GridLayoutActivity.class);
// startActivity(t);
finish();
}
}
public class ChfrListListener implements OnClickListener {
public void onClick(View v) {
if ((haveInternet() == true)
&& (GridLayoutActivity.hasAccessToken() == true)) {
// TODO Auto-generated method stub
pd = ProgressDialog.show(NameListActivity.this, "",
"正在从服务器上获取数据,可能需要较长时间,请耐心等待 ...");
/* 开启一个新线程,在新线程里执行耗时的方法 */
new Thread(new Runnable() {
public void run() {
Intent t = new Intent(NameListActivity.this,
ChooseFromListActivity.class);
startActivity(t);
finish();
handler.sendEmptyMessage(0);// 执行耗时的方法之后发送消给handler
}
}).start();
} else {
Intent t = new Intent(NameListActivity.this,
WebViewActivity.class);
startActivity(t);
finish();
}
}
}
private void initPopupWindow() {
view = getLayoutInflater().inflate(R.layout.namewindow, null);
popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
// 这里设置显示PopuWindow之后在外面点击是否有效。如果为false的话,那么点击PopuWindow外面并不会关闭PopuWindow。
popupWindow.setOutsideTouchable(true);// 不能在没有焦点的时候使用
}
private boolean haveInternet() {
NetworkInfo info = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo();
if (info == null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) {
// here is the roaming option you can change it if you want to
// disable internet while roaming, just return false
return true;
}
return true;
}
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {// handler接收到消息后就会执行此方法
pd.dismiss();// 关闭ProgressDialog
}
};
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_name_list, menu);
return true;
}
}
My question is : when I input words in the EditText, nothing happened. But when I press backspace did the AutoCompleteTextView show the suggestion list ... the problem is in the editAuto.setAdapter(adapter);
What is wrong?
make the following changes in your code
1) Instead of
private AutoCompleteTextView editAuto = null; JUST WRITE private AutoCompleteTextView editAuto;
2) Add this line to onCrate()
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, <your array name here>);
and remove this line from onTextChangedTask()
ArrayList<String> userNameArrayList = new ArrayList<String>();
3) Add this line to onCrate()
editAuto.setAdapter(adapter);
I know this is way late but for those who face similar problems here is the solution to show the autoCompleteTextView's drop down whenever you want i.e on button click or onTextChanged. After you set the ArrayAdapter for the autoCompleteTextView just put the following line.
autoCompleteTextView.showDropDown();

android - update progressbar

I would like to update spinner object after I get a google calendar name in a different thread. When I execute this, it crashes. I am not sure if I need to make it work with a different approach or if there is something wrong with it.
private void updateGoogleCalendar() {
try {
Thread.sleep(4000);
List<String> list = new ArrayList<String>();
list.add("Sample Calendar");
updatedCalendarNames = list.toArray(new String[0]);
progressBar.dismiss();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void initializeWidgets() {
final Spinner spinner = (Spinner) layout.findViewById(R.id.googleCalendarSelection);
final Button refreshCalendarBtn = (Button) layout.findViewById(R.id.refreshCalendarBtn);
refreshCalendarBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
progressBar = ProgressDialog.show(getContext(), "", "Loading...");
new Thread(new Runnable() {
#Override
public void run() {
updateGoogleCalendar();
final ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(getContext(), android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
while (updatedCalendarNames == null) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (String calendarName : updatedCalendarNames) {
CharSequence charSequence = calendarName + "";
adapter.add(charSequence);
}
}
}).start();
}
});
}
you need to add your ui update code into event thread only, and to notify UI/Event Thread you need to implement Handler or AsyncTask, for example you can update by handler as follows:
public void initializeWidgets() {
final Spinner spinner = (Spinner) layout.findViewById(R.id.googleCalendarSelection);
final Button refreshCalendarBtn = (Button) layout.findViewById(R.id.refreshCalendarBtn);
refreshCalendarBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
progressBar = ProgressDialog.show(getContext(), "", "Loading...");
new Thread(new Runnable() {
#Override
public void run() {
updateGoogleCalendar();
final ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(getContext(), android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
while (updatedCalendarNames == null) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (String calendarName : updatedCalendarNames) {
Message msg=handler.obtainMessage();
msg.obj = calendarName + "";
handler.sendMessage(msg);
}
}
}).start();
}
});
}
Handler handler=new Handler()
{
public void handleMessage(Message msg)
{
String str=(String)msg.obj;
adapter.add(charSequence);
}
};
You don't say where it crashes or how, but I imagine it might be due to you trying to update the UI from a non-UI thread. Take a look at the AsyncTask (see here) for information.

Categories

Resources