I am currently developing an app in android studio.The goal of my app is to have one page(MainActivity.java & activityMain.xml) display a spinner. The items in this spinner are items from a remote database. When the user selects an item in this spinner I want that selected item to be displayed in a separate page(Map.java map.xml).
I used a putExtra method in MainActivity to store the selected item into a string variable:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(
getApplicationContext(),
parent.getItemAtPosition(position).toString() + " Selected" ,
Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainActivity.this, Map.class);
String text = spinnerFood.getSelectedItem().toString();
intent.putExtra("SPINNER_KEY", text);
startActivity(intent);
}
Then in my Map class I am calling that string using getExtras:
String spinnerString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
spinnerString= null;
} else {
spinnerString= extras.getString("STRING_I_NEED");
}
} else {
spinnerString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
I can pass this string from MainActivity to Map successfully. My problem is when I try to display this string is does not appear on the XML page or on my phone when I run the app. I used the following code to try and display the string:
TextView e = (TextView)findViewById(R.id.textView);
e.setText(spinnerString);
Could someone please tell me where I am going wrong?
Here is my MainActivity class:
package com.example.cillin.infoandroidhivespinnermysql;
import java.util.ArrayList;
...
public class MainActivity extends Activity implements OnItemSelectedListener {
private Button btnAddNewCategory;
private TextView txtCategory;
public Spinner spinnerFood;
//public String spinnerValue;
// array list for spinner adapter
private ArrayList<Category> categoriesList;
ProgressDialog pDialog;
// API urls
// Url to create new category
private String URL_NEW_CATEGORY = "http://food_api/new_category.php";
// Url to get all categories
private String URL_CATEGORIES = "http://food_api/get_categories.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAddNewCategory = (Button) findViewById(R.id.btnAddNewCategory);
spinnerFood = (Spinner) findViewById(R.id.spinFood);
txtCategory = (TextView) findViewById(R.id.txtCategory);
categoriesList = new ArrayList<Category>();
// spinner item select listener
spinnerFood.setOnItemSelectedListener(this);
// Add new category click event
btnAddNewCategory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (txtCategory.getText().toString().trim().length() > 0) {
// new category name
String newCategory = txtCategory.getText().toString();
// Call Async task to create new category
new AddNewCategory().execute(newCategory);
} else {
Toast.makeText(getApplicationContext(),
"Please enter category name", Toast.LENGTH_SHORT)
.show();
}
}
});
new GetCategories().execute();
}
/**
* Adding spinner data
* */
public void populateSpinner() {
List<String> lables = new ArrayList<String>();
txtCategory.setText("");
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerFood.setAdapter(spinnerAdapter);
//String text = spinnerFood.getSelectedItem().toString();
}
/**
* Async task to get all food categories
* */
private class GetCategories extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Fetching food categories..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_CATEGORIES, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("categories");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("id"),
catObj.getString("name"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
}
}
/**
* Async task to create a new food category
* */
private class AddNewCategory extends AsyncTask<String, Void, Void> {
boolean isNewCategoryCreated = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Creating new category..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... arg) {
String newCategory = arg[0];
// Preparing post params
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", newCategory));
ServiceHandler serviceClient = new ServiceHandler();
String json = serviceClient.makeServiceCall(URL_NEW_CATEGORY,
ServiceHandler.POST, params);
Log.d("Create Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
boolean error = jsonObj.getBoolean("error");
// checking for error node in json
if (!error) {
// new category created successfully
isNewCategoryCreated = true;
} else {
Log.e("Create Category Error: ", "> " + jsonObj.getString("message"));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
if (isNewCategoryCreated) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// fetching all categories
new GetCategories().execute();
}
});
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(
getApplicationContext(),
parent.getItemAtPosition(position).toString() + " Selected" ,
Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainActivity.this, Map.class);
String text = spinnerFood.getSelectedItem().toString();
intent.putExtra("SPINNER_KEY", text);
startActivity(intent);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
Here is Map.java:
package com.example.cillin.infoandroidhivespinnermysql;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
/**
* Created by cillin on 06/07/2015.
*/
public class Map extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//This page layout is located in the menu XML file
//SetContentView links a Java file, to its XML file for the layout
setContentView(R.layout.map);
/*Spinner mySpinner = (Spinner)findViewById(R.id.spinFood);
String text = mySpinner.getSelectedItem().toString();
EditText e = (EditText) findViewById (R.id.editText1);
e.setText(text);*/
String spinnerString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
spinnerString= null;
} else {
spinnerString= extras.getString("STRING_I_NEED");
}
} else {
spinnerString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
/*if (getIntent() != null && getIntent().getExtras() != null) {
Bundle bundle = getIntent().getExtras();
if (bundle.getString("SPINNER_KEY") != null) {
spinnerString = bundle.getString("SPINNER_KEY");
}
}*/
//String a = "ddd";
TextView e = (TextView)findViewById(R.id.textView);
e.setText(spinnerString);
Button mainm = (Button)findViewById(R.id.mainmenu);
mainm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//This button is linked to the map page
Intent i = new Intent(Map.this, MainMenu.class);
//Activating the intent
startActivity(i);
}
});
}
}
Here is my map.xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="300dp"
android:layout_height="300dp"
android:id="#+id/imageView"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:src="#drawable/map_image"
android:contentDescription="#string/map"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp" />
<Button
android:id="#+id/mainmenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="140dp"
android:layout_marginTop = "450dp"
android:text="Main Menu" />
<TextView
android:layout_width="200dp"
android:layout_height="20dp"
android:id="#+id/textView"
android:layout_below="#+id/imageView"
android:layout_alignRight="#+id/imageView"
android:layout_alignEnd="#+id/imageView" />
</RelativeLayout>
you have to use getIntent().getStringExtra("STRING_I_NEED");
getIntent.getExtras() will work only if you pass Bundle in calling activity
I fixed it:
String spinnerString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
spinnerString= null;
} else {
spinnerString= extras.getString("STRING_I_NEED");
}
} else {
spinnerString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
I changed "STRING_I_NEED" to "SPINNER_KEY"
Related
i am trying to send Data (ID value) from one activity to other
but it wouldn't send correct data , i want it to send only ID Value of Clicked Item to next activity , here is my code
public class Order extends AppCompatActivity {
private ListView lvUsers;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading, please wait.....");
lvUsers = (ListView) findViewById(R.id.lvUsers);
new JSONTask().execute("http://146.185.178.83/resttest/order");
}
public class JSONTask extends AsyncTask<String, String, List<OrderModel> > {
#Override
protected void onPreExecute(){
super.onPreExecute();
dialog.show();
}
#Override
protected List<OrderModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line=reader.readLine()) !=null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
List<OrderModel> orderModelList = new ArrayList<>();
Gson gson = new Gson();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
OrderModel orderModel = gson.fromJson(finalObject.toString(), OrderModel.class);
orderModelList.add(orderModel);
}
return orderModelList;
}catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection !=null) {
connection.disconnect();
}
try {
if (reader !=null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<OrderModel> result) {
super.onPostExecute(result);
dialog.dismiss();
OrderAdapter adapter = new OrderAdapter(getApplicationContext(), R.layout.row_order, result);
lvUsers.setAdapter(adapter);
}
}
public class OrderAdapter extends ArrayAdapter {
public List<OrderModel> orderModelList;
private int resource;
private LayoutInflater inflater;
public OrderAdapter(Context context, int resource, List<OrderModel> objects) {
super(context, resource, objects);
orderModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
holder = new ViewHolder();
convertView=inflater.inflate(resource, null);
holder.bOrderNo = (Button) convertView.findViewById(R.id.bOrderNo);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
final int orderId = orderModelList.get(position).getId();
holder.bOrderNo.setText("Order No: " + orderModelList.get(position).getOrderId());
holder.bOrderNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Order.this, OrderSelected.class);
intent.putExtra("parameter_name", orderId);
startActivity(intent);
}
});
return convertView;
}
class ViewHolder{
private Button bOrderNo;
}
}
}
The holder gets executed in loop i guess is why it wouldn't send right Id.
How do i get it to send only Id of the clicked orderId
you can check this link to see how json Response looks like http://146.185.178.83/resttest/order
You have a silly mistake in your code . I have edited single line in your code . I think you are getting same "orderId" every time instead of actual "orderId". Check this one . I hope your problem will resolve .
final int index = position;
holder.bOrderNo.setText("Order No: " + orderModelList.get(position).getOrderId());
holder.bOrderNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Order.this, OrderSelected.class);
intent.putExtra("parameter_name", orderModelList.get(index).getId());
startActivity(intent);
}
});
Please try
In place of
intent.putExtra("parameter_name", orderId);
Please put
intent.putExtra("parameter_name", orderModelList.get(position).getId());
I am creating an app. my app is crash when i enter any word after provide space in autocompletetextview and then again when i enter any word then its crash. please help me. using following code.........
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,
LocationListener, AdapterView.OnItemClickListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker,FindMarker;
LocationRequest mLocationRequest;
AutoCompleteTextView atvPlaces;
DownloadTask placesDownloadTask;
DownloadTask placeDetailsDownloadTask;
ParserTask placesParserTask;
ParserTask placeDetailsParserTask;
LatLng latLng;
final int PLACES = 0;
final int PLACES_DETAILS = 1;
ListView lv;
ImageButton remove;
private boolean exit = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onLocationChanged(mLastLocation);
}
});
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
remove = (ImageButton)findViewById(R.id.place_autocomplete_clear_button);
// Getting a reference to the AutoCompleteTextView
atvPlaces = (AutoCompleteTextView) findViewById(R.id.id_search_EditText);
atvPlaces.setThreshold(1);
// Adding textchange listener
atvPlaces.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Creating a DownloadTask to download Google Places matching "s"
placesDownloadTask = new DownloadTask(PLACES);
// Getting url to the Google Places Autocomplete api
String url = getAutoCompleteUrl(s.toString().trim());
// Start downloading Google Places
// This causes to execute doInBackground() of DownloadTask class
placesDownloadTask.execute(url);
if (!atvPlaces.getText().toString().equals("")){
lv.setVisibility(View.VISIBLE);
remove.setVisibility(View.VISIBLE);
}else {
lv.setVisibility(View.GONE);
remove.setVisibility(View.GONE);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
// Setting an item click listener for the AutoCompleteTextView dropdown list
/* atvPlaces.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int index,
long id) {
ListView lv = (ListView) arg0;
SimpleAdapter adapter = (SimpleAdapter) arg0.getAdapter();
HashMap<String, String> hm = (HashMap<String, String>) adapter.getItem(index);
// Creating a DownloadTask to download Places details of the selected place
placeDetailsDownloadTask = new DownloadTask(PLACES_DETAILS);
// Getting url to the Google Places details api
String url = getPlaceDetailsUrl(hm.get("reference"));
// Start downloading Google Place Details
// This causes to execute doInBackground() of DownloadTask class
placeDetailsDownloadTask.execute(url);
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
});*/
lv=(ListView)findViewById(R.id.list);
lv.setOnItemClickListener(this);
setListenerOnWidget();
}
private void setListenerOnWidget() {
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
atvPlaces.setText("");
}
};
remove.setOnClickListener(listener);
}
#Override
public void onBackPressed() {
if(exit){
finish();
}else {
Toast.makeText(this, "Tap Back again to Exit.",
Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
}
}, 3 * 1000);
}
}
#Override
public void onItemClick (AdapterView < ? > adapterView, View view,int i, long l){
//ListView lv = (ListView) adapterView;
SimpleAdapter adapter = (SimpleAdapter) adapterView.getAdapter();
HashMap<String, String> hm = (HashMap<String, String>) adapter.getItem(i);
// Creating a DownloadTask to download Places details of the selected place
placeDetailsDownloadTask = new DownloadTask(PLACES_DETAILS);
// Getting url to the Google Places details api
String url = getPlaceDetailsUrl(hm.get("reference"));
// Start downloading Google Place Details
// This causes to execute doInBackground() of DownloadTask class
placeDetailsDownloadTask.execute(url);
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
String str = ((TextView) view.findViewById(R.id.place_name)).getText().toString();
Toast.makeText(this,str, Toast.LENGTH_SHORT).show();
atvPlaces.setText(str.replace(' ',','));
lv.setVisibility(view.GONE);
}
private String getPlaceDetailsUrl(String ref) {
// Obtain browser key from https://code.google.com/apis/console
String key = "key=**************************************";
// reference of place
String reference = "reference=" + ref;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = reference + "&" + sensor + "&" + key;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/details/" + output + "?" + parameters;
return url;
}
private String getAutoCompleteUrl(String place) {
// Obtain browser key from https://code.google.com/apis/console
String key = "key=*********************************";
// place to be be searched
String input = "input=" + place;
// place type to be searched
String types = "types=geocode";
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = input + "&" + types + "&" + sensor + "&" + key;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/autocomplete/" + output + "?" + parameters;
return url;
}
/**
* A method to download json data from url
*/
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
//mLocationRequest.setInterval(1000);
//mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if(mCurrLocationMarker != null){
mCurrLocationMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
MarkerOptions markerOption = new MarkerOptions();
markerOption.position(latLng);
markerOption.title("Current Position");
markerOption.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOption);
Toast.makeText(this,"Location changed",Toast.LENGTH_SHORT).show();
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(13).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
if(mGoogleApiClient != null){
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
}
loadNearByPlaces(location.getLatitude(), location.getLongitude());
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResult) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
if (grantResult.length > 0
&& grantResult[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "permisison denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
private void loadNearByPlaces(double latitude, double longitude) {
//YOU Can change this type at your own will, e.g hospital, cafe, restaurant.... and see how it all works
String type = "atm";
StringBuilder googlePlacesUrl =
new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location=").append(latitude).append(",").append(longitude);
googlePlacesUrl.append("&radius=").append(PROXIMITY_RADIUS);
googlePlacesUrl.append("&types=").append(type);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + GOOGLE_BROWSER_API_KEY);
JsonObjectRequest request = new JsonObjectRequest(googlePlacesUrl.toString(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject result) {
Log.i(TAG, "onResponse: Result= " + result.toString());
parseLocationResult(result);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: Error= " + error);
Log.e(TAG, "onErrorResponse: Error= " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(request);
}
private void parseLocationResult(JSONObject result) {
String id, place_id, placeName = null, reference, icon, vicinity = null;
double latitude, longitude;
try {
JSONArray jsonArray = result.getJSONArray("results");
if (result.getString(STATUS).equalsIgnoreCase(OK)) {
//mMap.clear();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject place = jsonArray.getJSONObject(i);
id = place.getString(ATM_ID);
place_id = place.getString(PLACE_ID);
if (!place.isNull(NAME)) {
placeName = place.getString(NAME);
}
if (!place.isNull(VICINITY)) {
vicinity = place.getString(VICINITY);
}
latitude = place.getJSONObject(GEOMETRY).getJSONObject(LOCATION)
.getDouble(LATITUDE);
longitude = place.getJSONObject(GEOMETRY).getJSONObject(LOCATION)
.getDouble(LONGITUDE);
reference = place.getString(REFERENCE);
icon = place.getString(ICON);
MarkerOptions markerOptions = new MarkerOptions();
LatLng latLng = new LatLng(latitude, longitude);
markerOptions.position(latLng);
markerOptions.title(placeName);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory .HUE_BLUE));
markerOptions.snippet(vicinity);
mMap.addMarker(markerOptions);
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker arg0) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
View myContentsView = getLayoutInflater().inflate(R.layout.marker, null);
TextView tvTitle = ((TextView)myContentsView.findViewById(R.id.title));
tvTitle.setText(marker.getTitle());
TextView tvSnippet = ((TextView)myContentsView.findViewById(R.id.snippet));
tvSnippet.setText(marker.getSnippet());
return myContentsView;
}
});
}
Toast.makeText(getBaseContext(), jsonArray.length() + " ATM_FOUND!",
Toast.LENGTH_SHORT).show();
} else if (result.getString(STATUS).equalsIgnoreCase(ZERO_RESULTS)) {
Toast.makeText(getBaseContext(), "No ATM found in 5KM radius!!!",
Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, "parseLocationResult: Error=" + e.getMessage());
}
}
private class DownloadTask extends AsyncTask<String, Void, String> {
private int downloadType = 0;
// Constructor
public DownloadTask(int type) {
this.downloadType = type;
}
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try {
// Fetching the data from web service
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
switch (downloadType) {
case PLACES:
// Creating ParserTask for parsing Google Places
placesParserTask = new ParserTask(PLACES);
// Start parsing google places json data
// This causes to execute doInBackground() of ParserTask class
placesParserTask.execute(result);
break;
case PLACES_DETAILS:
// Creating ParserTask for parsing Google Places
placeDetailsParserTask = new ParserTask(PLACES_DETAILS);
// Starting Parsing the JSON string
// This causes to execute doInBackground() of ParserTask class
placeDetailsParserTask.execute(result);
}
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
int parserType = 0;
public ParserTask(int type) {
this.parserType = type;
}
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
JSONObject jObject;
List<HashMap<String, String>> list = null;
try {
jObject = new JSONObject(jsonData[0]);
switch (parserType) {
case PLACES:
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
// Getting the parsed data as a List construct
list = placeJsonParser.parse(jObject);
break;
case PLACES_DETAILS:
PlaceDetailsJSONParser placeDetailsJsonParser = new PlaceDetailsJSONParser();
// Getting the parsed data as a List construct
list = placeDetailsJsonParser.parse(jObject);
}
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return list;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
switch (parserType) {
case PLACES:
String[] from = new String[]{"description"};
int[] to = new int[]{R.id.place_name};
// Creating a SimpleAdapter for the AutoCompleteTextView
//SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), result, android.R.layout.simple_list_item_1, from, to);
// Setting the adapter
//atvPlaces.setAdapter(adapter);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, result,R.layout.row,from,to);
// Adding data into listview
lv.setAdapter(adapter);
break;
case PLACES_DETAILS:
String location = atvPlaces.getText().toString();
if (location != null && !location.equals("")) {
new GeocoderTask().execute(location);
}
break;
}
}
}
private class GeocoderTask extends AsyncTask<String, Void, List<Address>> {
#Override
protected List<Address> doInBackground(String... locationName) {
// TODO Auto-generated method stub
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
protected void onPostExecute(List<Address> addresses) {
if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
}
for(int i=0;i<addresses.size();i++){
Address address = (Address)addresses.get(i);
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Find Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
FindMarker = mMap.addMarker(markerOptions);
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(13).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
loadNearByPlaces(address.getLatitude(), address.getLongitude());
}
}
}
}
my app is crash when i enter any word after provide space in autocompletetextview and then again when i enter any word then its crash....
Your list is initialized to null at
List<HashMap<String, String>> list = null;
And if the parsing fire any exception, the list will be still null since it won't get initialized & setting a null List to an adapter will produce the NullPointerException at getCount(). So just ensure to initialize it.
List<HashMap<String, String>> list = new ArrayList<>();
IMPORTANT
When you use a space & try to call that URL, it will fire a FileNotFoundException if not encoded properly. In your case, URL url = new URL(strUrl); is firing that exception while using space character.
Easiest way is to replace space with %20. In getAutoCompleteUrl() before return, put the following code to replace space with %20.
private String getAutoCompleteUrl(String place) {
-------existing code----
url = url.replaceAll(" ", "%20");
return url;
}
Actually i had faced the same situation. You are adding data to autocomplete textview dynamically , basically just like google for each word you are typing u are getting that data from server , if i am wrong please correct me.
Use this code for populating data into autocomplete textview dynamically from server depending upon your search
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.SyncStateContract.Columns;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.Filter;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
public class TestActivity extends Activity {
public Context mContext;
// views declaration
public AutoCompleteTextView txtAutoComplete;
public ListView lvItems;
// arrayList for Adaptor
ArrayList<String> listItems;
// getting input from AutocompleteTxt
String strItemName;
// making Adaptor for autocompleteTextView
ArrayAdapter<String> adaptorAutoComplete;
private static final int ADDRESS_TRESHOLD = 2;
private Filter filter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// for showing full screen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_listitem);
mContext = this;
listItems = new ArrayList<String>();
// Declaring and getting all views objects
Button btnShare = (Button) findViewById(R.id.ListItem_btnShare);
Button btnSort = (Button) findViewById(R.id.ListItem_btnSort);
lvItems = (ListView) findViewById(R.id.ListItem_lvItem);
txtAutoComplete = (AutoCompleteTextView) findViewById(R.id.ListItem_autoComplete);
// adding listeners to button
btnShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
btnSort.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
String[] from = { "name" };
int[] to = { android.R.id.text1 };
SimpleCursorAdapter a = new SimpleCursorAdapter(this,
android.R.layout.simple_dropdown_item_1line, null, from, to, 0);
a.setStringConversionColumn(1);
FilterQueryProvider provider = new FilterQueryProvider() {
#Override
public Cursor runQuery(CharSequence constraint) {
// run in the background thread
if (constraint == null) {
return null;
}
String[] columnNames = { Columns._ID, "name" };
MatrixCursor c = new MatrixCursor(columnNames);
try {
// total code for implementing my way of auto complte
String SOAP_ACTION = "your action";
String NAMESPACE = "your name space";
String METHOD_NAME = "your method name";
String URL = "your Url";
SoapObject objSoap = null;
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
// Use this to add parameters
request.addProperty("KEY", yourkey);
request.addProperty("Key", constraint);
request.addProperty("Key", Id);
// Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
HttpTransportSE androidHttpTransport = new HttpTransportSE(
URL);
// this is the actual part that will call the webservice
androidHttpTransport.call(SOAP_ACTION, envelope);
// Get the SoapResult from the envelope body.
objSoap = (SoapObject) envelope.getResponse();
if (objSoap != null) {
String strData = objSoap.toString();
}
if (objSoap != null) {
System.out.println("getPropertyCountinevents//////////"
+ objSoap.getPropertyCount());
for (int i = 0; i < objSoap.getPropertyCount(); i++) {
Object obj = objSoap.getProperty(i);
if (obj instanceof SoapObject) {
SoapObject objNew = (SoapObject) obj;
c.newRow()
.add(i)
.add(objNew.getProperty("Itemname")
.toString());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return c;
}
};
a.setFilterQueryProvider(provider);
txtAutoComplete.setAdapter(a);
} // on create ends
} // final class ends
replace mine code of getting data from server to yours i.e calling webservices through http calls and it will work like a charm.
I'm getting json data and putting it in hashmap and hashmap into an arraylist. All is happening in fragment extending ListFragment
protected String doInBackground(String... urls) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("full_name", etUserSearch.getText().toString());
responseReceive = JsonPostClient.SendHttpPost(urls[0],
jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
try {
Success = responseReceive.getJSONArray("Success");
for (int i = 0; i < Success.length(); i++) {
JSONObject c = Success.getJSONObject(i);
String full_name = c.getString(TAG_FULL_NAME);
String user_name = c.getString(TAG_USER_NAME);
String user_id = c.getString(TAG_USER_ID);
HashMap<String, String> friends = new HashMap<String, String>();
// adding each child node to HashMap key => value
friends.put(TAG_FULL_NAME, full_name);
friends.put(TAG_USER_NAME, user_name);
friends.put(TAG_USER_ID, user_id);
// adding contact to contact list
FriendSearchList.add(friends);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.d("hello", "");
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
printFriends();
};
I'm checking that data is valid by printFriends() method and wanna show only 'TAG_FULL_NAME' data in a listview. My ListView initialization
View rootView = inflater.inflate(R.layout.tab_add_friends, container,
false);
lv = (ListView) rootView.findViewById(R.id.listView);
Method for checking data and loading in ListView
public void printFriends() {
int len = FriendSearchList.size();
for (int i = 0; i < len; i++) {
String f_name = FriendSearchList.get(i).get(TAG_FULL_NAME);
String u_name = FriendSearchList.get(i).get(TAG_USER_NAME);
String u_id = FriendSearchList.get(i).get(TAG_USER_ID);
Log.d("full_name", f_name);
Log.d("user_name", u_name);
Log.d("user_id", u_id);
}
ListAdapter adapter = new SimpleAdapter(getActivity(),
FriendSearchList, R.layout.tab_addfriend_list,
new String[] { TAG_FULL_NAME }, new int[] { R.id.full_name });
setListAdapter(adapter);
}
tab_add_friends 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:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
tab_addfriend_list xml layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<!-- Name Label -->
<TextView
android:id="#+id/full_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="#43bd00"
android:textSize="16sp"
android:textStyle="bold" />
</LinearLayout>
There is no error showing just nothing is showing into listview. Need suggestion or clue to get rid of this problem.
I have the same problem once
the problem is you are feeding the data using simple adapter but you may be inflate the rowView outside the ui thread and feed the from the post execute . thtas why your view dont getting the data . actually you dont have to inflate the rowview here is the hole code for you .Another thing print friend method also useless just initialize the simple adapter in the onPostExecute() method.
`public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
private boolean isConnection = false;
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
ArrayList<HashMap<String, String>> oflineContactList;
private MyContactDataSource dataSource;
List<Contatcs> oflineContatcs;
// private ListAdapter adapter1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataSource = new MyContactDataSource(MainActivity.this);
dataSource.open();
contactList = new ArrayList<HashMap<String,String>>();
oflineContactList = dataSource.getContatcs();
Log.i("data", oflineContactList.toString());
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, oflineContactList,
R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL,
TAG_PHONE_MOBILE }, new int[] { R.id.email,
R.id.name, R.id.mobile });
setListAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// getting values from selected ListItem
String name = ((TextView) arg1.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) arg1.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) arg1.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent intent = new Intent(MainActivity.this, SingleListItemActivity.class);
intent.putExtra(TAG_NAME, name);
intent.putExtra(TAG_EMAIL, cost);
intent.putExtra(TAG_PHONE_MOBILE, description);
startActivity(intent);
}
});
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Data is loading...please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Creating service handler class instance
ServiceHandler mHandler = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = mHandler.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if(jsonStr != null){
try {
JSONObject jsonObject = new JSONObject(jsonStr);
//Getting JSON Array node
contacts = jsonObject.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
contact.put(TAG_PHONE_MOBILE, mobile);
// adding contact to contact list
contactList.add(contact);
}
dataSource.creareContacts(contactList);
dataSource.close();
} catch (JSONException e) {
e.printStackTrace();
}
}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if(pDialog.isShowing()){
pDialog.dismiss();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL,
TAG_PHONE_MOBILE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
}`
The problem is that you are passing an Arraylist of HashMap where SimpleAdapter wont have any idea on which data is to put in the layout of the ListView items.
You can use this to implement items in your ListView
sample:
ListAdapter adapter = new SimpleAdapter(getActivity(),
FriendSearchList, R.layout.tab_addfriend_list,
new String[] { TAG_FULL_NAME }, new int[] { R.id.full_name }){
#Override
public int getCount() {
return FriendSearchList.size();
}
#Override
public View getView(int position,View convertView,ViewGroup parent) {
View v;
if(convertView == null)
{
v = getActivity().getLayoutInflater().inflate(R.layout.tab_addfriend_list, parent);
TextView tx = (TextView) v.findViewById(R.id.full_name);
tx.setText(FriendSearchList.get(i).get(TAG_FULL_NAME));
} else
v = convertView;
return v;
}
};
Actually i am getting url from json,now in my listview its shows all the list of youtube url which was there in json parsing.After clicking the url it is going to youtube page and that video is playing,I dont want to go to othersite from my application,the video has to be shown in my applicaiton,for that how i will use youtube embed in my application.
How to show the listof youtube videos in my listview,now it showing the url,I want it has to show the small videos of listview if we click the video it will play the youtube video in my apps using embed
Myactivity.java
public class PoojaVideos extends Activity implements FetchDataListener1 {
private ProgressDialog dialog;
ListView lv2;
private List<Application1> items;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item1);
lv2 =(ListView)findViewById(R.id.listV_main);
lv2.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = lv2.getItemAtPosition(position);
Application1 obj_itemDetails = (Application1)o;
final Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(((Application1) o).getUrlWiki()));
startActivity(i);
}
});
//praycount.setOnClickListener(this);
initView();
}
private void initView(){
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://www.ginfy.com/api/v1/videos.json";
FetchDataTask1 task = new FetchDataTask1(this);
task.execute(url);
}
#Override
public void onFetchComplete(List<Application1> data) {
this.items = data;
// dismiss the progress dialog
if ( dialog != null )
dialog.dismiss();
// create new adapter
ApplicationAdapter1 adapter = new ApplicationAdapter1(this, data);
// set the adapter to list
lv2.setAdapter(adapter);
}
#Override
public void onFetchFailure(String msg) {
if ( dialog != null )
dialog.dismiss();
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
} This is the activity for showing listview and after clicking the item in list it is going to youtube page.
mylayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView
android:layout_height="wrap_content"
android:layout_width="fill_parent" android:id="#+id/listV_main"/>
</LinearLayout>
I dont want to go in youtube site,the video has to show in my application itself,for that how to use embed
Application Adapter.java
public class ApplicationAdapter1 extends ArrayAdapter<Application1> {
private List<Application1> items;
private LayoutInflater inflator;
private PoojaVideos activity;
private ProgressDialog dialog;
public ApplicationAdapter1(PoojaVideos context, List<Application1> items){
super(context, R.layout.activity_row1, items);
this.items = items;
inflator = LayoutInflater.from(getContext());
activity=context;
}
#Override
public int getCount(){
return items.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder holder = null;
//View v = convertView;
if ( convertView == null ){
convertView = inflator.inflate(R.layout.activity_row1, null);
holder = new ViewHolder();
holder.prayersLinkWiki = (TextView) convertView.findViewById(R.id.prayersLinkWiki);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
Application1 app1 = items.get(position);
holder.prayersLinkWiki.setText(Html.fromHtml(app1.getUrlWiki()));
return convertView;
}
class ViewHolder {
public TextView prayersLinkWiki;
}
//return convertView;
}
Fetchdatatask1.java
public class FetchDataTask1 extends AsyncTask<String, Void, String>
{
private final FetchDataListener1 listener;
private OnClickListener onClickListener;
private String msg;
public FetchDataTask1(FetchDataListener1 listener)
{
this.listener = listener;
}
#Override
protected String doInBackground(String... params)
{
if ( params == null )
return null;
// get url from params
String url = params[0];
try
{
// create http connection
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
// connect
HttpResponse response = client.execute(httpget);
// get response
HttpEntity entity = response.getEntity();
if ( entity == null )
{
msg = "No response from server";
return null;
}
// get response content and convert it to json string
InputStream is = entity.getContent();
return streamToString(is);
}
catch ( IOException e )
{
msg = "No Network Connection";
}
return null;
}
#Override
protected void onPostExecute(String sJson)
{
if ( sJson == null )
{
if ( listener != null )
listener.onFetchFailure(msg);
return;
}
try
{
// convert json string to json object
JSONObject jsonObject = new JSONObject(sJson);
JSONArray aJson = jsonObject.getJSONArray("youtube_url");
// create apps list
List<Application1> apps = new ArrayList<Application1>();
for ( int i = 0; i < aJson.length(); i++ )
{
JSONObject json = aJson.getJSONObject(i);
Application1 app1 = new Application1();
app1.setUrlWiki("https://www.youtube.com/watch?v="+json.getString("youtube_url"));
// add the app to apps list
apps.add(app1);
}
//notify the activity that fetch data has been complete
if ( listener != null )
listener.onFetchComplete(apps);
}
catch ( JSONException e )
{
e.printStackTrace();
msg = "Invalid response";
if ( listener != null )
listener.onFetchFailure(msg);
return;
}
}
/**
* This function will convert response stream into json string
*
* #param is
* respons string
* #return json string
* #throws IOException
*/
public String streamToString(final InputStream is) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ( (line = reader.readLine()) != null )
{
sb.append(line + "\n");
}
}
catch ( IOException e )
{
throw e;
}
finally
{
try
{
is.close();
}
catch ( IOException e )
{
throw e;
}
}
return sb.toString();
}
}
this is for the row url showing layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:descendantFocusability="blocksDescendants">
<TextView
android:id="#+id/prayersLinkWiki"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="web"
android:textSize="15sp" />
</RelativeLayout>
In my listview it will shown the url,after clicking the url it goes to youtube site for video,for the listview in holder url can we use embed for list of youtube videos in this line holder.prayersLinkWiki.setText(Html.fromHtml(app1.getUrlWiki()));
Remove The Code final Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(((Application1) o).getUrlWiki()));
startActivity(i); add code to open a dialog with webview. In the webview load youtube URL
Hi I am writting an android application to get information from a url and show it in a ListView. All are working well. but it takes long time to show the View because i read the file from url on onCreate() method.
I want read from the URL asynchronously, so view response time will not harmed.
Am I using the ProgressBar correctly?.
public class cseWatch extends Activity {
TextView txt1 ;
Button btnBack;
ListView listView1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchresult);
Button btnBack=(Button) findViewById(R.id.btn_bck);
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent MyIntent1 = new Intent(v.getContext(),cseWatchMain.class);
startActivity(MyIntent1);
}
});
ArrayList<SearchResults> searchResults = GetSearchResults();
//after loaded result hide progress bar
ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
final ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(new MyCustomBaseAdapter(cseWatch.this, searchResults));
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = lv.getItemAtPosition(position);
SearchResults fullObject = (SearchResults)o;
Toast.makeText(cseWatch.this, "You have chosen: " + " " + fullObject.getName(), Toast.LENGTH_LONG).show();
}
});
}//end of onCreate
private ArrayList<SearchResults> GetSearchResults(){
ArrayList<SearchResults> results = new ArrayList<SearchResults>();
SearchResults sr;
InputStream in;
try{
txt1 = (TextView) findViewById(R.id.txtDisplay);
txt1.setText("Sending request...");
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://www.myurl?reportType=CSV");
HttpResponse response = httpclient.execute(httpget);
in = response.getEntity().getContent();
txt1.setText("parsing CSV...");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
try {
String line;
reader.readLine(); //IGNORE FIRST LINE
while ((line = reader.readLine()) != null) {
String[] RowData = line.split(",");
sr = new SearchResults();
String precent = String.format("%.2g%n",Double.parseDouble(RowData[12])).trim();
double chng=Double.parseDouble(RowData[11]);
String c;
if(chng > 0){
sr.setLine2Color(Color.GREEN);
c="▲";
}else if(chng < 0){
sr.setLine2Color(Color.rgb(255, 0, 14));
c="▼";
}else{
sr.setLine2Color(Color.rgb(2, 159, 223));
c="-";
}
sr.setName(c+RowData[2]+"-"+RowData[1]);
DecimalFormat fmt = new DecimalFormat("###,###,###,###.##");
String price = fmt.format(Double.parseDouble(RowData[6])).trim();
String tradevol = fmt.format(Double.parseDouble(RowData[8])).trim();
sr.setLine1("PRICE: Rs."+price+" TRADE VOL:"+tradevol);
sr.setLine2("CHANGE:"+c+RowData[11]+" ("+precent+"%)");
results.add(sr);
txt1.setText("Loaded...");
// do something with "data" and "value"
}
}
catch (IOException ex) {
Log.i("Error:IO",ex.getMessage());
}
finally {
try {
in.close();
}
catch (IOException e) {
Log.i("Error:Close",e.getMessage());
}
}
}catch(Exception e){
Log.i("Error:",e.getMessage());
new AlertDialog.Builder(cseWatch.this).setTitle("Watch out!").setMessage(e.getMessage()).setNeutralButton("Close", null).show();
}
return results;
}
}
AsyncTask should be used to move the heavylifting away from UI thread. http://developer.android.com/reference/android/os/AsyncTask.html
I think you should use a runable.
demo code:
final ListView lv = (ListView) findViewById(R.id.listView1);
Handler handler = new Handler(app.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
lv.setAdapter(new MyCustomBaseAdapter(cseWatch.this, searchResults));
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = lv.getItemAtPosition(position);
SearchResults fullObject = (SearchResults)o;
Toast.makeText(cseWatch.this, "You have chosen: " + " " + fullObject.getName(), Toast.LENGTH_LONG).show();
}
});
}
}, 1000);
try it.^-^