I parsed json to adapt for my autocompleteTextView. I tried to match the value parsed by my json object with the value entered by user.
But some where i am failing. please help me in matching these values.
i have to match the string(acity) that is entered by user with my parsed json value stored in responseList.
This is how i am trying.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
new HttpGetTask().execute();
Button shwBtn = (Button) findViewById(R.id.showBtn);
shwBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AutoCompleteTextView city1 = (AutoCompleteTextView) findViewById(R.id.autoCity);
EditText area1 = (EditText) findViewById(R.id.edArea);
String aCity = city1.getText().toString().trim();
String aArea = area1.getText().toString().trim();
//here i have to match acity with all the values in responseList before sending it to next activity
Intent myInt = new Intent(getBaseContext(),
Map1Activity.class);
String city = city1.getText().toString();
String area = area1.getText().toString();
myInt.putExtra("city", city);
myInt.putExtra("area", area);
startActivity(myInt);
}
});
}
private class HttpGetTask extends AsyncTask<Void, Void, String> {
String URL = "xyzz.cities.json?app_id=test";
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
#Override
protected String doInBackground(Void... params) {
// http stuff
return null;
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray json = new JSONArray(result);
//getting my response(cities)
Log.v("ResponseCity", result);
final List<String> responseList = new ArrayList<String>();
for (int i = 0; i < json.length(); i++) {
final JSONObject e = json.getJSONObject(i);
String name = e.getString("name");
//Adding all values to a stringList
responseList.add(name);
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(SearchActivity.this,
android.R.layout.simple_dropdown_item_1line,
responseList);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autoCity);
textView.setAdapter(adapter);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (null != mClient)
mClient.close();
}
}
So lets assume you need to match a certain city before you intent to a map :
private final List<String> responseList;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
new HttpGetTask().execute();
Button shwBtn = (Button) findViewById(R.id.showBtn);
shwBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AutoCompleteTextView city1 = (AutoCompleteTextView) findViewById(R.id.autoCity);
EditText area1 = (EditText) findViewById(R.id.edArea);
String aCity = city1.getText().toString().trim();
String aArea = area1.getText().toString().trim();
//here i have to match acity with all the values in responseList before sending it to next activity
for(int i=0; i<responseList.size(); i++) {
if(responseList.get(i).equals(aCity)) {
Intent myInt = new Intent(getBaseContext(),
Map1Activity.class);
String city = city1.getText().toString();
String area = area1.getText().toString();
myInt.putExtra("city", city);
myInt.putExtra("area", area);
startActivity(myInt);
}
}
}
});
}
private class HttpGetTask extends AsyncTask<Void, Void, String> {
String URL = "xyzz.cities.json?app_id=test";
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
#Override
protected String doInBackground(Void... params) {
// http stuff
return null;
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray json = new JSONArray(result);
//getting my response(cities)
Log.v("ResponseCity", result);
responseList = new ArrayList<String>();
for (int i = 0; i < json.length(); i++) {
final JSONObject e = json.getJSONObject(i);
String name = e.getString("name");
//Adding all values to a stringList
responseList.add(name);
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(SearchActivity.this,
android.R.layout.simple_dropdown_item_1line,
responseList);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autoCity);
textView.setAdapter(adapter);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (null != mClient)
mClient.close();
}
}
It should be something like that if I didnt guess your intent wrongly.
Related
I have the next problem, I tried to send Arraylist<string> values from AsyncTask class to other class call graphics but I don’t know what I do wrong and how to get Arraylist<string> values in the other class, because I have a lot of sintaxis errors I my code
AsyncTask class
public class fetch extends AsyncTask<Void,Void,ArrayList<String>> {
//v funcional
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected ArrayList<String> doInBackground(Void... voids) {
String Id ="";
String Time ="";
String Pressure="";
ArrayList<String> IdArray = new ArrayList<String>();
ArrayList<String> TimeArray = new ArrayList<String>();
ArrayList<String> PressureArray = new ArrayList<String>();
String IdS=""+IdArray;
String TimeS=""+TimeArray;
String PresureS=""+PressureArray;
data.set(1,TimeS);
data.set(2,TimeS);
data.set(3,TimeS);
return data;
}
#Override
protected void onPostExecute(ArrayList<String> result){
super.onPostExecute(result);
Graphics.data.setText(data);
}}
The graphics class
public class Graphics extends AppCompatActivity {
public static TextView data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.graphics);
Button firstButton = (Button) findViewById(R.id.json);
data = (TextView) findViewById(R.id.msgTxt);
firstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fetch process = new fetch();
ArrayList<String> data= process.execute();
data.get(1);
}
});
}
you can create an interface which your "Graphics" implements it , and pass it to your AsyncTask class.
like this
public interface BlaBlaBla {
void doBla(ArrayList<String> myBla);
}
and in your "Graphics" :
class Graphics extends AppCompatActivity implements BlaBlaBla {
fetch process = new fetch(this);
}
and for asyncClass :
public class fetch extends AsyncTask<Void,Void,ArrayList<String>> {
//constructor
BlaBlaBla bla;
public fetch(BlaBlaBla bla){
this.bla=bla;
}
//when your task is complete use bla.doBla(pass your array here);
}
my solution
Fetch class
public class Fetch extends AsyncTask<Void,Void,String[][]> {
public static int KEY = 0;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected String[][] doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
String url = "http:xxxxxxx/xxx.json";
String jsonStr = sh.makeServiceCall(url);
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(jsonStr);
int nTiempos=jsonObj.length();
String[] IdKeyArray = new String[nTie];
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(String.valueOf(i));
IdKeyArray[i] = c.getString("Key");
String[][] valores={IdKeyArray};
return valores;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
And this is the "call" the other class where I get the values
private String[][] valores;
Fetch process = new Fetch();
process.execute();
try {
valores=process.get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
pm.setText(String.valueOf(valores[Fetch.Key][0]));
}
}
}
ChooseCategory.java
public class ChooseCategory extends ListActivity {
private ListView lv;
//ArrayAdapter<FoodStores> arrayAdapter;
private ArrayList<FoodStores> storefoodList;
private String URL_STORES = "http://10.0.2.2/get_stores.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lv = (ListView)findViewById(R.id.list);
storefoodList = new ArrayList<FoodStores>();
new GetFoodStores().execute();
}
private class GetFoodStores extends AsyncTask<Void,Void,Void> {
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandlerFood jsonParserFood = new ServiceHandlerFood();
String json = jsonParserFood.makeServiceCall(URL_STORES, ServiceHandlerFood.GET);
Log.e("Response: ", " > " + json);
if(json != null){
try{
JSONObject jsonObj = new JSONObject(json);
if(jsonObj != null){
JSONArray storeListFood = jsonObj.getJSONArray("storelistfood");
for(int i = 0; i < storeListFood.length(); i++){
JSONObject storeFoodObj = (JSONObject) storeListFood.get(i);
FoodStores foodStores = new FoodStores(storeFoodObj.getInt("id"),storeFoodObj.getString("STORENAME"));
storefoodList.add(foodStores);
}
}
}catch(JSONException e){
e.printStackTrace();
}
}else{
Log.e("JSON Data", "No data received from server");
}
return null;
}
#Override
protected void onPostExecute(Void result){
super.onPostExecute(result);
populateListView();
}
}
Here is the function of my populateListView
private void populateListView(){
List<String> labels = new ArrayList<String>();
for(int i = 0; i < storefoodList.size(); i++){
labels.add(storefoodList.get(i).getName());
}
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,R.layout.restaurant_list,labels);
Log.d("Labels:", labels.toString());
lv.setAdapter(listAdapter);
}
What I am trying to do here is to get the list of stores from PHP to Android via JSON and store them in ArrayList and then populate them into ListView. I have tried displaying labels, it is displaying the correct stuff.
The error from Emulator is that it just shows blank screen and then it crashes.
The error from logcat is
java.lang.NullPointerException
at call.rocket.user.callarocket.ChooseCategory.populateListView
Do like
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,R.layout.restaurant_list,labels);
setListAdapter(listAdapter);
as you directly extends ListActivity also remove
lv = (ListView)findViewById(R.id.list);
and make sure your ListView id is android:id="#android:id/list"
Go to Tutorial
I have this code where I get the data from Facebook Graph API which seems working, my problem is when i add the hashmap to my arraylist its not working, i toasted the size of my array and I always get zero. please help. here is the code:
public class PageFeedHome extends Fragment {
ArrayList<HashMap<String, String>> feedList;
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_MESSAGE = "message";
private String feedMessage;
ListView listView;
BaseAdapter adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.feed_home_activity,
container, false);
listView = (ListView) view.findViewById(R.id.feed_lv);
feedList = new ArrayList<HashMap<String, String>>();
new LoadPosts().execute();
return view;
}
private class LoadPosts extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Session.openActiveSession(getActivity(), true,
new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
new Request(session, "/163340583656/feed",
null, HttpMethod.GET,
new Request.Callback() {
public void onCompleted(
Response response) {
/* handle the result */
Log.i("PostFeedResponse", response.toString());
try {
GraphObject graphObj = response
.getGraphObject();
JSONObject json = graphObj
.getInnerJSONObject();
JSONArray jArray = json
.getJSONArray("data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject currObj = jArray.getJSONObject(i);
final String feedId = currObj.getString("id");
if (currObj.has("message")) {
feedMessage = currObj.getString("message");
} else if (currObj.has("story")) {
feedMessage = currObj.getString("story");
} else {
feedMessage = "Posted a something";
}
JSONObject fromObj = currObj.getJSONObject("from");
String from = fromObj.getString("name");
HashMap<String, String> feed = new HashMap<String, String>();
feed.put(TAG_ID, feedId);
feed.put(TAG_MESSAGE, feedMessage);
feed.put(TAG_NAME, from);
feedList.add(feed);
Log.i("added" , feedList.toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).executeAsync();
}
}
});
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(getActivity(), ""+feedList.size(), Toast.LENGTH_LONG).show();
adapter = new SimpleAdapter(getActivity(), feedList,
R.layout.feed_item_view, new String[] { TAG_MESSAGE, TAG_NAME,
TAG_ID }, new int[] { R.id.message, R.id.author, R.id.id_tv });
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}
I am making an application where i need to take the input from the user and append that input with the string and use that as a url for data parsing
But the edit text content is null even though i am entering text in edittext
I converted edittext content to string as below
EditText edit = (EditText)findViewById(R.Id.tv5);
And inside onclicklistener
String data = edit.getText().toString();
Can anybody tell me why the data.length() is giving me zero?
my complete main activity is below:
public class Pnr extends Activity {
EditText edit;
TextView text1;
Button button;
String pnr, check;
HttpClient client;
JSONObject json;
int s;
String URL = "pnrbuddy.com/pnrstatus=";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pnr);
edit = (EditText) findViewById(R.id.tv5);
text1 = (TextView) findViewById(R.id.textView2);
button = (Button) findViewById(R.id.button1);
client = new DefaultHttpClient();
pnr = String.valueOf(edit.getText());
s = pnr.length();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Read().execute("trainNo");
}
});
}
public JSONObject pnrStatus(String key) throws ClientProtocolException,
IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
url.append(key);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
JSONObject last = new JSONObject();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
last = new JSONObject(data);
return last;
} else {
return last;
}
}
public class Read extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
json = pnrStatus(pnr);
return json.getString(arg0[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return s + "";
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
text1.setText(" " + result);
}
}
}
when i enter the string instead of accepting from edittext in the string URL along with the exsisting string the code works
URL="pnrbuddy/pnrstatus=myText";
why i m unable to get string from editText?
try with this
EditText edit = (EditText)findViewById(R.id.tv5);
String data = edit.getText().toString();
If you are try to get length in onclicklistener in EditText it will give u 0 only.In this case try to get from onTextChange.
Replace your on create method by this n try
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pnr);
edit = (EditText) findViewById(R.id.tv5);
text1 = (TextView) findViewById(R.id.textView2);
button = (Button) findViewById(R.id.button1);
client = new DefaultHttpClient();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
pnr =edit.getText().toString();
s = pnr.length();
new Read().execute("trainNo");
}
});
}
Actually your getting text when the activity is created not when button is clicked, So placing the gettext code in onclick method would resolve your problem
I have spinner in my Activity which is set the item from JSON data and when i select any item from spinner and set into the spinner, and i have done all this things properly.But when i want to remove selected item from spinner i got exception:
E/AndroidRuntime(1022): java.lang.UnsupportedOperationException"
and
E/AndroidRuntime(1022):atandroid.widget.ArrayAdapter.remove(ArrayAdapter.java:212)
at the code line of
E/AndroidRuntime(1022):at com.spinnerdemo.SpinDemo$1.onItemSelected(SpinDemo.java:102)
Here is my code:
public class SpinDemo extends Activity {
private static String strUrl = "http://192.168.1.61/jyoti/android_app/all_questions.php";
private static String TAG_ID = "id";
private static String TAG_CODE = "q_prefix";
private static String TAG_CODE_ARR = "Questions";
JSONArray jsonArray = null;
Spinner codeSpinner, spinner2;
EditText edTextSpinnerItem;
String[] items;
String strEdtext;
String strid , strcode ;
ArrayList<String> codeList;
public ArrayAdapter<String> adapter ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
codeList = new ArrayList<String>();
codeSpinner = (Spinner) findViewById(R.id.spinner2);
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(strUrl);
try
{
jsonArray = json.getJSONArray(TAG_CODE_ARR);
// looping through All Contacts
final String[] items = new String[jsonArray.length()];
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject c = jsonArray.getJSONObject(i);
// Storing each json item in variable
strid = c.getString(TAG_ID);
strcode = c.getString(TAG_CODE);
items[i] = c.getString(TAG_CODE);
System.out.println("Hello events " + items);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
codeSpinner.setAdapter(adapter);
}
}
catch (JSONException e) {
e.printStackTrace();
}
codeSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3)
{
// TODO Auto-generated method stub
String anyvariable=String.valueOf(codeSpinner.getSelectedItem());
System.out.println("anyvariable = " + anyvariable);
edTextSpinnerItem=(EditText)findViewById(R.id.editText_SpinnerItem);
edTextSpinnerItem.setText(anyvariable);
System.out.println("edTextSpinnerItem " + edTextSpinnerItem);
String t = adapter.getItem(pos);
System.out.println("Get The Item Position From Adapter = " + t);
adapter.remove(t);
adapter.notifyDataSetChanged();
codeSpinner.setAdapter(adapter);
//mySpinner.setAdapter(m_adapterForSpinner);
//adapter.remove((String)codeSpinner.getSelectedItem());
//adapter.notifyDataSetChanged();
//System.out.println("Item is Removed From The Spinner Drop Dwon List");
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
}
}
I think that the problem is caused from the deleting an element that is actual selected
Try to use a list instead of an Array for the items:
http://developer.android.com/reference/android/widget/ArrayAdapter.html#ArrayAdapter(android.content.Context,%20int,%20int,%20java.util.List)
Then in the on item selected use
items.remove(t);
Instead of:
adapter.remove(t);
With this change you remove the item from the ArrayList(List) and not from the adapter.
The adapter notifyDataSetChanged capture the change on the List and refresh the spinner
Try this..
1) Give spinner setadapter after for loop
2) If you need to remove any item. You need to use ArrayList it is the easy way.
I Posted code after some changes.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
codeList = new ArrayList<String>();
codeSpinner = (Spinner) findViewById(R.id.spinner2);
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(strUrl);
try
{
jsonArray = json.getJSONArray(TAG_CODE_ARR);
// looping through All Contacts
final String[] items = new String[jsonArray.length()];
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject c = jsonArray.getJSONObject(i);
// Storing each json item in variable
strid = c.getString(TAG_ID);
strcode = c.getString(TAG_CODE);
items[i] = c.getString(TAG_CODE);
System.out.println("Hello events " + items);
codeList.add(strcode);
}
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,codeList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
codeSpinner.setAdapter(adapter);
}
catch (JSONException e) {
e.printStackTrace();
}
codeSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3)
{
// TODO Auto-generated method stub
String anyvariable=String.valueOf(codeSpinner.getSelectedItem());
System.out.println("anyvariable = " + anyvariable);
edTextSpinnerItem=(EditText)findViewById(R.id.editText_SpinnerItem);
edTextSpinnerItem.setText(anyvariable);
System.out.println("edTextSpinnerItem " + edTextSpinnerItem);
String t = adapter.getItem(pos);
System.out.println("Get The Item Position From Adapter = " + t);
Object t2 = adapter.getItem(pos);
Log.v("t2", ""+t2);
codeList.remove(t2);
adapter.notifyDataSetChanged();
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
}