I am trying to display the message based on the response from the server but somehow its failing everytime. When i am running the same code from java class seperately from different project by providing static values it is running properly and i am able to get the response code. Please refer the code and help me rectify the error.
MainActivity.java
public class MainActivity extends Activity implements OnClickListener,
Runnable {
Context context;
EditText editTextNum, editText, editUserName, editPassword;
Button btnsend;
ProgressDialog pd;
String gateway_name;
Thread t;
Spinner spinner1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
editUserName = (EditText) findViewById(R.id.edit_userName);
editPassword = (EditText) findViewById(R.id.edit_password);
editTextNum = (EditText) findViewById(R.id.edit_number);
editText = (EditText) findViewById(R.id.edit_message);
spinner1 = (Spinner) findViewById(R.id.SpinnerGateway);
btnsend = (Button) findViewById(R.id.btnsend);
btnsend.setOnClickListener(this);
}
/** Called when the user clicks the Send button */
public void sendMessage() {
String usrname = editUserName.getText().toString();
String usrPassword = editPassword.getText().toString();
String number = editTextNum.getText().toString();
String message = editText.getText().toString();
gateway_name = String.valueOf(spinner1.getSelectedItem());
String msgreciever = number;
String testMessage = message;
try {
SmsSender.sendMessage(msgreciever, testMessage, usrname,
usrPassword, gateway_name);
} catch (Exception ex) {
Toast.makeText(MainActivity.this, "SMS Sending Failed.",
Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_settings:
settingmenuClicked();
return true;
case R.id.menu_help:
showHelp();
return true;
case R.id.menu_inbox:
showInbox();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
public boolean isValid() {
if (editUserName.getText().length() == 10
&& editPassword.getText().length() != 0
&& editTextNum.getText().length() == 10
&& editText.getText().length() != 0) {
return true;
}
return false;
}
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == btnsend) {
if (!isOnline()) {
Toast.makeText(MainActivity.this,
"No Internet Access..Cannot Send SMS",
Toast.LENGTH_SHORT).show();
} else if (!isValid()) {
Toast.makeText(MainActivity.this,
"All fields are required. Try Again.",
Toast.LENGTH_SHORT).show();
} else {
pd = ProgressDialog.show(MainActivity.this, "Free Sms",
"Sending SMS..Please Wait..!!", true);
t = new Thread(this);
t.start();
}
}
}
public void settingmenuClicked() {
Toast.makeText(MainActivity.this, "Setting Menu Coming Soon",
Toast.LENGTH_SHORT).show();
}
public void showHelp() {
Toast.makeText(MainActivity.this, "Help Coming Soon",
Toast.LENGTH_SHORT).show();
}
public void showInbox() {
//Intent intent = new Intent(this, Inbox.class);
//startActivity(intent);
}
public void run() {
// TODO Auto-generated method stub
sendMessage();
mHandler.sendEmptyMessage(0);
}
public Handler mHandler = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
pd.dismiss();
String response = SmsSender.responsecode;
if(response == "1"){
Toast.makeText(MainActivity.this, "Message Sent Successfully",Toast.LENGTH_SHORT).show();
} else if(response == "-1"){
Toast.makeText(MainActivity.this, "Server Error",Toast.LENGTH_SHORT).show();
} else if(response == "-2"){
Toast.makeText(MainActivity.this, "Invalid Username",Toast.LENGTH_SHORT).show();
} else if(response == "-3"){
Toast.makeText(MainActivity.this, "Invalid Message Text",Toast.LENGTH_SHORT).show();
} else if(response == "-4"){
Toast.makeText(MainActivity.this, "Login Failed",Toast.LENGTH_SHORT).show();
} else if(response == "-5"){
Toast.makeText(MainActivity.this, "IP is blocked",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Unknown Error",Toast.LENGTH_SHORT).show();
}
//Toast.makeText(MainActivity.this, "Message Sent To Server",
// Toast.LENGTH_SHORT).show();
editTextNum.setText("");
editText.setText("");
editTextNum.requestFocus();
}
};
}
SmsSender.java
public class SmsSender {
static final String _url = "http://ubaid.tk/sms/sms.aspx";
static final String charset = "UTF-8";
public static String responsecode = "0";
// to build the query string that will send the message
private static String buildRequestString(String targetPhoneNo,
String message, String userName, String Password, String Gateway) throws UnsupportedEncodingException {
String[] params = new String[5];
params[0] = userName;
params[1] = Password;
params[2] = message;
params[3] = targetPhoneNo;
params[4] = Gateway;
String query = String.format(
"uid=%s&pwd=%s&msg=%s&phone=%s&provider=%s",
URLEncoder.encode(params[0], charset),
URLEncoder.encode(params[1], charset),
URLEncoder.encode(params[2], charset),
URLEncoder.encode(params[3], charset),
URLEncoder.encode(params[4], charset));
return query;
}
public static void sendMessage(String reciever, String message, String userName, String password, String Gateway)
throws Exception {
// To establish the connection and perform the post request
URLConnection connection = new URL(_url + "?"
+ buildRequestString(reciever, message, userName, password, Gateway)).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
// This automatically fires the request and we can use it to determine
// the response status
InputStream response = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(response));
System.out.println(br.readLine());
responsecode = br.readLine();
}
public static void main(String[] args) throws Exception {
// To DO
//String testPhoneNo = "9876543210";
//String testMessage = "Sending Messages From java is not too hard";
//sendMessage(testPhoneNo, testMessage);
}
}
I think you are a victim of too much copy and paste from the example. I suspect you are getting a response (otherwise you would encounter an exception). You are then are just throwing it away to a System.out.println(). Then when you go to set responsecode readLine() returns null.
I tried to test it for myself, but I cannot use the API outside of India.
Related
So I have implemented so far asking for the user to give me permission to their google account. I need to then take that token and add it to the following URL https://api.comma.ai/v1/auth/?access_token= to get a token from them and store that token so that I can use it. However, as the title I get {"success": false, "error": "oauth failed"} which is better than the 401 that I was getting...I think? This is my first time diving into this. I am not sure where I am going wrong on this. Any help is greatly appreciated.
MainActivity.java
public class MainActivity extends AppCompatActivity {
Context mContext = MainActivity.this;
private AccountManager mAccountManager;
private AuthPreferences authPreferences;
EditText emailText;
TextView responseView;
ProgressBar progressBar;
static final String API_KEY = "";
static final String API_URL = "https://api.comma.ai/v1/auth/?access_token=";
static final String ClientId = "45471411055-m902j8c6jo4v6mndd2jiuqkanjsvcv6j.apps.googleusercontent.com";
static final String ClientSecret = "";
static final String SCOPE = "https://www.googleapis.com/auth/userinfo.email";
private static final int AUTHORIZATION_CODE = 1993;
private static final int ACCOUNT_CODE = 1601;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
responseView = (TextView) findViewById(R.id.responseView);
emailText = (EditText) findViewById(R.id.emailText);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
final Context context = this;
mAccountManager = AccountManager.get(this);
authPreferences = new AuthPreferences(this);
SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (authPreferences.getUser() != null && authPreferences.getToken() != null) {
doCoolAuthenticatedStuff();
new RetrieveFeedTask().execute();
} else{
chooseAccount();
}
}
});
// Button queryButton = (Button) findViewById(R.id.queryButton);
//
// queryButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// if (isNetworkAvailable() == true) {
// new RetrieveFeedTask().execute();
// Intent intent = new Intent(context, NavDrawerActivity.class);
// startActivity(intent);
// } else {
// Toast.makeText(MainActivity.this, "No Network Service, please check your WiFi or Mobile Data Connection", Toast.LENGTH_SHORT).show();
// }
// }
// });
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
boolean dontShowDialog = sharedPref.getBoolean("DONT_SHOW_DIALOG", false);
if (!dontShowDialog) {
WifivsDataDialog myDiag = new WifivsDataDialog();
myDiag.show(getFragmentManager(), "WiFi");
myDiag.setCancelable(false);
}
}
private void doCoolAuthenticatedStuff() {
Log.e("AuthApp", authPreferences.getToken());
}
private void chooseAccount() {
Intent intent = AccountManager.newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null, null, null, null);
startActivityForResult(intent, ACCOUNT_CODE);
}
private void requestToken() {
Account userAccount = null;
String user = authPreferences.getUser();
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
for (Account account : mAccountManager.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE)) {
if (account.name.equals(user)) {
userAccount = account;
break;
}
}
mAccountManager.getAuthToken(userAccount, "oauth2:" + SCOPE, null, this, new OnTokenAcquired(), null);
}
private void invalidateToken()
{
AccountManager mAccountManager = AccountManager.get(this);
mAccountManager.invalidateAuthToken("com.google", authPreferences.getToken());
authPreferences.setToken(null);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == AUTHORIZATION_CODE) {
requestToken();
} else if (requestCode == ACCOUNT_CODE) {
String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
authPreferences.setUser(accountName);
// invalidate old tokens which might be cached. we want a fresh
// one, which is guaranteed to work
invalidateToken();
requestToken();
}
}
}
public class OnTokenAcquired implements AccountManagerCallback<Bundle>
{
#Override
public void run(AccountManagerFuture<Bundle> result)
{
try {
Bundle bundle = result.getResult();
Intent launch = (Intent) bundle.get(AccountManager.KEY_INTENT);
if(launch != null)
{
startActivityForResult(launch, AUTHORIZATION_CODE);
} else {
String token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
authPreferences.setToken(token);
doCoolAuthenticatedStuff();
}
} catch (Exception e){
Log.e("ERROR", e.getMessage(), e);
}
}
}
public boolean isNetworkAvailable()
{
ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if(networkInfo != null && networkInfo.isConnected())
{
Log.e("Network Testing", "Available");
return true;
}
Log.e("Network Testing", "Not Available");
return false;
}
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
private Exception exception;
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
responseView.setText("");
}
protected String doInBackground(Void... urls) {
// Do some validation here
try {
URL url = new URL(API_URL + authPreferences);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.addRequestProperty("client_id", ClientId);
urlConnection.addRequestProperty("client_secret", ClientSecret);
urlConnection.setRequestProperty("Authorization", "OAuth " + authPreferences);
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
//
// TODO: check this.exception
// TODO: do something with the feed
// try {
// JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
// String requestID = object.getString("requestId");
// int likelihood = object.getInt("likelihood");
// JSONArray photos = object.getJSONArray("photos");
// .
// .
// .
// .
// } catch (JSONException e) {
// e.printStackTrace();
// }
}
}
}
And here is the AuthPreferences.java if anyone needs to look at it.
public class AuthPreferences {
private static final String KEY_USER = "user";
private static final String KEY_TOKEN = "token";
private SharedPreferences preferences;
public AuthPreferences(Context context) {
preferences = context
.getSharedPreferences("auth", Context.MODE_PRIVATE);
}
public void setUser(String user) {
Editor editor = preferences.edit();
editor.putString(KEY_USER, user);
editor.commit();
}
public void setToken(String password) {
Editor editor = preferences.edit();
editor.putString(KEY_TOKEN, password);
editor.commit();
}
public String getUser() {
return preferences.getString(KEY_USER, null);
}
public String getToken() {
return preferences.getString(KEY_TOKEN, null);
}
}
I did never use Android for OAuth2 but as far as I understand your code I think there are a few errors.
Fix the RetrieveFeedTask (OAuth2 Token is typically Bearer Token for all I know), use the access token like this:
URL url = new URL(API_URL + authPreferences.getToken());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.addRequestProperty("client_id", ClientId);
urlConnection.addRequestProperty("client_secret", ClientSecret);
urlConnection.setRequestProperty("Authorization", "OAuth " + authPreferences.getToken());
Furthermore I am not sure if your approach is correct (can you post a link where this snippet is from?). As far as I understand OAuth2 I would expect that at this time you can simply authorize by using a Bearer token und do no longer have to supply the access token in the URL / the client id and secrets. Or you may be missing a step (e.g. splitting the upper codes in two requests). Make sure you are explicitely following the OAuth2 standard and be sure what grant type you are using. Then debug your application to find out where the error is returned.
I am using the following MainActivity, and I am still getting the following error message:
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:344)
at android.widget.Toast.<init>(Toast.java:100)
at android.widget.Toast.makeText(Toast.java:258)
at com.example.edtomach.whatstheweather.MainActivity$DownloadTask.doInBackground(MainActivity.java:114)
at com.example.edtomach.whatstheweather.MainActivity$DownloadTask.doInBackground(MainActivity.java:80)
Why am I getting this error? The relevant code is here:
public class MainActivity extends Activity {
EditText cityname;
TextView resulttextview;
public void findWeather(View view) {
Log.i("cityname", cityname.getText().toString());
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(cityname.getWindowToken(), 0);
try {
String encodedCityName = URLEncoder.encode(cityname.getText().toString(), "UTF-8");
DownloadTask task = new DownloadTask();
task.execute("http://api.openweathermap.org/data/2.5/weather?q=" + encodedCityName);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "could not find weather", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityname = (EditText) findViewById(R.id.cityname);
resulttextview = (TextView) findViewById(R.id.resulttextview);
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "could not find weather", Toast.LENGTH_LONG).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = "";
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
Log.i("Weather content", weatherInfo);
JSONArray arr = new JSONArray(weatherInfo);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
String main = "";
String description = "";
main = jsonPart.getString("main");
description = jsonPart.getString("description");
if (main != "" && description != "") {
message += main + ": " + description + "\r\n";
}
}
if (message != "") {
resulttextview.setText(message);
} else {
Toast.makeText(getApplicationContext(), "could not find weather", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "could not find weather", Toast.LENGTH_LONG).show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
do not put anything can modife the main thread on the doBackground methods which herited from asynctask process , in your case you put toast message when you catch exception :
Toast.makeText(getApplicationContext(), "could not find weather", Toast.LENGTH_LONG).show();
instead that use logger message like e.g: Log.(TAG, "your message");
I have been following a tutorial (http://www.androidhive.info/2012/08/android-working-with-google-places-and-maps-tutorial/) in order to make a listview display nearest restaurant to your location in radius of 5km.
However i keep getting an error, in my Runnable it says that the status variable is null. I don't really understand why this error pops up. Can you guys give me a short explanation and help find a solution??
PlacesList.java
public class PlacesList implements Serializable {
public String status;
public List<Place> results;
}
DisplayLocations.java
public class DisplayLocations extends Activity {
boolean isInternetPresent = false;
ConnectionDetector cd;
GooglePlaces googlePlaces;
PlacesList nearPlaces;
GPSTracker gps;
Button shownOnMap;
ProgressDialog pDialog;
ListView lv;
ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String, String>>();
public static String KEY_REFERENCE = "reference";
public static String KEY_NAME = "name";
public static String KEY_VICINITY = "vicinity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_locations);
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
if(!isInternetPresent){
Toast.makeText(getApplicationContext(), "Get a working connection", Toast.LENGTH_SHORT).show();
return;
}
gps = new GPSTracker(DisplayLocations.this);
if(gps.canGetLocation()){
}else{
gps.showSettingsAlert();
}
lv = (ListView)findViewById(R.id.list);
shownOnMap = (Button)findViewById(R.id.btn_show_map);
new LoadPlaces().execute();
shownOnMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
Intent i = new Intent(getApplicationContext(), PlacesMapActivity.class);
i.putExtra("user_latitude", Double.toString(gps.getLatitude()));
i.putExtra("user_longitude", Double.toString(gps.getLongitude()));
i.putExtra("near_places", nearPlaces);
startActivity(i);
*/
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String reference = ((TextView) findViewById(R.id.reference)).getText().toString();
/*
Intent in = new Intent(getApplicationContext(), SingePlaceActivity.class);
in.putExtra(KEY_REFERENCE, reference);
startActivity(in);
*/
}
});
}
class LoadPlaces extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DisplayLocations.this);
pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
googlePlaces = new GooglePlaces();
try{
String types = "cafe|restaurant";
double radius = 5000;
nearPlaces = googlePlaces.search(gps.getLatitude(), gps.getLongitude(), radius, types);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
#Override
public void run() {
String status = nearPlaces.status;
if (status.equals("OK")){
if(nearPlaces.results != null){
for (Place p : nearPlaces.results){
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_REFERENCE, p.reference);
map.put(KEY_NAME, p.name);
placesListItems.add(map);
}
ListAdapter adapter = new SimpleAdapter(DisplayLocations.this, placesListItems, R.layout.location_listview_item,
new String[]{KEY_REFERENCE, KEY_NAME}, new int[]{R.id.reference, R.id.name});
lv.setAdapter(adapter);
}
}
else if(status.equals("ZERO_RESULTS")){
// Zero results found
Toast.makeText(getApplicationContext(), "No Results", Toast.LENGTH_SHORT);
}
else if(status.equals("UNKNOWN_ERROR"))
{
Toast.makeText(getApplicationContext(), "Unknown error", Toast.LENGTH_SHORT);
}
else if(status.equals("OVER_QUERY_LIMIT"))
{
Toast.makeText(getApplicationContext(), "Query limit reached !", Toast.LENGTH_SHORT);
}
else if(status.equals("REQUEST_DENIED"))
{
Toast.makeText(getApplicationContext(), "Request denied", Toast.LENGTH_SHORT);
}
else if(status.equals("INVALID_REQUEST"))
{
Toast.makeText(getApplicationContext(), "Invalid request", Toast.LENGTH_SHORT);
}
else
{
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT);
}
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_display_locations, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
GooglePlaces.java
public class GooglePlaces {
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
private final String API_KEY = "AIzaSyCxY1X7hC7SOab7V3GbWd1u42fGThgYOhg";
//GooglePlaces search URL
private static final String PLACES_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/search/json?";
private static final String PLACES_TEXT_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/search/json?";
private static final String PLACES_DETAILS_URL = "https://maps.googleapis.com/maps/api/place/details/json?";
private double mLatitiude;
private double mLongitude;
private double mRadius;
public PlacesList search(double latitude, double longitude, double radius, String types) throws Exception{
this.mLatitiude = latitude;
this.mLongitude = longitude;
this.mRadius = radius;
try {
HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
HttpRequest request = httpRequestFactory.buildGetRequest(new GenericUrl(PLACES_SEARCH_URL));
request.getUrl().put("key", API_KEY);
request.getUrl().put("location", mLatitiude + "," + mLongitude);
request.getUrl().put("radius", mRadius); // in meters
request.getUrl().put("sensor", "false");
if (types != null)
request.getUrl().put("types", types);
PlacesList list = request.execute().parseAs(PlacesList.class);
// Check log cat for places response status
Log.d("Places Status", "" + list.status);
return list;
} catch (HttpResponseException e) {
Log.e("Error:", e.getMessage());
return null;
}
}
public PlaceDetails getPlaceDetails(String reference) throws Exception{
try{
HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
HttpRequest request = httpRequestFactory.buildGetRequest(new GenericUrl(PLACES_DETAILS_URL));
request.getUrl().put("reference", reference);
request.getUrl().put("key", API_KEY);
request.getUrl().put("sensor",false);
PlaceDetails place = request.execute().parseAs(PlaceDetails.class);
return place;
}catch (HttpResponseException e){
throw e;
}
}
public static HttpRequestFactory createRequestFactory(final HttpTransport transport){
return transport.createRequestFactory(new HttpRequestInitializer() {
#Override
public void initialize(HttpRequest request) throws IOException {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setUserAgent("Application Test");
request.setHeaders(httpHeaders);
JsonObjectParser parser = new JsonObjectParser(new JsonFactory() {
#Override
public JsonParser createJsonParser(InputStream in) throws IOException {
return null;
}
#Override
public JsonParser createJsonParser(InputStream in, Charset charset) throws IOException {
return null;
}
#Override
public JsonParser createJsonParser(String value) throws IOException {
return null;
}
#Override
public JsonParser createJsonParser(Reader reader) throws IOException {
return null;
}
#Override
public JsonGenerator createJsonGenerator(OutputStream out, Charset enc) throws IOException {
return null;
}
#Override
public JsonGenerator createJsonGenerator(Writer writer) throws IOException {
return null;
}
});
request.setParser(parser);
}
});
}
}
Line 132 of DisplayLocations.java is :
String status = nearPlaces.status;
This is the stacktrace :
java.lang.NullPointerException: Attempt to read from field 'java.lang.String com.example.dell.exampleapplication.PlacesList.status' on a null object reference
at com.example.dell.exampleapplication.DisplayLocations$LoadPlaces$1.run(DisplayLocations.java:132)
at android.app.Activity.runOnUiThread(Activity.java:5517)
at com.example.dell.exampleapplication.DisplayLocations$LoadPlaces.onPostExecute(DisplayLocations.java:129)
at com.example.dell.exampleapplication.DisplayLocations$LoadPlaces.onPostExecute(DisplayLocations.java:98)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5834)
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:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
Any help and explanation would be appreciated.
Thanks, have a nice day.
EDIT:
nearPlaces.status = ... (the status: probably from GooglePlaces) in doInBackGround
then you can do:
String status = nearPlaces.status; in onPostExecute
Add the line
#Override
protected String doInBackground(String... params) {
googlePlaces = new GooglePlaces();
try{
String types = "cafe|restaurant";
double radius = 5000;
nearPlaces = googlePlaces.search(gps.getLatitude(), gps.getLongitude(), radius, types);
nearPlaces.status = "OK"; //Add this line for testing, your code should work now, because status is not NULL anymore.
}catch (Exception e){
e.printStackTrace();
}
return null;
}
i have used two edit text boxes where i have done validation for both the edittext boxes for email and confirm email address i have used text matcher and validation is working fine for me no issues when i checked it the data entered in the edittext is going inside database when i click the send button if there are error as well how to make the button disable when there will be error in any of the text boxes after correcting the error it has to deploy the data entered into database else it has to disable the button
i need to enter some thing to block the send button
I have done the validation here for edittext3 and edittext4 so if there any errors in this button has to disable where i must include
send.setEnabled(false);
send.setEnabled(true);
i must include this above method in this code
edittext3.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
Is_Valid_Email_Address(edittext3);
}
public void Is_Valid_Email_Address(EditText edittext3) {
if (edittext3.getText().toString() == null) {
edittext3.setError("Invalid Email Address");
valid_email = null;
} else if (isEmailValid(edittext3.getText().toString()) == false) {
edittext3.setError("Invalid Email Address");
valid_email = null;
} else if(edittext3.length() == 0 || edittext3.equals("") || edittext3 == null || "".equals(edittext3.getText().toString())) {
valid_email = null;
}else {
valid_email = edittext3.getText().toString();
}
}
});
edittext4.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
Is_Valid_Confirm_Address(edittext4);
}
public void Is_Valid_Confirm_Address(EditText edittext4) {
if (edittext4.getText().toString() == null) {
edittext4.setError("Invalid Email Address");
valid_confirm = null;
} else if (isEmailValid(edittext4.getText().toString()) == false) {
edittext4.setError("Invalid Email Address");
valid_confirm = null;
} else if (edittext4.getText().toString().equals(edittext3.getText().toString())) {
valid_confirm = edittext4.getText().toString();
} else if(edittext4.length() == 0 || edittext4.equals("") || edittext4 == null || "".equals(edittext4.getText().toString())) {
valid_confirm = null;
} else {
edittext4.setError("Confirm Email is Not Matching");
valid_confirm = null;
}
}
});
//if there are any errors then button must become disable or enable to add it into database
Button send= (Button)findViewById(R.id.send_email);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = edittext3.getText().toString();
String confirm = edittext4.getText().toString();
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email_address",email));
nameValuePairs.add(new BasicNameValuePair("confirm_email_address",confirm));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.132/Android_App/Sendata.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("log_tag", "connection success ");
Toast.makeText(getApplicationContext(), "contact you shortly.", Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
Intent i = new Intent(getBaseContext(),SecondActivity.class);
startActivity(i);
}
is.close();
result=sb.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
try
{
JSONObject json_data = new JSONObject(result);
CharSequence w= (CharSequence) json_data.get("result");
Toast.makeText(getApplicationContext(), w, Toast.LENGTH_SHORT).show();
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
}
}
});
}
private boolean isEmailValid(String email) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
does anyone know please help me thanks in advance
public void afterTextChanged(Editable s) {
if(Is_Valid_Email_Address(edittext3.getText().toString())){
send.setEnabled(true);
}else{
send.setEnabled(false);
}
}
Maybe try this? Apply it for edittext4 too.
Try this way.
I am having an Android activity in a package say com.blah.blah1 and a java class in another package say com.blah.blah2 , I am trying to access the java class from the activity, but it is throwing error as
02-06 14:35:03.360: E/dalvikvm(580): Could not find class
'org.json.simple.parser.JSONParser', referenced from method
com.blah.blah2.Login.login
Please help resolve
I am using eclipse
My jars are in libs folder
I have added the json jar to the build path
I am using jar json-simple-1.1.jar
I am working under Android 4.0.3
eclipse java compiler version 1.6
please find below the activity and java class for you reference
public class Chat_NewActivity extends Activity {
private String className = "Chat_NewActivity";
/** Asyn parameters */
private String response;
/** login() parameters */
LinkedHashMap<String,String> parameters ;
String responseToAsync = null;
UrlRequestAndResponse request = null;
static ResponseParameters param = null;
static String userId = null;
static String secureKey = null;
static String status = null;
static String sessionId = null;
/** Called when the activity is first created and loads main.xml content */
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(className, "Creating mail layout for the app...");
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(className, "Created");
}
/** action for items selected in Preferences menu */
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.settings_menu:
Intent settingsActivity = new Intent(getBaseContext(),
Chat_PreferenceActivity.class);
startActivity(settingsActivity);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
/** action calling on Start Chat button is clicked */
public void startChat(View view) {
Log.i(className, "Start Chat button is clicked");
Log.i(className, "performing action for staring chat");
Log.i(className, "performing user validation");
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
Chat_AppInfo.pref_email = sharedPref.getString("email",null);
if (Chat_AppInfo.pref_email != null && Chat_AppInfo.pref_email.matches("[a-zA-Z0-9._-]+#[a-z]+.[a-z]+")
&& Chat_AppInfo.pref_email.length() > 0) {
/** Intent i = new Intent(getApplicationContext(), AppActivity.class); */
Chat_AppInfo.pref_firstName = sharedPref.getString("firstName",null).toString();
Chat_AppInfo.pref_lastName = sharedPref.getString("lastName",null).toString();
EditText getsubject = (EditText) findViewById(R.id.subject);
Chat_AppInfo.pref_subject = getsubject.getText().toString();
Log.i(className, "first name : "+Chat_AppInfo.pref_firstName);
Log.i(className, "last name : "+Chat_AppInfo.pref_lastName);
Log.i(className, "last name : "+Chat_AppInfo.pref_email);
Log.i(className, "subject : "+Chat_AppInfo.pref_subject);
if(Chat_AppInfo.pref_firstName != null ||
Chat_AppInfo.pref_lastName != null ||
Chat_AppInfo.pref_subject.length() > 0) {
Log.i(className, "validation completed!!!");
checkNetworkConnection();
/**i.putExtra(AppInfo.firstName, get_FirstName_From_Pref);
i.putExtra(AppInfo.lastName, get_LastName_From_Pref);
i.putExtra(AppInfo.email, get_MailId_From_Pref);
i.putExtra(AppInfo.connection_Url, get_MailId_From_Pref);
i.putExtra(AppInfo.subject, subject);
startActivity(i);*/
} else {
Toast.makeText(getApplicationContext(), "Insufficient Credentials", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "E-mail is Invalid!!!", Toast.LENGTH_SHORT).show();
}
}
protected void checkNetworkConnection() {
Log.i(className, "Checking for Network / wi-fi connection!!!");
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
Log.i(className, "Network connection available!!!");
new AsyncConnectionEstablisher().execute(Chat_AppInfo.service_url+"LoginAction");
} else {
Log.i(className, "Network connection not available!!!");
Toast.makeText(getApplicationContext(), "Network Connection Not Available", Toast.LENGTH_SHORT).show();
}
}
private class AsyncConnectionEstablisher extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
Log.i(className, "Performing asynchronous connection...");
String output = null;
for (String url : urls) {
output = getOutputFromUrl(url);
}
return output;
}
private String getOutputFromUrl(String url) {
String output = null;
try {
Login createSessionObj = new Login();
createSessionObj.login(url);
output = createSessionObj.sessionId(Chat_AppInfo.service_url+"JoinAction");
//output = login(url);
} catch (Exception e) {
e.printStackTrace();
}
return output;
}
// onPostExecute displays the results of the AsyncTask.
protected void onPostExecute(String result) {
Log.i(className, "response is : "+result);
}
}
}
import java.io.IOException;
import java.util.LinkedHashMap;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import android.util.Log;
public class Login {
private String className = "Login";
LinkedHashMap<String,String> parameters ;
String responseToAsync = null;
UrlRequestAndResponse request = null;
String response;
static ResponseParameters param = null;
static String userId = null;
static String secureKey = null;
static String status = null;
static String sessionId = null;
public void login(String url) {
Log.i(className, "Calling login action with service URL : "+url);
parameters = new LinkedHashMap<String,String>();
parameters.put("firstname", Chat_AppInfo.pref_firstName);
parameters.put("lastname", Chat_AppInfo.pref_lastName);
parameters.put("email", Chat_AppInfo.pref_email);
parameters.put("subject", Chat_AppInfo.pref_subject);
request = new UrlRequestAndResponse();
request.setUrlRequestParameters(url, parameters, null);
request.convertStreamToJson();
response = request.getUrlResponseJson();
try {
JSONObject json = (JSONObject)new JSONParser().parse(response);
param.setUserId((String) json.get("userId"));
param.setSecureKey ((String) json.get("secureKey"));
param.setStatus((String) json.get("status"));
} catch (NullPointerException e) {
System.out.println("Properly set the setUrlRequestParameters(url, parameters, header) , convertStreamToJson() in the request...");
} catch (ParseException e) {
System.out.println("Parse the JSON String properly... Or Check the Servlet Response is in JSON format...");
}
try {
userId = param.getUserId();
secureKey = param.getSecureKey();
status = param.getStatus();
Log.i(className, "{\"userId\":\""+userId+"\",\"secureKey\":\""+secureKey+"\", \"status\":\""+status+"\"} ");
//sessionId(Chat_AppInfo.service_url+"JoinAction");
} catch (NullPointerException e) {
System.out.println("Check the parameters in response...");
}
}
}
Are you sure you have included org.json.simple.parser.JSONParser class in your app? Cause it doesn't seem to be on the default json package for android http://developer.android.com/reference/org/json/package-summary.html so maybe you should try to include these classes manually http://code.google.com/p/json-simple/source/browse/trunk/src/org/json/simple/parser/JSONParser.java?r=73