can anyone explain how to initialize realm instance outside the Activity? for example while parsing json with volley and gson? - json

This is my Api class where json parsing is being done. But wherever I call Realm.getDefaultInstance(), at that line app stops running..Please help ...m stuck..Thanks in advance..
package com.portea.internal.api.realm_api;
import android.content.Context;
import android.util.Base64;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.portea.internal.app.App;
import com.portea.internal.constants.Constants;
import com.portea.internal.constants.PrintLog;
import com.portea.internal.enums.Transaction;
import com.portea.internal.network.Network;
import com.portea.internal.realm_pojo_container.AppointmentPojos.Appointments;
import com.portea.internal.realm_pojo_container.AppointmentPojos.AppointmmentMainObject;
import com.portea.internal.utils.Utils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import io.realm.Realm;
import io.realm.RealmList;
/**
* Created by Dipti on 26/3/17.
*/
public class ApiAppointment extends Request<JSONObject> {
private Response.Listener<JSONObject> listener;
private boolean isSubordinateAppointment = false;
private boolean forceReload = false;
String Tag = "ApiAppointment";
// RealmList<AppointmmentMainObject> realmObjList =null;
RealmList<AppointmmentMainObject> inpList = null;
Collection<AppointmmentMainObject> realmApts;
private Context context;
private Realm my_realm;//where to initialize this realm instance and where to close it
AppointmmentMainObject obj1, obj2;
public ApiAppointment(Response.Listener<JSONObject> listener, Response.ErrorListener errorListener, String url) {
super(Request.Method.GET, getApiUrl(url), errorListener);
this.listener = listener;
setRetryPolicy(new DefaultRetryPolicy(60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
public ApiAppointment(Response.Listener<JSONObject> listener, Response.ErrorListener errorListener, String url, boolean forceReload) {
super(Request.Method.GET, getApiUrl(url), errorListener);
this.listener = listener;
this.forceReload = forceReload;
setRetryPolicy(new DefaultRetryPolicy(60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Log.v(Tag + "dip", "" + getApiUrl(url));
}
public ApiAppointment(Response.Listener<JSONObject> listener, Response.ErrorListener errorListener, String url, String append) {
super(Request.Method.GET, getApiUrl(url) + append, errorListener);
this.listener = listener;
isSubordinateAppointment = true;
setRetryPolicy(new DefaultRetryPolicy(60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Log.v(Tag, "" + getApiUrl(url) + append);
}
public ApiAppointment(Response.Listener<JSONObject> listener, Response.ErrorListener errorListener, String url, String append, boolean forceReload) {
super(Request.Method.GET, getApiUrl(url) + append, errorListener);
this.listener = listener;
this.forceReload = forceReload;
isSubordinateAppointment = true;
setRetryPolicy(new DefaultRetryPolicy(60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Log.e(Tag, " " + getApiUrl(url) + append);
}
static String getApiUrl(String url_append) {
String lastSynced = App.getPref().get(Constants.STORAGE_KEY_LAST_APPOINTMENT_SYNCED);
if (lastSynced == null) {
lastSynced = "0";
}
if (url_append.length() > 0) {
lastSynced = "0";
}
return Network.getTxnPath(Transaction.APPOINTMENTS, "/get?user_id="
+ App.getUser().getUserId() + "&key=" + App.getUser().getKey()
+ "&version=" + App.version + "&last_synced=" + lastSynced + url_append);
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
Log.v(Tag, "========================================>>");
//Utils.sendLogoutBroadCast(App.getAppContext(), response.statusCode);
Gson gson = new GsonBuilder().create();
// Realm.init(App.getAppContext());
// my_realm = Realm.getDefaultInstance();
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
Log.i(Tag, jsonString);
JSONObject MainObject = new JSONObject(jsonString);
JSONArray dataObj = MainObject.getJSONArray("data");
for (int i = 0; i < dataObj.length(); i++) {
JSONObject singleUserObj = dataObj.getJSONObject(i);
JSONArray apointment = singleUserObj.getJSONArray("appointments");
for (int j = 0; j < apointment.length(); j++) {
JSONObject appointmentObj = apointment.getJSONObject(j);
// Appointments appointments=realm.createObjectFromJson(Appointments.class,appointmentObj);
// Log.v("Realmcheck",appointments.toString());
Type type = new TypeToken<RealmList<Appointments>>() {}.getType();
RealmList<Appointments> appointmentsObjList = gson.fromJson(apointment.toString(), type);
// List<Appointments> realm_copy_of_list=my_realm.copyToRealm(appointmentsObjList); Log.v("size", String.valueOf(appointmentsObjList.toString()));
RealmList<Appointments> apo = new RealmList<Appointments>();
Log.v("dipti", appointmentsObjList.get(j).toString());
// apo = (RealmList<Appointments>) my_realm.copyToRealm(appointmentsObjList);
}
}
// Log.v(Tag + "xx", AppointmmentMainObject.getClinicianName());
// Log.i("packageFee", String.valueOf(AppointmmentMainObject.getPackageFee()));
return Response.success(MainObject, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
PrintLog.d("e: " + e);
e.printStackTrace();
return Response.error(new ParseError(e));
} catch (JSONException je) {
PrintLog.d("je: " + je);
je.printStackTrace();
return Response.error(new ParseError(je));
} catch (NullPointerException ne) {
PrintLog.d("ne: " + ne);
return Response.error(new ParseError(ne));
}
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
String creds = String.format("%s:%s", "stage", "d7kVzNZDqn");
String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.NO_WRAP);
params.put("Authorization", auth);
params.put("DEVICE_ID", App.deviceId);
return params;
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
try {
Utils.sendLogoutBroadCast(App.getAppContext(),
volleyError.networkResponse.statusCode);
Log.e("onErrorResponse", ""
+ volleyError.networkResponse.statusCode);
} catch (Exception e) {
e.printStackTrace();
}
return volleyError;
}
#Override
protected void deliverResponse(JSONObject response) {
}
}

I think your main problem is in the Realm initialization. You should have an application class and initialize your Realm in there. Like this:
public class BaseApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
Realm.init(this);
RealmConfiguration config = new RealmConfiguration.Builder().build();
Realm.setDefaultConfiguration(config);
}
}
And then you can call my_realm = Realm.getDefaultInstance();
I hope this solves your problem.

Related

Received Data Provider Mismatch error

Tried below code but receiving Data Provider Mismatch error. Could anyone help out on this?
package appModules;
import org.testng.annotations.Test;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.testng.annotations.DataProvider;
import org.testng.annotations.BeforeTest;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
public class NewTest {
public WebDriver driver;
public WebDriverWait wait;
String appURL =
"https://dev.agencyport.rsagroup.ca:8443/agencyportal/ProcessLogoff";
//Locators
private By username = By.id("USERID");
private By password = By.id("PASSWORD");
#BeforeClass
public void testSetup() {
System.setProperty("webdriver.firefox.marionette",
"C:\\Automation\\geckodriver.exe");
driver=new FirefoxDriver();
driver.manage().window().maximize();
wait = new WebDriverWait(driver, 5);
}
#Test(dataProvider = "login")
public void Login(String Username, String Password) {
driver.findElement(username).sendKeys(Username);
driver.findElement(password).sendKeys(Password);
}
#DataProvider (name="login")
public Object[][] dp() throws Exception{
Object[][] arrayObject =
getExcelData("C:\\Automation\\testData.xls","New");
return arrayObject;
}
public String[][] getExcelData(String fileName, String sheetName) throws
Exception {
String[][] arrayExcelData = null;
try {
FileInputStream fs = new FileInputStream(fileName);
Workbook wb = Workbook.getWorkbook(fs);
Sheet sh = wb.getSheet(sheetName);
int totalNoOfCols = sh.getColumns();
System.out.println(totalNoOfCols);
int totalNoOfRows = sh.getRows();
System.out.println(totalNoOfRows);
arrayExcelData = new String[totalNoOfRows-1][totalNoOfCols];
for (int i=1 ; i <totalNoOfRows; i++) {
for (int j=0; j <totalNoOfCols; j++) {
arrayExcelData[i-1][j] = sh.getCell(j, i).getContents();
System.out.println(arrayExcelData[i-1][j]);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
}
return arrayExcelData;
}
#Test
public void tearDown() {
driver.quit();
}
}
Received below error -
org.testng.internal.reflect.MethodMatcherException:
Data provider mismatch
Method: Login([Parameter{index=0, type=java.lang.String,
declaredAnnotations=[]}, Parameter{index=1, type=java.lang.String,
declaredAnnotations=[]}])
Arguments: [(java.lang.String) agent,(java.lang.String) password,
(java.lang.String) ]
atorg.testng.internal.reflect.DataProviderMethodMatcher.getConformingArguments(DataProviderMethodMatcher.java:45)
at org.testng.internal.Parameters.injectParameters(Parameters.java:796)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:982)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:648)
at org.testng.TestRunner.run(TestRunner.java:505)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
at org.testng.SuiteRunner.run(SuiteRunner.java:364)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
at org.testng.TestNG.runSuites(TestNG.java:1049)
at org.testng.TestNG.run(TestNG.java:1017)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)`
You are passing return value of arrayObject with incorrect Data Type,
You need to get String value from Excel File in Data Provider Method, and That you need to pass in Object.
Refer below Example, for Reference:
#DataProvider
public Iterator<Object[]> getTestData()
{
ArrayList<Object[]> testdata = new ArrayList<Object[]>();
try {
reader = new excelUtility(excelTestDataFile);
} catch (Exception e) {
e.printStackTrace();
}
sheetName = className;
for (int rowNumber = 2; rowNumber <= reader.getRowCount(sheetName); rowNumber++) {
String caseNo = reader.getCellData(sheetName, "Case", rowNumber);
String emailid = reader.getCellData(sheetName, "Email ID", rowNumber);
String password = reader.getCellData(sheetName, "Password", rowNumber);
String message = reader.getCellData(sheetName, "Expected Result", rowNumber);
Object ob[] =
{ caseNo, emailid, password, message };
testdata.add(ob);
}
return testdata.iterator();
}
And this is the #Test Receiver of Data Provider:
#Test(dataProvider = "getTestData")
public void calllogin(String caseNO, String emailid, String password, String expectedResult) throws Exception
{
******
}

Register Page Data store but no JSON encode received

I'm sure it's just a minor problem but I can't figure out what I need to change: I have a register page in my app. When the user inserts data, the data is passed to php script and stored in MYSQL database. The connection works as I get a new user in the db, but the json $success doesn't work - I want to make a Toast and change to a new activity if the user could register, but it does nothing when I click on the button.
Here is my Java Code:
package com.example.android.festivalapp;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class JetztRegistrieren extends Startseite {
Button bRegistrierungAbschliessen;
EditText etUserName, etUserMail, etUserPasswort, etUserPasswort2, etGeburtsdatum, etTelefonnummer;
RadioButton rbMaennlich, rbWeiblich;
RadioGroup rgGeschlecht;
protected String enteredname, enteredemail, enteredpassword, enteredpassword2, enteredGeb, enteredTelnr, userGender;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jetzt_registrieren);
bRegistrierungAbschliessen = (Button) findViewById(R.id.bRegistrierungAbschliessen);
etUserName = (EditText) findViewById(R.id.etUserName);
etUserMail = (EditText) findViewById(R.id.etUserMail);
etUserPasswort = (EditText) findViewById(R.id.etUserPasswort);
etUserPasswort2 = (EditText) findViewById(R.id.etUserPasswort2);
etGeburtsdatum = (EditText) findViewById(R.id.etGeburtsdatum);
etTelefonnummer = (EditText) findViewById(R.id.etTelefonnummer);
rgGeschlecht = (RadioGroup) findViewById(R.id.rgGeschlecht);
rbMaennlich = (RadioButton) findViewById(R.id.rbMaennlich);
rbWeiblich = (RadioButton) findViewById(R.id.rbWeiblich);
bRegistrierungAbschliessen.setOnClickListener(new View.OnClickListener() {
//testen, ob Mail und Passwort ausgefüllt oder lang genug
#Override
public void onClick(View v) {
enteredname = etUserName.getText().toString();
enteredemail = etUserMail.getText().toString();
enteredpassword = etUserPasswort.getText().toString();
enteredpassword2 = etUserPasswort2.getText().toString();
enteredTelnr = etTelefonnummer.getText().toString();
enteredGeb = etGeburtsdatum.getText().toString();
userGender = ((RadioButton) findViewById(rgGeschlecht.getCheckedRadioButtonId())).getText().toString();
String serverUrl = "http://www.pou-pou.de/stagedriver/android/register.php";
AsyncDataClass asyncRequestObject = new AsyncDataClass();
asyncRequestObject.execute(serverUrl, enteredname, enteredemail, enteredpassword, enteredpassword2, enteredTelnr, enteredGeb, userGender);
if (enteredname.equals("") || enteredemail.equals("") || enteredpassword.equals("") || enteredpassword2.equals("") || enteredGeb.equals("")) {
Toast.makeText(JetztRegistrieren.this, "Bitte alle Felder ausfüllen", Toast.LENGTH_LONG).show();
return;
}
}
class AsyncDataClass extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost("http://www.pou-pou.de/stagedriver/android/register.php");
String jsonResult = "";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("enteredname", params[1]));
nameValuePairs.add(new BasicNameValuePair("enteredemail", params[2]));
nameValuePairs.add(new BasicNameValuePair("enteredpassword", params[3]));
nameValuePairs.add(new BasicNameValuePair("enteredpassword2", params[4]));
nameValuePairs.add(new BasicNameValuePair("enteredTelnr", params[5]));
nameValuePairs.add(new BasicNameValuePair("enteredGeb", params[6]));
nameValuePairs.add(new BasicNameValuePair("userGender", params[7]));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonResult;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
int jsonResult = returnParsedJsonObject(result);
if (jsonResult == 0) {
Toast.makeText(JetztRegistrieren.this, "Passwörter stimmen nicht überein", Toast.LENGTH_LONG).show();
return;
}
if (jsonResult == 1) {
Intent intent = new Intent(JetztRegistrieren.this, Startseite.class);
Toast.makeText(JetztRegistrieren.this, "Willkommen bei Stage Driver! Jetzt loslegen.", Toast.LENGTH_LONG).show();
startActivity(intent);
return;
}
System.out.println("Resulted Value: " + result);
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
e.printStackTrace();
}
return answer;
}
}
private int returnParsedJsonObject(String result) {
JSONObject resultObject = null;
int returnedResult = 2;
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
});
}
}
And this is the php file:
<?php
include('config.php');
session_start();
$name = $_POST["enteredname"];
$pass = $_POST["enteredpassword"];
$pass2 = $_POST["enteredpassword2"];
$email = $_POST["enteredemail"];
$tel = $_POST["enteredTelnr"];
$geb = $_POST["enteredGeb"];
$gender = $_POST["userGender"];
if($pass != $pass2) {
$success = 0;
}
else {
$hash = md5($pass);
$speichern = "INSERT INTO user (user_name, user_pw, user_mail, user_tel, user_geb, user_geschl)
VALUES('$name', '$hash', '$email', '$tel', '$geb', '$gender');";
mysql_query($speichern) or die(mysql_error());
if($speichern) {
$success = 1;
}
}
echo json_encode($success);
?>
Thanks in advance!
The problem is that you are not returning an HTTP header for the content type you are returning.
Add this to the top of your php script:
header("Content-Type: application/json;charset=utf-8");
So I think I found the error, in the log it says the jsonresult cannot be converted, it's because in the php script I wrote $success = 0; but instead I think it has to be something like $response["success"] = 0;

GoogleMaps displaying "locals" on wrong position

i want to display the CurrentPosition of the mobile phone and display all bar|cafe nearby the position.
The CurrentPosition works.
But the displaying of the bars/cafes is wrong. It seems like they are showing up from the center of vienna and not from the position of my phone.
Would be really thankful if someone could find the problem
MapsActivity.java
package androfenix.currentpositionandplacesnearby;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
LatLng latLng;
double mLatitude=0;
double mLongitude=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Mit setMapType setzen wir das Aussehen der Karte auf "Hybrid"
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onPause()
{
super.onPause();
//Unregister for location callbacks:
if (mGoogleApiClient != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
// Create a LatLng object for the current location
latLng = new LatLng(location.getLatitude(), location.getLongitude());
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
StringBuilder sbValue = new StringBuilder(sbMethod());
PlacesTask placesTask = new PlacesTask();
placesTask.execute(sbValue.toString());
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
// You can add here other case statements according to your requirement.
}
}
public StringBuilder sbMethod() throws SecurityException
{
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=" + mLatitude + "," + mLongitude);
sb.append("&radius=50000");
sb.append("&sensor=true");
sb.append("&keyword=" + "bar|cafe");
sb.append("&key= SERVER API KEY ");
Log.d("Map", "url: " + sb.toString());
return sb;
}
private class PlacesTask extends AsyncTask<String, Integer, String>
{
String data = null;
// 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;
}
// Executed after the complete execution of doInBackground() method
#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 ParserTask
parserTask.execute(result);
}
}
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", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
Place_JSON placeJson = new Place_JSON();
try {
jObject = new JSONObject(jsonData[0]);
places = placeJson.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, String>> list) {
Log.d("Map", "list size: " + list.size());
// Clears all the existing markers;
//mGoogleMap.clear();
for (int i = 0; i < list.size(); i++) {
// Creating a marker
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");
Log.d("Map", "place: " + name);
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
markerOptions.title(name + " : " + vicinity);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
// Placing a marker on the touched position
Marker m = mMap.addMarker(markerOptions);
// ZZZZZZZZZZZZZZZZZZZ
}
}
}
public class Place_JSON {
/**
* Receives a JSONObject and returns a list
*/
public List<HashMap<String, String>> parse(JSONObject jObject) {
JSONArray jPlaces = null;
try {
/** Retrieves all the elements in the 'places' array */
jPlaces = jObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
/** Invoking getPlaces with the array of json object
* where each json object represent a place
*/
return getPlaces(jPlaces);
}
private List<HashMap<String, String>> getPlaces(JSONArray jPlaces) {
int placesCount = jPlaces.length();
List<HashMap<String, String>> placesList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> place = null;
/** Taking each place, parses and adds to list object */
for (int i = 0; i < placesCount; i++) {
try {
/** Call getPlace with place JSON object to parse the place */
place = getPlace((JSONObject) jPlaces.get(i));
placesList.add(place);
} catch (JSONException e) {
e.printStackTrace();
}
}
return placesList;
}
/**
* Parsing the Place JSON object
*/
private HashMap<String, String> getPlace(JSONObject jPlace)
{
HashMap<String, String> place = new HashMap<String, String>();
String placeName = "-NA-";
String vicinity = "-NA-";
String latitude = "";
String longitude = "";
String reference = "";
try {
// Extracting Place name, if available
if (!jPlace.isNull("name")) {
placeName = jPlace.getString("name");
}
// Extracting Place Vicinity, if available
if (!jPlace.isNull("vicinity")) {
vicinity = jPlace.getString("vicinity");
}
latitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
longitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
reference = jPlace.getString("reference");
place.put("place_name", placeName);
place.put("vicinity", vicinity);
place.put("lat", latitude);
place.put("lng", longitude);
place.put("reference", reference);
} catch (JSONException e) {
e.printStackTrace();
}
return place;
}
}
}
Using the Google Places API for Android, you can discover the place where the device is currently located. That is, the place at the device's currently-reported location. Examples of places include local businesses, points of interest, and geographic locations.
If your app uses PlaceDetectionApi.getCurrentPlace() must request the ACCESS_FINE_LOCATION permission.
The following code sample retrieves the list of places where the device is most likely to be located, and logs the name and likelihood for each place.
PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
.getCurrentPlace(mGoogleApiClient, null);
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
#Override
public void onResult(PlaceLikelihoodBuffer likelyPlaces) {
for (PlaceLikelihood placeLikelihood : likelyPlaces) {
Log.i(TAG, String.format("Place '%s' has likelihood: %g",
placeLikelihood.getPlace().getName(),
placeLikelihood.getLikelihood()));
}
likelyPlaces.release();
}
});
The PlacePicker provides a UI dialog that displays an interactive map and a list of nearby places, including places corresponding to geographical addresses and local businesses. Users can choose a place, and your app can then retrieve the details of the selected place.
The following code snippet retrieves the place that the user has selected:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
String toastMsg = String.format("Place: %s", place.getName());
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
}
}
}

Google docs api for Java (exception)

I have a problem with google docs. I want to retrieve all your files by using OAuth 2.0. The problem is that once you do, and authorization when trying to download a file gives me this error:
Exception in thread "main" java.lang.NullPointerException
at GoogleBlack.readUrl(GoogleBlack.java:95)
at GoogleBlack.getDocument(GoogleBlack.java:87)
at GoogleBlack.go(GoogleBlack.java:187)
at GoogleBlack.main(GoogleBlack.java:222)
Here's the code I use
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.gdata.client.GoogleService;
import com.google.gdata.client.GoogleAuthTokenFactory.UserToken;
import com.google.gdata.client.docs.DocsService;
import com.google.gdata.data.MediaContent;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.data.docs.DocumentListFeed;
import com.google.gdata.data.media.MediaSource;
import com.google.gdata.util.ServiceException;
public class GoogleBlack {
private static final String APPLICATION_NAME = "Homework";
public DocsService service;
public GoogleService spreadsheetsService;
static String CLIENT_ID = "***********";
static String CLIENT_SECRET = "**************";
static String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
static List<String> SCOPES = Arrays.asList("https://docs.google.com/feeds");
public void getSpreadSheet(String id, String i, String ids, String type) throws Exception {
UserToken docsToken = (UserToken) service.getAuthTokenFactory()
.getAuthToken();
UserToken spreadsheetsToken = (UserToken) spreadsheetsService
.getAuthTokenFactory().getAuthToken();
service.setUserToken(spreadsheetsToken.getValue());
URL url = null;
if(type.equals("doc"))
{
url = new URL("https://docs.google.com/feeds/download/documents/Export?id="+ ids);
}
else
{
url = new URL("https://docs.google.com/feeds/download/spreadsheets/Export?key="+ ids +"&exportFormat="+ type + "&gid=0");
i += ".xls";
}
System.out.println("Spred = " + url.toString());
readUrl1(url.toString(), i, type);
service.setUserToken(docsToken.getValue());
}
public void readUrl1(String url, String i, String type) throws IOException, ServiceException
{
MediaContent mc = new MediaContent();
mc.setUri(url);
MediaSource ms = service.getMedia(mc);
System.out.println("Name: "+i);
BufferedInputStream bin = new BufferedInputStream(ms.getInputStream());
OutputStream out = new FileOutputStream(i);
BufferedOutputStream bout = new BufferedOutputStream(out);
while (true) {
int datum = bin.read();
if (datum == -1)
break;
bout.write(datum);
}
bout.flush();
}
public void getDocument(String id, String i) throws Exception {
URL url = new URL(id);
readUrl(url,i);
}
public void readUrl(URL url, String i) throws Exception {
MediaContent mc = new MediaContent();
mc.setUri(url.toString());
System.out.println("Url "+ url.toString());
System.out.println("MC: " + mc.toString());
MediaSource ms = service.getMedia(mc);
System.out.println("Name: "+i);
BufferedInputStream bin = new BufferedInputStream(ms.getInputStream());
OutputStream out = new FileOutputStream(i);
BufferedOutputStream bout = new BufferedOutputStream(out);
while (true) {
int datum = bin.read();
if (datum == -1)
break;
bout.write(datum);
}
bout.flush();
// FileOutputStream fout = null;
// fout = new FileOutputStream(i);
// fout.write(cbuf.);
// fout.close();
}
static Credential getCredentials() {
HttpTransport transport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
// Step 1: Authorize -->
String authorizationUrl =
new GoogleAuthorizationCodeRequestUrl(CLIENT_ID, REDIRECT_URI, SCOPES).build();
// Point or redirect your user to the authorizationUrl.
System.out.println("Go to the following link in your browser:");
System.out.println(authorizationUrl);
// Read the authorization code from the standard input stream.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is the authorization code?");
String code = null;
try {
code = in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// End of Step 1 <--
// Step 2: Exchange -->
GoogleTokenResponse response = null;
try {
response = new GoogleAuthorizationCodeTokenRequest(transport, jsonFactory, CLIENT_ID, CLIENT_SECRET,
code, REDIRECT_URI).execute();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// End of Step 2 <--
// Build a new GoogleCredential instance and return it.
return new GoogleCredential.Builder().setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.setJsonFactory(jsonFactory).setTransport(transport).build()
.setAccessToken(response.getAccessToken()).setRefreshToken(response.getRefreshToken());
}
public void go() throws Exception {
DocsService service = new DocsService(APPLICATION_NAME);
service.setOAuth2Credentials(getCredentials());
URL feedUrl = new URL("https://docs.google.com/feeds/default/private/full/");
DocumentListFeed feed = service.getFeed(feedUrl, DocumentListFeed.class);
System.out.println("Feed " + feed.getEntries().size());
for(int i = 0; i < feed.getEntries().size(); i++)
{
DocumentListEntry entry = feed.getEntries().get(i);
if(entry.getType().equals("file"))
{
MediaContent mc1 = (MediaContent) entry.getContent();
String UrlForDownload = mc1.getUri();
System.out.println("Type is: " + entry.getType());
System.out.println("File Name is: " + entry.getTitle().getPlainText());
System.out.println("URL "+ UrlForDownload);
getDocument(UrlForDownload, entry.getFilename());
}
else
{
MediaContent mc1 = (MediaContent) entry.getContent();
String UrlForDownload = mc1.getUri();
System.out.println("URL "+ UrlForDownload);
System.out.println("Type is: " + entry.getType());
System.out.println("File Name is: " + entry.getTitle().getPlainText());
if(entry.getTitle().getPlainText().equals("Web Design 2011/2012 - Материали"))
{
continue;
}
if(entry.getType().equals("spreadsheet"))
{
String name = entry.getTitle().getPlainText().replaceAll(" ", "");
System.out.println("name: " + name);
getSpreadSheet(UrlForDownload, name, entry.getDocId(),"xls");
}
else
{
String name = entry.getTitle().getPlainText().replaceAll(" ", "");
System.out.println("name: " + name);
getSpreadSheet(UrlForDownload, name, entry.getDocId(),"doc");
}
}
}
}
public static void main(String[] args) throws Exception {
new GoogleBlack().go();
}
}
95 row - MediaSource ms = service.getMedia(mc);
87 row - readUrl(url,i);
187 row - getDocument(UrlForDownload, entry.getFilename());
222 row - new GoogleBlack().go();
I apologize if I am not well explained!!!
You never initialized the "public DocsService service;" member of your GoogleBlack class, so when you call "service.getMedia(mc);" you're getting a NullPointerException.

How to Parse JSON String in LWUIT

How to parse a JSON object in LWUIT,give me some example or some link from where i can read this.Suppose i have the objects given below.
"{'guild': 'Crimson', 'region': 'us', 'realm': 'Caelestrasz', 'timestamp': 1311860040}"
Json Example Code:This Code will work for json.
package com.ndtv.parser;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import com.ndtv.callback.jsonActivelistener;
import com.ndtv.datatype.StockActiveItem;
import json.me.JSONArray;
import json.me.JSONException;
import json.me.JSONObject;
public class StockActiveParser {
public Vector jsonObjVector = new Vector();
public JSONArray arrayObj = null;
public String name,LastPrice;
protected jsonActivelistener mjsonListener;
public static boolean ParserCanceled = false;
public void setjsonListener(jsonActivelistener listener) {
mjsonListener = listener;
}
// Non-blocking.
public void parser(final String url) {
Thread t = new Thread() {
public void run() {
// set up the network connection
try {
jsonParse(url);
}
catch (Exception e) {
mjsonListener.parserExceptionListing(e);
}
mjsonListener.parseDidFinishListing();
}
};
t.start();
}
protected void jsonParse(String url) {
StringBuffer stringBuffer = new StringBuffer();
InputStream is = null;
HttpConnection hc = null;
System.out.println(url);
try {
hc = (HttpConnection)Connector.open(url);
is = hc.openInputStream();
int ch;
while ((ch = is.read()) != -1) {
stringBuffer.append((char) ch);
}
}
catch (SecurityException se) {
System.out.println("security exception:"+se);
}
catch (NullPointerException npe) {
System.out.println("null pointer excception:"+npe);
}
catch (IOException ioe) {
System.out.println("io exception:"+ioe);
}
try{
hc.close();
is.close();
}catch(Exception e) {
System.out.println("Error in MostActivePareser Connection close:"+e);
e.printStackTrace();
}
String jsonData = stringBuffer.toString();
try {
JSONObject js = new JSONObject(jsonData);
JSONArray js2 = js.getJSONArray("values");
System.out.println(js2.length());
for (int i = 0; i < js2.length(); i++) {
StockActiveItem item = new StockActiveItem();
JSONObject jsObj = js2.getJSONObject(i);
item.name = jsObj.getString("name");
item.last_traded_price = jsObj.getString("last_traded_price");
item.change = jsObj.getString("change");
item.price_diff = jsObj.getString("price_diff");
item.chart=jsObj.getString("chart");
item.company_id=jsObj.getString("company_id");
mjsonListener.itemParsedListing(item);
}
} catch (JSONException e1) {
System.out.println("Json Data error:"+e1);
e1.printStackTrace();
}
catch (NullPointerException e) {
System.out.println("null error:"+e);
}
}
}
public class StockActiveItem
{
public String name ="";
public String last_traded_price ="";
public String change="";
public String price_diff ="";
public String chart="";
public String company_id="";
public String year_high="";
public String year_low="";
}
you just replace name, for example guild replacing name.If any doubt ask me.
Use LWUIT JSONParser and parser the JSON format string. Just use MIDP_IO.jar from latest LWUIT 1.5 for this.
I was able to use sample code provided in below given links successfully in my app.
http://jimmod.com/blog/2010/03/java-me-j2me-json-implementation-tutorialsample/
http://jimmod.com/blog/2011/09/java-me-j2me-json-implementation-for-array-object/
BTW, Latest JSON ME library can be found here : https://github.com/upictec/org.json.me/
You can use JSON jar and and import that in your project. After that create a JSON object and you can use optString or getString methods of that object accordingly to get the values.