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
Related
I currently working with a project and stuck on the radio button which getting only the checked radio in xml, I search many case regarding with this concern and still got the same problem.
here is the activity which toasting only the checked radio in xml
package com.example.kapoyei.hatidtubiganapp;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.kapoyei.hatidtubiganapp.helper.Http;
import com.example.kapoyei.hatidtubiganapp.helper.Network;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
public class ClientActivity extends Activity implements View.OnClickListener {
public static String jsonObject;
SharedPreferences sharedPref;
Intent i;
Button btnLogout, btnBreakPoint;
Spinner spnStation;
ImageView btnReserve, btnStationList, btnPending, btnHistory;
TextView txtSelectDate;
EditText no_container;
RadioGroup radioGroup;
RadioButton radioButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnReserve = (ImageView) findViewById(R.id.btnReserve);
btnStationList = (ImageView) findViewById(R.id.btnStation);
btnPending = (ImageView) findViewById(R.id.btnPending);
btnHistory = (ImageView) findViewById(R.id.btnHistory);
btnPending.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
i = new Intent(ClientActivity.this, PendingClientOrderActivity.class);
startActivity(i);
}
});
btnStationList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
i = new Intent(ClientActivity.this, StationList.class);
startActivity(i);
}
});
btnReserve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(ClientActivity.this);
LayoutInflater inflater = getLayoutInflater();
view = inflater.inflate(R.layout.layout_dialog_reserve, null);
spnStation = (Spinner) view.findViewById(R.id.spnStation);
txtSelectDate = (TextView) view.findViewById(R.id.txtDate);
no_container = (EditText) view.findViewById(R.id.etContainer);
radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
radioButton = (RadioButton) view.findViewById(radioGroup.getCheckedRadioButtonId());
btnBreakPoint = (Button) view.findViewById(R.id.btnBreakPoint);
final Calendar c = Calendar.getInstance();
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, day);
String dateFormat = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat, Locale.US);
txtSelectDate.setText(sdf.format(c.getTime()));
}
};
txtSelectDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new DatePickerDialog(ClientActivity.this,
date,
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH)).show();
}
});
btnBreakPoint.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(no_container.getText().toString().isEmpty() || txtSelectDate.getText().toString().equalsIgnoreCase("-- CLICK TO DATE DELIVER --")) {
Toast.makeText(getApplicationContext(), "All fields require", Toast.LENGTH_SHORT).show();
} else {
/*Bundle bundle = new Bundle();
bundle.putString("station", spnStation.getSelectedItem().toString());
bundle.putString("date", txtSelectDate.getText().toString());
bundle.putString("no_container", no_container.getText().toString());
bundle.putString("type", Integer.toString(radioGroup.getCheckedRadioButtonId()));
i = new Intent(ClientActivity.this, CheckOut.class);
i.putExtras(bundle);
startActivity(i);*/
String typeOrder = radioButton.getText().toString();
Toast.makeText(getApplicationContext(), typeOrder, Toast.LENGTH_LONG).show();
}
}
});
Network network = new Network(getApplicationContext());
if(network.isNetwork()) {
new ClientActivity.GetStationList().execute();
} else {
Toast.makeText(getApplicationContext(), "Coud not get stations", Toast.LENGTH_SHORT).show();
}
builder.setView(view);
builder.setCancelable(true);
AlertDialog dialog = builder.create();
dialog.show();
}
});
btnHistory.setOnClickListener(this);
btnLogout.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if(view.getId() == R.id.btnLogout) {
finish();
sharedPref = getSharedPreferences("ht", MODE_PRIVATE);
SharedPreferences.Editor modify = sharedPref.edit();
modify.putBoolean("login", false);
modify.putString("id", "");
modify.putString("auth", "");
modify.apply();
i = new Intent(ClientActivity.this, LoginActivity.class);
startActivity(i);
}
if(view.getId() == R.id.btnHistory) {
i = new Intent(ClientActivity.this, HistoryActivity.class);
startActivity(i);
}
}
public class GetStationList extends AsyncTask<Void, Void, String> {
ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ClientActivity.this);
pd.setMessage("Getting station ...");
pd.setCancelable(false);
pd.show();
}
#Override
protected void onPostExecute(String result) {
pd.cancel();
json(result);
}
#Override
protected String doInBackground(Void... voids) {
String data = "";
jsonObject = "";
try {
String link = (String) Http.url + "?type=getstationlist";
URL getURL = new URL(link);
HttpURLConnection httpURLConnection = (HttpURLConnection) getURL.openConnection();
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
InputStream is = (InputStream) httpURLConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while((data = reader.readLine()) != null) {
jsonObject += data;
}
Log.i("", jsonObject);
return jsonObject;
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
public void json(String json) {
List<String> collectionName = new ArrayList<>();
if(json != null) {
try {
JSONObject jobj = new JSONObject(json);
JSONArray jarray = jobj.getJSONArray("stationlist");
String name = "";
String id = "";
for(int i = 0; i < jarray.length(); i++) {
JSONObject obj = jarray.getJSONObject(i);
name = obj.getString("name");
collectionName.add(name);
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(getBaseContext(), android.R.layout.simple_list_item_1, collectionName);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnStation.setAdapter(adapter);
} catch(Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Connection problem", Toast.LENGTH_SHORT).show();
}
}
}
}
and here is the xml where located the layout of my radio
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Station"
android:layout_margin="10dp"
android:textSize="20sp"/>
<Spinner
android:id="#+id/spnStation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Date"
android:layout_margin="10dp"
android:textSize="20sp"/>
<TextView
android:id="#+id/txtDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="-- CLICK TO DATE DELIVER --"
android:textSize="15sp"
android:layout_margin="10dp"
android:layout_gravity="center"
android:textAlignment="center"/>
<EditText
android:id="#+id/etContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="No. Of Containers"
android:layout_margin="10dp"/>
<RadioGroup
android:id="#+id/radioGroup"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioButton
android:id="#+id/Gallon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Gallon"
android:checked="true"/>
<RadioButton
android:id="#+id/Litre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Litre" />
</RadioGroup>
<Button
android:id="#+id/btnBreakPoint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_margin="10dp"
android:text="Proceed to Check Out" />
</LinearLayout>
</RelativeLayout>
You can apply the below codes:
int radioid = radioButtonGroup.getCheckedRadioButtonId();
View radio_button= radioButtonGroup.findViewById(radioButtonID);
int index = radioButtonGroup.indexOfChild(radioButton);
If the RadioGroup contains other Views (like a TextView) then the indexOfChild() method will return wrong index.
To get selected RadioButton Text on RadioGroup follow the below code:
RadioButton radio = (RadioButton) radioButtonGroup.getChildAt(index);
String text = radio.getText().toString();
Why this is happened? Because before you click Break Point button, you change the radio button id but not bind it to your variable, your variable still storing the old value. You need to add this code
radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
radioButton = (RadioButton) view.findViewById(radioGroup.getCheckedRadioButtonId());
above
String typeOrder = radioButton.getText().toString();
so it will shown
btnBreakPoint.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
...
radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
radioButton = (RadioButton) view.findViewById(radioGroup.getCheckedRadioButtonId());
String typeOrder = radioButton.getText().toString();
...
}
or you can move the scope of radioGroup assignment to onCreate scope
I want to add currency converter in side menu of my app. But i am unable to get conversion after on click().
On click "calculate" i am not getting conversion.
Please see the code why i am not able to click . I have used yahoo api.
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;
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 rootView) {
//t.setText(exResult);
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();
}
}
}
});
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);
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();
}
return s;
}
#Override
protected void onPostExecute(String exResult) {
// t = (TextView) rootView.findViewById(R.id.textView4);
// t.setText(exResult);
}
}
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();
}
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:
05-09 17:33:30.425 2238-2238/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: info.androidhive.customlistviewvolley, PID: 2238
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:156)
at org.json.JSONObject.<init>(JSONObject.java:173)
at info.androidhive.customlistviewvolley.model.CurrencyConverter$1.onClick(CurrencyConverter.java:74)
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)
05-09 17:33:30.430 1233-1513/? W/ActivityManager: Force finishing activity info.androidhive.customlistviewvolley/.MainActivity
You are trying to invoke String from UI thread that has no connection to it. As one of the possible workarounds you can create global variable and assign to it at
#Override
protected void onPostExecute(String exResult) {
// t = (TextView) rootView.findViewById(R.id.textView4);
// t.setText(exResult);
globalString = exResult;
}
Afterwards you can use it code. Please read about AsyncTask lifecycle and Android Threads.
updated Answer:
CurreencyConverter.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 am creating an eWallet application like many existing ones. I have lots of classes that do different stuff but i need some advice in a group of them. I have created a listview witch fetches the categories i have created and saved in a phpMyAdmin database. I am displaying this data on a list view successfully. This list view just shows the list of the categories to the user and if he clicks a list item a new activity appers which llows him to edit or delete the list item.
Now i used the same code (i lterally used the same code!) to create a second listview inside a dialog box. Imagine that this listview appears inside the dialog box when i click an edit text which has an on click listener. I successfully display the data in this second list view as well. Now on this dialog box when i click a list item/category (lets say Sports category) i want the name of the edit text to change to the category i chose. But i am confused because i use the same code and methods that open the edit and delete activity on my first list view. I hope i did not confuse you too much.
Here is the code that downloads the data in my list views.
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.ListView;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class ExDownloaderActivity extends AsyncTask<Void, Integer, String>
{
Context context;
String address;
ListView expenseListView;
ProgressDialog progressDialog;
public ExDownloaderActivity(Context context, String address, ListView exCategoryListView)
{
this.context = context;
this.address = address;
this.expenseListView = exCategoryListView;
}
//B4 JOB STARTS
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Fetch Data");
progressDialog.setMessage("Fetching Data...Please wait");
progressDialog.show();
}
#Override
protected String doInBackground(Void... params)
{
String data = downloadData();
return data;
}
#Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String string)
{
super.onPostExecute(string);
progressDialog.dismiss();
if(string != null)
{
ExParserActivity parser = new ExParserActivity(context, string, expenseListView);
parser.execute();
}
else
{
Toast.makeText(context, "Unable to download data",Toast.LENGTH_LONG).show();
}
}
private String downloadData()
{
//connect and get a stream of data
InputStream inputStream = null;
//to store each line
String line = null;
try
{
URL url = new URL(address);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer stringBuffer = new StringBuffer();
if(bufferedReader!= null)
{
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line + "\n");
}
}
else
{
return null;
}
return stringBuffer.toString();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if(inputStream != null)
{
try
{
inputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return null;
}
}
Second Class
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class ExParserActivity extends AsyncTask<Void, Integer, Integer>
{
Context context;
ListView exListView;
String data;
ArrayList<String> exCategories = new ArrayList<>();
ProgressDialog progressDialog;
public ExParserActivity(Context context, String data, ListView lv)
{
this.context = context;
this.data = data;
this.exListView = lv;
}
//B4 JOB STARTS
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Parser");
progressDialog.setMessage("Parsing...Please wait");
progressDialog.show();
}
//Heavy job
#Override
protected Integer doInBackground(Void... params)
{
return this.parse();
}
#Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Integer integer)
{
super.onPostExecute(integer);
progressDialog.dismiss();
if(integer == 1)
{
//ADAPTER
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, exCategories);
//ADAPT TO LIST VIEW
exListView.setAdapter(arrayAdapter);
//ON CLICK LISTENER
exListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
context.startActivity(new Intent(context, UpdateDeleteExCategories.class));
//Snackbar.make(view, exCategories.get(position), Snackbar.LENGTH_SHORT).show();
}
});
}
else
{
Toast.makeText(context, "Unable to Parse", Toast.LENGTH_LONG).show();
}
}
//PARSE RECEIVED DATA
private int parse()
{
try
{
//ADD THAT DATA TO JSON ARRAY FIRST
JSONArray jsonArray = new JSONArray(data);
//CREATE JO OBJECT TO HOLD A SINGLE ITEM
JSONObject jsonObject = null;
exCategories.clear();
//LOOP THROUGH THE ARRAY
for(int i = 0; i < jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
//RETRIEVE NAME
String exCatName = jsonObject.getString("exCatName");
//ADD IT TO ARRAY LIST
exCategories.add(exCatName);
}
//IF ITS SUCCESSFUL RETURN 1
return 1;
}
catch (JSONException e)
{
e.printStackTrace();
}
//IF IT IS NOT SUCCESSFUL RETURN 0
return 0;
}
}
Third Class
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.Calendar;
public class AddExpenseActivity extends SwipeFunctionActivity
{
private ImageView backImageView;
private TextView setDateTextView;
private EditText categoryEditText, amountEditText;
int year, month, day;
static final int DIALOG_ID = 0; //Initialise the variable to 0.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_expense);
final Calendar calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
setDateTextView = (TextView)findViewById(R.id.setDateTextView);
backImageView = (ImageView)findViewById(R.id.backImageView);
categoryEditText = (EditText)findViewById(R.id.categoryEditText);
amountEditText = (EditText)findViewById(R.id.amountEditText);
setDateTextView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
showDialog(DIALOG_ID);
}
});
categoryEditText.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
pickCategoryMethod();
}
});
backImageView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
backMethod();
}
});
}
#Override
protected Dialog onCreateDialog(int id)
{
if (id == DIALOG_ID)
{
return new DatePickerDialog(this, dpickerListener, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener dpickerListener = new DatePickerDialog.OnDateSetListener()
{
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
AddExpenseActivity.this.year = year;
month = monthOfYear + 1;
day = dayOfMonth;
showDate(AddExpenseActivity.this.year, month, day);
//Toast.makeText(AddExpenseActivity.this, "Selected date: " + dayOfMonth + " / " + (monthOfYear+1) + " / " + year, Toast.LENGTH_LONG).show();
}
};
private void showDate(int year, int month, int day)
{
setDateTextView.setText(new StringBuilder().append(day).append("/")
.append(month).append("/").append(year));
}
public void pickCategoryMethod()
{
String url = "http://192.168.0.3/myapp/fexcateg.php";
//
final Dialog dialog = new Dialog(AddExpenseActivity.this);
dialog.setContentView(R.layout.activity_pick_category);
dialog.setTitle(" Pick your Category");
final ListView pickCategoryListView = (ListView)dialog.findViewById(R.id.pickCategoryListView);
final ExDownloaderActivity downloader = new ExDownloaderActivity(this, url, pickCategoryListView);
//Execute download
downloader.execute();
//pickCategoryListView = (ListView)dialog.findViewById(R.id.pickCategoryListView);
//This makes the dialog visible.
dialog.show();
}
public void backMethod()
{
//startActivity(new Intent(getApplicationContext(), BalanceActivity.class));
finish();
}
#Override
public void onSwipeLeft()
{
super.onSwipeLeft();
startActivity(new Intent(getApplicationContext(), AddIncomeActivity.class));
finish();
}
#Override
public void onSwipeRight()
{
super.onSwipeRight();
startActivity(new Intent(getApplicationContext(), AddSavingActivity.class));
finish();
}
}
So for my problem now. I want when i click a category inside the dialog box, the categoryEditText variable i have in the trird class to change in the name of the item i clicked in the listview. First of all where do i have to write this code and secondly how to do it. I am kind of lost becasue is really a big app:/
Many thanks !!!
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 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.