i trying to connect with themoviedb.orgbut there's some issues
MainActivityFragment.java
public class MainActivityFragment extends Fragment {
public Item[] dataAdapter ;
public MainActivityFragment() {
this.updateData();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_fragment, menu);
}
#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.refresh_settings) {
startActivity(new Intent(getActivity(),SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
CustomArrayAdapter adapter =new CustomArrayAdapter(this.getActivity() , R.layout.item , dataAdapter);
// Get a reference to the ListView, and attach this adapter to it.
GridView gridView = (GridView) rootView.findViewById(R.id.main_grid_view);
gridView.setAdapter(adapter);
return rootView;
}
private void updateData() {
GetData DataTask = new GetData();
DataTask.execute();
}
#Override
public void onStart() {
super.onStart();
this.updateData();
}
public class GetData extends AsyncTask<Void, Void, Item[]> {
private final String LOG_TAG = GetData.class.getSimpleName();
private Item[] getDataFromJson(String forecastJsonStr)
throws JSONException{
// These are the names of the JSON objects that need to be extracted.
final String RESULTS = "results";
final String IMG_PATH = "poster_path";
final String TITLE = "title";
JSONObject dataJson = new JSONObject(forecastJsonStr);
JSONArray dataArray = dataJson.getJSONArray(RESULTS);
int numofresults = dataArray.length();
Item[] resultStrs = new Item[0];
for(int i = 0; i < numofresults; i++) {
// For now, using the format "Day, description, hi/low"
String img_path;
String title;
JSONObject movieData = dataArray.getJSONObject(i);
img_path = movieData.getString(IMG_PATH);
img_path ="http://image.tmdb.org/t/p/w185"+img_path;
title = movieData.getString(TITLE);
Item element = new Item(img_path,title);
resultStrs[i] = element;
}
return resultStrs;
}
#Override
protected Item[] doInBackground(Void... strings) {
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String dataJsonStr = null;
String parm = getString(R.string.pref_sort_most);
String api_key = "API KEY";
try {
final String BASE_URL =
"http://api.themoviedb.org/3/discover/movie?";
final String QUERY_PARAM = "sort_by";
final String APPID_PARAM = "api_key";
Uri builtUri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, parm)
.appendQueryParameter(APPID_PARAM, api_key)
.build();
URL url = new URL(builtUri.toString());
// Create the request to themoviedb.org, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
dataJsonStr = buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return getDataFromJson(dataJsonStr);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Item[] result) {
if (result != null) {
dataAdapter = result;
}
// New data is back from the server. Hooray!
}
}
}
CustomArrayAdapter.java
public class CustomArrayAdapter extends ArrayAdapter<Item> {
Context context;
int resource;
Item objects[] = null;
public CustomArrayAdapter(Context context, int resource, Item[] objects) {
super(context, resource, objects);
this.resource = resource;
this.context = context;
this.objects = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
DataHolder holder = null;
if(row == null)
{
row = LayoutInflater.from(getContext()).inflate(
R.layout.item, parent, false);
holder = new DataHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.image_main_item);
holder.txtTitle = (TextView)row.findViewById(R.id.title_movie);
row.setTag(holder);
}else
{
holder = (DataHolder)row.getTag();
}
Item item = objects[position];
holder.txtTitle.setText(item.title);
Picasso.with(context).load(item.icon).into(holder.imgIcon);
return row;
}
static class DataHolder
{
ImageView imgIcon;
TextView txtTitle;
}
}
Item.java
public class Item {
public String icon;
public String title;
public Item(){
super();
}
public Item(String icon, String title) {
super();
this.icon = icon;
this.title = title;
}
}
and here my Logcat
12-23 15:06:40.832 1644-1644/com.example.mohamed.movieapp
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.mohamed.movieapp, PID: 1644
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mohamed.movieapp/com.example.mohamed.movieapp.MainActivity}:
android.view.InflateException: Binary XML file line #1: Error
inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: android.view.InflateException: Binary XML file line #1: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
at android.view.LayoutInflater.inflate(LayoutInflater.java:482)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at com.example.mohamed.movieapp.MainActivity.onCreate(MainActivity.java:19)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: storage == null
at java.util.Arrays$ArrayList.(Arrays.java:38)
at java.util.Arrays.asList(Arrays.java:155)
at android.widget.ArrayAdapter.(ArrayAdapter.java:128)
at com.example.mohamed.movieapp.CustomArrayAdapter.(CustomArrayAdapter.java:25)
at com.example.mohamed.movieapp.MainActivityFragment.onCreateView(MainActivityFragment.java:78)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1036)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1226)
at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1328)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2284)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:111)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:314)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:31)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733)
at android.view.LayoutInflater.inflate(LayoutInflater.java:482)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at com.example.mohamed.movieapp.MainActivity.onCreate(MainActivity.java:19)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
thnks for advice and interaction
So during onCreateView which gets called early in life cylce, you are trying to create array adapter out of empty uninitialized array. Please move setAdapter call to your post execute.
Note: any particular reason to update data in constructor? You are anyway calling it onStart.
Related
When open renderer page many times, when back to last page, it crashed and log this exception:
System.NotSupportedException: Unable to activate instance of type
AppZPMC.Droid.Renderers.CustomVideoWebViewRenderer from native handle
0xff9919cc (key_handle 0xf2ff0de).
Here is my code:
public class CustomVideoWebViewRenderer : WebViewRenderer
{
string url;
Activity activity;
WebView webView;
View customView;
CustomVideoWebView element;
FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);
FrameLayout fullscreenContainer;
WebChromeClient.ICustomViewCallback customViewCallback;
public CustomVideoWebViewRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
webView = this.Control;
activity = CrossCurrentActivity.Current.Activity;
if (e.NewElement != null)
{
element = e.NewElement as CustomVideoWebView;
url = element.VideoUrl;
}
if (webView != null)
{
InitWebView();
}
}
protected override void OnDetachedFromWindow()
{
if (Element == null)
{
return;
}
base.OnDetachedFromWindow();
if (Control != null)
{
Control.StopLoading();
Control.LoadUrl("");
Control.Reload();
Control.Destroy();
}
}
public void FullScreen(Activity pActivity)
{
element.IsFullScreen = true;
WindowManagerLayoutParams attrs = pActivity.Window.Attributes;
attrs.Flags |= WindowManagerFlags.Fullscreen;
attrs.Flags |= WindowManagerFlags.KeepScreenOn;
pActivity.Window.Attributes = attrs;
pActivity.RequestedOrientation = Android.Content.PM.ScreenOrientation.Landscape;
}
public void SmallScreen(Activity pActivity)
{
element.IsFullScreen = false;
WindowManagerLayoutParams attrs = pActivity.Window.Attributes;
attrs.Flags &= ~WindowManagerFlags.Fullscreen;
attrs.Flags &= ~WindowManagerFlags.KeepScreenOn;
pActivity.Window.Attributes = attrs;
pActivity.RequestedOrientation = Android.Content.PM.ScreenOrientation.UserPortrait;
}
private void InitWebView()
{
WebChromeClient wvcc = new WebChromeClient();
WebSettings webSettings = webView.Settings;
webSettings.JavaScriptEnabled = true;
webSettings.SetSupportZoom(false);
webSettings.CacheMode = CacheModes.NoCache;
webView.SetWebViewClient(new VideoWebViewClient());
FrameLayout frameLayout = new FrameLayout(activity.ApplicationContext);
frameLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);
webView.SetWebChromeClient(new VideoWebChromeClient(frameLayout, ShowCustomView, HideCustomView));
webView.LoadUrl(url);
}
private class VideoWebViewClient : WebViewClient
{
public override bool ShouldOverrideUrlLoading(WebView view, IWebResourceRequest request)
{
view.LoadUrl(request.Url.ToString());
return base.ShouldOverrideUrlLoading(view, request);
}
}
private class VideoWebChromeClient : WebChromeClient
{
FrameLayout frameLayout;
Action HideCustomView;
Action<View, ICustomViewCallback> ShowCustomView;
public VideoWebChromeClient(FrameLayout frameLayout, Action<View, ICustomViewCallback> showCustomView, Action hideCustomView)
{
this.frameLayout = frameLayout;
ShowCustomView = showCustomView;
HideCustomView = hideCustomView;
}
public override View VideoLoadingProgressView => frameLayout;
public override void OnShowCustomView(View view, ICustomViewCallback callback)
{
ShowCustomView(view, callback);
base.OnShowCustomView(view, callback);
}
public override void OnHideCustomView()
{
HideCustomView();
base.OnHideCustomView();
}
}
private void ShowCustomView(View view, WebChromeClient.ICustomViewCallback callback)
{
if (customView != null)
{
callback.OnCustomViewHidden();
return;
}
FrameLayout decor = (FrameLayout)activity.Window.DecorView;
fullscreenContainer = new FullscreenHolder(activity.ApplicationContext);
fullscreenContainer.AddView(view, COVER_SCREEN_PARAMS);
decor.AddView(fullscreenContainer, COVER_SCREEN_PARAMS);
customView = view;
customViewCallback = callback;
FullScreen(activity);
}
private void HideCustomView()
{
if (customView == null)
{
return;
}
FrameLayout decor = (FrameLayout)activity.Window.DecorView;
decor.RemoveView(fullscreenContainer);
fullscreenContainer = null;
customView = null;
customViewCallback.OnCustomViewHidden();
webView.Visibility = ViewStates.Visible;
SmallScreen(activity);
}
private class FullscreenHolder : FrameLayout
{
public FullscreenHolder(Context ctx) : base(ctx)
{
SetBackgroundColor(Color.Black);
}
public override bool OnTouchEvent(MotionEvent e)
{
return true;
}
}
}
This is full crash log:
Java.Lang.Error: Exception of type 'Java.Lang.Error' was thrown.
java.lang.Error: Java callstack:
md5ff1c77b81adfd2c553f48967fc623ae5.CustomVideoWebViewRenderer.n_onDetachedFromWindow(Native Method)
md5ff1c77b81adfd2c553f48967fc623ae5.CustomVideoWebViewRenderer.onDetachedFromWindow(CustomVideoWebViewRenderer.java:45)
android.view.View.dispatchDetachedFromWindow(View.java:14595)
android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:3074)
android.view.ViewGroup.removeAllViewsInLayout(ViewGroup.java:4792)
android.view.ViewGroup.removeAllViews(ViewGroup.java:4738)
md5270abb39e60627f0f200893b490a1ade.FragmentContainer.n_onDestroyView(Native Method)
md5270abb39e60627f0f200893b490a1ade.FragmentContainer.onDestroyView(FragmentContainer.java:59)
android.support.v4.app.Fragment.performDestroyView(Fragment.java:2480)
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1422)
android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1569)
android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:753)
android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2415)
android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2201)
android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2155)
android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2064)
android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:718)
android.os.Handler.handleCallback(Handler.java:742)
android.os.Handler.dispatchMessage(Handler.java:95)
android.os.Looper.loop(Looper.java:157)
android.app.ActivityThread.main(ActivityThread.java:5551)
java.lang.reflect.Method.invoke(Native Method)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:742)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:632)
Its common problem (bug) in Xamarin.Forms, take a look at: https://github.com/xamarin/Xamarin.Forms/issues/1646, no fix yet :(
I have tried using callback similar to my fragments and other people suggestion on callbacks, However I've had no luck i could be doing the callbacks wrong. The Toast inside the onResponse method of JsonArrayRequest returns an array size of 2. But i get 0 on the toast outside of the request. consignment.class implements parcelable
public class BackgroundTask{
String json_url;
Gson gson;
Type listType;
ProgressDialog pDialog;
ArrayList<Consignment> arrayList = new ArrayList<>();
AppController appController;
ConsAdapter adapter;
Context context;
public BackgroundTask(Context context){
this.context = context;
listType = new TypeToken<List<Consignment>>(){}.getType();
appController = AppController.getInstance();
gson = new Gson();
}
public void getAllCons(final GetAllConsListener callBack) {
String tag_json_obj = "json_obj_req";
//showProgressDialog();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, json_url,null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
callBack.onSuccess(response.toString());
//hideProgressDialog();
Toast.makeText(context, "Consignments:"+arrayList.size(), Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(context, "Error...", Toast.LENGTH_SHORT).show();
error.printStackTrace();
//hideProgressDialog();
}
});
appController.addToRequestQueue(jsonArrayRequest);
}
Activity Class:
public class GetConsActivity extends AppCompatActivity {
RecyclerView recyclerView;
ConsAdapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<Consignment> arrayList;
TextView txtView;
BackgroundTask backgroundTask;
Type listType;
Gson gson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_cons);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
gson = new Gson();
listType = new TypeToken<ArrayList<Consignment>>(){}.getType();
BackgroundTask backgroundTask = new BackgroundTask(GetConsActivity.this);
backgroundTask.getAllCons(new GetAllConsListener() {
#Override
public void onSuccess(String response) {
ArrayList<Consignment> list = parseResponse(response);
updateUI(list);
//Toast.makeText(GetConsActivity.this, "Consignments:"+arrayList.size(), Toast.LENGTH_LONG).show();
Log.d("ONSUCCESS", "ARRAYSIZE: "+arrayList.size());
}
});
}
public ArrayList<Consignment> parseResponse(String response){
ArrayList<Consignment> list = new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(response);
Log.d("PARSE", "parseResponse: "+jsonArray.length());
JSONObject jsonObject = jsonArray.getJSONObject(0);
for (int i = 0; i<jsonArray.length();i++){
Consignment con = null;
Log.d("PARSE", "parseID: "+jsonObject.getInt("conid"));
con.setConid(jsonObject.getInt("conid"));
Log.d("PARSE", "conID: "+con.getConid());
con.setDescription(jsonObject.getString("description"));
list.add(con);
}
Log.d("PARSED", "parsedResponse: "+list.size());
} catch (JSONException e) {
e.printStackTrace();
}
//arrayList =gson.fromJson(response,new TypeToken<ArrayList<Consignment>>(){}.getType());
//updateUI(arrayList);
return list;
}
public void updateUI(ArrayList<Consignment> consignments){
this.arrayList = consignments;
Log.d("UPDATE", "parseResponse: "+consignments.size());
if (adapter == null) {
adapter = new ConsAdapter(consignments,GetConsActivity.this);
recyclerView.setAdapter(adapter);
}else{
adapter.setConsignments(consignments);
adapter.notifyDataSetChanged();
}
}
Error:
D/mali_winsys: EGLint new_window_surface(egl_winsys_display*, void*, EGLSurface, EGLConfig, egl_winsys_surface**, egl_color_buffer_format*, EGLBoolean) returns 0x3000, [1440x2560]-format:1
E/RecyclerView: No adapter attached; skipping layout
I/qtaguid: Untagging socket 51
D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 84 - 0, 0) vi=Rect(0, 84 - 0, 0) or=1
E/RecyclerView: No adapter attached; skipping layout
D/PARSE: parseResponse: 4
D/PARSE: parseID: 123456789
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.angel.createcon, PID: 26952
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.angel.createcon.Consignment.setConid(int)' on a null object reference
at com.angel.createcon.GetConsActivity.parseResponse(GetConsActivity.java:80)
at com.angel.createcon.GetConsActivity$2.onSuccess(GetConsActivity.java:56)
at com.angel.createcon.BackgroundTask$2.onResponse(BackgroundTask.java:50)
at com.angel.createcon.BackgroundTask$2.onResponse(BackgroundTask.java:47)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7331)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
I/Process: Sending signal. PID: 26952 SIG: 9
Application terminated.
So I'll take a stab at this - having the activity implement the listener that way is a bit strange, though I don't think that's the issue. I also don't understand why you chose to save the list type to a variable - I've not seen anyone do that before.
However, getting to your question about the toast and why it's 0 - If you're talking about the toast that comes after the getAllCons call -it's because that code is executed before the callback code. completes.
Try something like this and see what it does.
public class BackgroundTask{
String json_url;
Gson gson;
Type listType;
Context context;
public BackgroundTask(Context context){
this.context = context;
listType = new TypeToken<List<Consignment>>(){}.getType();
appController = AppController.getInstance();
gson = new Gson();
}
public void getAllCons(final GetAllConsListener callBack) {
String tag_json_obj = "json_obj_req";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, json_url,null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
callBack.onSuccess(response.toString());
Toast.makeText(context, "Consignments:"+arrayList.size(), Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
appController.addToRequestQueue(jsonArrayRequest);
}
public class GetConsActivity extends AppCompatActivity {
RecyclerView recyclerView;
ConsAdapter adapter;
RecyclerView.LayoutManager layoutManager;
TextView txtView;
BackgroundTask backgroundTask;
Gson gson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_cons);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
gson = new Gson();
BackgroundTask backgroundTask = new BackgroundTask(GetConsActivity.this);
backgroundTask.getAllCons(new GetAllConsListener() {
#Override
public void onSuccess(String response) {
List<Consignment> values = parseResponse(response);
updateUI(values);
}
});
//code may execute here but callback is not yet complete.
}
public List<Consignment> parseResponse(String response){
return gson.fromJson(response,listType);
}
private void updateUI(List<Consignment> consignments){
if(adapter == null){
adapter = new ConsAdapter(consignments)
recyclerView.setAdapter(adapter);
} else {
adapter.consignments = consignments;
adapter.notifyDataSetChanged();
}
}
HibernateSpatialJPA class:
public class HibernateSpatialJPA {
private static final EntityManagerFactory emFactory;
static {
try {
emFactory = Persistence.createEntityManagerFactory("org.hibernate.events.jpa");
}catch(Throwable ex){
System.err.println("Cannot create EntityManagerFactory.");
throw new ExceptionInInitializerError(ex);
}
}
public static EntityManager createEntityManager() {
return emFactory.createEntityManager();
}
public static void close(){
emFactory.close();
}
}
this is manager class:
public class SavegeojsonManager {
SavegeojsonEntity theEvent = new SavegeojsonEntity();
public boolean insert(JSONObject json)
{
GeoJSON item = new GeoJSON(json);
return insert(item);
}
public boolean insert(GeoJSON item)
{
boolean success=false;
try {
String vectorType = item.getType();
EntityManager em = HibernateSpatialJPA.createEntityManager();
em.getTransaction().begin();
theEvent.setVectorType(vectorType);
em.persist(theEvent);
em.getTransaction().commit();
em.close();
success=true;
}
catch (Exception ex) {
System.out.println(ex.getMessage());
success = false;
}
HibernateSpatialJPA.close();
return success;
}
}
and this is GeoJsonClass :
public class GeoJSON
{
private int id;
private String type;
private String data;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getType() {return type;}
public void setType(String type) {this.type = type;}
public String getData() {return data;}
public void setData(String data) { this.data = data; }
public GeoJSON() {
}
public GeoJSON(JSONObject json) {
parse(json);
}
public GeoJSON parse(JSONObject json) {
StringWriter out = new StringWriter();
json.write(out);
this.data = out.toString();
this.type = json.getString("type");
try {
out.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
throw new RuntimeException(ex);
}
return this;
}
}
But I am not able to save into database because error :
enter code here : "error while committing the transaction."
Do you have any idea about this error ?
Below is the Exception stack trace:-
javax.persistence.RollbackException: Error while committing the transaction
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:92)
at com.springapp.model.SavegeojsonManager.insert(SavegeojsonManager.java:32)
at com.springapp.model.SavegeojsonManager.insert(SavegeojsonManager.java:19)
at com.springapp.mvc.HSpatialController.saveGeoJson(HSpatialController.java:46)
...
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: ERROR: column "vectortype" of relation "savegeojson" does not exist Position: 76 at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1377) at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1300) at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:80) ... 40 more Caused by: org.hibernate.exception.SQLGrammarException: ERROR: column "vectortype" of relation "savegeojson" does not exist Position: 76 at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:122) at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110) at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129) at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81) at com.sun.proxy.$Proxy26.executeUpdate(Unknown Source) at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:56) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2962) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3403) at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:88) at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:362) at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:354) at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:275) at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:326) at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:52) at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1214) at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:403) at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101) at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175) at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:75) ... 40 more Caused by: org.postgresql.util.PSQLException: ERROR: column "vectortype" of relation "savegeojson" does not exist Position: 76 at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2062) at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1795) at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257) at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:479) at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:367) at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:321) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122) ... 56 more
You are saving Entity SavegeojsonEntity to postgresql db and this error means:
Caused by: org.postgresql.util.PSQLException: ERROR: column "vectortype" of relation "savegeojson" does not exist
Position: 76
Table that SavegeojsonEntity are mapped to does not have column vectortype. Check in your db that column exists in table.
If it does not exist you need to add that column to table.
I am new to Android app development. I have read several posts which suggest that I have to use AsyncTask to get into a PHP file and edit a database.
Here is my class with AsyncTask.
private class urlEditTask extends AsyncTask<Void, Void, Void>{
final String propName;
final String roomLoc;
final String roomType;
public urlEditTask(final String propName, final String roomLoc, final String roomType){
super();
this.propName = propName;
this.roomLoc = roomLoc;
this.roomType = roomType;
}
#Override
protected Void doInBackground(Void... params) {
editDB(propName, roomLoc, roomType);
return null;
}
protected void onPostExecute(Void... params) {
Toast.makeText(getApplicationContext(), "Loading....", Toast.LENGTH_LONG).show();
}
private void editDB(final String propName, final String roomLoc, final String roomType){
String name = etName.getText().toString();
String contact = etContact.getText().toString();
String email = etEmail.getText().toString();
String rentStart = etRentStart.getText().toString();
String rentEnd = etRentEnd.getText().toString();
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
nameValuePair.add(new BasicNameValuePair("name", name));
nameValuePair.add(new BasicNameValuePair("propName", propName));
nameValuePair.add(new BasicNameValuePair("roomLoc", roomLoc));
nameValuePair.add(new BasicNameValuePair("roomType", roomType));
nameValuePair.add(new BasicNameValuePair("contact", contact));
nameValuePair.add(new BasicNameValuePair("email", email));
nameValuePair.add(new BasicNameValuePair("rentStart", rentStart));
nameValuePair.add(new BasicNameValuePair("rentEnd", rentEnd));
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://hoome.hk/EditDB.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
String msg = "Data entered successfully";
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
Log.e("ClientProtocol", "Log_tag");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I want the task to be executed after I clicked a button.
Here is my code for execution.
Button confirmEdit = (Button) findViewByID(R.id.confirmEdit);
confirmEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new urlEditTask(itemValue1, itemValue2, itemValue3).execute();
}
});
Probably, I don't quite understand how AsyncTask works.
May I know why I get NetworkOnMainThreadException with the above codes?
Here is the log:
07-20 04:14:01.480 2588-2603/hk.hoome.www.contracthandler E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: hk.hoome.www.contracthandler, PID: 2588
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:336)
at android.widget.Toast.<init>(Toast.java:100)
at android.widget.Toast.makeText(Toast.java:250)
at hk.hoome.www.contracthandler.MainActivity$urlEditTask.doInBackground(MainActivity.java:443)
at hk.hoome.www.contracthandler.MainActivity$urlEditTask.doInBackground(MainActivity.java:399)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
i was developing app in android to get my nearby places and when i tried to run i made everything but got this exception and i do not know what is the reason to cause this exception. Please Helppp
LogCat
02-24 02:26:03.366: E/Trace(21173): error opening trace file: No such file or directory (2)
02-24 02:26:04.562: E/GooglePlayServicesUtil(21173): The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.
02-24 02:26:11.773: E/AndroidRuntime(21173): FATAL EXCEPTION: main
02-24 02:26:11.773: E/AndroidRuntime(21173): java.lang.NullPointerException
02-24 02:26:11.773: E/AndroidRuntime(21173): at com.appscourt.maps.places.near.me.MainActivity$ParserTask.onPostExecute(MainActivity.java:270)
02-24 02:26:11.773: E/AndroidRuntime(21173): at com.appscourt.maps.places.near.me.MainActivity$ParserTask.onPostExecute(MainActivity.java:1)
02-24 02:26:11.773: E/AndroidRuntime(21173): at android.os.AsyncTask.finish(AsyncTask.java:631)
02-24 02:26:11.773: E/AndroidRuntime(21173): at android.os.AsyncTask.access$600(AsyncTask.java:177)
02-24 02:26:11.773: E/AndroidRuntime(21173): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
02-24 02:26:11.773: E/AndroidRuntime(21173): at android.os.Handler.dispatchMessage(Handler.java:99)
02-24 02:26:11.773: E/AndroidRuntime(21173): at android.os.Looper.loop(Looper.java:137)
02-24 02:26:11.773: E/AndroidRuntime(21173): at android.app.ActivityThread.main(ActivityThread.java:5059)
02-24 02:26:11.773: E/AndroidRuntime(21173): at java.lang.reflect.Method.invokeNative(Native Method)
02-24 02:26:11.773: E/AndroidRuntime(21173): at java.lang.reflect.Method.invoke(Method.java:511)
02-24 02:26:11.773: E/AndroidRuntime(21173): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
02-24 02:26:11.773: E/AndroidRuntime(21173): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
02-24 02:26:11.773: E/AndroidRuntime(21173): at dalvik.system.NativeStart.main(Native Method)
MainActivity
public class MainActivity extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
Spinner placeTypeSpinner;
String[] placeType = null;
String[] placeTypeName = null;
double latitude = 0;
double longitude = 0;
Button btnFind;
HashMap<String, String> mMarkerPlaceLink = new HashMap<String, String>();
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Array of places type
placeType = getResources().getStringArray(R.array.place_type);
//Array of places type name
placeTypeName = getResources().getStringArray(R.array.place_type_name);
// Creating an array adapter with an array of Place types
// to populate the spinner
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, placeTypeName);
//Getting reference to the spinner
placeTypeSpinner = (Spinner)findViewById(R.id.spr_place_type);
//Setting adapter on spinner to set place types
placeTypeSpinner.setAdapter(adapter);
// Getting reference to Find Button
btnFind = ( Button ) findViewById(R.id.btnFind);
//Getting google play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if(status != ConnectionResult.SUCCESS) {
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
} else { //Google Play Services are available
//Getting reference to the SupportMapFragment
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
googleMap.setMyLocationEnabled(true);
LocationManager locMan = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locMan.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locMan.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locMan.requestLocationUpdates(provider, 20000, 0, this);
googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Intent intent = new Intent(getBaseContext(), PlaceDetailsActivity.class);
String reference = mMarkerPlaceLink.get(marker.getId());
intent.putExtra("reference", reference);
// Starting the Place Details Activity
startActivity(intent);
}
});
btnFind.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int selectedPos = placeTypeSpinner.getSelectedItemPosition();
String type = placeType[selectedPos];
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=" + latitude + "," + longitude);
sb.append("&radius = 5000");
sb.append("&types = "+type);
sb.append("&sensor = true");
sb.append("&key = AIzaSyAbz9kNQKmgGRZJJj5fGcrp4DyfyvbxHm8");
// Creating a new non-ui thread task to download json data
PlacesTask placesTask = new PlacesTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
}
});
}
//initializeMap();
}
/** A method to download json data from url */
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;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public class PlacesTask extends AsyncTask<String, Integer, String>{
String data = null;
//MainActivity mainActivity = new MainActivity();
// Invoked by execute() method of this object
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
}catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
ParserTask parserTask= new ParserTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
public class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
JSONObject jObject;
//MainActivity mainActivity = new MainActivity();
//GoogleMap gMap;
//Invoked by execute() method of this object
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a List construct */
places = placeJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
return places;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> list) {
//Clear all existing markers
//gMap = mainActivity.googleMap;
googleMap.clear();
super.onPostExecute(list);
for(int i = 0 ; i < list.size() ; i++) {
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("place_name");
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
//This will be displayed on taping the marker
markerOptions.title(name + " : " + vicinity);
// Placing a marker on the touched position
googleMap.addMarker(markerOptions);
}
}
}
}
I think you are using Google's places api using HTTP GET. Like https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=Your_key.
While using GET method, be careful about the white spaces. Inside your code, there are spaces on both sides of " = ". So format your StringBuilder without spaces and try again.
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=" + latitude + "," + longitude);
sb.append("&radius=5000"); // take care of spaces here
sb.append("&types="+type); //
sb.append("&sensor=true"); //
sb.append("&key=Your_KEY"); //
After building your url, Log it and copy-paste it inside a web browser to check it.