Opening PlacePicker on SearchView single click - android

I'm using SearchView as below in my code :
xml :
<android.support.v7.widget.SearchView
android:id="#+id/searchView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="false"
android:focusable="false"
app:iconifiedByDefault="false"
app:queryBackground="#color/transparant"
app:queryHint="#string/search"
app:searchIcon="#drawable/ic_search">
Java :
mSearchView = (SearchView) rootView.findViewById(R.id.searchView);
txtSearchText = (TextView) mSearchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
txtSearchText.setOnClickListener(this);
onCLick :
case R.id.search_src_text:
loadPlacePicker();
break;
But, the issue is SearchView needs a double click to open up PlacePicker.
I need to open PlacePicker on the single onClick Event of SearchView. How do I do that?

You need to change the value of searchView attribute clickable & focusable to true
<android.support.v7.widget.SearchView
android:id="#+id/searchView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
app:iconifiedByDefault="false"
app:queryBackground="#color/transparant"
app:queryHint="#string/search"
app:searchIcon="#drawable/ic_search">

Use this.
import android.annotation.TargetApi;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ListAdapter;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class LocationAutoCompletePRMView extends AutoCompleteTextView implements AdapterView.OnItemClickListener
{
GetCityHelperG_ GET_CITY_G;
SelectedLocationListener selectedLocationListener;
public LocationAutoCompletePRMView(Context context)
{
super(context);
}
public LocationAutoCompletePRMView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public LocationAutoCompletePRMView(Context context, AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public LocationAutoCompletePRMView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
{
super(context, attrs, defStyleAttr, defStyleRes);
}
#Override
public <T extends ListAdapter & Filterable> void setAdapter(T adapter)
{
super.setAdapter(adapter);
}
public void startLocationAdapter(Context con, SelectedLocationListener selectedLocationListener)
{
this.selectedLocationListener = selectedLocationListener;
GET_CITY_G = new GetCityHelperG_(con, android.R.layout.simple_list_item_1);
this.setAdapter(GET_CITY_G);
this.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l)
{
Latlng_data resultList = GET_CITY_G.set_LAT_Lng_value(position);
selectedLocationListener.onResult(resultList);
}
// ************************************************************* INTERFACE FOR SENDING THE SELECTED LOCATION DATA BACK TO THE CALLING CLASS ******************************************************************
public interface SelectedLocationListener
{
public void onResult(Latlng_data latLongModel);
}
// ********************************************************* ADAPTER **********************************************************************
public class GetCityHelperG_ extends ArrayAdapter<String> implements Filterable
{
public List<Latlng_data> resultList = new ArrayList<>();
private Context con;
public GetCityHelperG_(Context context, int textViewResourceId)
{
super(context, textViewResourceId);
con = context;
}
#Override
public int getCount()
{
return resultList.size();
}
#Override
public String getItem(int index)
{
try
{
return resultList.get(index).getAddress();
}
catch (Exception e)
{
}
return "";
}
#Override
public Filter getFilter()
{
Filter filter = new Filter()
{
#Override
protected FilterResults performFiltering(final CharSequence constraint)
{
FilterResults filterResults = new FilterResults();
if (constraint != null)
{
if (!fetchingAddress)
{
resultList = GetAddressByString(con, constraint.toString());
}
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results)
{
try
{
if (results != null && results.count > 0)
{
notifyDataSetChanged();
}
else
{
notifyDataSetInvalidated();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
return filter;
}
boolean fetchingAddress = false;
private List<Latlng_data> GetAddressByString(Context con, final String addressssss)
{
fetchingAddress = true;
String addressReturn = "";
Geocoder geocoder = new Geocoder(con, Locale.getDefault());
List<Latlng_data> dataList = new ArrayList<>();
List<Address> addresses;
try
{
addresses = geocoder.getFromLocationName(addressssss, 3);
Latlng_data l = null;
for (int i = 0; i < addresses.size(); i++)
{
int getMAxAddrss = addresses.get(i).getMaxAddressLineIndex();
for (int g = 0; g < getMAxAddrss; g++)
{
addressReturn = addressReturn + "," + addresses.get(i).getAddressLine(g);
}
addressReturn = addressReturn.substring(1, addressReturn.length());
l = new Latlng_data();
l.setAddress(addressReturn);
l.setLat(addresses.get(0).getLatitude());
l.setLng(addresses.get(0).getLongitude());
addressReturn = "";
dataList.add(l);
}
if (addresses.isEmpty())
{
dataList = getLocationFromString(addressssss);
}
}
catch (Exception e)
{
dataList = getLocationFromString(addressssss);
}
catch (Error e)
{
dataList = getLocationFromString(addressssss);
}
fetchingAddress = false;
return dataList;
}
// Directly access google map for location
public List<Latlng_data> getLocationFromString(String address)
{
List<Latlng_data> Ldata = new ArrayList<Latlng_data>();
try
{
String URL = "http://maps.google.com/maps/api/geocode/json?address=" + URLEncoder.encode(address, "UTF-8") + "&en&sensor=false";
JSONObject jsonObject = new JSONObject(new WebServiceHandler().performGetCall(URL));
JSONArray results = jsonObject.getJSONArray("results");
Latlng_data l;
for (int j = 0; j < results.length(); j++)
{
l = new Latlng_data();
double lng = results.getJSONObject(j).getJSONObject("geometry").getJSONObject("location").getDouble("lng");
double lat = results.getJSONObject(j).getJSONObject("geometry").getJSONObject("location").getDouble("lat");
String addrsssssName = results.getJSONObject(j).getString("formatted_address");
l.setAddress(addrsssssName != null ? addrsssssName : "");
l.setLat(lng);
l.setLng(lat);
Ldata.add(l);
}
}
catch (Exception e)
{
return Ldata;
}
catch (Error e)
{
return Ldata;
}
return Ldata;
}
public Latlng_data set_LAT_Lng_value(int position)
{
return resultList.get(position);
}
}
// ************************************************************* LATITUDE LONGITUDE MODEL ******************************************************************
public class Latlng_data
{
String address;
double lat, lng;
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
public double getLat()
{
return lat;
}
public void setLat(double lat)
{
this.lat = lat;
}
public double getLng()
{
return lng;
}
public void setLng(double lng)
{
this.lng = lng;
}
}
// ***************************************************************** WEBSERVICE CLASS FOR GETTINGRESPONSE FROM GOOGLE **************************************************************
public class WebServiceHandler
{
public String performGetCall(String url) throws Exception
{
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null)
{
response.append(inputLine);
}
in.close();
//print result
Log.e("== get Call response====".toUpperCase(), response.toString());
return response.toString(); //this is your response
}
}
}
XML layout code
<com.ameba.ptfix.COMMON.WebUtils.LocationAutoCompletePRMView
android:id="#+id/tvAutoComplete"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Type here..."
android:maxLength="150"
android:padding="5dp"
android:textColor="#color/BlackNew"
android:textColorHint="#color/grey_medium"
android:textSize="#dimen/small_text_size" />

Related

JSONArray not updating immediately

Whenever in my Popular Movies Udacity project, I click on a movie poster in the favorites movie collection, which is maintained as a database offline, the URL list gets updated correctly but the JSONArray made in the AsyncTask does not update immediately.
package com.example.android.popularmovies;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.example.android.popularmovies.Database.Contract;
import com.example.android.popularmovies.utilities.NetworkUtils;
import com.facebook.stetho.Stetho;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private final static String BASE_POSTER_URL = "http://image.tmdb.org/t/p/w500/";
private static String OPTION = "OPTION";
TextView mNoFavorites;
// = new JSONArray();
JSONArray favoriteJsonArray;
int optionChosen;
private ProgressBar mProgessBar;
private TextView mErrorMessage;
private Button mRetry;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private URL url;
private ArrayList<String> posterList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null)
optionChosen = savedInstanceState.getInt(OPTION);
Stetho.initializeWithDefaults(this);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2);
mRecyclerView.setLayoutManager(mLayoutManager);
//mAdapter = new MainActivityAdapter(this, posterList, null);
//mRecyclerView.setAdapter(mAdapter);
mProgessBar = findViewById(R.id.progess_bar);
mErrorMessage = findViewById(R.id.error_message);
mRetry = findViewById(R.id.retry);
mNoFavorites = findViewById(R.id.no_favorites_yet);
favoriteJsonArray = new JSONArray();
tryToConnect(new View(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.preferences, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
try {
if (item.getItemId() == R.id.top_rated) {
mRecyclerView.setVisibility(View.VISIBLE);
mNoFavorites.setVisibility(View.INVISIBLE);
url = NetworkUtils.buildUrl("top_rated");
if (url != null) {
mErrorMessage.setVisibility(View.INVISIBLE);
mRetry.setVisibility(View.INVISIBLE);
new FetchMovies().execute(url, null, null);
}
optionChosen = 1;
}
if (item.getItemId() == R.id.most_popular) {
mRecyclerView.setVisibility(View.VISIBLE);
mNoFavorites.setVisibility(View.INVISIBLE);
url = NetworkUtils.buildUrl("most_popular");
if (url != null) {
mErrorMessage.setVisibility(View.INVISIBLE);
mRetry.setVisibility(View.INVISIBLE);
new FetchMovies().execute(url, null, null);
}
optionChosen = 2;
}
if (item.getItemId() == R.id.favorites) {
optionFavorites();
optionChosen = 3;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (java.lang.NullPointerException e) {
e.printStackTrace();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
if (optionChosen == 3)
optionFavorites();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(OPTION, optionChosen);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
/* public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
optionChosen = savedInstanceState.getInt(OPTION);
}
*/
private void optionFavorites() {
try {
String[] projection = {"movie_id", "favorite_poster_path"};
Cursor cursor = getContentResolver().query(
Contract.FavoriteMovieDatabase.CONTENT_URI,
projection,
null,
null,
null
);
ArrayList<String> posterPathArrayList = new ArrayList<>();
ArrayList<URL> urlArrayList = new ArrayList<>();
if (cursor != null && cursor.moveToFirst()) {
do {
String posterPath = cursor.getString(cursor.getColumnIndex(Contract.FavoriteMovieDatabase.FAVORITE_POSTER_PATH));
posterPathArrayList.add(BASE_POSTER_URL + posterPath);
int movieId = cursor.getInt(cursor.getColumnIndex("movie_id"));
URL favoriteURL = NetworkUtils.buildUrl("favorites", movieId);
urlArrayList.add(favoriteURL);
} while (cursor.moveToNext());
Log.d("urllist", "" + urlArrayList.toString());
new FetchFavorites().execute(urlArrayList, null, null);
mAdapter = new MainActivityAdapter(MainActivity.this, posterPathArrayList, favoriteJsonArray);
mRecyclerView.setAdapter(mAdapter);
} else {
mRecyclerView.setVisibility(View.INVISIBLE);
mNoFavorites.setVisibility(View.VISIBLE);
}
} catch (java.lang.NullPointerException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
private void noConnection() {
mErrorMessage.setText(R.string.no_connection);
mErrorMessage.setVisibility(View.VISIBLE);
mRetry.setText(R.string.retry);
mRetry.setVisibility(View.VISIBLE);
}
public void tryToConnect(View v) {
try {
url = NetworkUtils.buildUrl("most_popular");
} catch (MalformedURLException e) {
e.printStackTrace();
}
if (url != null) {
mErrorMessage.setVisibility(View.INVISIBLE);
mRetry.setVisibility(View.INVISIBLE);
new FetchMovies().execute(url, null, null);
}
}
private class FetchMovies extends AsyncTask<URL, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgessBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(URL... params) {
URL searchUrl = params[0];
String searchResults = null;
try {
searchResults = NetworkUtils.getResponseFromHttpUrl(searchUrl);
} catch (IOException e) {
e.printStackTrace();
}
return searchResults;
}
#Override
protected void onPostExecute(String searchResults) {
mProgessBar.setVisibility(View.INVISIBLE);
try {
posterList = new ArrayList<>();
if (searchResults != null && !searchResults.equals("")) {
JSONObject jsonObject = new JSONObject(searchResults);
JSONArray pageOne = jsonObject.getJSONArray("results");
int length = pageOne.length();
for (int i = 0; i < length; i++) {
JSONObject result = pageOne.getJSONObject(i);
String posterPath = BASE_POSTER_URL + result.getString("poster_path");
posterList.add(posterPath);
}
mAdapter = new MainActivityAdapter(MainActivity.this, posterList, pageOne);
mRecyclerView.setAdapter(mAdapter);
} else noConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private class FetchFavorites extends AsyncTask<ArrayList<URL>, Void, ArrayList<String>> {
#Override
protected ArrayList<String> doInBackground(ArrayList<URL>... params) {
ArrayList<URL> urlArrayList = params[0];
ArrayList<String> stringArrayList = new ArrayList<>();
String searchResults;
URL searchUrl;
favoriteJsonArray = new JSONArray();
for (int i = 0; i < urlArrayList.size(); i++)
try {
searchUrl = urlArrayList.get(i);
searchResults = NetworkUtils.getResponseFromHttpUrl(searchUrl);
stringArrayList.add(searchResults);
} catch (IOException e) {
e.printStackTrace();
}
return stringArrayList;
}
#Override
protected void onPostExecute(ArrayList<String> stringArrayList) {
for (int i = 0; i < stringArrayList.size(); i++)
try {
favoriteJsonArray.put(new JSONObject(stringArrayList.get(i)));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
urlArrayList gets updated correctly when database changes occur, but favoriteJsonArray, which is updated inside AsyncTask, does not. Why?
There are two problems in you code:
in FetchFavorites.doInBackground(), you assign a new JSONArray() to favoriteJsonArray, but your mAdapter is still hold the old reference, which is an empty JSONArray.
you didn't call mAdapter.notifyDataSetChanged() after update the favoriteJsonArray.
You can solve the problems in to ways:
do not new JSONArray() in FetchFavorites.doInBackground(), and call mAdapter.notifyDataSetChanged() after update the favoriteJsonArray, but there is still a problem, you should clear the favoriteJsonArray every time you fetch the new data, and clear a JSONArray is kind of boring (there is no clear() method).
new JSONArray(), but edit your MainActivityAdapter, add a method like setFavorites(JSONArray array), and set the new created favoriteJsonArray to it then call mAdapter.notifyDataSetChanged().

how add marker on map onmaplong click?

Address Dailoge This is an Fragment when I click on image another activity (Location Activity)start in which Google map open.
Here is code of Address Dailoge fragment
when map open i want show the Current Location of user and user select the location from map using map picker
when user select the Location i want to take the Addresses of the street zipcode,state,country set it to the form.
public class AddressDialog extends DialogFragment {
public interface AddressListener {
void address(Address address);
void editedAddress(Address locationModel, int index);
}
private static final String TAG = "AddressDialog";
#BindView(R.id.addresslineone)
FormAnimationView addresslineone;
private GoogleApiClient mClient;
#BindView(R.id.addresslinetwo)
FormAnimationView addresslinetwo;
#BindView(R.id.city)
FormAnimationView cityView;
#BindView(R.id.state)
FormAnimationView stateView;
#BindView(R.id.country)
FormAnimationView countryView;
private boolean isfromEdit;
#BindView(R.id.pincode)
FormAnimationView pincode;
#BindView(R.id.edit_spinner_1)
EditSpinner mEditSpinner1;
private Address address = new Address();
private AddressListener addressListener;
private int index;
#OnClick(R.id.closedialog)
public void closeClick() {
this.dismiss();
}
#BindView(R.id.searchmap)
ImageView openmap;
#OnClick(R.id.searchmap)
public void searchmapclick() {
startActivityForResult(new Intent(getActivity(), LocationActivity.class), 100);
}
#OnClick(R.id.addaddressimg)
public void addClick() {
if (addressListener != null && address != null) {
if (!TextUtils.isEmpty(mEditSpinner1.getText()) &&
!TextUtils.isEmpty(addresslineone.getText())
&& !TextUtils.isEmpty(addresslinetwo.getText())
&& !TextUtils.isEmpty(cityView.getText())
&& !TextUtils.isEmpty(stateView.getText())
&& !TextUtils.isEmpty(pincode.getText())
&& !TextUtils.isEmpty(countryView.getText())) {
//locationModel.setAddressType(mEditSpinner1.getText().toString());
//address.setCountry(addresslinetwo.getText().toString());
// address.setLocality();
//address.setLocality("");
address.setRegion(stateView.getText().toString());
address.setFormatted(addresslineone.getText().toString());
address.setFormatted(addresslinetwo.getText().toString());
address.setCountry(countryView.getText().toString());
address.setLocality(cityView.getText().toString());
// address.setState(stateView.getText().toString());
address.setPostalCode(pincode.getText().toString());
address.setStreetAddress(addresslineone.getText().toString());
address.setStreetAddress(addresslinetwo.getText().toString());
address.setType(mEditSpinner1.getText().toString());
// address.setRegion();
if (!isfromEdit) {
addressListener.address(address);
} else {
addressListener.editedAddress(address, address.getIndex());
}
this.dismiss();
} else {
Toast.makeText(getActivity(), "All fields are mandetory", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onStart() {
super.onStart();
mClient.connect();
}
#Override
public void onStop() {
mClient.disconnect();
super.onStop();
}
// #Override
// public void onAttach(Context context) {
// super.onAttach(context);
// //addressListener = (AddressListener) context;
// }
public void setListener(AddressListener addressListener) {
this.addressListener = addressListener;
}
/* #NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final View view = View.inflate(getActivity(), R.layout.address_selection_view, null);
Dialog dialog = new Dialog(getActivity(), R.style.DialogFragment);
dialog.setContentView(view);
return dialog;
}*/
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
// getDialog().getWindow().getWindowStyle().gets;
View rootView = inflater.inflate(R.layout.address_selection_view, container, false);
// getDialog().setTitle("Simple Dialog");
ButterKnife.bind(this, rootView);
mClient = new GoogleApiClient
.Builder(getContext())
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.build();
try {
Address locationModel = (Address) getArguments().get("data");
if (locationModel != null) {
// getAddressDetails(locationModel.getAddress());
address.setAddressId(locationModel.getAddressId());
address.setFormatted("");
address.setCountry(addresslinetwo.getText().toString());
address.setLocality("");
address.setRegion("");
address.setPostalCode(pincode.getText().toString());
address.setStreetAddress(addresslineone.getText().toString());
address.setStreetAddress(addresslinetwo.getText().toString());
addresslineone.setText(locationModel.getStreetAddress());
addresslinetwo.setText(locationModel.getStreetAddress());
/*addresslinetwo.setText(locationModel.getCountry());*/
pincode.setText(locationModel.getPostalCode());
mEditSpinner1.setText(locationModel.getType());
countryView.setText(locationModel.getCountry());
stateView.setText(locationModel.getRegion());
cityView.setText(locationModel.getLocality());
isfromEdit = true;
}
} catch (Exception e) {
}
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
init();
}
private void init() {
addresslineone.setHintMessage("Address Line 1 (Street / landmark)");
addresslineone.setInputType(InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS);
addresslineone.setTintColor(Color.parseColor("#de3f5abd"));
addresslineone.setFontStyle("fonts/Helvetica.otf");
addresslinetwo.setHintMessage("Address Line 2 (City / Country)");
addresslinetwo.setInputType(InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS);
addresslinetwo.setTintColor(Color.parseColor("#de3f5abd"));
addresslinetwo.setFontStyle("fonts/Helvetica.otf");
pincode.setHintMessage("Post / Zip / Pin Code");
pincode.setInputType(InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS);
pincode.setFontStyle("fonts/Helvetica.otf");
pincode.setTintColor(Color.parseColor("#de3f5abd"));
stateView.setInputType(InputType.TYPE_CLASS_TEXT);
stateView.setHintMessage("State");
stateView.setTintColor(Color.parseColor("#de3f5abd"));
stateView.setFontStyle("fonts/Helvetica.otf");
countryView.setInputType(InputType.TYPE_CLASS_TEXT);
countryView.setHintMessage("Country");
countryView.setTintColor(Color.parseColor("#de3f5abd"));
countryView.setFontStyle("fonts/Helvetica.otf");
cityView.setInputType(InputType.TYPE_CLASS_TEXT);
cityView.setHintMessage("City");
cityView.setTintColor(Color.parseColor("#de3f5abd"));
cityView.setFontStyle("fonts/Helvetica.otf");
ListAdapter adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item,
getResources().getStringArray(R.array.edits_array_1));
mEditSpinner1.setAdapter(adapter);
}
public void getAddressDetails(String address) {
StringBuilder stringBuilder = new StringBuilder();
if (address != null) {
String[] addressSlice = address.toString().split(", ");
String country = addressSlice[addressSlice.length - 1];
if (country != null) {
addresslinetwo.setText(country);
countryView.setText(country);
}
stringBuilder.append("Country:" + country);
if (addressSlice.length > 1) {
String[] stateAndPostalCode = addressSlice[addressSlice.length - 2].split(" ");
if (stateAndPostalCode.length > 1) {
String postalCode = stateAndPostalCode[stateAndPostalCode.length - 1];
String state = "";
for (int i = 0; i < stateAndPostalCode.length - 1; i++) {
state += (i == 0 ? "" : " ") + stateAndPostalCode[i];
}
stringBuilder.append("PostalCode:" + postalCode);
stringBuilder.append("State:" + state);
if (postalCode != null) {
pincode.setText(postalCode);
}
if (state != null) {
stateView.setText("" + state);
// pincode.setText(pincode.getText() + "," + state);
}
} else {
String state = stateAndPostalCode[stateAndPostalCode.length - 1];
stringBuilder.append("State:" + state);
stateView.setText("" + state);
}
}
String city = null;
if (addressSlice.length > 2)
city = addressSlice[addressSlice.length - 3].toString();
if (city != null) {
cityView.setText("" + city);
// addresslinetwo.setText(addresslinetwo.getText() + "," + city);
stringBuilder.append("City:" + city);
}
String stAddress1 = "";
if (addressSlice.length == 4)
stAddress1 = addressSlice[0];
else if (addressSlice.length > 3) {
String stAddress2 = addressSlice[addressSlice.length - 4];
for (int i = 0; i < addressSlice.length - 4; i++) {
stAddress1 += (i == 0 ? "" : ", ") + addressSlice[i];
}
}
stringBuilder.append("Address1:" + stAddress1);
if (stAddress1 != null) {
addresslineone.setText(stAddress1);
// addresslineone.getText().replaceAll("null", "");
}
}
// if(place.getLatLng()!=null)
// {
// String latitude = "" + place.getLatLng().latitude;
// String longitude = "" + place.getLatLng().longitude;
// }
Log.e(TAG, "getAddressDetails: " + stringBuilder.toString());
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Log.e(TAG, "onActivityResult: " + requestCode);
if (requestCode == 100) {
try {
if (data.getExtras() != null && data.getExtras().getSerializable("data") != null) {
LocationModel locationModel = (LocationModel) data.getExtras().getSerializable("data");
if (locationModel != null) {
// addresslineone.setText(locationModel.getLocationname());
getAddressDetails(locationModel.getAddress());
//latitude = String.valueOf(locationModel.getLatitude());
//longitude = String.valueOf(locationModel.getLongitude());
}
}
} catch (Exception e) {
}
}
}
}
Here is the code of Location Activity
Map
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.location.places.ui.PlaceSelectionListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.planfisheye.fisheye.BaseActivity;
import com.planfisheye.fisheye.R;
import com.planfisheye.fisheye.adapters.NearByGetLocationParser;
import com.planfisheye.fisheye.adapters.PlacesAutoCompleteAdapter;
import com.planfisheye.fisheye.adapters.PlacesModel;
import com.planfisheye.fisheye.helper.CustomDialog;
import com.planfisheye.fisheye.models.LocationModel;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Created by venkateshmurthy on 24/12/16.
*/
public class LocationActivity extends BaseActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener, PlaceSelectionListener {
private static final String TAG = "LocationActivity";
MapView mapView;
GoogleMap map;
private GoogleApiClient mClient;
#BindView(R.id.autocompletesearch)
AutoCompleteTextView autoSearch;
private static final int REQUEST_SELECT_PLACE = 1000;
private LatLng latlangObj;
private String address;
private String locationname;
private CustomDialog mCustomDialog;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
#OnClick(R.id.doneclick)
public void doneClick() {
if(latlangObj!=null) {
LocationModel locationModel=new LocationModel();
locationModel.setLatitude(latlangObj.latitude);
locationModel.setLongitude(latlangObj.longitude);
locationModel.setLocationname(locationname);
locationModel.setAddress(address);
Intent intent=new Intent();
intent.putExtra("data",locationModel);
setResult(13, intent);
finish();
}else {
finish();
}
overridePendingTransition(R.anim.enter, R.anim.exit);
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_select);
ButterKnife.bind(this);
mapView = (MapView) findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mCustomDialog=new CustomDialog(this);
// try {
// Intent intent = new PlaceAutocomplete.IntentBuilder
// (PlaceAutocomplete.MODE_OVERLAY)
// // .setBoundsBias(BOUNDS_MOUNTAIN_VIEW)
// .build(this);
// startActivityForResult(intent, REQUEST_SELECT_PLACE);
// } catch (GooglePlayServicesRepairableException |
// GooglePlayServicesNotAvailableException e) {
// e.printStackTrace();
// }
// PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
// getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
// autocompleteFragment.setOnPlaceSelectedListener(this);
// autocompleteFragment.setHint("Search a Location");
mClient = new GoogleApiClient
.Builder(this)
.addApi(Places.GEO_DATA_API)
.enableAutoManage(this, this)
.addApi(Places.PLACE_DETECTION_API)
.build();
mClient.connect();
autoSearch.setAdapter(new PlacesAutoCompleteAdapter(this, R.layout.autocomplete_list_item));
autoSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
autoSearch.setText("");
}
});
autoSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//CommonUtils.hideKeyBoard(getActivity());
mCustomDialog.show();
final PlacesModel hm = (PlacesModel) autoSearch.getAdapter().getItem(position);
Log.e("place_id", "" + hm.getPlaceid());
// placetext.setText("" + hm.getDescription());
//AIzaSyA9_CVo9IETbjjqqBHC1eEYesVsaMPflIk
String[] codeInfo =
TextUtils.split(hm.getDescription(), ",");
// getLatLng(hm.getPlaceid());
Places.GeoDataApi.getPlaceById(mClient, hm.getPlaceid())
.setResultCallback(new ResultCallback<PlaceBuffer>() {
#Override
public void onResult(PlaceBuffer places) {
mCustomDialog.dismiss();
if (places.getStatus().isSuccess() && places.getCount() > 0) {
final Place myPlace = places.get(0);
//getAddressDetails(myPlace);
Log.e("name", "Place found: " + myPlace.getName() + "\t" + myPlace.getAddress()+"\t"+myPlace.getLatLng());
if(myPlace.getAddress()!=null) {
address = myPlace.getAddress().toString();
}
latlangObj= myPlace.getLatLng();
locationname=hm.getDescription();
Log.e("latitude:", "" + latlangObj.latitude);
Log.e("longitude:", "" + latlangObj.longitude);
Marker marker = map.addMarker(new MarkerOptions()
.position(new LatLng(latlangObj.latitude, latlangObj.longitude))
.title("" + hm.getDescription()));
marker.showInfoWindow();
marker.setDraggable(true);
map.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12.0f));
} else {
Log.e("place", "Place not found");
}
places.release();
}
});
autoSearch.setText(""+hm.getDescription());
autoSearch.setSelection(autoSearch.getText().length());
}
});
// Needs to call MapsInitializer before doing any CameraUpdateFactory calls
MapsInitializer.initialize(this);
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
mClient.disconnect();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
public void onMapReady(GoogleMap googleMap) {
this.map = googleMap;
}
#Override
public void onPlaceSelected(Place place) {
}
#Override
public void onError(Status status) {
}
private class NearbyLatlngTask extends AsyncTask<String, Integer, String> {
String data = null;
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result) {
GetLatLngTask parserTask = new GetLatLngTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class GetLatLngTask extends AsyncTask<String, Integer, List<HashMap<String, Double>>> {
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String, Double>> doInBackground(String... jsonData) {
List<HashMap<String, Double>> places = null;
NearByGetLocationParser nearPlaceJsonParser = new NearByGetLocationParser();
try {
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a List construct */
places = nearPlaceJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String, Double>> list) {
// Clears all the existing markers
// mGoogleMap.clear();
if (list != null) {
for (int i = 0; i < list.size(); i++) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, Double> hmPlace = list.get(i);
// Getting latitude of the place
double lat = hmPlace.get("lat");
// Getting longitude of the place
double lng = hmPlace.get("lng");
Log.e("lat", "lat" + lat);
Log.e("long", "long" + lng);
Toast.LENGTH_SHORT).show();
}
}
}
}
/**
* 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;
}
private void getLatLng(String placeID) {
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/details/json?placeid=" + placeID);
sb.append("&key=AIzaSyBiV3T00af_2jM0Vinlcws2Gc6K7ktVp38");
NearbyLatlngTask placesTask = new NearbyLatlngTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
Check this,
map.setOnMapLongClickListener(new OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latLng) {
addMarker();
}
});
add this is addMarker method,
private void addMarker() {
// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps");
googleMap.addMarker(marker);
}

Android get attribute value from xml

I am trying to make an app which uses last.fm's web API, sends a query for similar artists and returns all the names of the similar artists. It seems as though I manage to connect and get the xml response properly. However, I cannot extract the value of the name-attribute. I am using artistName = xmlData.getAttributeValue(null, "name"); but all it gives me is null.
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.*;
#SuppressWarnings("FieldCanBeLocal")
public class MainActivity extends Activity implements Observer {
private final String INPUTERROR = "Invalid/missing artist name.";
private NetworkCommunication nc;
private ArrayList<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nc = new NetworkCommunication();
nc.register(this);
list = new ArrayList<>();
ListView lv = (ListView)findViewById(R.id.ListView_similarArtistsList);
ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}
public void searchButton_Clicked(View v){
EditText inputField = (EditText)findViewById(R.id.editText_artistName);
String searchString = inputField.getText().toString();
searchString = cleanSearchString(searchString);
if(validateSearchString(searchString)){
nc.setSearchString(searchString);
nc.execute();
}
else{
Toast.makeText(MainActivity.this, INPUTERROR, Toast.LENGTH_SHORT).show();
}
}
private String cleanSearchString(String oldSearchString){
String newString = oldSearchString.trim();
newString = newString.replace(" ", "");
return newString;
}
private boolean validateSearchString(String searchString){
boolean rValue = true;
if(TextUtils.isEmpty(searchString)){
rValue = false;
}
return rValue;
}
#Override
public void update(String artistName) {
list.add(artistName);
}
}
Here is my Network Communications class:
import android.os.AsyncTask;
import android.util.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
#SuppressWarnings("FieldCanBeLocal")
class NetworkCommunication extends AsyncTask<Object, String, Integer> implements Subject {
private final String MYAPIKEY = "--------------------------";
private final String ROOT = "http://ws.audioscrobbler.com/2.0/";
private final String METHOD = "?method=artist.getsimilar";
private ArrayList<Observer> observers;
private int amountOfArtists = 0;
private String foundArtistName;
private String searchString;
NetworkCommunication(){
observers = new ArrayList<>();
}
void setSearchString(String newSearchString){
searchString = newSearchString;
}
private XmlPullParser sendRequest(){
try{
URL url = new URL(ROOT + METHOD + "&artist=" + searchString + "&api_key=" + MYAPIKEY);
XmlPullParser receivedData = XmlPullParserFactory.newInstance().newPullParser();
receivedData.setInput(url.openStream(), null);
return receivedData;
}
catch (IOException | XmlPullParserException e){
Log.e("ERROR", e.getMessage(), e);
}
return null;
}
private int tryProcessData(XmlPullParser xmlData){
int artistsFound = 0;
String artistName;
int eventType;
try{
while ((eventType = xmlData.next()) != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if(xmlData.getName().equals("name")){
artistName = xmlData.getAttributeValue(null, "name");
publishProgress(artistName);
artistsFound++;
}
}
}
}
catch (IOException | XmlPullParserException e){
Log.e("ERROR", e.getMessage(), e);
}
if (artistsFound == 0) {
publishProgress();
}
return artistsFound;
}
#Override
protected Integer doInBackground(Object... params) {
XmlPullParser data = sendRequest();
if(data != null){
return tryProcessData(data);
}
else{
return null;
}
}
#Override
protected void onProgressUpdate(String... values){
/*
if (values.length == 0) {
//No data found...
}
*/
if (values.length == 1) {
setFoundArtistName(values[0]);
notifyObserver();
}
super.onProgressUpdate(values);
}
private void setFoundArtistName(String newArtistName){
foundArtistName = newArtistName;
}
#Override
public void register(Observer newObserver) {
observers.add(newObserver);
}
#Override
public void unregister(Observer deleteObserver) {
observers.remove(deleteObserver);
}
#Override
public void notifyObserver() {
for (Observer o : observers) {
Log.i("my tag.... ", "name = " + foundArtistName);
o.update(foundArtistName);
}
}
}
Here's a screenshot of the xml response in Google Chrome:
The only thing I am interested in extracting at this moment is the the value of the Name-Element.
I am logging the value of foundArtistName (in the method notifyObserver) it gives me A LOT of "my tag.... name = null my tag.... name = null my tag.... name = null etc.."
EDIT: I tried using getText() instead of getAttributeValue(), but it also gives me null.
I found the solution. I was using: artistName = xmlData.getAttributeValue(null, "name");, when I really should've used: artistName = xmlData.nextText();

My list is loading again when I am Pressing Back Button

I am also getting ArrayListIndexOutofBound when I am pressing list item when the orientation is changed.As far my knowledge of android I have written Parcelable code correctly.But I think my issues are with the recycler view setup.I am confused with two declaration of my adapter.Help me
MainActivity.class
package com.reader.ashishyadav271.hackernewsmaterial;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.os.PersistableBundle;
import android.support.v4.util.LruCache;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import com.wang.avi.AVLoadingIndicatorView;
import org.json.JSONArray;
import org.json.JSONObject;
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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements MyCustomAdapter.ClickListener {
private static final String STATE_LIST = "state_list";
Map<Integer, String> articleURLs = new HashMap<>();
Map<Integer, String> articleTitles = new HashMap<>();
Map<Integer, String> articleDates =new HashMap<>();
Map<Integer, String> articleAuthors =new HashMap<>();
ArrayList<Integer> articleIds=new ArrayList<>();
SQLiteDatabase articlesDB;
ArrayList<Information> data=new ArrayList<>();
ArrayList<String> titles=new ArrayList<>();
ArrayList<String> urls=new ArrayList<>();
ArrayList<String> authors=new ArrayList<>();
ArrayList<String> dateAndTimes=new ArrayList<>();
MyCustomAdapter adapter;
RecyclerView recyclerView;
AVLoadingIndicatorView av;
List<DownloadTask> tasks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
av= (AVLoadingIndicatorView) findViewById(R.id.avloadingIndicatorView);
av.setVisibility(View.INVISIBLE);
tasks = new ArrayList<>();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView= (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(
getApplicationContext()
));
articlesDB = this.openOrCreateDatabase("Articles", MODE_PRIVATE, null);
articlesDB.execSQL("CREATE TABLE IF NOT EXISTS article (id INTEGER PRIMARY KEY," +
" articleId INTEGER," +
" url VARCHAR," +
" title VARCHAR," +
" author VARCHAR," +
" date VARCHAR)");
if(savedInstanceState != null) {
data=savedInstanceState.getParcelableArrayList(STATE_LIST);
adapter=new MyCustomAdapter(getApplicationContext(),data);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}else{
if (isOnline()) {
requestData("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty");
} else {
updateDisplay();
Toast.makeText(this, "Network isn't available", Toast.LENGTH_LONG).show();
}
}
//adapter=new MyCustomAdapter(getApplicationContext(),getData());
//adapter.setClickListener(this);
//recyclerView.setAdapter(adapter);
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
private void requestData(String uri) {
DownloadTask task = new DownloadTask();
task.execute(uri);
}
#Override
public void itemClicked(View view, int position) {
Intent i = new Intent(getApplicationContext(), Main2Activity.class);
i.putExtra("articleUrl", urls.get(position));
startActivity(i);
}
protected void updateDisplay() {
adapter=new MyCustomAdapter(getApplicationContext(),getData());
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(STATE_LIST, data);
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if (tasks.size() == 0) {
av.setVisibility(View.VISIBLE);
}
tasks.add(this);
}
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
JSONArray jsonArray = new JSONArray(result);
articlesDB.execSQL("DELETE FROM article");
for (int i = 0; i < 15; i++) {
String articleId = jsonArray.getString(i);
url = new URL("https://hacker-news.firebaseio.com/v0/item/" + articleId + ".json?print=pretty");
urlConnection = (HttpURLConnection) url.openConnection();
in = urlConnection.getInputStream();
reader = new InputStreamReader(in);
data = reader.read();
String articleInfo = "";
while (data != -1 ) {
char current = (char) data;
articleInfo += current;
data = reader.read();
}
JSONObject jsonObject = new JSONObject(articleInfo);
String articleTitle = jsonObject.getString("title");
String articleURL = jsonObject.getString("url");
String articleDate=jsonObject.getString("time");
String articleAuthor=jsonObject.getString("by");
long unixSeconds = Long.valueOf(articleDate);
Date date = new Date(unixSeconds*1000L); // *1000 is to convert seconds to milliseconds
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); // the format of your date
String formattedarticleDate = sdf.format(date);
articleIds.add(Integer.valueOf(articleId));
articleTitles.put(Integer.valueOf(articleId), articleTitle);
articleURLs.put(Integer.valueOf(articleId), articleURL);
articleDates.put(Integer.valueOf(articleId), formattedarticleDate);
articleAuthors.put(Integer.valueOf(articleId), articleAuthor);
String sql = "INSERT INTO article (articleId, url, title, author, date) VALUES (? , ? , ? , ?, ?)";
SQLiteStatement statement = articlesDB.compileStatement(sql);
statement.bindString(1, articleId);
statement.bindString(2, articleURL);
statement.bindString(3, articleTitle);
statement.bindString(4, articleAuthor);
statement.bindString(5, formattedarticleDate);
statement.execute();
}
}catch (Exception e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
tasks.remove(this);
if (tasks.size() == 0) {
av.setVisibility(View.INVISIBLE);
}
updateDisplay();
}
}
private List<Information> getData() {
/*List<Information> data=new ArrayList<>();
for(int i=0;i<20;i++){
titles.add(i,"Wikileaks Asssange wins UN ruling on arbitrary detention");
url.add(i,"https://www.google.co.in/search?q=best+custom+list+row");
date.add(i,"3 hrs");
author.add(i,"aburan28");
}
for(int i=0;i<20;i++){
Information current=new Information();
current.title=titles.get(i);
current.url=url.get(i);
current.author=author.get(i);
current.date=date.get(i);
data.add(current);
}
return data;*/
Cursor c = articlesDB.rawQuery("SELECT * FROM article", null);
try {
int urlIndex = c.getColumnIndex("url");
int titleIndex = c.getColumnIndex("title");
int authorIndex = c.getColumnIndex("author");
int dateIndex = c.getColumnIndex("date");
c.moveToFirst();
titles.clear();
//urls.clear();
authors.clear();
dateAndTimes.clear();
int i=0;
while (c != null) {
titles.add(c.getString(titleIndex));
urls.add(c.getString(urlIndex));
authors.add(c.getString(authorIndex));
dateAndTimes.add(c.getString(dateIndex));
Information current=new Information();
current.title=titles.get(i);
current.url=urls.get(i);
current.author=authors.get(i);
current.date = dateAndTimes.get(i);
data.add(current);
i++;
c.moveToNext();
}
}catch (Exception e) {
e.printStackTrace();
}finally {
c.close();
}
return data;
}
#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) {
startActivity(new Intent(getApplicationContext(),SettingsActivity.class));
return true;
}
if (id == R.id.action_about) {
startActivity(new Intent(getApplicationContext(),About.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
Information.class
package com.reader.ashishyadav271.hackernewsmaterial;
import android.os.Parcel;
import android.os.Parcelable;
public class Information implements Parcelable {
public String title;
public String author;
public String date;
public String url;
public Information(){
}
protected Information(Parcel in) {
title = in.readString();
author = in.readString();
date = in.readString();
url = in.readString();
}
public static final Creator<Information> CREATOR = new Creator<Information>() {
#Override
public Information createFromParcel(Parcel in) {
return new Information(in);
}
#Override
public Information[] newArray(int size) {
return new Information[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(author);
dest.writeString(date);
dest.writeString(url);
}
}
Log Cat Error
02-06 14:52:58.106 8369-8369/com.reader.ashishyadav271.hackernewsmaterial E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.reader.ashishyadav271.hackernewsmaterial, PID: 8369
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.reader.ashishyadav271.hackernewsmaterial.MainActivity.itemClicked(MainActivity.java:137)
at com.reader.ashishyadav271.hackernewsmaterial.MyCustomAdapter$MyViewHolder.onClick(MyCustomAdapter.java:77)
at android.view.View.performClick(View.java:4471)
at android.view.View$PerformClick.run(View.java:18778)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5345)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
at dalvik.system.NativeStart.main(Native Method)
Now I get it after years.I would have simply used.
FLAG_ACTIVITY_CLEAR_TOP - If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.

RingtonePreference Theme

Im creating an Android App, totaly in Holo.Light Theme.
All the preferences are light, except for the Ringtonepreference!
I have even tried setting the BGColor and the textColor in the Preferences.xml:
<RingtonePreference
android:icon="#drawable/ic_menu_note"
android:key="ringtone"
android:persistent="true"
android:summary="#string/settings_ringtone2"
android:background="#000000"
android:textColor="#ffffff"
android:title="#string/settings_ringtone" />
Android ignores everything..
Has anybody a clue on how to change the Theme of the RingtonePreference to Holo.Light?
I have found an answer myself, couse as it seems, no App can touch the Ringtonemanager's settings..
So what I did is extending the Listpreference:
package de.Psychologie.socialintelligence;
import java.io.IOException;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Parcel;
import android.os.Parcelable;
import android.preference.ListPreference;
import android.util.AttributeSet;
public class CustomRingtonepreference extends ListPreference{
private MediaPlayer mMediaPlayer;
CharSequence[] mEntries;
CharSequence[] mEntryValues;
private int mClickedDialogEntryIndex;
private String mValue;
public CustomRingtonepreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomRingtonepreference(Context context) {
super(context);
}
/**
* Sets the value of the key. This should be one of the entries in
* {#link #getEntryValues()}.
*
* #param value The value to set for the key.
*/
public void setValue(String value) {
mValue = value;
persistString(value);
}
/**
* Sets the value to the given index from the entry values.
*
* #param index The index of the value to set.
*/
public void setValueIndex(int index) {
if (mEntryValues != null) {
setValue(mEntryValues[index].toString());
}
}
/**
* Returns the value of the key. This should be one of the entries in
* {#link #getEntryValues()}.
*
* #return The value of the key.
*/
public String getValue() {
return mValue;
}
/**
* Returns the entry corresponding to the current value.
*
* #return The entry corresponding to the current value, or null.
*/
public CharSequence getEntry() {
int index = getValueIndex();
return index >= 0 && mEntries != null ? mEntries[index] : null;
}
public int findIndexOfValue(String value) {
if (value != null && mEntryValues != null) {
for (int i = mEntryValues.length - 1; i >= 0; i--) {
if (mEntryValues[i].equals(value)) {
return i;
}
}
}
return -1;
}
private int getValueIndex() {
return findIndexOfValue(mValue);
}
#Override
protected void onPrepareDialogBuilder(Builder builder) {
super.onPrepareDialogBuilder(builder);
mMediaPlayer = new MediaPlayer();
mEntries = getEntries();
mEntryValues = getEntryValues();
if (mEntries == null || mEntryValues == null) {
throw new IllegalStateException(
"ListPreference requires an entries array and an entryValues array.");
}
mClickedDialogEntryIndex = getValueIndex();
builder.setSingleChoiceItems(mEntries, mClickedDialogEntryIndex,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mClickedDialogEntryIndex = which;
String value = mEntryValues[which].toString();
try {
playSong(value);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
builder.setPositiveButton("OK", this);
builder.setNegativeButton("Abbrechen", this);
}
private void playSong(String path) throws IllegalArgumentException,
IllegalStateException, IOException {
//Log.d("ringtone", "playSong :: " + path);
mMediaPlayer.reset();
mMediaPlayer.setDataSource(path);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
// mMediaPlayer.setLooping(true);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
#Override
protected void onRestoreInstanceState(Parcelable state) {
if (state == null || !state.getClass().equals(SavedState.class)) {
// Didn't save state for us in onSaveInstanceState
super.onRestoreInstanceState(state);
return;
}
SavedState myState = (SavedState) state;
super.onRestoreInstanceState(myState.getSuperState());
setValue(myState.value);
}
private static class SavedState extends BaseSavedState {
String value;
public SavedState(Parcel source) {
super(source);
value = source.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeString(value);
}
public SavedState(Parcelable superState) {
super(superState);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult && mClickedDialogEntryIndex >= 0 && mEntryValues != null) {
String value = mEntryValues[mClickedDialogEntryIndex].toString();
if (callChangeListener(value)) {
setValue(value);
}
}
mMediaPlayer.stop();
mMediaPlayer.release();
}
#Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getString(index);
}
#Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
setValue(restoreValue ? getPersistedString(mValue) : (String) defaultValue);
}
#Override
protected Parcelable onSaveInstanceState() {
final Parcelable superState = super.onSaveInstanceState();
if (isPersistent()) {
// No need to save instance state since it's persistent
return superState;
}
final SavedState myState = new SavedState(superState);
myState.value = getValue();
return myState;
}
}
And vor adding the Values I chose the Programmatical way:
//Import All Ringtones
RingtoneManager rm = new RingtoneManager(UserSettingActivity.this);
rm.setType(RingtoneManager.TYPE_ALARM|RingtoneManager.TYPE_RINGTONE );
final Cursor ringtones = rm.getCursor();
List<String> mEntries = new ArrayList<String>();
List<String> mEntryValues = new ArrayList<String>();
for (ringtones.moveToFirst(); !ringtones.isAfterLast(); ringtones.moveToNext()) {
mEntries.add(ringtones.getString(RingtoneManager.TITLE_COLUMN_INDEX));
mEntryValues.add(ringtones.getString(RingtoneManager.URI_COLUMN_INDEX));
}
ringtonepref.setEntryValues(mEntryValues.toArray(new CharSequence[mEntryValues.size()]));
ringtonepref.setEntries(mEntries.toArray(new CharSequence[mEntries.size()]));
And for the initial Initiation with the default Ringtone:
//Sets the default Alarm to the chosen Value
ringtonepref.setValue(RingtoneManager.getActualDefaultRingtoneUri(getBaseContext(), RingtoneManager.TYPE_ALARM).toString());
I hope it helps someone ;)
Well, after spending half the night to get it working, I got a proper solution. I took the advice Trinitrotoluol has written here and merged this with my own functionality. Here is my CustomListPreference (complete, with no step missing)...
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.preference.ListPreference;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.RadioButton;
import java.util.ArrayList;
import java.util.List;
public class CustomListPreference extends ListPreference {
/* Konstante */
private final String TAG = ((Object) this).getClass().getSimpleName();
Context mContext;
LayoutInflater mInflater;
ArrayList<RadioButton> mButtonList;
private MediaPlayer mMediaPlayer;
CharSequence[] mEntries;
CharSequence[] mEntryValues;
private int mActivePositionInList;
private int mTmpActivePositionInList;
private String mValue;
private String mPath;
private String mTmpPath;
public CustomListPreference(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
mInflater = LayoutInflater.from(context);
mButtonList = new ArrayList<RadioButton>();
Log.d(TAG, "Konstruktor");
// Manager für Benachrichtigungstöne
RingtoneManager ringtoneManager = new RingtoneManager(context);
ringtoneManager.setType(RingtoneManager.TYPE_NOTIFICATION);
final Cursor ringtones = ringtoneManager.getCursor();
List<String> entries = new ArrayList<String>();
List<String> entryValues = new ArrayList<String>();
loadData();
// keine Töne (disabled notification / "warnings")
entries.add("Keine");
entryValues.add("NONE");
for (ringtones.moveToFirst(); !ringtones.isAfterLast(); ringtones.moveToNext()) {
// Anzeige (displays data to screen)
entries.add(ringtones.getString(RingtoneManager.TITLE_COLUMN_INDEX));
// ID beziehen (getting the ID to add it at the end of the path)
int id = ringtones.getInt(ringtones.getColumnIndex(MediaStore.MediaColumns._ID));
// ID ans Ende anfügen (attach ID to the end of the path)
entryValues.add(ringtones.getString(RingtoneManager.URI_COLUMN_INDEX) + "/" + id);
Log.d(TAG, "Tone: " + ringtones.getString(RingtoneManager.URI_COLUMN_INDEX) + "/" + id);
}
setEntryValues(entryValues.toArray(new CharSequence[entryValues.size()]));
setEntries(entries.toArray(new CharSequence[entries.size()]));
}
public CustomListPreference(Context context) {
super(context);
}
public void loadData() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor edit = sp.edit();
if (sp.contains("audio_path")) {
mTmpPath = mPath = sp.getString("audio_path", "NONE");
} else {
edit.putString("audio_path", mPath);
edit.commit();
}
if (sp.contains("audio_id")) {
mTmpActivePositionInList = mActivePositionInList = sp.getInt("audio_id", 0);
} else {
edit.putInt("audio_id", 0);
edit.commit();
}
}
public void setValue(String audioPath, int cursorPosition) {
SharedPreferences sp = getPreferenceManager()
.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor edit = sp.edit();
edit.putString("audio_path", audioPath);
edit.putInt("audio_id", cursorPosition);
edit.commit();
}
public void setOldValues() {
SharedPreferences sp = getPreferenceManager()
.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor edit = sp.edit();
edit.putString("audio_path", mTmpPath);
edit.putInt("audio_id", mTmpActivePositionInList);
edit.commit();
}
public void setValueIndex(int index) {
if (mEntryValues != null) {
setValue(mEntryValues[index].toString());
}
}
public String getValue() {
return mValue;
}
public CharSequence getEntry() {
int index = getValueIndex();
return index >= 0 && mEntries != null ? mEntries[index] : null;
}
public int findIndexOfValue(String value) {
if (value != null && mEntryValues != null) {
for (int i = mEntryValues.length - 1; i >= 0; i--) {
if (mEntryValues[i].equals(value)) {
return i;
}
}
}
return -1;
}
private int getValueIndex() {
return findIndexOfValue(mValue);
}
#Override
protected void onPrepareDialogBuilder(Builder builder) {
super.onPrepareDialogBuilder(builder);
mMediaPlayer = new MediaPlayer();
mEntries = getEntries();
mEntryValues = getEntryValues();
if (mEntries == null || mEntryValues == null) {
throw new IllegalStateException(
"ListPreference requires an entries array and an entryValues array.");
}
builder.setSingleChoiceItems(mEntries, mActivePositionInList,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mActivePositionInList = which;
String path = mEntryValues[which].toString();
try {
RingtoneManager.getRingtone(getContext(), Uri.parse(path)).play();
mPath = path;
} catch (Exception e) {
Log.e(TAG, "Fehler beim Abspielen (Error) : " + e);
}
}
});
builder.setPositiveButton("OK", this);
builder.setNegativeButton("Abbrechen", this);
}
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
Log.d(TAG, "pos");
setValue(mPath, mActivePositionInList);
}
if (!positiveResult) {
Log.d(TAG, "neg");
mPath = mTmpPath;
mActivePositionInList = mTmpActivePositionInList;
setOldValues();
}
}
}
to get it right in front on the screen, you can add this snippet to your prefs.xml
<de.yourpackage.right.activities.CustomListPreference
android:dialogTitle="Some text"
android:summary="some text too"
android:title="and more text"
/>
Finally I'm quite happy to get it working now..
PS: if you have questions, feel free to ask.

Categories

Resources